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.

274004 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, int) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  790. { kEventClassWindow, kEventWindowHandleDeactivate } };
  791. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  792. InstallWindowEventHandler (wrapperWindow, upp,
  793. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  794. windowEventTypes, this, &eventHandlerRef);
  795. setOurSizeToEmbeddedViewSize();
  796. setEmbeddedWindowToOurSize();
  797. creationTime = Time::getCurrentTime();
  798. }
  799. }
  800. void deleteWindow()
  801. {
  802. removeView (embeddedView);
  803. embeddedView = 0;
  804. if (wrapperWindow != 0)
  805. {
  806. RemoveEventHandler (eventHandlerRef);
  807. DisposeWindow (wrapperWindow);
  808. wrapperWindow = 0;
  809. }
  810. }
  811. void setOurSizeToEmbeddedViewSize()
  812. {
  813. int w, h;
  814. if (getEmbeddedViewSize (w, h))
  815. {
  816. if (w != getWidth() || h != getHeight())
  817. {
  818. startTimer (50);
  819. setSize (w, h);
  820. if (getParentComponent() != 0)
  821. getParentComponent()->setSize (w, h);
  822. }
  823. else
  824. {
  825. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  826. }
  827. }
  828. else
  829. {
  830. stopTimer();
  831. }
  832. }
  833. void setEmbeddedWindowToOurSize()
  834. {
  835. if (! recursiveResize)
  836. {
  837. recursiveResize = true;
  838. if (embeddedView != 0)
  839. {
  840. HIRect r;
  841. r.origin.x = 0;
  842. r.origin.y = 0;
  843. r.size.width = (float) getWidth();
  844. r.size.height = (float) getHeight();
  845. HIViewSetFrame (embeddedView, &r);
  846. }
  847. if (wrapperWindow != 0)
  848. {
  849. Rect wr;
  850. wr.left = getScreenX();
  851. wr.top = getScreenY();
  852. wr.right = wr.left + getWidth();
  853. wr.bottom = wr.top + getHeight();
  854. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  855. ShowWindow (wrapperWindow);
  856. }
  857. recursiveResize = false;
  858. }
  859. }
  860. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  861. {
  862. setEmbeddedWindowToOurSize();
  863. }
  864. void componentPeerChanged()
  865. {
  866. deleteWindow();
  867. createWindow();
  868. }
  869. void componentVisibilityChanged (Component&)
  870. {
  871. if (isShowing())
  872. createWindow();
  873. else
  874. deleteWindow();
  875. setEmbeddedWindowToOurSize();
  876. }
  877. static void recursiveHIViewRepaint (HIViewRef view)
  878. {
  879. HIViewSetNeedsDisplay (view, true);
  880. HIViewRef child = HIViewGetFirstSubview (view);
  881. while (child != 0)
  882. {
  883. recursiveHIViewRepaint (child);
  884. child = HIViewGetNextView (child);
  885. }
  886. }
  887. void timerCallback()
  888. {
  889. setOurSizeToEmbeddedViewSize();
  890. // To avoid strange overpainting problems when the UI is first opened, we'll
  891. // repaint it a few times during the first second that it's on-screen..
  892. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  893. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  894. }
  895. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  896. EventRef event)
  897. {
  898. switch (GetEventKind (event))
  899. {
  900. case kEventWindowHandleDeactivate:
  901. ActivateWindow (wrapperWindow, TRUE);
  902. break;
  903. case kEventWindowGetClickActivation:
  904. {
  905. getTopLevelComponent()->toFront (false);
  906. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  907. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  908. sizeof (ClickActivationResult), &howToHandleClick);
  909. HIViewSetNeedsDisplay (embeddedView, true);
  910. }
  911. break;
  912. }
  913. return noErr;
  914. }
  915. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  916. EventRef event, void* userData)
  917. {
  918. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  919. }
  920. protected:
  921. WindowRef wrapperWindow;
  922. HIViewRef embeddedView;
  923. bool recursiveResize;
  924. Time creationTime;
  925. EventHandlerRef eventHandlerRef;
  926. };
  927. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  928. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  929. END_JUCE_NAMESPACE
  930. #endif
  931. #define JUCE_AMALGAMATED_TEMPLATE 1
  932. //==============================================================================
  933. #if JUCE_BUILD_CORE
  934. /*** Start of inlined file: juce_FileLogger.cpp ***/
  935. BEGIN_JUCE_NAMESPACE
  936. FileLogger::FileLogger (const File& logFile_,
  937. const String& welcomeMessage,
  938. const int maxInitialFileSizeBytes)
  939. : logFile (logFile_)
  940. {
  941. if (maxInitialFileSizeBytes >= 0)
  942. trimFileSize (maxInitialFileSizeBytes);
  943. if (! logFile_.exists())
  944. {
  945. // do this so that the parent directories get created..
  946. logFile_.create();
  947. }
  948. logStream = logFile_.createOutputStream (256);
  949. jassert (logStream != 0);
  950. String welcome;
  951. welcome << "\r\n**********************************************************\r\n"
  952. << welcomeMessage
  953. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  954. << "\r\n";
  955. logMessage (welcome);
  956. }
  957. FileLogger::~FileLogger()
  958. {
  959. }
  960. void FileLogger::logMessage (const String& message)
  961. {
  962. if (logStream != 0)
  963. {
  964. DBG (message);
  965. const ScopedLock sl (logLock);
  966. (*logStream) << message << "\r\n";
  967. logStream->flush();
  968. }
  969. }
  970. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  971. {
  972. if (maxFileSizeBytes <= 0)
  973. {
  974. logFile.deleteFile();
  975. }
  976. else
  977. {
  978. const int64 fileSize = logFile.getSize();
  979. if (fileSize > maxFileSizeBytes)
  980. {
  981. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  982. jassert (in != 0);
  983. if (in != 0)
  984. {
  985. in->setPosition (fileSize - maxFileSizeBytes);
  986. String content;
  987. {
  988. MemoryBlock contentToSave;
  989. contentToSave.setSize (maxFileSizeBytes + 4);
  990. contentToSave.fillWith (0);
  991. in->read (contentToSave.getData(), maxFileSizeBytes);
  992. in = 0;
  993. content = contentToSave.toString();
  994. }
  995. int newStart = 0;
  996. while (newStart < fileSize
  997. && content[newStart] != '\n'
  998. && content[newStart] != '\r')
  999. ++newStart;
  1000. logFile.deleteFile();
  1001. logFile.appendText (content.substring (newStart), false, false);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1007. const String& logFileName,
  1008. const String& welcomeMessage,
  1009. const int maxInitialFileSizeBytes)
  1010. {
  1011. #if JUCE_MAC
  1012. File logFile ("~/Library/Logs");
  1013. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1014. .getChildFile (logFileName);
  1015. #else
  1016. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1017. if (logFile.isDirectory())
  1018. {
  1019. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1020. .getChildFile (logFileName);
  1021. }
  1022. #endif
  1023. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1024. }
  1025. END_JUCE_NAMESPACE
  1026. /*** End of inlined file: juce_FileLogger.cpp ***/
  1027. /*** Start of inlined file: juce_Logger.cpp ***/
  1028. BEGIN_JUCE_NAMESPACE
  1029. Logger::Logger()
  1030. {
  1031. }
  1032. Logger::~Logger()
  1033. {
  1034. }
  1035. static Logger* currentLogger = 0;
  1036. void Logger::setCurrentLogger (Logger* const newLogger,
  1037. const bool deleteOldLogger)
  1038. {
  1039. Logger* const oldLogger = currentLogger;
  1040. currentLogger = newLogger;
  1041. if (deleteOldLogger)
  1042. delete oldLogger;
  1043. }
  1044. void Logger::writeToLog (const String& message)
  1045. {
  1046. if (currentLogger != 0)
  1047. currentLogger->logMessage (message);
  1048. else
  1049. outputDebugString (message);
  1050. }
  1051. #if JUCE_LOG_ASSERTIONS
  1052. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1053. {
  1054. String m ("JUCE Assertion failure in ");
  1055. m << filename << ", line " << lineNum;
  1056. Logger::writeToLog (m);
  1057. }
  1058. #endif
  1059. END_JUCE_NAMESPACE
  1060. /*** End of inlined file: juce_Logger.cpp ***/
  1061. /*** Start of inlined file: juce_Random.cpp ***/
  1062. BEGIN_JUCE_NAMESPACE
  1063. Random::Random (const int64 seedValue) throw()
  1064. : seed (seedValue)
  1065. {
  1066. }
  1067. Random::~Random() throw()
  1068. {
  1069. }
  1070. void Random::setSeed (const int64 newSeed) throw()
  1071. {
  1072. seed = newSeed;
  1073. }
  1074. void Random::combineSeed (const int64 seedValue) throw()
  1075. {
  1076. seed ^= nextInt64() ^ seedValue;
  1077. }
  1078. void Random::setSeedRandomly()
  1079. {
  1080. combineSeed ((int64) (pointer_sized_int) this);
  1081. combineSeed (Time::getMillisecondCounter());
  1082. combineSeed (Time::getHighResolutionTicks());
  1083. combineSeed (Time::getHighResolutionTicksPerSecond());
  1084. combineSeed (Time::currentTimeMillis());
  1085. }
  1086. int Random::nextInt() throw()
  1087. {
  1088. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1089. return (int) (seed >> 16);
  1090. }
  1091. int Random::nextInt (const int maxValue) throw()
  1092. {
  1093. jassert (maxValue > 0);
  1094. return (nextInt() & 0x7fffffff) % maxValue;
  1095. }
  1096. int64 Random::nextInt64() throw()
  1097. {
  1098. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1099. }
  1100. bool Random::nextBool() throw()
  1101. {
  1102. return (nextInt() & 0x80000000) != 0;
  1103. }
  1104. float Random::nextFloat() throw()
  1105. {
  1106. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1107. }
  1108. double Random::nextDouble() throw()
  1109. {
  1110. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1111. }
  1112. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1113. {
  1114. BigInteger n;
  1115. do
  1116. {
  1117. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1118. }
  1119. while (n >= maximumValue);
  1120. return n;
  1121. }
  1122. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1123. {
  1124. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1125. while ((startBit & 31) != 0 && numBits > 0)
  1126. {
  1127. arrayToChange.setBit (startBit++, nextBool());
  1128. --numBits;
  1129. }
  1130. while (numBits >= 32)
  1131. {
  1132. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1133. startBit += 32;
  1134. numBits -= 32;
  1135. }
  1136. while (--numBits >= 0)
  1137. arrayToChange.setBit (startBit + numBits, nextBool());
  1138. }
  1139. Random& Random::getSystemRandom() throw()
  1140. {
  1141. static Random sysRand (1);
  1142. return sysRand;
  1143. }
  1144. END_JUCE_NAMESPACE
  1145. /*** End of inlined file: juce_Random.cpp ***/
  1146. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1147. BEGIN_JUCE_NAMESPACE
  1148. RelativeTime::RelativeTime (const double seconds_) throw()
  1149. : seconds (seconds_)
  1150. {
  1151. }
  1152. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1153. : seconds (other.seconds)
  1154. {
  1155. }
  1156. RelativeTime::~RelativeTime() throw()
  1157. {
  1158. }
  1159. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1160. {
  1161. return RelativeTime (milliseconds * 0.001);
  1162. }
  1163. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1164. {
  1165. return RelativeTime (milliseconds * 0.001);
  1166. }
  1167. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1168. {
  1169. return RelativeTime (numberOfMinutes * 60.0);
  1170. }
  1171. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1172. {
  1173. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1174. }
  1175. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1176. {
  1177. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1178. }
  1179. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1180. {
  1181. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1182. }
  1183. int64 RelativeTime::inMilliseconds() const throw()
  1184. {
  1185. return (int64)(seconds * 1000.0);
  1186. }
  1187. double RelativeTime::inMinutes() const throw()
  1188. {
  1189. return seconds / 60.0;
  1190. }
  1191. double RelativeTime::inHours() const throw()
  1192. {
  1193. return seconds / (60.0 * 60.0);
  1194. }
  1195. double RelativeTime::inDays() const throw()
  1196. {
  1197. return seconds / (60.0 * 60.0 * 24.0);
  1198. }
  1199. double RelativeTime::inWeeks() const throw()
  1200. {
  1201. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1202. }
  1203. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1204. {
  1205. if (seconds < 0.001 && seconds > -0.001)
  1206. return returnValueForZeroTime;
  1207. String result;
  1208. if (seconds < 0)
  1209. result = "-";
  1210. int fieldsShown = 0;
  1211. int n = abs ((int) inWeeks());
  1212. if (n > 0)
  1213. {
  1214. result << n << ((n == 1) ? TRANS(" week ")
  1215. : TRANS(" weeks "));
  1216. ++fieldsShown;
  1217. }
  1218. n = abs ((int) inDays()) % 7;
  1219. if (n > 0)
  1220. {
  1221. result << n << ((n == 1) ? TRANS(" day ")
  1222. : TRANS(" days "));
  1223. ++fieldsShown;
  1224. }
  1225. if (fieldsShown < 2)
  1226. {
  1227. n = abs ((int) inHours()) % 24;
  1228. if (n > 0)
  1229. {
  1230. result << n << ((n == 1) ? TRANS(" hr ")
  1231. : TRANS(" hrs "));
  1232. ++fieldsShown;
  1233. }
  1234. if (fieldsShown < 2)
  1235. {
  1236. n = abs ((int) inMinutes()) % 60;
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" min ")
  1240. : TRANS(" mins "));
  1241. ++fieldsShown;
  1242. }
  1243. if (fieldsShown < 2)
  1244. {
  1245. n = abs ((int) inSeconds()) % 60;
  1246. if (n > 0)
  1247. {
  1248. result << n << ((n == 1) ? TRANS(" sec ")
  1249. : TRANS(" secs "));
  1250. ++fieldsShown;
  1251. }
  1252. if (fieldsShown < 1)
  1253. {
  1254. n = abs ((int) inMilliseconds()) % 1000;
  1255. if (n > 0)
  1256. {
  1257. result << n << TRANS(" ms");
  1258. ++fieldsShown;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return result.trimEnd();
  1265. }
  1266. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1267. {
  1268. seconds = other.seconds;
  1269. return *this;
  1270. }
  1271. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1272. {
  1273. return seconds == other.seconds;
  1274. }
  1275. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1276. {
  1277. return seconds != other.seconds;
  1278. }
  1279. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1280. {
  1281. return seconds > other.seconds;
  1282. }
  1283. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1284. {
  1285. return seconds < other.seconds;
  1286. }
  1287. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1288. {
  1289. return seconds >= other.seconds;
  1290. }
  1291. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1292. {
  1293. return seconds <= other.seconds;
  1294. }
  1295. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1296. {
  1297. return RelativeTime (seconds + timeToAdd.seconds);
  1298. }
  1299. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1300. {
  1301. return RelativeTime (seconds - timeToSubtract.seconds);
  1302. }
  1303. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1304. {
  1305. return RelativeTime (seconds + secondsToAdd);
  1306. }
  1307. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1308. {
  1309. return RelativeTime (seconds - secondsToSubtract);
  1310. }
  1311. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1312. {
  1313. seconds += timeToAdd.seconds;
  1314. return *this;
  1315. }
  1316. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1317. {
  1318. seconds -= timeToSubtract.seconds;
  1319. return *this;
  1320. }
  1321. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1322. {
  1323. seconds += secondsToAdd;
  1324. return *this;
  1325. }
  1326. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1327. {
  1328. seconds -= secondsToSubtract;
  1329. return *this;
  1330. }
  1331. END_JUCE_NAMESPACE
  1332. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1333. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1334. BEGIN_JUCE_NAMESPACE
  1335. const String SystemStats::getJUCEVersion() 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, b;
  1363. a.set ((Type) 10);
  1364. a += (Type) 15;
  1365. a.memoryBarrier();
  1366. a -= (Type) 5;
  1367. ++a;
  1368. ++a;
  1369. --a;
  1370. a.memoryBarrier();
  1371. /* These are some simple test cases to check the atomics - let me know
  1372. if any of these assertions fail on your system!
  1373. */
  1374. jassert (a.get() == (Type) 21);
  1375. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1376. jassert (a.get() == (Type) 21);
  1377. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1378. jassert (a.get() == (Type) 101);
  1379. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1380. jassert (a.get() == (Type) 101);
  1381. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1382. jassert (a.get() == (Type) 200);
  1383. jassert (a.exchange ((Type) 300) == (Type) 200);
  1384. jassert (a.get() == (Type) 300);
  1385. b = a;
  1386. jassert (b.get() == a.get());
  1387. }
  1388. static void juce_testAtomics()
  1389. {
  1390. juce_testAtomicType ((int) 0);
  1391. juce_testAtomicType ((unsigned int) 0);
  1392. juce_testAtomicType ((int32) 0);
  1393. juce_testAtomicType ((uint32) 0);
  1394. juce_testAtomicType ((long) 0);
  1395. juce_testAtomicType ((void*) 0);
  1396. juce_testAtomicType ((int*) 0);
  1397. #if ! ((JUCE_WINDOWS && JUCE_32BIT) || JUCE_PPC) // 64-bit intrinsics aren't available on some old platforms
  1398. juce_testAtomicType ((int64) 0);
  1399. juce_testAtomicType ((uint64) 0);
  1400. #endif
  1401. }
  1402. #endif
  1403. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1404. {
  1405. if (! juceInitialisedNonGUI)
  1406. {
  1407. #if JUCE_MAC || JUCE_IPHONE
  1408. const ScopedAutoReleasePool pool;
  1409. #endif
  1410. #if JUCE_DEBUG
  1411. {
  1412. // Some simple test code to keep an eye on things and make sure these functions
  1413. // work ok on all platforms. Let me know if any of these assertions fail!
  1414. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1415. static_jassert (sizeof (int8) == 1);
  1416. static_jassert (sizeof (uint8) == 1);
  1417. static_jassert (sizeof (int16) == 2);
  1418. static_jassert (sizeof (uint16) == 2);
  1419. static_jassert (sizeof (int32) == 4);
  1420. static_jassert (sizeof (uint32) == 4);
  1421. static_jassert (sizeof (int64) == 8);
  1422. static_jassert (sizeof (uint64) == 8);
  1423. char a1[7];
  1424. jassert (numElementsInArray(a1) == 7);
  1425. int a2[3];
  1426. jassert (numElementsInArray(a2) == 3);
  1427. juce_testAtomics();
  1428. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1429. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1430. // Some quick stream tests..
  1431. int randomInt = Random::getSystemRandom().nextInt();
  1432. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1433. double randomDouble = Random::getSystemRandom().nextDouble();
  1434. String randomString;
  1435. for (int i = 50; --i >= 0;)
  1436. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1437. MemoryOutputStream mo;
  1438. mo.writeInt (randomInt);
  1439. mo.writeIntBigEndian (randomInt);
  1440. mo.writeCompressedInt (randomInt);
  1441. mo.writeString (randomString);
  1442. mo.writeInt64 (randomInt64);
  1443. mo.writeInt64BigEndian (randomInt64);
  1444. mo.writeDouble (randomDouble);
  1445. mo.writeDoubleBigEndian (randomDouble);
  1446. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1447. jassert (mi.readInt() == randomInt);
  1448. jassert (mi.readIntBigEndian() == randomInt);
  1449. jassert (mi.readCompressedInt() == randomInt);
  1450. jassert (mi.readString() == randomString);
  1451. jassert (mi.readInt64() == randomInt64);
  1452. jassert (mi.readInt64BigEndian() == randomInt64);
  1453. jassert (mi.readDouble() == randomDouble);
  1454. jassert (mi.readDoubleBigEndian() == randomDouble);
  1455. }
  1456. #endif
  1457. // Now the real initialisation..
  1458. juceInitialisedNonGUI = true;
  1459. DBG (SystemStats::getJUCEVersion());
  1460. SystemStats::initialiseStats();
  1461. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1462. }
  1463. }
  1464. #if JUCE_WINDOWS
  1465. // This is imported from the sockets code..
  1466. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1467. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1468. #endif
  1469. #if JUCE_DEBUG
  1470. extern void juce_CheckForDanglingStreams();
  1471. #endif
  1472. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1473. {
  1474. if (juceInitialisedNonGUI)
  1475. {
  1476. #if JUCE_MAC || JUCE_IPHONE
  1477. const ScopedAutoReleasePool pool;
  1478. #endif
  1479. #if JUCE_WINDOWS
  1480. // need to shut down sockets if they were used..
  1481. if (juce_CloseWin32SocketLib != 0)
  1482. (*juce_CloseWin32SocketLib)();
  1483. #endif
  1484. LocalisedStrings::setCurrentMappings (0);
  1485. Thread::stopAllThreads (3000);
  1486. #if JUCE_DEBUG
  1487. juce_CheckForDanglingStreams();
  1488. #endif
  1489. juceInitialisedNonGUI = false;
  1490. }
  1491. }
  1492. #ifdef JUCE_DLL
  1493. void* juce_Malloc (const int size)
  1494. {
  1495. return malloc (size);
  1496. }
  1497. void* juce_Calloc (const int size)
  1498. {
  1499. return calloc (1, size);
  1500. }
  1501. void* juce_Realloc (void* const block, const int size)
  1502. {
  1503. return realloc (block, size);
  1504. }
  1505. void juce_Free (void* const block)
  1506. {
  1507. free (block);
  1508. }
  1509. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1510. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1511. {
  1512. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1513. }
  1514. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1515. {
  1516. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1517. }
  1518. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1519. {
  1520. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1521. }
  1522. void juce_DebugFree (void* const block)
  1523. {
  1524. _free_dbg (block, _NORMAL_BLOCK);
  1525. }
  1526. #endif
  1527. #endif
  1528. END_JUCE_NAMESPACE
  1529. /*** End of inlined file: juce_SystemStats.cpp ***/
  1530. /*** Start of inlined file: juce_Time.cpp ***/
  1531. #ifdef _MSC_VER
  1532. #pragma warning (disable: 4514)
  1533. #pragma warning (push)
  1534. #endif
  1535. #ifndef JUCE_WINDOWS
  1536. #include <sys/time.h>
  1537. #else
  1538. #include <ctime>
  1539. #endif
  1540. #include <sys/timeb.h>
  1541. BEGIN_JUCE_NAMESPACE
  1542. #ifdef _MSC_VER
  1543. #pragma warning (pop)
  1544. #ifdef _INC_TIME_INL
  1545. #define USE_NEW_SECURE_TIME_FNS
  1546. #endif
  1547. #endif
  1548. namespace TimeHelpers
  1549. {
  1550. static struct tm millisToLocal (const int64 millis) throw()
  1551. {
  1552. struct tm result;
  1553. const int64 seconds = millis / 1000;
  1554. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1555. {
  1556. // use extended maths for dates beyond 1970 to 2037..
  1557. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1558. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1559. const int days = (int) (jdm / literal64bit (86400));
  1560. const int a = 32044 + days;
  1561. const int b = (4 * a + 3) / 146097;
  1562. const int c = a - (b * 146097) / 4;
  1563. const int d = (4 * c + 3) / 1461;
  1564. const int e = c - (d * 1461) / 4;
  1565. const int m = (5 * e + 2) / 153;
  1566. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1567. result.tm_mon = m + 2 - 12 * (m / 10);
  1568. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1569. result.tm_wday = (days + 1) % 7;
  1570. result.tm_yday = -1;
  1571. int t = (int) (jdm % literal64bit (86400));
  1572. result.tm_hour = t / 3600;
  1573. t %= 3600;
  1574. result.tm_min = t / 60;
  1575. result.tm_sec = t % 60;
  1576. result.tm_isdst = -1;
  1577. }
  1578. else
  1579. {
  1580. time_t now = static_cast <time_t> (seconds);
  1581. #if JUCE_WINDOWS
  1582. #ifdef USE_NEW_SECURE_TIME_FNS
  1583. if (now >= 0 && now <= 0x793406fff)
  1584. localtime_s (&result, &now);
  1585. else
  1586. zeromem (&result, sizeof (result));
  1587. #else
  1588. result = *localtime (&now);
  1589. #endif
  1590. #else
  1591. // more thread-safe
  1592. localtime_r (&now, &result);
  1593. #endif
  1594. }
  1595. return result;
  1596. }
  1597. static int extendedModulo (const int64 value, const int modulo) throw()
  1598. {
  1599. return (int) (value >= 0 ? (value % modulo)
  1600. : (value - ((value / modulo) + 1) * modulo));
  1601. }
  1602. static uint32 lastMSCounterValue = 0;
  1603. }
  1604. Time::Time() throw()
  1605. : millisSinceEpoch (0)
  1606. {
  1607. }
  1608. Time::Time (const Time& other) throw()
  1609. : millisSinceEpoch (other.millisSinceEpoch)
  1610. {
  1611. }
  1612. Time::Time (const int64 ms) throw()
  1613. : millisSinceEpoch (ms)
  1614. {
  1615. }
  1616. Time::Time (const int year,
  1617. const int month,
  1618. const int day,
  1619. const int hours,
  1620. const int minutes,
  1621. const int seconds,
  1622. const int milliseconds,
  1623. const bool useLocalTime) throw()
  1624. {
  1625. jassert (year > 100); // year must be a 4-digit version
  1626. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1627. {
  1628. // use extended maths for dates beyond 1970 to 2037..
  1629. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1630. : 0;
  1631. const int a = (13 - month) / 12;
  1632. const int y = year + 4800 - a;
  1633. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1634. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1635. - 32045;
  1636. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1637. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1638. + milliseconds;
  1639. }
  1640. else
  1641. {
  1642. struct tm t;
  1643. t.tm_year = year - 1900;
  1644. t.tm_mon = month;
  1645. t.tm_mday = day;
  1646. t.tm_hour = hours;
  1647. t.tm_min = minutes;
  1648. t.tm_sec = seconds;
  1649. t.tm_isdst = -1;
  1650. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1651. if (millisSinceEpoch < 0)
  1652. millisSinceEpoch = 0;
  1653. else
  1654. millisSinceEpoch += milliseconds;
  1655. }
  1656. }
  1657. Time::~Time() throw()
  1658. {
  1659. }
  1660. Time& Time::operator= (const Time& other) throw()
  1661. {
  1662. millisSinceEpoch = other.millisSinceEpoch;
  1663. return *this;
  1664. }
  1665. int64 Time::currentTimeMillis() throw()
  1666. {
  1667. static uint32 lastCounterResult = 0xffffffff;
  1668. static int64 correction = 0;
  1669. const uint32 now = getMillisecondCounter();
  1670. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1671. if (now < lastCounterResult)
  1672. {
  1673. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1674. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1675. {
  1676. // get the time once using normal library calls, and store the difference needed to
  1677. // turn the millisecond counter into a real time.
  1678. #if JUCE_WINDOWS
  1679. struct _timeb t;
  1680. #ifdef USE_NEW_SECURE_TIME_FNS
  1681. _ftime_s (&t);
  1682. #else
  1683. _ftime (&t);
  1684. #endif
  1685. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1686. #else
  1687. struct timeval tv;
  1688. struct timezone tz;
  1689. gettimeofday (&tv, &tz);
  1690. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1691. #endif
  1692. }
  1693. }
  1694. lastCounterResult = now;
  1695. return correction + now;
  1696. }
  1697. uint32 juce_millisecondsSinceStartup() throw();
  1698. uint32 Time::getMillisecondCounter() throw()
  1699. {
  1700. const uint32 now = juce_millisecondsSinceStartup();
  1701. if (now < TimeHelpers::lastMSCounterValue)
  1702. {
  1703. // in multi-threaded apps this might be called concurrently, so
  1704. // make sure that our last counter value only increases and doesn't
  1705. // go backwards..
  1706. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1707. TimeHelpers::lastMSCounterValue = now;
  1708. }
  1709. else
  1710. {
  1711. TimeHelpers::lastMSCounterValue = now;
  1712. }
  1713. return now;
  1714. }
  1715. uint32 Time::getApproximateMillisecondCounter() throw()
  1716. {
  1717. jassert (TimeHelpers::lastMSCounterValue != 0);
  1718. return TimeHelpers::lastMSCounterValue;
  1719. }
  1720. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1721. {
  1722. for (;;)
  1723. {
  1724. const uint32 now = getMillisecondCounter();
  1725. if (now >= targetTime)
  1726. break;
  1727. const int toWait = targetTime - now;
  1728. if (toWait > 2)
  1729. {
  1730. Thread::sleep (jmin (20, toWait >> 1));
  1731. }
  1732. else
  1733. {
  1734. // xxx should consider using mutex_pause on the mac as it apparently
  1735. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1736. for (int i = 10; --i >= 0;)
  1737. Thread::yield();
  1738. }
  1739. }
  1740. }
  1741. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1742. {
  1743. return ticks / (double) getHighResolutionTicksPerSecond();
  1744. }
  1745. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1746. {
  1747. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1748. }
  1749. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1750. {
  1751. return Time (currentTimeMillis());
  1752. }
  1753. const String Time::toString (const bool includeDate,
  1754. const bool includeTime,
  1755. const bool includeSeconds,
  1756. const bool use24HourClock) const throw()
  1757. {
  1758. String result;
  1759. if (includeDate)
  1760. {
  1761. result << getDayOfMonth() << ' '
  1762. << getMonthName (true) << ' '
  1763. << getYear();
  1764. if (includeTime)
  1765. result << ' ';
  1766. }
  1767. if (includeTime)
  1768. {
  1769. const int mins = getMinutes();
  1770. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1771. << (mins < 10 ? ":0" : ":") << mins;
  1772. if (includeSeconds)
  1773. {
  1774. const int secs = getSeconds();
  1775. result << (secs < 10 ? ":0" : ":") << secs;
  1776. }
  1777. if (! use24HourClock)
  1778. result << (isAfternoon() ? "pm" : "am");
  1779. }
  1780. return result.trimEnd();
  1781. }
  1782. const String Time::formatted (const String& format) const throw()
  1783. {
  1784. String buffer;
  1785. int bufferSize = 128;
  1786. buffer.preallocateStorage (bufferSize);
  1787. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1788. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1789. {
  1790. bufferSize += 128;
  1791. buffer.preallocateStorage (bufferSize);
  1792. }
  1793. return buffer;
  1794. }
  1795. int Time::getYear() const throw()
  1796. {
  1797. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1798. }
  1799. int Time::getMonth() const throw()
  1800. {
  1801. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1802. }
  1803. int Time::getDayOfMonth() const throw()
  1804. {
  1805. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1806. }
  1807. int Time::getDayOfWeek() const throw()
  1808. {
  1809. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1810. }
  1811. int Time::getHours() const throw()
  1812. {
  1813. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1814. }
  1815. int Time::getHoursInAmPmFormat() const throw()
  1816. {
  1817. const int hours = getHours();
  1818. if (hours == 0)
  1819. return 12;
  1820. else if (hours <= 12)
  1821. return hours;
  1822. else
  1823. return hours - 12;
  1824. }
  1825. bool Time::isAfternoon() const throw()
  1826. {
  1827. return getHours() >= 12;
  1828. }
  1829. int Time::getMinutes() const throw()
  1830. {
  1831. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1832. }
  1833. int Time::getSeconds() const throw()
  1834. {
  1835. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1836. }
  1837. int Time::getMilliseconds() const throw()
  1838. {
  1839. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1840. }
  1841. bool Time::isDaylightSavingTime() const throw()
  1842. {
  1843. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1844. }
  1845. const String Time::getTimeZone() const throw()
  1846. {
  1847. String zone[2];
  1848. #if JUCE_WINDOWS
  1849. _tzset();
  1850. #ifdef USE_NEW_SECURE_TIME_FNS
  1851. {
  1852. char name [128];
  1853. size_t length;
  1854. for (int i = 0; i < 2; ++i)
  1855. {
  1856. zeromem (name, sizeof (name));
  1857. _get_tzname (&length, name, 127, i);
  1858. zone[i] = name;
  1859. }
  1860. }
  1861. #else
  1862. const char** const zonePtr = (const char**) _tzname;
  1863. zone[0] = zonePtr[0];
  1864. zone[1] = zonePtr[1];
  1865. #endif
  1866. #else
  1867. tzset();
  1868. const char** const zonePtr = (const char**) tzname;
  1869. zone[0] = zonePtr[0];
  1870. zone[1] = zonePtr[1];
  1871. #endif
  1872. if (isDaylightSavingTime())
  1873. {
  1874. zone[0] = zone[1];
  1875. if (zone[0].length() > 3
  1876. && zone[0].containsIgnoreCase ("daylight")
  1877. && zone[0].contains ("GMT"))
  1878. zone[0] = "BST";
  1879. }
  1880. return zone[0].substring (0, 3);
  1881. }
  1882. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1883. {
  1884. return getMonthName (getMonth(), threeLetterVersion);
  1885. }
  1886. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1887. {
  1888. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1889. }
  1890. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1891. {
  1892. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1893. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1894. monthNumber %= 12;
  1895. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1896. : longMonthNames [monthNumber]);
  1897. }
  1898. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1899. {
  1900. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1901. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1902. day %= 7;
  1903. return TRANS (threeLetterVersion ? shortDayNames [day]
  1904. : longDayNames [day]);
  1905. }
  1906. END_JUCE_NAMESPACE
  1907. /*** End of inlined file: juce_Time.cpp ***/
  1908. /*** Start of inlined file: juce_BitArray.cpp ***/
  1909. BEGIN_JUCE_NAMESPACE
  1910. BigInteger::BigInteger()
  1911. : numValues (4),
  1912. highestBit (-1),
  1913. negative (false)
  1914. {
  1915. values.calloc (numValues + 1);
  1916. }
  1917. BigInteger::BigInteger (const int value)
  1918. : numValues (4),
  1919. highestBit (31),
  1920. negative (value < 0)
  1921. {
  1922. values.calloc (numValues + 1);
  1923. values[0] = abs (value);
  1924. highestBit = getHighestBit();
  1925. }
  1926. BigInteger::BigInteger (int64 value)
  1927. : numValues (4),
  1928. highestBit (63),
  1929. negative (value < 0)
  1930. {
  1931. values.calloc (numValues + 1);
  1932. if (value < 0)
  1933. value = -value;
  1934. values[0] = (unsigned int) value;
  1935. values[1] = (unsigned int) (value >> 32);
  1936. highestBit = getHighestBit();
  1937. }
  1938. BigInteger::BigInteger (const unsigned int value)
  1939. : numValues (4),
  1940. highestBit (31),
  1941. negative (false)
  1942. {
  1943. values.calloc (numValues + 1);
  1944. values[0] = value;
  1945. highestBit = getHighestBit();
  1946. }
  1947. BigInteger::BigInteger (const BigInteger& other)
  1948. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1949. highestBit (other.getHighestBit()),
  1950. negative (other.negative)
  1951. {
  1952. values.malloc (numValues + 1);
  1953. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1954. }
  1955. BigInteger::~BigInteger()
  1956. {
  1957. }
  1958. void BigInteger::swapWith (BigInteger& other) throw()
  1959. {
  1960. values.swapWith (other.values);
  1961. swapVariables (numValues, other.numValues);
  1962. swapVariables (highestBit, other.highestBit);
  1963. swapVariables (negative, other.negative);
  1964. }
  1965. BigInteger& BigInteger::operator= (const BigInteger& other)
  1966. {
  1967. if (this != &other)
  1968. {
  1969. highestBit = other.getHighestBit();
  1970. numValues = jmax (4, (highestBit >> 5) + 1);
  1971. negative = other.negative;
  1972. values.malloc (numValues + 1);
  1973. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1974. }
  1975. return *this;
  1976. }
  1977. void BigInteger::ensureSize (const int numVals)
  1978. {
  1979. if (numVals + 2 >= numValues)
  1980. {
  1981. int oldSize = numValues;
  1982. numValues = ((numVals + 2) * 3) / 2;
  1983. values.realloc (numValues + 1);
  1984. while (oldSize < numValues)
  1985. values [oldSize++] = 0;
  1986. }
  1987. }
  1988. bool BigInteger::operator[] (const int bit) const throw()
  1989. {
  1990. return bit <= highestBit && bit >= 0
  1991. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1992. }
  1993. int BigInteger::toInteger() const throw()
  1994. {
  1995. const int n = (int) (values[0] & 0x7fffffff);
  1996. return negative ? -n : n;
  1997. }
  1998. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  1999. {
  2000. BigInteger r;
  2001. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2002. r.ensureSize (numBits >> 5);
  2003. r.highestBit = numBits;
  2004. int i = 0;
  2005. while (numBits > 0)
  2006. {
  2007. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2008. numBits -= 32;
  2009. startBit += 32;
  2010. }
  2011. r.highestBit = r.getHighestBit();
  2012. return r;
  2013. }
  2014. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2015. {
  2016. if (numBits > 32)
  2017. {
  2018. jassertfalse // use getBitRange() if you need more than 32 bits..
  2019. numBits = 32;
  2020. }
  2021. numBits = jmin (numBits, highestBit + 1 - startBit);
  2022. if (numBits <= 0)
  2023. return 0;
  2024. const int pos = startBit >> 5;
  2025. const int offset = startBit & 31;
  2026. const int endSpace = 32 - numBits;
  2027. uint32 n = ((uint32) values [pos]) >> offset;
  2028. if (offset > endSpace)
  2029. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2030. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2031. }
  2032. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2033. {
  2034. if (numBits > 32)
  2035. {
  2036. jassertfalse
  2037. numBits = 32;
  2038. }
  2039. for (int i = 0; i < numBits; ++i)
  2040. {
  2041. setBit (startBit + i, (valueToSet & 1) != 0);
  2042. valueToSet >>= 1;
  2043. }
  2044. }
  2045. void BigInteger::clear()
  2046. {
  2047. if (numValues > 16)
  2048. {
  2049. numValues = 4;
  2050. values.calloc (numValues + 1);
  2051. }
  2052. else
  2053. {
  2054. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2055. }
  2056. highestBit = -1;
  2057. negative = false;
  2058. }
  2059. void BigInteger::setBit (const int bit)
  2060. {
  2061. if (bit >= 0)
  2062. {
  2063. if (bit > highestBit)
  2064. {
  2065. ensureSize (bit >> 5);
  2066. highestBit = bit;
  2067. }
  2068. values [bit >> 5] |= (1 << (bit & 31));
  2069. }
  2070. }
  2071. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2072. {
  2073. if (shouldBeSet)
  2074. setBit (bit);
  2075. else
  2076. clearBit (bit);
  2077. }
  2078. void BigInteger::clearBit (const int bit) throw()
  2079. {
  2080. if (bit >= 0 && bit <= highestBit)
  2081. values [bit >> 5] &= ~(1 << (bit & 31));
  2082. }
  2083. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2084. {
  2085. while (--numBits >= 0)
  2086. setBit (startBit++, shouldBeSet);
  2087. }
  2088. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2089. {
  2090. if (bit >= 0)
  2091. shiftBits (1, bit);
  2092. setBit (bit, shouldBeSet);
  2093. }
  2094. bool BigInteger::isZero() const throw()
  2095. {
  2096. return getHighestBit() < 0;
  2097. }
  2098. bool BigInteger::isOne() const throw()
  2099. {
  2100. return getHighestBit() == 0 && ! negative;
  2101. }
  2102. bool BigInteger::isNegative() const throw()
  2103. {
  2104. return negative && ! isZero();
  2105. }
  2106. void BigInteger::setNegative (const bool neg) throw()
  2107. {
  2108. negative = neg;
  2109. }
  2110. void BigInteger::negate() throw()
  2111. {
  2112. negative = (! negative) && ! isZero();
  2113. }
  2114. int BigInteger::countNumberOfSetBits() const throw()
  2115. {
  2116. int total = 0;
  2117. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2118. {
  2119. unsigned int n = values[i];
  2120. if (n == 0xffffffff)
  2121. {
  2122. total += 32;
  2123. }
  2124. else
  2125. {
  2126. while (n != 0)
  2127. {
  2128. total += (n & 1);
  2129. n >>= 1;
  2130. }
  2131. }
  2132. }
  2133. return total;
  2134. }
  2135. int BigInteger::getHighestBit() const throw()
  2136. {
  2137. for (int i = highestBit + 1; --i >= 0;)
  2138. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2139. return i;
  2140. return -1;
  2141. }
  2142. int BigInteger::findNextSetBit (int i) const throw()
  2143. {
  2144. for (; i <= highestBit; ++i)
  2145. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2146. return i;
  2147. return -1;
  2148. }
  2149. int BigInteger::findNextClearBit (int i) const throw()
  2150. {
  2151. for (; i <= highestBit; ++i)
  2152. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2153. break;
  2154. return i;
  2155. }
  2156. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2157. {
  2158. if (other.isNegative())
  2159. return operator-= (-other);
  2160. if (isNegative())
  2161. {
  2162. if (compareAbsolute (other) < 0)
  2163. {
  2164. BigInteger temp (*this);
  2165. temp.negate();
  2166. *this = other;
  2167. operator-= (temp);
  2168. }
  2169. else
  2170. {
  2171. negate();
  2172. operator-= (other);
  2173. negate();
  2174. }
  2175. }
  2176. else
  2177. {
  2178. if (other.highestBit > highestBit)
  2179. highestBit = other.highestBit;
  2180. ++highestBit;
  2181. const int numInts = (highestBit >> 5) + 1;
  2182. ensureSize (numInts);
  2183. int64 remainder = 0;
  2184. for (int i = 0; i <= numInts; ++i)
  2185. {
  2186. if (i < numValues)
  2187. remainder += values[i];
  2188. if (i < other.numValues)
  2189. remainder += other.values[i];
  2190. values[i] = (unsigned int) remainder;
  2191. remainder >>= 32;
  2192. }
  2193. jassert (remainder == 0);
  2194. highestBit = getHighestBit();
  2195. }
  2196. return *this;
  2197. }
  2198. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2199. {
  2200. if (other.isNegative())
  2201. return operator+= (-other);
  2202. if (! isNegative())
  2203. {
  2204. if (compareAbsolute (other) < 0)
  2205. {
  2206. BigInteger temp (other);
  2207. swapWith (temp);
  2208. operator-= (temp);
  2209. negate();
  2210. return *this;
  2211. }
  2212. }
  2213. else
  2214. {
  2215. negate();
  2216. operator+= (other);
  2217. negate();
  2218. return *this;
  2219. }
  2220. const int numInts = (highestBit >> 5) + 1;
  2221. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2222. int64 amountToSubtract = 0;
  2223. for (int i = 0; i <= numInts; ++i)
  2224. {
  2225. if (i <= maxOtherInts)
  2226. amountToSubtract += (int64) other.values[i];
  2227. if (values[i] >= amountToSubtract)
  2228. {
  2229. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2230. amountToSubtract = 0;
  2231. }
  2232. else
  2233. {
  2234. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2235. values[i] = (unsigned int) n;
  2236. amountToSubtract = 1;
  2237. }
  2238. }
  2239. return *this;
  2240. }
  2241. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2242. {
  2243. BigInteger total;
  2244. highestBit = getHighestBit();
  2245. const bool wasNegative = isNegative();
  2246. setNegative (false);
  2247. for (int i = 0; i <= highestBit; ++i)
  2248. {
  2249. if (operator[](i))
  2250. {
  2251. BigInteger n (other);
  2252. n.setNegative (false);
  2253. n <<= i;
  2254. total += n;
  2255. }
  2256. }
  2257. total.setNegative (wasNegative ^ other.isNegative());
  2258. swapWith (total);
  2259. return *this;
  2260. }
  2261. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2262. {
  2263. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2264. const int divHB = divisor.getHighestBit();
  2265. const int ourHB = getHighestBit();
  2266. if (divHB < 0 || ourHB < 0)
  2267. {
  2268. // division by zero
  2269. remainder.clear();
  2270. clear();
  2271. }
  2272. else
  2273. {
  2274. const bool wasNegative = isNegative();
  2275. swapWith (remainder);
  2276. remainder.setNegative (false);
  2277. clear();
  2278. BigInteger temp (divisor);
  2279. temp.setNegative (false);
  2280. int leftShift = ourHB - divHB;
  2281. temp <<= leftShift;
  2282. while (leftShift >= 0)
  2283. {
  2284. if (remainder.compareAbsolute (temp) >= 0)
  2285. {
  2286. remainder -= temp;
  2287. setBit (leftShift);
  2288. }
  2289. if (--leftShift >= 0)
  2290. temp >>= 1;
  2291. }
  2292. negative = wasNegative ^ divisor.isNegative();
  2293. remainder.setNegative (wasNegative);
  2294. }
  2295. }
  2296. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2297. {
  2298. BigInteger remainder;
  2299. divideBy (other, remainder);
  2300. return *this;
  2301. }
  2302. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2303. {
  2304. // this operation doesn't take into account negative values..
  2305. jassert (isNegative() == other.isNegative());
  2306. if (other.highestBit >= 0)
  2307. {
  2308. ensureSize (other.highestBit >> 5);
  2309. int n = (other.highestBit >> 5) + 1;
  2310. while (--n >= 0)
  2311. values[n] |= other.values[n];
  2312. if (other.highestBit > highestBit)
  2313. highestBit = other.highestBit;
  2314. highestBit = getHighestBit();
  2315. }
  2316. return *this;
  2317. }
  2318. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2319. {
  2320. // this operation doesn't take into account negative values..
  2321. jassert (isNegative() == other.isNegative());
  2322. int n = numValues;
  2323. while (n > other.numValues)
  2324. values[--n] = 0;
  2325. while (--n >= 0)
  2326. values[n] &= other.values[n];
  2327. if (other.highestBit < highestBit)
  2328. highestBit = other.highestBit;
  2329. highestBit = getHighestBit();
  2330. return *this;
  2331. }
  2332. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2333. {
  2334. // this operation will only work with the absolute values
  2335. jassert (isNegative() == other.isNegative());
  2336. if (other.highestBit >= 0)
  2337. {
  2338. ensureSize (other.highestBit >> 5);
  2339. int n = (other.highestBit >> 5) + 1;
  2340. while (--n >= 0)
  2341. values[n] ^= other.values[n];
  2342. if (other.highestBit > highestBit)
  2343. highestBit = other.highestBit;
  2344. highestBit = getHighestBit();
  2345. }
  2346. return *this;
  2347. }
  2348. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2349. {
  2350. BigInteger remainder;
  2351. divideBy (divisor, remainder);
  2352. swapWith (remainder);
  2353. return *this;
  2354. }
  2355. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2356. {
  2357. shiftBits (numBitsToShift, 0);
  2358. return *this;
  2359. }
  2360. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2361. {
  2362. return operator<<= (-numBitsToShift);
  2363. }
  2364. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2365. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2366. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2367. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2368. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2369. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2370. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2371. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2372. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2373. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2374. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2375. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2376. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2377. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2378. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2379. int BigInteger::compare (const BigInteger& other) const throw()
  2380. {
  2381. if (isNegative() == other.isNegative())
  2382. {
  2383. const int absComp = compareAbsolute (other);
  2384. return isNegative() ? -absComp : absComp;
  2385. }
  2386. else
  2387. {
  2388. return isNegative() ? -1 : 1;
  2389. }
  2390. }
  2391. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2392. {
  2393. const int h1 = getHighestBit();
  2394. const int h2 = other.getHighestBit();
  2395. if (h1 > h2)
  2396. return 1;
  2397. else if (h1 < h2)
  2398. return -1;
  2399. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2400. if (values[i] != other.values[i])
  2401. return (values[i] > other.values[i]) ? 1 : -1;
  2402. return 0;
  2403. }
  2404. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2405. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2406. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2407. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2408. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2409. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2410. void BigInteger::shiftBits (int bits, const int startBit)
  2411. {
  2412. if (highestBit < 0)
  2413. return;
  2414. if (startBit > 0)
  2415. {
  2416. if (bits < 0)
  2417. {
  2418. // right shift
  2419. for (int i = startBit; i <= highestBit; ++i)
  2420. setBit (i, operator[] (i - bits));
  2421. highestBit = getHighestBit();
  2422. }
  2423. else if (bits > 0)
  2424. {
  2425. // left shift
  2426. for (int i = highestBit + 1; --i >= startBit;)
  2427. setBit (i + bits, operator[] (i));
  2428. while (--bits >= 0)
  2429. clearBit (bits + startBit);
  2430. }
  2431. }
  2432. else
  2433. {
  2434. if (bits < 0)
  2435. {
  2436. // right shift
  2437. bits = -bits;
  2438. if (bits > highestBit)
  2439. {
  2440. clear();
  2441. }
  2442. else
  2443. {
  2444. const int wordsToMove = bits >> 5;
  2445. int top = 1 + (highestBit >> 5) - wordsToMove;
  2446. highestBit -= bits;
  2447. if (wordsToMove > 0)
  2448. {
  2449. int i;
  2450. for (i = 0; i < top; ++i)
  2451. values [i] = values [i + wordsToMove];
  2452. for (i = 0; i < wordsToMove; ++i)
  2453. values [top + i] = 0;
  2454. bits &= 31;
  2455. }
  2456. if (bits != 0)
  2457. {
  2458. const int invBits = 32 - bits;
  2459. --top;
  2460. for (int i = 0; i < top; ++i)
  2461. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2462. values[top] = (values[top] >> bits);
  2463. }
  2464. highestBit = getHighestBit();
  2465. }
  2466. }
  2467. else if (bits > 0)
  2468. {
  2469. // left shift
  2470. ensureSize (((highestBit + bits) >> 5) + 1);
  2471. const int wordsToMove = bits >> 5;
  2472. int top = 1 + (highestBit >> 5);
  2473. highestBit += bits;
  2474. if (wordsToMove > 0)
  2475. {
  2476. int i;
  2477. for (i = top; --i >= 0;)
  2478. values [i + wordsToMove] = values [i];
  2479. for (i = 0; i < wordsToMove; ++i)
  2480. values [i] = 0;
  2481. bits &= 31;
  2482. }
  2483. if (bits != 0)
  2484. {
  2485. const int invBits = 32 - bits;
  2486. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2487. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2488. values [wordsToMove] = values [wordsToMove] << bits;
  2489. }
  2490. highestBit = getHighestBit();
  2491. }
  2492. }
  2493. }
  2494. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2495. {
  2496. while (! m->isZero())
  2497. {
  2498. if (n->compareAbsolute (*m) > 0)
  2499. swapVariables (m, n);
  2500. *m -= *n;
  2501. }
  2502. return *n;
  2503. }
  2504. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2505. {
  2506. BigInteger m (*this);
  2507. while (! n.isZero())
  2508. {
  2509. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2510. return simpleGCD (&m, &n);
  2511. BigInteger temp1 (m), temp2;
  2512. temp1.divideBy (n, temp2);
  2513. m = n;
  2514. n = temp2;
  2515. }
  2516. return m;
  2517. }
  2518. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2519. {
  2520. BigInteger exp (exponent);
  2521. exp %= modulus;
  2522. BigInteger value (1);
  2523. swapWith (value);
  2524. value %= modulus;
  2525. while (! exp.isZero())
  2526. {
  2527. if (exp [0])
  2528. {
  2529. operator*= (value);
  2530. operator%= (modulus);
  2531. }
  2532. value *= value;
  2533. value %= modulus;
  2534. exp >>= 1;
  2535. }
  2536. }
  2537. void BigInteger::inverseModulo (const BigInteger& modulus)
  2538. {
  2539. if (modulus.isOne() || modulus.isNegative())
  2540. {
  2541. clear();
  2542. return;
  2543. }
  2544. if (isNegative() || compareAbsolute (modulus) >= 0)
  2545. operator%= (modulus);
  2546. if (isOne())
  2547. return;
  2548. if (! (*this)[0])
  2549. {
  2550. // not invertible
  2551. clear();
  2552. return;
  2553. }
  2554. BigInteger a1 (modulus);
  2555. BigInteger a2 (*this);
  2556. BigInteger b1 (modulus);
  2557. BigInteger b2 (1);
  2558. while (! a2.isOne())
  2559. {
  2560. BigInteger temp1, temp2, multiplier (a1);
  2561. multiplier.divideBy (a2, temp1);
  2562. temp1 = a2;
  2563. temp1 *= multiplier;
  2564. temp2 = a1;
  2565. temp2 -= temp1;
  2566. a1 = a2;
  2567. a2 = temp2;
  2568. temp1 = b2;
  2569. temp1 *= multiplier;
  2570. temp2 = b1;
  2571. temp2 -= temp1;
  2572. b1 = b2;
  2573. b2 = temp2;
  2574. }
  2575. while (b2.isNegative())
  2576. b2 += modulus;
  2577. b2 %= modulus;
  2578. swapWith (b2);
  2579. }
  2580. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2581. {
  2582. return stream << value.toString (10);
  2583. }
  2584. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2585. {
  2586. String s;
  2587. BigInteger v (*this);
  2588. if (base == 2 || base == 8 || base == 16)
  2589. {
  2590. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2591. static const char* const hexDigits = "0123456789abcdef";
  2592. for (;;)
  2593. {
  2594. const int remainder = v.getBitRangeAsInt (0, bits);
  2595. v >>= bits;
  2596. if (remainder == 0 && v.isZero())
  2597. break;
  2598. s = String::charToString (hexDigits [remainder]) + s;
  2599. }
  2600. }
  2601. else if (base == 10)
  2602. {
  2603. const BigInteger ten (10);
  2604. BigInteger remainder;
  2605. for (;;)
  2606. {
  2607. v.divideBy (ten, remainder);
  2608. if (remainder.isZero() && v.isZero())
  2609. break;
  2610. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2611. }
  2612. }
  2613. else
  2614. {
  2615. jassertfalse // can't do the specified base!
  2616. return String::empty;
  2617. }
  2618. s = s.paddedLeft ('0', minimumNumCharacters);
  2619. return isNegative() ? "-" + s : s;
  2620. }
  2621. void BigInteger::parseString (const String& text, const int base)
  2622. {
  2623. clear();
  2624. const juce_wchar* t = text;
  2625. if (base == 2 || base == 8 || base == 16)
  2626. {
  2627. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2628. for (;;)
  2629. {
  2630. const juce_wchar c = *t++;
  2631. const int digit = CharacterFunctions::getHexDigitValue (c);
  2632. if (((unsigned int) digit) < (unsigned int) base)
  2633. {
  2634. operator<<= (bits);
  2635. operator+= (digit);
  2636. }
  2637. else if (c == 0)
  2638. {
  2639. break;
  2640. }
  2641. }
  2642. }
  2643. else if (base == 10)
  2644. {
  2645. const BigInteger ten ((unsigned int) 10);
  2646. for (;;)
  2647. {
  2648. const juce_wchar c = *t++;
  2649. if (c >= '0' && c <= '9')
  2650. {
  2651. operator*= (ten);
  2652. operator+= ((int) (c - '0'));
  2653. }
  2654. else if (c == 0)
  2655. {
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. setNegative (text.trimStart().startsWithChar ('-'));
  2661. }
  2662. const MemoryBlock BigInteger::toMemoryBlock() const
  2663. {
  2664. const int numBytes = (getHighestBit() + 8) >> 3;
  2665. MemoryBlock mb ((size_t) numBytes);
  2666. for (int i = 0; i < numBytes; ++i)
  2667. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2668. return mb;
  2669. }
  2670. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2671. {
  2672. clear();
  2673. for (int i = (int) data.getSize(); --i >= 0;)
  2674. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2675. }
  2676. END_JUCE_NAMESPACE
  2677. /*** End of inlined file: juce_BitArray.cpp ***/
  2678. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2679. BEGIN_JUCE_NAMESPACE
  2680. MemoryBlock::MemoryBlock() throw()
  2681. : size (0)
  2682. {
  2683. }
  2684. MemoryBlock::MemoryBlock (const size_t initialSize,
  2685. const bool initialiseToZero) throw()
  2686. {
  2687. if (initialSize > 0)
  2688. {
  2689. size = initialSize;
  2690. data.allocate (initialSize, initialiseToZero);
  2691. }
  2692. else
  2693. {
  2694. size = 0;
  2695. }
  2696. }
  2697. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2698. : size (other.size)
  2699. {
  2700. if (size > 0)
  2701. {
  2702. jassert (other.data != 0);
  2703. data.malloc (size);
  2704. memcpy (data, other.data, size);
  2705. }
  2706. }
  2707. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2708. const size_t sizeInBytes) throw()
  2709. : size (jmax ((size_t) 0, sizeInBytes))
  2710. {
  2711. jassert (sizeInBytes >= 0);
  2712. if (size > 0)
  2713. {
  2714. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2715. data.malloc (size);
  2716. if (dataToInitialiseFrom != 0)
  2717. memcpy (data, dataToInitialiseFrom, size);
  2718. }
  2719. }
  2720. MemoryBlock::~MemoryBlock() throw()
  2721. {
  2722. jassert (size >= 0); // should never happen
  2723. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2724. }
  2725. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2726. {
  2727. if (this != &other)
  2728. {
  2729. setSize (other.size, false);
  2730. memcpy (data, other.data, size);
  2731. }
  2732. return *this;
  2733. }
  2734. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2735. {
  2736. return matches (other.data, other.size);
  2737. }
  2738. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2739. {
  2740. return ! operator== (other);
  2741. }
  2742. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2743. {
  2744. return size == dataSize
  2745. && memcmp (data, dataToCompare, size) == 0;
  2746. }
  2747. // this will resize the block to this size
  2748. void MemoryBlock::setSize (const size_t newSize,
  2749. const bool initialiseToZero) throw()
  2750. {
  2751. if (size != newSize)
  2752. {
  2753. if (newSize <= 0)
  2754. {
  2755. data.free();
  2756. size = 0;
  2757. }
  2758. else
  2759. {
  2760. if (data != 0)
  2761. {
  2762. data.realloc (newSize);
  2763. if (initialiseToZero && (newSize > size))
  2764. zeromem (data + size, newSize - size);
  2765. }
  2766. else
  2767. {
  2768. data.allocate (newSize, initialiseToZero);
  2769. }
  2770. size = newSize;
  2771. }
  2772. }
  2773. }
  2774. void MemoryBlock::ensureSize (const size_t minimumSize,
  2775. const bool initialiseToZero) throw()
  2776. {
  2777. if (size < minimumSize)
  2778. setSize (minimumSize, initialiseToZero);
  2779. }
  2780. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2781. {
  2782. swapVariables (size, other.size);
  2783. data.swapWith (other.data);
  2784. }
  2785. void MemoryBlock::fillWith (const uint8 value) throw()
  2786. {
  2787. memset (data, (int) value, size);
  2788. }
  2789. void MemoryBlock::append (const void* const srcData,
  2790. const size_t numBytes) throw()
  2791. {
  2792. if (numBytes > 0)
  2793. {
  2794. const size_t oldSize = size;
  2795. setSize (size + numBytes);
  2796. memcpy (data + oldSize, srcData, numBytes);
  2797. }
  2798. }
  2799. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2800. {
  2801. const char* d = static_cast<const char*> (src);
  2802. if (offset < 0)
  2803. {
  2804. d -= offset;
  2805. num -= offset;
  2806. offset = 0;
  2807. }
  2808. if (offset + num > size)
  2809. num = size - offset;
  2810. if (num > 0)
  2811. memcpy (data + offset, d, num);
  2812. }
  2813. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2814. {
  2815. char* d = static_cast<char*> (dst);
  2816. if (offset < 0)
  2817. {
  2818. zeromem (d, -offset);
  2819. d -= offset;
  2820. num += offset;
  2821. offset = 0;
  2822. }
  2823. if (offset + num > size)
  2824. {
  2825. const size_t newNum = size - offset;
  2826. zeromem (d + newNum, num - newNum);
  2827. num = newNum;
  2828. }
  2829. if (num > 0)
  2830. memcpy (d, data + offset, num);
  2831. }
  2832. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2833. {
  2834. if (startByte < 0)
  2835. {
  2836. numBytesToRemove += startByte;
  2837. startByte = 0;
  2838. }
  2839. if (startByte + numBytesToRemove >= size)
  2840. {
  2841. setSize (startByte);
  2842. }
  2843. else if (numBytesToRemove > 0)
  2844. {
  2845. memmove (data + startByte,
  2846. data + startByte + numBytesToRemove,
  2847. size - (startByte + numBytesToRemove));
  2848. setSize (size - numBytesToRemove);
  2849. }
  2850. }
  2851. const String MemoryBlock::toString() const throw()
  2852. {
  2853. return String (static_cast <const char*> (getData()), size);
  2854. }
  2855. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2856. {
  2857. int res = 0;
  2858. size_t byte = bitRangeStart >> 3;
  2859. int offsetInByte = (int) bitRangeStart & 7;
  2860. size_t bitsSoFar = 0;
  2861. while (numBits > 0 && (size_t) byte < size)
  2862. {
  2863. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2864. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2865. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2866. bitsSoFar += bitsThisTime;
  2867. numBits -= bitsThisTime;
  2868. ++byte;
  2869. offsetInByte = 0;
  2870. }
  2871. return res;
  2872. }
  2873. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2874. {
  2875. size_t byte = bitRangeStart >> 3;
  2876. int offsetInByte = (int) bitRangeStart & 7;
  2877. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2878. while (numBits > 0 && (size_t) byte < size)
  2879. {
  2880. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2881. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2882. const unsigned int tempBits = bitsToSet << offsetInByte;
  2883. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2884. ++byte;
  2885. numBits -= bitsThisTime;
  2886. bitsToSet >>= bitsThisTime;
  2887. mask >>= bitsThisTime;
  2888. offsetInByte = 0;
  2889. }
  2890. }
  2891. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2892. {
  2893. ensureSize (hex.length() >> 1);
  2894. char* dest = data;
  2895. int i = 0;
  2896. for (;;)
  2897. {
  2898. int byte = 0;
  2899. for (int loop = 2; --loop >= 0;)
  2900. {
  2901. byte <<= 4;
  2902. for (;;)
  2903. {
  2904. const juce_wchar c = hex [i++];
  2905. if (c >= '0' && c <= '9')
  2906. {
  2907. byte |= c - '0';
  2908. break;
  2909. }
  2910. else if (c >= 'a' && c <= 'z')
  2911. {
  2912. byte |= c - ('a' - 10);
  2913. break;
  2914. }
  2915. else if (c >= 'A' && c <= 'Z')
  2916. {
  2917. byte |= c - ('A' - 10);
  2918. break;
  2919. }
  2920. else if (c == 0)
  2921. {
  2922. setSize (static_cast <size_t> (dest - data));
  2923. return;
  2924. }
  2925. }
  2926. }
  2927. *dest++ = (char) byte;
  2928. }
  2929. }
  2930. static const char* const encodingTable
  2931. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2932. const String MemoryBlock::toBase64Encoding() const throw()
  2933. {
  2934. const size_t numChars = ((size << 3) + 5) / 6;
  2935. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2936. const int initialLen = destString.length();
  2937. destString.preallocateStorage (initialLen + 2 + numChars);
  2938. juce_wchar* d = destString;
  2939. d += initialLen;
  2940. *d++ = '.';
  2941. for (size_t i = 0; i < numChars; ++i)
  2942. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2943. *d++ = 0;
  2944. return destString;
  2945. }
  2946. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2947. {
  2948. const int startPos = s.indexOfChar ('.') + 1;
  2949. if (startPos <= 0)
  2950. return false;
  2951. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2952. setSize (numBytesNeeded, true);
  2953. const int numChars = s.length() - startPos;
  2954. const juce_wchar* srcChars = s;
  2955. srcChars += startPos;
  2956. int pos = 0;
  2957. for (int i = 0; i < numChars; ++i)
  2958. {
  2959. const char c = (char) srcChars[i];
  2960. for (int j = 0; j < 64; ++j)
  2961. {
  2962. if (encodingTable[j] == c)
  2963. {
  2964. setBitRange (pos, 6, j);
  2965. pos += 6;
  2966. break;
  2967. }
  2968. }
  2969. }
  2970. return true;
  2971. }
  2972. END_JUCE_NAMESPACE
  2973. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2974. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2975. BEGIN_JUCE_NAMESPACE
  2976. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2977. : properties (ignoreCaseOfKeyNames),
  2978. fallbackProperties (0),
  2979. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2980. {
  2981. }
  2982. PropertySet::PropertySet (const PropertySet& other) throw()
  2983. : properties (other.properties),
  2984. fallbackProperties (other.fallbackProperties),
  2985. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2986. {
  2987. }
  2988. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2989. {
  2990. properties = other.properties;
  2991. fallbackProperties = other.fallbackProperties;
  2992. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2993. propertyChanged();
  2994. return *this;
  2995. }
  2996. PropertySet::~PropertySet()
  2997. {
  2998. }
  2999. void PropertySet::clear()
  3000. {
  3001. const ScopedLock sl (lock);
  3002. if (properties.size() > 0)
  3003. {
  3004. properties.clear();
  3005. propertyChanged();
  3006. }
  3007. }
  3008. const String PropertySet::getValue (const String& keyName,
  3009. const String& defaultValue) const throw()
  3010. {
  3011. const ScopedLock sl (lock);
  3012. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3013. if (index >= 0)
  3014. return properties.getAllValues() [index];
  3015. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3016. : defaultValue;
  3017. }
  3018. int PropertySet::getIntValue (const String& keyName,
  3019. const int defaultValue) const throw()
  3020. {
  3021. const ScopedLock sl (lock);
  3022. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3023. if (index >= 0)
  3024. return properties.getAllValues() [index].getIntValue();
  3025. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3026. : defaultValue;
  3027. }
  3028. double PropertySet::getDoubleValue (const String& keyName,
  3029. const double defaultValue) const throw()
  3030. {
  3031. const ScopedLock sl (lock);
  3032. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3033. if (index >= 0)
  3034. return properties.getAllValues()[index].getDoubleValue();
  3035. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3036. : defaultValue;
  3037. }
  3038. bool PropertySet::getBoolValue (const String& keyName,
  3039. const bool defaultValue) const throw()
  3040. {
  3041. const ScopedLock sl (lock);
  3042. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3043. if (index >= 0)
  3044. return properties.getAllValues() [index].getIntValue() != 0;
  3045. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3046. : defaultValue;
  3047. }
  3048. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3049. {
  3050. XmlDocument doc (getValue (keyName));
  3051. return doc.getDocumentElement();
  3052. }
  3053. void PropertySet::setValue (const String& keyName,
  3054. const String& value) throw()
  3055. {
  3056. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3057. if (keyName.isNotEmpty())
  3058. {
  3059. const ScopedLock sl (lock);
  3060. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3061. if (index < 0 || properties.getAllValues() [index] != value)
  3062. {
  3063. properties.set (keyName, value);
  3064. propertyChanged();
  3065. }
  3066. }
  3067. }
  3068. void PropertySet::removeValue (const String& keyName) throw()
  3069. {
  3070. if (keyName.isNotEmpty())
  3071. {
  3072. const ScopedLock sl (lock);
  3073. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3074. if (index >= 0)
  3075. {
  3076. properties.remove (keyName);
  3077. propertyChanged();
  3078. }
  3079. }
  3080. }
  3081. void PropertySet::setValue (const String& keyName, const int value) throw()
  3082. {
  3083. setValue (keyName, String (value));
  3084. }
  3085. void PropertySet::setValue (const String& keyName, const double value) throw()
  3086. {
  3087. setValue (keyName, String (value));
  3088. }
  3089. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3090. {
  3091. setValue (keyName, String (value ? "1" : "0"));
  3092. }
  3093. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3094. {
  3095. setValue (keyName, (xml == 0) ? String::empty
  3096. : xml->createDocument (String::empty, true));
  3097. }
  3098. bool PropertySet::containsKey (const String& keyName) const throw()
  3099. {
  3100. const ScopedLock sl (lock);
  3101. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3102. }
  3103. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. fallbackProperties = fallbackProperties_;
  3107. }
  3108. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3109. {
  3110. const ScopedLock sl (lock);
  3111. XmlElement* const xml = new XmlElement (nodeName);
  3112. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3113. {
  3114. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3115. e->setAttribute ("name", properties.getAllKeys()[i]);
  3116. e->setAttribute ("val", properties.getAllValues()[i]);
  3117. }
  3118. return xml;
  3119. }
  3120. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3121. {
  3122. const ScopedLock sl (lock);
  3123. clear();
  3124. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3125. {
  3126. if (e->hasAttribute ("name")
  3127. && e->hasAttribute ("val"))
  3128. {
  3129. properties.set (e->getStringAttribute ("name"),
  3130. e->getStringAttribute ("val"));
  3131. }
  3132. }
  3133. if (properties.size() > 0)
  3134. propertyChanged();
  3135. }
  3136. void PropertySet::propertyChanged()
  3137. {
  3138. }
  3139. END_JUCE_NAMESPACE
  3140. /*** End of inlined file: juce_PropertySet.cpp ***/
  3141. /*** Start of inlined file: juce_Variant.cpp ***/
  3142. BEGIN_JUCE_NAMESPACE
  3143. var::var() throw()
  3144. : type (voidType)
  3145. {
  3146. value.doubleValue = 0;
  3147. }
  3148. var::~var() throw()
  3149. {
  3150. if (type == stringType)
  3151. delete value.stringValue;
  3152. else if (type == objectType && value.objectValue != 0)
  3153. value.objectValue->decReferenceCount();
  3154. }
  3155. const var var::null;
  3156. var::var (const var& valueToCopy)
  3157. : type (valueToCopy.type),
  3158. value (valueToCopy.value)
  3159. {
  3160. if (type == stringType)
  3161. value.stringValue = new String (*(value.stringValue));
  3162. else if (type == objectType && value.objectValue != 0)
  3163. value.objectValue->incReferenceCount();
  3164. }
  3165. var::var (const int value_) throw()
  3166. : type (intType)
  3167. {
  3168. value.intValue = value_;
  3169. }
  3170. var::var (const bool value_) throw()
  3171. : type (boolType)
  3172. {
  3173. value.boolValue = value_;
  3174. }
  3175. var::var (const double value_) throw()
  3176. : type (doubleType)
  3177. {
  3178. value.doubleValue = value_;
  3179. }
  3180. var::var (const String& value_)
  3181. : type (stringType)
  3182. {
  3183. value.stringValue = new String (value_);
  3184. }
  3185. var::var (const char* const value_)
  3186. : type (stringType)
  3187. {
  3188. value.stringValue = new String (value_);
  3189. }
  3190. var::var (const juce_wchar* const value_)
  3191. : type (stringType)
  3192. {
  3193. value.stringValue = new String (value_);
  3194. }
  3195. var::var (DynamicObject* const object)
  3196. : type (objectType)
  3197. {
  3198. value.objectValue = object;
  3199. if (object != 0)
  3200. object->incReferenceCount();
  3201. }
  3202. var::var (MethodFunction method_) throw()
  3203. : type (methodType)
  3204. {
  3205. value.methodValue = method_;
  3206. }
  3207. void var::swapWith (var& other) throw()
  3208. {
  3209. swapVariables (type, other.type);
  3210. swapVariables (value, other.value);
  3211. }
  3212. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3213. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3214. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3215. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3216. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3217. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3218. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3219. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3220. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3221. var::operator int() const
  3222. {
  3223. switch (type)
  3224. {
  3225. case voidType: break;
  3226. case intType: return value.intValue;
  3227. case boolType: return value.boolValue ? 1 : 0;
  3228. case doubleType: return static_cast <int> (value.doubleValue);
  3229. case stringType: return value.stringValue->getIntValue();
  3230. case objectType: break;
  3231. default: jassertfalse; break;
  3232. }
  3233. return 0;
  3234. }
  3235. var::operator bool() const
  3236. {
  3237. switch (type)
  3238. {
  3239. case voidType: break;
  3240. case intType: return value.intValue != 0;
  3241. case boolType: return value.boolValue;
  3242. case doubleType: return value.doubleValue != 0;
  3243. case stringType: return value.stringValue->getIntValue() != 0
  3244. || value.stringValue->trim().equalsIgnoreCase ("true")
  3245. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3246. case objectType: return value.objectValue != 0;
  3247. default: jassertfalse; break;
  3248. }
  3249. return false;
  3250. }
  3251. var::operator float() const
  3252. {
  3253. return (float) operator double();
  3254. }
  3255. var::operator double() const
  3256. {
  3257. switch (type)
  3258. {
  3259. case voidType: break;
  3260. case intType: return value.intValue;
  3261. case boolType: return value.boolValue ? 1.0 : 0.0;
  3262. case doubleType: return value.doubleValue;
  3263. case stringType: return value.stringValue->getDoubleValue();
  3264. case objectType: break;
  3265. default: jassertfalse; break;
  3266. }
  3267. return 0.0;
  3268. }
  3269. const String var::toString() const
  3270. {
  3271. switch (type)
  3272. {
  3273. case voidType: return String::empty;
  3274. case intType: return String (value.intValue);
  3275. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3276. case doubleType: return String (value.doubleValue);
  3277. case stringType: return *(value.stringValue);
  3278. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3279. case methodType: return "Method";
  3280. default: jassertfalse; break;
  3281. }
  3282. return String::empty;
  3283. }
  3284. var::operator const String() const
  3285. {
  3286. return toString();
  3287. }
  3288. DynamicObject* var::getObject() const
  3289. {
  3290. return type == objectType ? value.objectValue : 0;
  3291. }
  3292. bool var::equals (const var& other) const throw()
  3293. {
  3294. switch (type)
  3295. {
  3296. case voidType: return other.isVoid();
  3297. case intType: return value.intValue == static_cast <int> (other);
  3298. case boolType: return value.boolValue == static_cast <bool> (other);
  3299. case doubleType: return value.doubleValue == static_cast <double> (other);
  3300. case stringType: return (*(value.stringValue)) == other.toString();
  3301. case objectType: return value.objectValue == other.getObject();
  3302. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3303. default: jassertfalse; break;
  3304. }
  3305. return false;
  3306. }
  3307. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3308. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3309. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3310. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3311. void var::writeToStream (OutputStream& output) const
  3312. {
  3313. switch (type)
  3314. {
  3315. case voidType: output.writeCompressedInt (0); break;
  3316. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3317. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3318. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3319. case stringType:
  3320. {
  3321. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3322. output.writeCompressedInt (len + 1);
  3323. output.writeByte (5);
  3324. HeapBlock<char> temp (len);
  3325. value.stringValue->copyToUTF8 (temp, len);
  3326. output.write (temp, len);
  3327. break;
  3328. }
  3329. case objectType:
  3330. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3331. default: jassertfalse; break; // Is this a corrupted object?
  3332. }
  3333. }
  3334. const var var::readFromStream (InputStream& input)
  3335. {
  3336. const int numBytes = input.readCompressedInt();
  3337. if (numBytes > 0)
  3338. {
  3339. switch (input.readByte())
  3340. {
  3341. case 1: return var (input.readInt());
  3342. case 2: return var (true);
  3343. case 3: return var (false);
  3344. case 4: return var (input.readDouble());
  3345. case 5:
  3346. {
  3347. MemoryBlock mb;
  3348. input.readIntoMemoryBlock (mb, numBytes - 1);
  3349. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3350. }
  3351. default: input.skipNextBytes (numBytes - 1); break;
  3352. }
  3353. }
  3354. return var::null;
  3355. }
  3356. const var var::operator[] (const var::identifier& propertyName) const
  3357. {
  3358. if (type == objectType && value.objectValue != 0)
  3359. return value.objectValue->getProperty (propertyName);
  3360. return var::null;
  3361. }
  3362. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3363. {
  3364. if (type == objectType && value.objectValue != 0)
  3365. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3366. return var::null;
  3367. }
  3368. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3369. {
  3370. if (isMethod())
  3371. {
  3372. DynamicObject* const target = targetObject.getObject();
  3373. if (target != 0)
  3374. return (target->*(value.methodValue)) (arguments, numArguments);
  3375. }
  3376. return var::null;
  3377. }
  3378. const var var::call (const var::identifier& method) const
  3379. {
  3380. return invoke (method, 0, 0);
  3381. }
  3382. const var var::call (const var::identifier& method, const var& arg1) const
  3383. {
  3384. return invoke (method, &arg1, 1);
  3385. }
  3386. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3387. {
  3388. var args[] = { arg1, arg2 };
  3389. return invoke (method, args, 2);
  3390. }
  3391. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3392. {
  3393. var args[] = { arg1, arg2, arg3 };
  3394. return invoke (method, args, 3);
  3395. }
  3396. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3397. {
  3398. var args[] = { arg1, arg2, arg3, arg4 };
  3399. return invoke (method, args, 4);
  3400. }
  3401. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3402. {
  3403. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3404. return invoke (method, args, 5);
  3405. }
  3406. var::identifier::identifier() throw()
  3407. : hashCode (0)
  3408. {
  3409. }
  3410. var::identifier::identifier (const String& name_)
  3411. : name (name_),
  3412. hashCode (name_.hashCode())
  3413. {
  3414. /* An identifier string must be suitable for use as a script variable or XML
  3415. attribute, so it can only contain this limited set of characters.. */
  3416. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3417. }
  3418. var::identifier::identifier (const char* const name_)
  3419. : name (name_),
  3420. hashCode (name.hashCode())
  3421. {
  3422. /* An identifier string must be suitable for use as a script variable or XML
  3423. attribute, so it can only contain this limited set of characters.. */
  3424. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3425. }
  3426. var::identifier::~identifier()
  3427. {
  3428. }
  3429. END_JUCE_NAMESPACE
  3430. /*** End of inlined file: juce_Variant.cpp ***/
  3431. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3432. BEGIN_JUCE_NAMESPACE
  3433. NamedValueSet::NamedValue::NamedValue() throw()
  3434. {
  3435. }
  3436. inline NamedValueSet::NamedValue::NamedValue (const var::identifier& name_, const var& value_)
  3437. : name (name_), value (value_)
  3438. {
  3439. }
  3440. NamedValueSet::NamedValueSet() throw()
  3441. {
  3442. }
  3443. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3444. : values (other.values)
  3445. {
  3446. }
  3447. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3448. {
  3449. values = other.values;
  3450. return *this;
  3451. }
  3452. NamedValueSet::~NamedValueSet()
  3453. {
  3454. }
  3455. int NamedValueSet::size() const throw()
  3456. {
  3457. return values.size();
  3458. }
  3459. const var& NamedValueSet::operator[] (const var::identifier& name) const
  3460. {
  3461. for (int i = values.size(); --i >= 0;)
  3462. {
  3463. const NamedValue& v = values.getReference(i);
  3464. if (v.name == name)
  3465. return v.value;
  3466. }
  3467. return var::null;
  3468. }
  3469. const var NamedValueSet::getWithDefault (const var::identifier& name, const var& defaultReturnValue) const
  3470. {
  3471. const var* v = getItem (name);
  3472. return v != 0 ? *v : defaultReturnValue;
  3473. }
  3474. var* NamedValueSet::getItem (const var::identifier& name) const
  3475. {
  3476. for (int i = values.size(); --i >= 0;)
  3477. {
  3478. NamedValue& v = values.getReference(i);
  3479. if (v.name == name)
  3480. return &(v.value);
  3481. }
  3482. return 0;
  3483. }
  3484. bool NamedValueSet::set (const var::identifier& name, const var& newValue)
  3485. {
  3486. for (int i = values.size(); --i >= 0;)
  3487. {
  3488. NamedValue& v = values.getReference(i);
  3489. if (v.name == name)
  3490. {
  3491. if (v.value == newValue)
  3492. return false;
  3493. v.value = newValue;
  3494. return true;
  3495. }
  3496. }
  3497. values.add (NamedValue (name, newValue));
  3498. return true;
  3499. }
  3500. bool NamedValueSet::contains (const var::identifier& name) const
  3501. {
  3502. return getItem (name) != 0;
  3503. }
  3504. bool NamedValueSet::remove (const var::identifier& name)
  3505. {
  3506. for (int i = values.size(); --i >= 0;)
  3507. {
  3508. if (values.getReference(i).name == name)
  3509. {
  3510. values.remove (i);
  3511. return true;
  3512. }
  3513. }
  3514. return false;
  3515. }
  3516. const var::identifier NamedValueSet::getName (int index) const
  3517. {
  3518. jassert (((unsigned int) index) < (unsigned int) values.size());
  3519. return values [index].name;
  3520. }
  3521. void NamedValueSet::clear()
  3522. {
  3523. values.clear();
  3524. }
  3525. END_JUCE_NAMESPACE
  3526. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3527. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3528. BEGIN_JUCE_NAMESPACE
  3529. DynamicObject::DynamicObject()
  3530. {
  3531. }
  3532. DynamicObject::~DynamicObject()
  3533. {
  3534. }
  3535. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3536. {
  3537. var* const v = properties.getItem (propertyName);
  3538. return v != 0 && ! v->isMethod();
  3539. }
  3540. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3541. {
  3542. return properties [propertyName];
  3543. }
  3544. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3545. {
  3546. properties.set (propertyName, newValue);
  3547. }
  3548. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3549. {
  3550. properties.remove (propertyName);
  3551. }
  3552. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3553. {
  3554. return getProperty (methodName).isMethod();
  3555. }
  3556. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3557. const var* parameters,
  3558. int numParameters)
  3559. {
  3560. return properties [methodName].invoke (var (this), parameters, numParameters);
  3561. }
  3562. void DynamicObject::setMethod (const var::identifier& name,
  3563. var::MethodFunction methodFunction)
  3564. {
  3565. properties.set (name, var (methodFunction));
  3566. }
  3567. void DynamicObject::clear()
  3568. {
  3569. properties.clear();
  3570. }
  3571. END_JUCE_NAMESPACE
  3572. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3573. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3574. BEGIN_JUCE_NAMESPACE
  3575. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3576. {
  3577. jassert (keyData != 0);
  3578. jassert (keyBytes > 0);
  3579. static const uint32 initialPValues [18] =
  3580. {
  3581. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3582. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3583. 0x9216d5d9, 0x8979fb1b
  3584. };
  3585. static const uint32 initialSValues [4 * 256] =
  3586. {
  3587. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3588. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3589. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3590. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3591. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3592. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3593. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3594. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3595. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3596. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3597. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3598. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3599. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3600. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3601. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3602. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3603. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3604. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3605. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3606. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3607. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3608. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3609. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3610. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3611. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3612. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3613. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3614. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3615. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3616. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3617. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3618. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3619. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3620. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3621. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3622. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3623. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3624. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3625. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3626. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3627. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3628. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3629. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3630. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3631. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3632. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3633. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3634. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3635. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3636. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3637. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3638. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3639. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3640. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3641. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3642. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3643. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3644. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3645. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3646. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3647. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3648. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3649. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3650. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3651. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3652. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3653. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3654. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3655. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3656. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3657. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3658. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3659. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3660. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3661. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3662. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3663. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3664. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3665. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3666. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3667. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3668. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3669. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3670. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3671. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3672. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3673. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3674. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3675. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3676. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3677. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3678. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3679. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3680. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3681. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3682. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3683. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3684. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3685. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3686. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3687. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3688. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3689. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3690. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3691. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3692. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3693. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3694. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3695. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3696. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3697. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3698. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3699. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3700. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3701. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3702. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3703. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3704. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3705. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3706. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3707. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3708. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3709. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3710. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3711. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3712. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3713. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3714. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3715. };
  3716. memcpy (p, initialPValues, sizeof (p));
  3717. int i, j = 0;
  3718. for (i = 4; --i >= 0;)
  3719. {
  3720. s[i].malloc (256);
  3721. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3722. }
  3723. for (i = 0; i < 18; ++i)
  3724. {
  3725. uint32 d = 0;
  3726. for (int k = 0; k < 4; ++k)
  3727. {
  3728. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3729. if (++j >= keyBytes)
  3730. j = 0;
  3731. }
  3732. p[i] = initialPValues[i] ^ d;
  3733. }
  3734. uint32 l = 0, r = 0;
  3735. for (i = 0; i < 18; i += 2)
  3736. {
  3737. encrypt (l, r);
  3738. p[i] = l;
  3739. p[i + 1] = r;
  3740. }
  3741. for (i = 0; i < 4; ++i)
  3742. {
  3743. for (j = 0; j < 256; j += 2)
  3744. {
  3745. encrypt (l, r);
  3746. s[i][j] = l;
  3747. s[i][j + 1] = r;
  3748. }
  3749. }
  3750. }
  3751. BlowFish::BlowFish (const BlowFish& other)
  3752. {
  3753. for (int i = 4; --i >= 0;)
  3754. s[i].malloc (256);
  3755. operator= (other);
  3756. }
  3757. BlowFish& BlowFish::operator= (const BlowFish& other)
  3758. {
  3759. memcpy (p, other.p, sizeof (p));
  3760. for (int i = 4; --i >= 0;)
  3761. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3762. return *this;
  3763. }
  3764. BlowFish::~BlowFish()
  3765. {
  3766. }
  3767. uint32 BlowFish::F (const uint32 x) const throw()
  3768. {
  3769. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3770. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3771. }
  3772. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3773. {
  3774. uint32 l = data1;
  3775. uint32 r = data2;
  3776. for (int i = 0; i < 16; ++i)
  3777. {
  3778. l ^= p[i];
  3779. r ^= F(l);
  3780. swapVariables (l, r);
  3781. }
  3782. data1 = r ^ p[17];
  3783. data2 = l ^ p[16];
  3784. }
  3785. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3786. {
  3787. uint32 l = data1;
  3788. uint32 r = data2;
  3789. for (int i = 17; i > 1; --i)
  3790. {
  3791. l ^= p[i];
  3792. r ^= F(l);
  3793. swapVariables (l, r);
  3794. }
  3795. data1 = r ^ p[0];
  3796. data2 = l ^ p[1];
  3797. }
  3798. END_JUCE_NAMESPACE
  3799. /*** End of inlined file: juce_BlowFish.cpp ***/
  3800. /*** Start of inlined file: juce_MD5.cpp ***/
  3801. BEGIN_JUCE_NAMESPACE
  3802. MD5::MD5()
  3803. {
  3804. zerostruct (result);
  3805. }
  3806. MD5::MD5 (const MD5& other)
  3807. {
  3808. memcpy (result, other.result, sizeof (result));
  3809. }
  3810. MD5& MD5::operator= (const MD5& other)
  3811. {
  3812. memcpy (result, other.result, sizeof (result));
  3813. return *this;
  3814. }
  3815. MD5::MD5 (const MemoryBlock& data)
  3816. {
  3817. ProcessContext context;
  3818. context.processBlock (data.getData(), data.getSize());
  3819. context.finish (result);
  3820. }
  3821. MD5::MD5 (const void* data, const size_t numBytes)
  3822. {
  3823. ProcessContext context;
  3824. context.processBlock (data, numBytes);
  3825. context.finish (result);
  3826. }
  3827. MD5::MD5 (const String& text)
  3828. {
  3829. ProcessContext context;
  3830. const int len = text.length();
  3831. const juce_wchar* const t = text;
  3832. for (int i = 0; i < len; ++i)
  3833. {
  3834. // force the string into integer-sized unicode characters, to try to make it
  3835. // get the same results on all platforms + compilers.
  3836. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3837. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3838. }
  3839. context.finish (result);
  3840. }
  3841. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3842. {
  3843. ProcessContext context;
  3844. if (numBytesToRead < 0)
  3845. numBytesToRead = std::numeric_limits<int64>::max();
  3846. while (numBytesToRead > 0)
  3847. {
  3848. uint8 tempBuffer [512];
  3849. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3850. if (bytesRead <= 0)
  3851. break;
  3852. numBytesToRead -= bytesRead;
  3853. context.processBlock (tempBuffer, bytesRead);
  3854. }
  3855. context.finish (result);
  3856. }
  3857. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3858. {
  3859. processStream (input, numBytesToRead);
  3860. }
  3861. MD5::MD5 (const File& file)
  3862. {
  3863. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3864. if (fin != 0)
  3865. processStream (*fin, -1);
  3866. else
  3867. zerostruct (result);
  3868. }
  3869. MD5::~MD5()
  3870. {
  3871. }
  3872. namespace MD5Functions
  3873. {
  3874. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3875. {
  3876. for (int i = 0; i < (numBytes >> 2); ++i)
  3877. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3878. }
  3879. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3880. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3881. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3882. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3883. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3884. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3885. {
  3886. a += F (b, c, d) + x + ac;
  3887. a = rotateLeft (a, s) + b;
  3888. }
  3889. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3890. {
  3891. a += G (b, c, d) + x + ac;
  3892. a = rotateLeft (a, s) + b;
  3893. }
  3894. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3895. {
  3896. a += H (b, c, d) + x + ac;
  3897. a = rotateLeft (a, s) + b;
  3898. }
  3899. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3900. {
  3901. a += I (b, c, d) + x + ac;
  3902. a = rotateLeft (a, s) + b;
  3903. }
  3904. }
  3905. MD5::ProcessContext::ProcessContext()
  3906. {
  3907. state[0] = 0x67452301;
  3908. state[1] = 0xefcdab89;
  3909. state[2] = 0x98badcfe;
  3910. state[3] = 0x10325476;
  3911. count[0] = 0;
  3912. count[1] = 0;
  3913. }
  3914. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3915. {
  3916. int bufferPos = ((count[0] >> 3) & 0x3F);
  3917. count[0] += (uint32) (dataSize << 3);
  3918. if (count[0] < ((uint32) dataSize << 3))
  3919. count[1]++;
  3920. count[1] += (uint32) (dataSize >> 29);
  3921. const size_t spaceLeft = 64 - bufferPos;
  3922. size_t i = 0;
  3923. if (dataSize >= spaceLeft)
  3924. {
  3925. memcpy (buffer + bufferPos, data, spaceLeft);
  3926. transform (buffer);
  3927. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3928. transform (static_cast <const char*> (data) + i);
  3929. bufferPos = 0;
  3930. }
  3931. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3932. }
  3933. void MD5::ProcessContext::finish (void* const result)
  3934. {
  3935. unsigned char encodedLength[8];
  3936. MD5Functions::encode (encodedLength, count, 8);
  3937. // Pad out to 56 mod 64.
  3938. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3939. const int paddingLength = (index < 56) ? (56 - index)
  3940. : (120 - index);
  3941. uint8 paddingBuffer [64];
  3942. zeromem (paddingBuffer, paddingLength);
  3943. paddingBuffer [0] = 0x80;
  3944. processBlock (paddingBuffer, paddingLength);
  3945. processBlock (encodedLength, 8);
  3946. MD5Functions::encode (result, state, 16);
  3947. zerostruct (buffer);
  3948. }
  3949. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3950. {
  3951. using namespace MD5Functions;
  3952. uint32 a = state[0];
  3953. uint32 b = state[1];
  3954. uint32 c = state[2];
  3955. uint32 d = state[3];
  3956. uint32 x[16];
  3957. encode (x, bufferToTransform, 64);
  3958. enum Constants
  3959. {
  3960. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  3961. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  3962. };
  3963. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  3964. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  3965. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  3966. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  3967. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  3968. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  3969. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  3970. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  3971. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  3972. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  3973. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  3974. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  3975. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  3976. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  3977. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  3978. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  3979. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  3980. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  3981. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  3982. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  3983. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  3984. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  3985. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  3986. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  3987. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  3988. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  3989. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  3990. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  3991. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  3992. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  3993. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  3994. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  3995. state[0] += a;
  3996. state[1] += b;
  3997. state[2] += c;
  3998. state[3] += d;
  3999. zerostruct (x);
  4000. }
  4001. const MemoryBlock MD5::getRawChecksumData() const
  4002. {
  4003. return MemoryBlock (result, sizeof (result));
  4004. }
  4005. const String MD5::toHexString() const
  4006. {
  4007. return String::toHexString (result, sizeof (result), 0);
  4008. }
  4009. bool MD5::operator== (const MD5& other) const
  4010. {
  4011. return memcmp (result, other.result, sizeof (result)) == 0;
  4012. }
  4013. bool MD5::operator!= (const MD5& other) const
  4014. {
  4015. return ! operator== (other);
  4016. }
  4017. END_JUCE_NAMESPACE
  4018. /*** End of inlined file: juce_MD5.cpp ***/
  4019. /*** Start of inlined file: juce_Primes.cpp ***/
  4020. BEGIN_JUCE_NAMESPACE
  4021. namespace PrimesHelpers
  4022. {
  4023. static void createSmallSieve (const int numBits, BigInteger& result)
  4024. {
  4025. result.setBit (numBits);
  4026. result.clearBit (numBits); // to enlarge the array
  4027. result.setBit (0);
  4028. int n = 2;
  4029. do
  4030. {
  4031. for (int i = n + n; i < numBits; i += n)
  4032. result.setBit (i);
  4033. n = result.findNextClearBit (n + 1);
  4034. }
  4035. while (n <= (numBits >> 1));
  4036. }
  4037. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4038. const BigInteger& smallSieve, const int smallSieveSize)
  4039. {
  4040. jassert (! base[0]); // must be even!
  4041. result.setBit (numBits);
  4042. result.clearBit (numBits); // to enlarge the array
  4043. int index = smallSieve.findNextClearBit (0);
  4044. do
  4045. {
  4046. const int prime = (index << 1) + 1;
  4047. BigInteger r (base), remainder;
  4048. r.divideBy (prime, remainder);
  4049. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4050. if (r.isZero())
  4051. i += prime;
  4052. if ((i & 1) == 0)
  4053. i += prime;
  4054. i = (i - 1) >> 1;
  4055. while (i < numBits)
  4056. {
  4057. result.setBit (i);
  4058. i += prime;
  4059. }
  4060. index = smallSieve.findNextClearBit (index + 1);
  4061. }
  4062. while (index < smallSieveSize);
  4063. }
  4064. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4065. const int numBits, BigInteger& result, const int certainty)
  4066. {
  4067. for (int i = 0; i < numBits; ++i)
  4068. {
  4069. if (! sieve[i])
  4070. {
  4071. result = base + (unsigned int) ((i << 1) + 1);
  4072. if (Primes::isProbablyPrime (result, certainty))
  4073. return true;
  4074. }
  4075. }
  4076. return false;
  4077. }
  4078. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4079. {
  4080. const BigInteger one (1), two (2);
  4081. const BigInteger nMinusOne (n - one);
  4082. BigInteger d (nMinusOne);
  4083. const int s = d.findNextSetBit (0);
  4084. d >>= s;
  4085. BigInteger smallPrimes;
  4086. int numBitsInSmallPrimes = 0;
  4087. for (;;)
  4088. {
  4089. numBitsInSmallPrimes += 256;
  4090. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4091. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4092. if (numPrimesFound > iterations + 1)
  4093. break;
  4094. }
  4095. int smallPrime = 2;
  4096. while (--iterations >= 0)
  4097. {
  4098. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4099. BigInteger r (smallPrime);
  4100. r.exponentModulo (d, n);
  4101. if (r != one && r != nMinusOne)
  4102. {
  4103. for (int j = 0; j < s; ++j)
  4104. {
  4105. r.exponentModulo (two, n);
  4106. if (r == nMinusOne)
  4107. break;
  4108. }
  4109. if (r != nMinusOne)
  4110. return false;
  4111. }
  4112. }
  4113. return true;
  4114. }
  4115. }
  4116. const BigInteger Primes::createProbablePrime (const int bitLength,
  4117. const int certainty,
  4118. const int* randomSeeds,
  4119. int numRandomSeeds)
  4120. {
  4121. using namespace PrimesHelpers;
  4122. int defaultSeeds [16];
  4123. if (numRandomSeeds <= 0)
  4124. {
  4125. randomSeeds = defaultSeeds;
  4126. numRandomSeeds = numElementsInArray (defaultSeeds);
  4127. Random r (0);
  4128. for (int j = 10; --j >= 0;)
  4129. {
  4130. r.setSeedRandomly();
  4131. for (int i = numRandomSeeds; --i >= 0;)
  4132. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4133. }
  4134. }
  4135. BigInteger smallSieve;
  4136. const int smallSieveSize = 15000;
  4137. createSmallSieve (smallSieveSize, smallSieve);
  4138. BigInteger p;
  4139. for (int i = numRandomSeeds; --i >= 0;)
  4140. {
  4141. BigInteger p2;
  4142. Random r (randomSeeds[i]);
  4143. r.fillBitsRandomly (p2, 0, bitLength);
  4144. p ^= p2;
  4145. }
  4146. p.setBit (bitLength - 1);
  4147. p.clearBit (0);
  4148. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4149. while (p.getHighestBit() < bitLength)
  4150. {
  4151. p += 2 * searchLen;
  4152. BigInteger sieve;
  4153. bigSieve (p, searchLen, sieve,
  4154. smallSieve, smallSieveSize);
  4155. BigInteger candidate;
  4156. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4157. return candidate;
  4158. }
  4159. jassertfalse
  4160. return BigInteger();
  4161. }
  4162. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4163. {
  4164. using namespace PrimesHelpers;
  4165. if (! number[0])
  4166. return false;
  4167. if (number.getHighestBit() <= 10)
  4168. {
  4169. const int num = number.getBitRangeAsInt (0, 10);
  4170. for (int i = num / 2; --i > 1;)
  4171. if (num % i == 0)
  4172. return false;
  4173. return true;
  4174. }
  4175. else
  4176. {
  4177. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4178. return false;
  4179. return passesMillerRabin (number, certainty);
  4180. }
  4181. }
  4182. END_JUCE_NAMESPACE
  4183. /*** End of inlined file: juce_Primes.cpp ***/
  4184. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4185. BEGIN_JUCE_NAMESPACE
  4186. RSAKey::RSAKey()
  4187. {
  4188. }
  4189. RSAKey::RSAKey (const String& s)
  4190. {
  4191. if (s.containsChar (','))
  4192. {
  4193. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4194. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4195. }
  4196. else
  4197. {
  4198. // the string needs to be two hex numbers, comma-separated..
  4199. jassertfalse;
  4200. }
  4201. }
  4202. RSAKey::~RSAKey()
  4203. {
  4204. }
  4205. const String RSAKey::toString() const
  4206. {
  4207. return part1.toString (16) + "," + part2.toString (16);
  4208. }
  4209. bool RSAKey::applyToValue (BigInteger& value) const
  4210. {
  4211. if (part1.isZero() || part2.isZero() || value <= 0)
  4212. {
  4213. jassertfalse // using an uninitialised key
  4214. value.clear();
  4215. return false;
  4216. }
  4217. BigInteger result;
  4218. while (! value.isZero())
  4219. {
  4220. result *= part2;
  4221. BigInteger remainder;
  4222. value.divideBy (part2, remainder);
  4223. remainder.exponentModulo (part1, part2);
  4224. result += remainder;
  4225. }
  4226. value.swapWith (result);
  4227. return true;
  4228. }
  4229. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4230. {
  4231. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4232. // are fast to divide + multiply
  4233. for (int i = 2; i <= 65536; i *= 2)
  4234. {
  4235. const BigInteger e (1 + i);
  4236. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4237. return e;
  4238. }
  4239. BigInteger e (4);
  4240. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4241. ++e;
  4242. return e;
  4243. }
  4244. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4245. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4246. {
  4247. jassert (numBits > 16); // not much point using less than this..
  4248. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4249. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4250. const BigInteger n (p * q);
  4251. const BigInteger m (--p * --q);
  4252. const BigInteger e (findBestCommonDivisor (p, q));
  4253. BigInteger d (e);
  4254. d.inverseModulo (m);
  4255. publicKey.part1 = e;
  4256. publicKey.part2 = n;
  4257. privateKey.part1 = d;
  4258. privateKey.part2 = n;
  4259. }
  4260. END_JUCE_NAMESPACE
  4261. /*** End of inlined file: juce_RSAKey.cpp ***/
  4262. /*** Start of inlined file: juce_InputStream.cpp ***/
  4263. BEGIN_JUCE_NAMESPACE
  4264. char InputStream::readByte()
  4265. {
  4266. char temp = 0;
  4267. read (&temp, 1);
  4268. return temp;
  4269. }
  4270. bool InputStream::readBool()
  4271. {
  4272. return readByte() != 0;
  4273. }
  4274. short InputStream::readShort()
  4275. {
  4276. char temp[2];
  4277. if (read (temp, 2) == 2)
  4278. return (short) ByteOrder::littleEndianShort (temp);
  4279. return 0;
  4280. }
  4281. short InputStream::readShortBigEndian()
  4282. {
  4283. char temp[2];
  4284. if (read (temp, 2) == 2)
  4285. return (short) ByteOrder::bigEndianShort (temp);
  4286. return 0;
  4287. }
  4288. int InputStream::readInt()
  4289. {
  4290. char temp[4];
  4291. if (read (temp, 4) == 4)
  4292. return (int) ByteOrder::littleEndianInt (temp);
  4293. return 0;
  4294. }
  4295. int InputStream::readIntBigEndian()
  4296. {
  4297. char temp[4];
  4298. if (read (temp, 4) == 4)
  4299. return (int) ByteOrder::bigEndianInt (temp);
  4300. return 0;
  4301. }
  4302. int InputStream::readCompressedInt()
  4303. {
  4304. const unsigned char sizeByte = readByte();
  4305. if (sizeByte == 0)
  4306. return 0;
  4307. const int numBytes = (sizeByte & 0x7f);
  4308. if (numBytes > 4)
  4309. {
  4310. jassertfalse // trying to read corrupt data - this method must only be used
  4311. // to read data that was written by OutputStream::writeCompressedInt()
  4312. return 0;
  4313. }
  4314. char bytes[4] = { 0, 0, 0, 0 };
  4315. if (read (bytes, numBytes) != numBytes)
  4316. return 0;
  4317. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4318. return (sizeByte >> 7) ? -num : num;
  4319. }
  4320. int64 InputStream::readInt64()
  4321. {
  4322. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4323. if (read (n.asBytes, 8) == 8)
  4324. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4325. return 0;
  4326. }
  4327. int64 InputStream::readInt64BigEndian()
  4328. {
  4329. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4330. if (read (n.asBytes, 8) == 8)
  4331. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4332. return 0;
  4333. }
  4334. float InputStream::readFloat()
  4335. {
  4336. // the union below relies on these types being the same size...
  4337. static_jassert (sizeof (int32) == sizeof (float));
  4338. union { int32 asInt; float asFloat; } n;
  4339. n.asInt = (int32) readInt();
  4340. return n.asFloat;
  4341. }
  4342. float InputStream::readFloatBigEndian()
  4343. {
  4344. union { int32 asInt; float asFloat; } n;
  4345. n.asInt = (int32) readIntBigEndian();
  4346. return n.asFloat;
  4347. }
  4348. double InputStream::readDouble()
  4349. {
  4350. union { int64 asInt; double asDouble; } n;
  4351. n.asInt = readInt64();
  4352. return n.asDouble;
  4353. }
  4354. double InputStream::readDoubleBigEndian()
  4355. {
  4356. union { int64 asInt; double asDouble; } n;
  4357. n.asInt = readInt64BigEndian();
  4358. return n.asDouble;
  4359. }
  4360. const String InputStream::readString()
  4361. {
  4362. MemoryBlock buffer (256);
  4363. char* data = static_cast<char*> (buffer.getData());
  4364. size_t i = 0;
  4365. while ((data[i] = readByte()) != 0)
  4366. {
  4367. if (++i >= buffer.getSize())
  4368. {
  4369. buffer.setSize (buffer.getSize() + 512);
  4370. data = static_cast<char*> (buffer.getData());
  4371. }
  4372. }
  4373. return String::fromUTF8 (data, (int) i);
  4374. }
  4375. const String InputStream::readNextLine()
  4376. {
  4377. MemoryBlock buffer (256);
  4378. char* data = static_cast<char*> (buffer.getData());
  4379. size_t i = 0;
  4380. while ((data[i] = readByte()) != 0)
  4381. {
  4382. if (data[i] == '\n')
  4383. break;
  4384. if (data[i] == '\r')
  4385. {
  4386. const int64 lastPos = getPosition();
  4387. if (readByte() != '\n')
  4388. setPosition (lastPos);
  4389. break;
  4390. }
  4391. if (++i >= buffer.getSize())
  4392. {
  4393. buffer.setSize (buffer.getSize() + 512);
  4394. data = static_cast<char*> (buffer.getData());
  4395. }
  4396. }
  4397. return String::fromUTF8 (data, (int) i);
  4398. }
  4399. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4400. {
  4401. const int64 totalLength = getTotalLength();
  4402. if (totalLength >= 0)
  4403. {
  4404. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4405. totalLength - getPosition());
  4406. if (numBytes < 0)
  4407. numBytes = totalBytesRemaining;
  4408. else if (numBytes > 0)
  4409. numBytes = jmin (numBytes, totalBytesRemaining);
  4410. else
  4411. return 0;
  4412. }
  4413. const size_t originalBlockSize = block.getSize();
  4414. int totalBytesRead = 0;
  4415. if (numBytes > 0)
  4416. {
  4417. // know how many bytes we want, so we can resize the block first..
  4418. block.setSize (originalBlockSize + numBytes, false);
  4419. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4420. }
  4421. else
  4422. {
  4423. // read until end of stram..
  4424. const int chunkSize = 32768;
  4425. for (;;)
  4426. {
  4427. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4428. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4429. + originalBlockSize
  4430. + totalBytesRead,
  4431. chunkSize);
  4432. if (bytesJustIn == 0)
  4433. break;
  4434. totalBytesRead += bytesJustIn;
  4435. }
  4436. }
  4437. // trim off any excess left at the end
  4438. block.setSize (originalBlockSize + totalBytesRead, false);
  4439. return totalBytesRead;
  4440. }
  4441. const String InputStream::readEntireStreamAsString()
  4442. {
  4443. MemoryBlock mb;
  4444. const int size = readIntoMemoryBlock (mb);
  4445. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4446. }
  4447. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4448. {
  4449. if (numBytesToSkip > 0)
  4450. {
  4451. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4452. HeapBlock<char> temp (skipBufferSize);
  4453. while (numBytesToSkip > 0 && ! isExhausted())
  4454. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4455. }
  4456. }
  4457. END_JUCE_NAMESPACE
  4458. /*** End of inlined file: juce_InputStream.cpp ***/
  4459. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4460. BEGIN_JUCE_NAMESPACE
  4461. #if JUCE_DEBUG
  4462. static CriticalSection activeStreamLock;
  4463. static VoidArray activeStreams;
  4464. void juce_CheckForDanglingStreams()
  4465. {
  4466. /*
  4467. It's always a bad idea to leak any object, but if you're leaking output
  4468. streams, then there's a good chance that you're failing to flush a file
  4469. to disk properly, which could result in corrupted data and other similar
  4470. nastiness..
  4471. */
  4472. jassert (activeStreams.size() == 0);
  4473. };
  4474. #endif
  4475. OutputStream::OutputStream()
  4476. {
  4477. #if JUCE_DEBUG
  4478. const ScopedLock sl (activeStreamLock);
  4479. activeStreams.add (this);
  4480. #endif
  4481. }
  4482. OutputStream::~OutputStream()
  4483. {
  4484. #if JUCE_DEBUG
  4485. const ScopedLock sl (activeStreamLock);
  4486. activeStreams.removeValue (this);
  4487. #endif
  4488. }
  4489. void OutputStream::writeBool (const bool b)
  4490. {
  4491. writeByte (b ? (char) 1
  4492. : (char) 0);
  4493. }
  4494. void OutputStream::writeByte (char byte)
  4495. {
  4496. write (&byte, 1);
  4497. }
  4498. void OutputStream::writeShort (short value)
  4499. {
  4500. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4501. write (&v, 2);
  4502. }
  4503. void OutputStream::writeShortBigEndian (short value)
  4504. {
  4505. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4506. write (&v, 2);
  4507. }
  4508. void OutputStream::writeInt (int value)
  4509. {
  4510. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4511. write (&v, 4);
  4512. }
  4513. void OutputStream::writeIntBigEndian (int value)
  4514. {
  4515. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4516. write (&v, 4);
  4517. }
  4518. void OutputStream::writeCompressedInt (int value)
  4519. {
  4520. unsigned int un = (value < 0) ? (unsigned int) -value
  4521. : (unsigned int) value;
  4522. uint8 data[5];
  4523. int num = 0;
  4524. while (un > 0)
  4525. {
  4526. data[++num] = (uint8) un;
  4527. un >>= 8;
  4528. }
  4529. data[0] = (uint8) num;
  4530. if (value < 0)
  4531. data[0] |= 0x80;
  4532. write (data, num + 1);
  4533. }
  4534. void OutputStream::writeInt64 (int64 value)
  4535. {
  4536. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4537. write (&v, 8);
  4538. }
  4539. void OutputStream::writeInt64BigEndian (int64 value)
  4540. {
  4541. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4542. write (&v, 8);
  4543. }
  4544. void OutputStream::writeFloat (float value)
  4545. {
  4546. union { int asInt; float asFloat; } n;
  4547. n.asFloat = value;
  4548. writeInt (n.asInt);
  4549. }
  4550. void OutputStream::writeFloatBigEndian (float value)
  4551. {
  4552. union { int asInt; float asFloat; } n;
  4553. n.asFloat = value;
  4554. writeIntBigEndian (n.asInt);
  4555. }
  4556. void OutputStream::writeDouble (double value)
  4557. {
  4558. union { int64 asInt; double asDouble; } n;
  4559. n.asDouble = value;
  4560. writeInt64 (n.asInt);
  4561. }
  4562. void OutputStream::writeDoubleBigEndian (double value)
  4563. {
  4564. union { int64 asInt; double asDouble; } n;
  4565. n.asDouble = value;
  4566. writeInt64BigEndian (n.asInt);
  4567. }
  4568. void OutputStream::writeString (const String& text)
  4569. {
  4570. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4571. // if lots of large, persistent strings were to be written to streams).
  4572. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4573. HeapBlock<char> temp (numBytes);
  4574. text.copyToUTF8 (temp, numBytes);
  4575. write (temp, numBytes);
  4576. }
  4577. void OutputStream::writeText (const String& text, const bool asUnicode,
  4578. const bool writeUnicodeHeaderBytes)
  4579. {
  4580. if (asUnicode)
  4581. {
  4582. if (writeUnicodeHeaderBytes)
  4583. write ("\x0ff\x0fe", 2);
  4584. const juce_wchar* src = text;
  4585. bool lastCharWasReturn = false;
  4586. while (*src != 0)
  4587. {
  4588. if (*src == L'\n' && ! lastCharWasReturn)
  4589. writeShort ((short) L'\r');
  4590. lastCharWasReturn = (*src == L'\r');
  4591. writeShort ((short) *src++);
  4592. }
  4593. }
  4594. else
  4595. {
  4596. const char* src = text.toUTF8();
  4597. const char* t = src;
  4598. for (;;)
  4599. {
  4600. if (*t == '\n')
  4601. {
  4602. if (t > src)
  4603. write (src, (int) (t - src));
  4604. write ("\r\n", 2);
  4605. src = t + 1;
  4606. }
  4607. else if (*t == '\r')
  4608. {
  4609. if (t[1] == '\n')
  4610. ++t;
  4611. }
  4612. else if (*t == 0)
  4613. {
  4614. if (t > src)
  4615. write (src, (int) (t - src));
  4616. break;
  4617. }
  4618. ++t;
  4619. }
  4620. }
  4621. }
  4622. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4623. {
  4624. if (numBytesToWrite < 0)
  4625. numBytesToWrite = std::numeric_limits<int64>::max();
  4626. int numWritten = 0;
  4627. while (numBytesToWrite > 0 && ! source.isExhausted())
  4628. {
  4629. char buffer [8192];
  4630. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4631. if (num <= 0)
  4632. break;
  4633. write (buffer, num);
  4634. numBytesToWrite -= num;
  4635. numWritten += num;
  4636. }
  4637. return numWritten;
  4638. }
  4639. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4640. {
  4641. return stream << String (number);
  4642. }
  4643. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4644. {
  4645. return stream << String (number);
  4646. }
  4647. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4648. {
  4649. stream.writeByte (character);
  4650. return stream;
  4651. }
  4652. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4653. {
  4654. stream.write (text, (int) strlen (text));
  4655. return stream;
  4656. }
  4657. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4658. {
  4659. stream.write (data.getData(), (int) data.getSize());
  4660. return stream;
  4661. }
  4662. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4663. {
  4664. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4665. if (in != 0)
  4666. stream.writeFromInputStream (*in, -1);
  4667. return stream;
  4668. }
  4669. END_JUCE_NAMESPACE
  4670. /*** End of inlined file: juce_OutputStream.cpp ***/
  4671. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4672. BEGIN_JUCE_NAMESPACE
  4673. DirectoryIterator::DirectoryIterator (const File& directory,
  4674. bool isRecursive_,
  4675. const String& wildCard_,
  4676. const int whatToLookFor_)
  4677. : fileFinder (directory, isRecursive ? "*" : wildCard_),
  4678. wildCard (wildCard_),
  4679. path (File::addTrailingSeparator (directory.getFullPathName())),
  4680. index (-1),
  4681. totalNumFiles (-1),
  4682. whatToLookFor (whatToLookFor_),
  4683. isRecursive (isRecursive_)
  4684. {
  4685. // you have to specify the type of files you're looking for!
  4686. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4687. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4688. }
  4689. DirectoryIterator::~DirectoryIterator()
  4690. {
  4691. }
  4692. bool DirectoryIterator::next()
  4693. {
  4694. return next (0, 0, 0, 0, 0, 0);
  4695. }
  4696. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4697. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4698. {
  4699. if (subIterator != 0)
  4700. {
  4701. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4702. return true;
  4703. subIterator = 0;
  4704. }
  4705. String filename;
  4706. bool isDirectory, isHidden;
  4707. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4708. {
  4709. ++index;
  4710. if (! filename.containsOnly ("."))
  4711. {
  4712. const File fileFound (path + filename, 0);
  4713. bool matches = false;
  4714. if (isDirectory)
  4715. {
  4716. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4717. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4718. matches = (whatToLookFor & File::findDirectories) != 0;
  4719. }
  4720. else
  4721. {
  4722. matches = (whatToLookFor & File::findFiles) != 0;
  4723. }
  4724. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4725. if (matches && isRecursive)
  4726. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4727. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4728. matches = ! isHidden;
  4729. if (matches)
  4730. {
  4731. currentFile = fileFound;
  4732. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4733. if (isDirResult != 0) *isDirResult = isDirectory;
  4734. return true;
  4735. }
  4736. else if (subIterator != 0)
  4737. {
  4738. return next();
  4739. }
  4740. }
  4741. }
  4742. return false;
  4743. }
  4744. const File DirectoryIterator::getFile() const
  4745. {
  4746. if (subIterator != 0)
  4747. return subIterator->getFile();
  4748. return currentFile;
  4749. }
  4750. float DirectoryIterator::getEstimatedProgress() const
  4751. {
  4752. if (totalNumFiles < 0)
  4753. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4754. if (totalNumFiles <= 0)
  4755. return 0.0f;
  4756. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4757. : (float) index;
  4758. return detailedIndex / totalNumFiles;
  4759. }
  4760. END_JUCE_NAMESPACE
  4761. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4762. /*** Start of inlined file: juce_File.cpp ***/
  4763. #if ! JUCE_WINDOWS
  4764. #include <pwd.h>
  4765. #endif
  4766. BEGIN_JUCE_NAMESPACE
  4767. File::File (const String& fullPathName)
  4768. : fullPath (parseAbsolutePath (fullPathName))
  4769. {
  4770. }
  4771. File::File (const String& path, int)
  4772. : fullPath (path)
  4773. {
  4774. }
  4775. const File File::createFileWithoutCheckingPath (const String& path)
  4776. {
  4777. return File (path, 0);
  4778. }
  4779. File::File (const File& other)
  4780. : fullPath (other.fullPath)
  4781. {
  4782. }
  4783. File& File::operator= (const String& newPath)
  4784. {
  4785. fullPath = parseAbsolutePath (newPath);
  4786. return *this;
  4787. }
  4788. File& File::operator= (const File& other)
  4789. {
  4790. fullPath = other.fullPath;
  4791. return *this;
  4792. }
  4793. const File File::nonexistent;
  4794. const String File::parseAbsolutePath (const String& p)
  4795. {
  4796. if (p.isEmpty())
  4797. return String::empty;
  4798. #if JUCE_WINDOWS
  4799. // Windows..
  4800. String path (p.replaceCharacter ('/', '\\'));
  4801. if (path.startsWithChar (File::separator))
  4802. {
  4803. if (path[1] != File::separator)
  4804. {
  4805. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4806. If you're trying to parse a string that may be either a relative path or an absolute path,
  4807. you MUST provide a context against which the partial path can be evaluated - you can do
  4808. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4809. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4810. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4811. */
  4812. jassertfalse
  4813. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4814. }
  4815. }
  4816. else if (! path.containsChar (':'))
  4817. {
  4818. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4819. If you're trying to parse a string that may be either a relative path or an absolute path,
  4820. you MUST provide a context against which the partial path can be evaluated - you can do
  4821. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4822. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4823. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4824. */
  4825. jassertfalse
  4826. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4827. }
  4828. #else
  4829. // Mac or Linux..
  4830. String path (p.replaceCharacter ('\\', '/'));
  4831. if (path.startsWithChar ('~'))
  4832. {
  4833. if (path[1] == File::separator || path[1] == 0)
  4834. {
  4835. // expand a name of the form "~/abc"
  4836. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4837. + path.substring (1);
  4838. }
  4839. else
  4840. {
  4841. // expand a name of type "~dave/abc"
  4842. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4843. struct passwd* const pw = getpwnam (userName.toUTF8());
  4844. if (pw != 0)
  4845. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4846. }
  4847. }
  4848. else if (! path.startsWithChar (File::separator))
  4849. {
  4850. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4851. If you're trying to parse a string that may be either a relative path or an absolute path,
  4852. you MUST provide a context against which the partial path can be evaluated - you can do
  4853. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4854. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4855. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4856. */
  4857. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4858. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4859. }
  4860. #endif
  4861. return path.trimCharactersAtEnd (separatorString);
  4862. }
  4863. const String File::addTrailingSeparator (const String& path)
  4864. {
  4865. return path.endsWithChar (File::separator) ? path
  4866. : path + File::separator;
  4867. }
  4868. #if JUCE_LINUX
  4869. #define NAMES_ARE_CASE_SENSITIVE 1
  4870. #endif
  4871. bool File::areFileNamesCaseSensitive()
  4872. {
  4873. #if NAMES_ARE_CASE_SENSITIVE
  4874. return true;
  4875. #else
  4876. return false;
  4877. #endif
  4878. }
  4879. bool File::operator== (const File& other) const
  4880. {
  4881. #if NAMES_ARE_CASE_SENSITIVE
  4882. return fullPath == other.fullPath;
  4883. #else
  4884. return fullPath.equalsIgnoreCase (other.fullPath);
  4885. #endif
  4886. }
  4887. bool File::operator!= (const File& other) const
  4888. {
  4889. return ! operator== (other);
  4890. }
  4891. bool File::operator< (const File& other) const
  4892. {
  4893. #if NAMES_ARE_CASE_SENSITIVE
  4894. return fullPath < other.fullPath;
  4895. #else
  4896. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4897. #endif
  4898. }
  4899. bool File::operator> (const File& other) const
  4900. {
  4901. #if NAMES_ARE_CASE_SENSITIVE
  4902. return fullPath > other.fullPath;
  4903. #else
  4904. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4905. #endif
  4906. }
  4907. bool File::setReadOnly (const bool shouldBeReadOnly,
  4908. const bool applyRecursively) const
  4909. {
  4910. bool worked = true;
  4911. if (applyRecursively && isDirectory())
  4912. {
  4913. Array <File> subFiles;
  4914. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4915. for (int i = subFiles.size(); --i >= 0;)
  4916. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4917. }
  4918. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4919. }
  4920. bool File::deleteRecursively() const
  4921. {
  4922. bool worked = true;
  4923. if (isDirectory())
  4924. {
  4925. Array<File> subFiles;
  4926. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4927. for (int i = subFiles.size(); --i >= 0;)
  4928. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4929. }
  4930. return deleteFile() && worked;
  4931. }
  4932. bool File::moveFileTo (const File& newFile) const
  4933. {
  4934. if (newFile.fullPath == fullPath)
  4935. return true;
  4936. #if ! NAMES_ARE_CASE_SENSITIVE
  4937. if (*this != newFile)
  4938. #endif
  4939. if (! newFile.deleteFile())
  4940. return false;
  4941. return moveInternal (newFile);
  4942. }
  4943. bool File::copyFileTo (const File& newFile) const
  4944. {
  4945. return (*this == newFile)
  4946. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4947. }
  4948. bool File::copyDirectoryTo (const File& newDirectory) const
  4949. {
  4950. if (isDirectory() && newDirectory.createDirectory())
  4951. {
  4952. Array<File> subFiles;
  4953. findChildFiles (subFiles, File::findFiles, false);
  4954. int i;
  4955. for (i = 0; i < subFiles.size(); ++i)
  4956. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4957. return false;
  4958. subFiles.clear();
  4959. findChildFiles (subFiles, File::findDirectories, false);
  4960. for (i = 0; i < subFiles.size(); ++i)
  4961. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4962. return false;
  4963. return true;
  4964. }
  4965. return false;
  4966. }
  4967. const String File::getPathUpToLastSlash() const
  4968. {
  4969. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4970. if (lastSlash > 0)
  4971. return fullPath.substring (0, lastSlash);
  4972. else if (lastSlash == 0)
  4973. return separatorString;
  4974. else
  4975. return fullPath;
  4976. }
  4977. const File File::getParentDirectory() const
  4978. {
  4979. return File (getPathUpToLastSlash());
  4980. }
  4981. const String File::getFileName() const
  4982. {
  4983. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4984. }
  4985. int File::hashCode() const
  4986. {
  4987. return fullPath.hashCode();
  4988. }
  4989. int64 File::hashCode64() const
  4990. {
  4991. return fullPath.hashCode64();
  4992. }
  4993. const String File::getFileNameWithoutExtension() const
  4994. {
  4995. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4996. const int lastDot = fullPath.lastIndexOfChar ('.');
  4997. if (lastDot > lastSlash)
  4998. return fullPath.substring (lastSlash, lastDot);
  4999. else
  5000. return fullPath.substring (lastSlash);
  5001. }
  5002. bool File::isAChildOf (const File& potentialParent) const
  5003. {
  5004. if (potentialParent == File::nonexistent)
  5005. return false;
  5006. const String ourPath (getPathUpToLastSlash());
  5007. #if NAMES_ARE_CASE_SENSITIVE
  5008. if (potentialParent.fullPath == ourPath)
  5009. #else
  5010. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5011. #endif
  5012. {
  5013. return true;
  5014. }
  5015. else if (potentialParent.fullPath.length() >= ourPath.length())
  5016. {
  5017. return false;
  5018. }
  5019. else
  5020. {
  5021. return getParentDirectory().isAChildOf (potentialParent);
  5022. }
  5023. }
  5024. bool File::isAbsolutePath (const String& path)
  5025. {
  5026. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5027. #if JUCE_WINDOWS
  5028. || (path.isNotEmpty() && path[1] == ':');
  5029. #else
  5030. || path.startsWithChar ('~');
  5031. #endif
  5032. }
  5033. const File File::getChildFile (String relativePath) const
  5034. {
  5035. if (isAbsolutePath (relativePath))
  5036. {
  5037. // the path is really absolute..
  5038. return File (relativePath);
  5039. }
  5040. else
  5041. {
  5042. // it's relative, so remove any ../ or ./ bits at the start.
  5043. String path (fullPath);
  5044. if (relativePath[0] == '.')
  5045. {
  5046. #if JUCE_WINDOWS
  5047. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5048. #else
  5049. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5050. #endif
  5051. while (relativePath[0] == '.')
  5052. {
  5053. if (relativePath[1] == '.')
  5054. {
  5055. if (relativePath [2] == 0 || relativePath[2] == separator)
  5056. {
  5057. const int lastSlash = path.lastIndexOfChar (separator);
  5058. if (lastSlash >= 0)
  5059. path = path.substring (0, lastSlash);
  5060. relativePath = relativePath.substring (3);
  5061. }
  5062. else
  5063. {
  5064. break;
  5065. }
  5066. }
  5067. else if (relativePath[1] == separator)
  5068. {
  5069. relativePath = relativePath.substring (2);
  5070. }
  5071. else
  5072. {
  5073. break;
  5074. }
  5075. }
  5076. }
  5077. return File (addTrailingSeparator (path) + relativePath);
  5078. }
  5079. }
  5080. const File File::getSiblingFile (const String& fileName) const
  5081. {
  5082. return getParentDirectory().getChildFile (fileName);
  5083. }
  5084. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5085. {
  5086. if (bytes == 1)
  5087. {
  5088. return "1 byte";
  5089. }
  5090. else if (bytes < 1024)
  5091. {
  5092. return String ((int) bytes) + " bytes";
  5093. }
  5094. else if (bytes < 1024 * 1024)
  5095. {
  5096. return String (bytes / 1024.0, 1) + " KB";
  5097. }
  5098. else if (bytes < 1024 * 1024 * 1024)
  5099. {
  5100. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5101. }
  5102. else
  5103. {
  5104. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5105. }
  5106. }
  5107. bool File::create() const
  5108. {
  5109. if (exists())
  5110. return true;
  5111. {
  5112. const File parentDir (getParentDirectory());
  5113. if (parentDir == *this || ! parentDir.createDirectory())
  5114. return false;
  5115. FileOutputStream fo (*this, 8);
  5116. }
  5117. return exists();
  5118. }
  5119. bool File::createDirectory() const
  5120. {
  5121. if (! isDirectory())
  5122. {
  5123. const File parentDir (getParentDirectory());
  5124. if (parentDir == *this || ! parentDir.createDirectory())
  5125. return false;
  5126. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5127. return isDirectory();
  5128. }
  5129. return true;
  5130. }
  5131. const Time File::getCreationTime() const
  5132. {
  5133. int64 m, a, c;
  5134. getFileTimesInternal (m, a, c);
  5135. return Time (c);
  5136. }
  5137. const Time File::getLastModificationTime() const
  5138. {
  5139. int64 m, a, c;
  5140. getFileTimesInternal (m, a, c);
  5141. return Time (m);
  5142. }
  5143. const Time File::getLastAccessTime() const
  5144. {
  5145. int64 m, a, c;
  5146. getFileTimesInternal (m, a, c);
  5147. return Time (a);
  5148. }
  5149. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5150. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5151. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5152. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5153. {
  5154. if (! existsAsFile())
  5155. return false;
  5156. FileInputStream in (*this);
  5157. return getSize() == in.readIntoMemoryBlock (destBlock);
  5158. }
  5159. const String File::loadFileAsString() const
  5160. {
  5161. if (! existsAsFile())
  5162. return String::empty;
  5163. FileInputStream in (*this);
  5164. return in.readEntireStreamAsString();
  5165. }
  5166. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5167. {
  5168. return (whatToLookFor & (isDir ? findDirectories
  5169. : findFiles)) != 0
  5170. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5171. }
  5172. int File::findChildFiles (Array<File>& results,
  5173. const int whatToLookFor,
  5174. const bool searchRecursively,
  5175. const String& wildCardPattern) const
  5176. {
  5177. // you have to specify the type of files you're looking for!
  5178. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5179. int total = 0;
  5180. if (isDirectory())
  5181. {
  5182. // find child files or directories in this directory first..
  5183. String path (addTrailingSeparator (fullPath)), filename;
  5184. bool itemIsDirectory, itemIsHidden;
  5185. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5186. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5187. {
  5188. if (! filename.containsOnly ("."))
  5189. {
  5190. const File fileFound (path + filename, 0);
  5191. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5192. {
  5193. results.add (fileFound);
  5194. ++total;
  5195. }
  5196. if (searchRecursively && itemIsDirectory
  5197. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5198. {
  5199. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5200. }
  5201. }
  5202. }
  5203. }
  5204. return total;
  5205. }
  5206. int File::getNumberOfChildFiles (const int whatToLookFor,
  5207. const String& wildCardPattern) const
  5208. {
  5209. // you have to specify the type of files you're looking for!
  5210. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5211. int count = 0;
  5212. if (isDirectory())
  5213. {
  5214. String filename;
  5215. bool itemIsDirectory, itemIsHidden;
  5216. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5217. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5218. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5219. && ! filename.containsOnly ("."))
  5220. ++count;
  5221. }
  5222. else
  5223. {
  5224. // trying to search for files inside a non-directory?
  5225. jassertfalse
  5226. }
  5227. return count;
  5228. }
  5229. bool File::containsSubDirectories() const
  5230. {
  5231. if (isDirectory())
  5232. {
  5233. String filename;
  5234. bool itemIsDirectory;
  5235. DirectoryIterator::NativeIterator i (*this, "*");
  5236. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5237. if (itemIsDirectory)
  5238. return true;
  5239. }
  5240. return false;
  5241. }
  5242. const File File::getNonexistentChildFile (const String& prefix_,
  5243. const String& suffix,
  5244. bool putNumbersInBrackets) const
  5245. {
  5246. File f (getChildFile (prefix_ + suffix));
  5247. if (f.exists())
  5248. {
  5249. int num = 2;
  5250. String prefix (prefix_);
  5251. // remove any bracketed numbers that may already be on the end..
  5252. if (prefix.trim().endsWithChar (')'))
  5253. {
  5254. putNumbersInBrackets = true;
  5255. const int openBracks = prefix.lastIndexOfChar ('(');
  5256. const int closeBracks = prefix.lastIndexOfChar (')');
  5257. if (openBracks > 0
  5258. && closeBracks > openBracks
  5259. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5260. {
  5261. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5262. prefix = prefix.substring (0, openBracks);
  5263. }
  5264. }
  5265. // also use brackets if it ends in a digit.
  5266. putNumbersInBrackets = putNumbersInBrackets
  5267. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5268. do
  5269. {
  5270. if (putNumbersInBrackets)
  5271. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5272. else
  5273. f = getChildFile (prefix + String (num++) + suffix);
  5274. } while (f.exists());
  5275. }
  5276. return f;
  5277. }
  5278. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5279. {
  5280. if (exists())
  5281. {
  5282. return getParentDirectory()
  5283. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5284. getFileExtension(),
  5285. putNumbersInBrackets);
  5286. }
  5287. else
  5288. {
  5289. return *this;
  5290. }
  5291. }
  5292. const String File::getFileExtension() const
  5293. {
  5294. String ext;
  5295. if (! isDirectory())
  5296. {
  5297. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5298. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5299. ext = fullPath.substring (indexOfDot);
  5300. }
  5301. return ext;
  5302. }
  5303. bool File::hasFileExtension (const String& possibleSuffix) const
  5304. {
  5305. if (possibleSuffix.isEmpty())
  5306. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5307. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5308. if (semicolon >= 0)
  5309. {
  5310. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5311. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5312. }
  5313. else
  5314. {
  5315. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5316. {
  5317. if (possibleSuffix.startsWithChar ('.'))
  5318. return true;
  5319. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5320. if (dotPos >= 0)
  5321. return fullPath [dotPos] == '.';
  5322. }
  5323. }
  5324. return false;
  5325. }
  5326. const File File::withFileExtension (const String& newExtension) const
  5327. {
  5328. if (fullPath.isEmpty())
  5329. return File::nonexistent;
  5330. String filePart (getFileName());
  5331. int i = filePart.lastIndexOfChar ('.');
  5332. if (i >= 0)
  5333. filePart = filePart.substring (0, i);
  5334. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5335. filePart << '.';
  5336. return getSiblingFile (filePart + newExtension);
  5337. }
  5338. bool File::startAsProcess (const String& parameters) const
  5339. {
  5340. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5341. }
  5342. FileInputStream* File::createInputStream() const
  5343. {
  5344. if (existsAsFile())
  5345. return new FileInputStream (*this);
  5346. return 0;
  5347. }
  5348. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5349. {
  5350. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5351. if (out->failedToOpen())
  5352. return 0;
  5353. return out.release();
  5354. }
  5355. bool File::appendData (const void* const dataToAppend,
  5356. const int numberOfBytes) const
  5357. {
  5358. if (numberOfBytes > 0)
  5359. {
  5360. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5361. if (out == 0)
  5362. return false;
  5363. out->write (dataToAppend, numberOfBytes);
  5364. }
  5365. return true;
  5366. }
  5367. bool File::replaceWithData (const void* const dataToWrite,
  5368. const int numberOfBytes) const
  5369. {
  5370. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5371. if (numberOfBytes <= 0)
  5372. return deleteFile();
  5373. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5374. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5375. return tempFile.overwriteTargetFileWithTemporary();
  5376. }
  5377. bool File::appendText (const String& text,
  5378. const bool asUnicode,
  5379. const bool writeUnicodeHeaderBytes) const
  5380. {
  5381. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5382. if (out != 0)
  5383. {
  5384. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5385. return true;
  5386. }
  5387. return false;
  5388. }
  5389. bool File::replaceWithText (const String& textToWrite,
  5390. const bool asUnicode,
  5391. const bool writeUnicodeHeaderBytes) const
  5392. {
  5393. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5394. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5395. return tempFile.overwriteTargetFileWithTemporary();
  5396. }
  5397. const String File::createLegalPathName (const String& original)
  5398. {
  5399. String s (original);
  5400. String start;
  5401. if (s[1] == ':')
  5402. {
  5403. start = s.substring (0, 2);
  5404. s = s.substring (2);
  5405. }
  5406. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5407. .substring (0, 1024);
  5408. }
  5409. const String File::createLegalFileName (const String& original)
  5410. {
  5411. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5412. const int maxLength = 128; // only the length of the filename, not the whole path
  5413. const int len = s.length();
  5414. if (len > maxLength)
  5415. {
  5416. const int lastDot = s.lastIndexOfChar ('.');
  5417. if (lastDot > jmax (0, len - 12))
  5418. {
  5419. s = s.substring (0, maxLength - (len - lastDot))
  5420. + s.substring (lastDot);
  5421. }
  5422. else
  5423. {
  5424. s = s.substring (0, maxLength);
  5425. }
  5426. }
  5427. return s;
  5428. }
  5429. const String File::getRelativePathFrom (const File& dir) const
  5430. {
  5431. String thisPath (fullPath);
  5432. {
  5433. int len = thisPath.length();
  5434. while (--len >= 0 && thisPath [len] == File::separator)
  5435. thisPath [len] = 0;
  5436. }
  5437. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5438. : dir.fullPath));
  5439. const int len = jmin (thisPath.length(), dirPath.length());
  5440. int commonBitLength = 0;
  5441. for (int i = 0; i < len; ++i)
  5442. {
  5443. #if NAMES_ARE_CASE_SENSITIVE
  5444. if (thisPath[i] != dirPath[i])
  5445. #else
  5446. if (CharacterFunctions::toLowerCase (thisPath[i])
  5447. != CharacterFunctions::toLowerCase (dirPath[i]))
  5448. #endif
  5449. {
  5450. break;
  5451. }
  5452. ++commonBitLength;
  5453. }
  5454. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5455. --commonBitLength;
  5456. // if the only common bit is the root, then just return the full path..
  5457. if (commonBitLength <= 0
  5458. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5459. return fullPath;
  5460. thisPath = thisPath.substring (commonBitLength);
  5461. dirPath = dirPath.substring (commonBitLength);
  5462. while (dirPath.isNotEmpty())
  5463. {
  5464. #if JUCE_WINDOWS
  5465. thisPath = "..\\" + thisPath;
  5466. #else
  5467. thisPath = "../" + thisPath;
  5468. #endif
  5469. const int sep = dirPath.indexOfChar (separator);
  5470. if (sep >= 0)
  5471. dirPath = dirPath.substring (sep + 1);
  5472. else
  5473. dirPath = String::empty;
  5474. }
  5475. return thisPath;
  5476. }
  5477. const File File::createTempFile (const String& fileNameEnding)
  5478. {
  5479. const File tempFile (getSpecialLocation (tempDirectory)
  5480. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5481. .withFileExtension (fileNameEnding));
  5482. if (tempFile.exists())
  5483. return createTempFile (fileNameEnding);
  5484. else
  5485. return tempFile;
  5486. }
  5487. END_JUCE_NAMESPACE
  5488. /*** End of inlined file: juce_File.cpp ***/
  5489. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5490. BEGIN_JUCE_NAMESPACE
  5491. void* juce_fileOpen (const File& file, bool forWriting);
  5492. void juce_fileClose (void* handle);
  5493. int juce_fileRead (void* handle, void* buffer, int size);
  5494. int64 juce_fileSetPosition (void* handle, int64 pos);
  5495. FileInputStream::FileInputStream (const File& f)
  5496. : file (f),
  5497. currentPosition (0),
  5498. needToSeek (true)
  5499. {
  5500. totalSize = f.getSize();
  5501. fileHandle = juce_fileOpen (f, false);
  5502. }
  5503. FileInputStream::~FileInputStream()
  5504. {
  5505. juce_fileClose (fileHandle);
  5506. }
  5507. int64 FileInputStream::getTotalLength()
  5508. {
  5509. return totalSize;
  5510. }
  5511. int FileInputStream::read (void* buffer, int bytesToRead)
  5512. {
  5513. int num = 0;
  5514. if (needToSeek)
  5515. {
  5516. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5517. return 0;
  5518. needToSeek = false;
  5519. }
  5520. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5521. currentPosition += num;
  5522. return num;
  5523. }
  5524. bool FileInputStream::isExhausted()
  5525. {
  5526. return currentPosition >= totalSize;
  5527. }
  5528. int64 FileInputStream::getPosition()
  5529. {
  5530. return currentPosition;
  5531. }
  5532. bool FileInputStream::setPosition (int64 pos)
  5533. {
  5534. pos = jlimit ((int64) 0, totalSize, pos);
  5535. needToSeek |= (currentPosition != pos);
  5536. currentPosition = pos;
  5537. return true;
  5538. }
  5539. END_JUCE_NAMESPACE
  5540. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5541. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5542. BEGIN_JUCE_NAMESPACE
  5543. void* juce_fileOpen (const File& file, bool forWriting);
  5544. void juce_fileClose (void* handle);
  5545. int juce_fileWrite (void* handle, const void* buffer, int size);
  5546. int64 juce_fileSetPosition (void* handle, int64 pos);
  5547. FileOutputStream::FileOutputStream (const File& f,
  5548. const int bufferSize_)
  5549. : file (f),
  5550. bufferSize (bufferSize_),
  5551. bytesInBuffer (0)
  5552. {
  5553. fileHandle = juce_fileOpen (f, true);
  5554. if (fileHandle != 0)
  5555. {
  5556. currentPosition = getPositionInternal();
  5557. if (currentPosition < 0)
  5558. {
  5559. jassertfalse
  5560. juce_fileClose (fileHandle);
  5561. fileHandle = 0;
  5562. }
  5563. }
  5564. buffer.malloc (jmax (bufferSize_, 16));
  5565. }
  5566. FileOutputStream::~FileOutputStream()
  5567. {
  5568. flush();
  5569. juce_fileClose (fileHandle);
  5570. }
  5571. int64 FileOutputStream::getPosition()
  5572. {
  5573. return currentPosition;
  5574. }
  5575. bool FileOutputStream::setPosition (int64 newPosition)
  5576. {
  5577. if (newPosition != currentPosition)
  5578. {
  5579. flush();
  5580. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5581. }
  5582. return newPosition == currentPosition;
  5583. }
  5584. void FileOutputStream::flush()
  5585. {
  5586. if (bytesInBuffer > 0)
  5587. {
  5588. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5589. bytesInBuffer = 0;
  5590. }
  5591. flushInternal();
  5592. }
  5593. bool FileOutputStream::write (const void* const src, const int numBytes)
  5594. {
  5595. if (bytesInBuffer + numBytes < bufferSize)
  5596. {
  5597. memcpy (buffer + bytesInBuffer, src, numBytes);
  5598. bytesInBuffer += numBytes;
  5599. currentPosition += numBytes;
  5600. }
  5601. else
  5602. {
  5603. if (bytesInBuffer > 0)
  5604. {
  5605. // flush the reservoir
  5606. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5607. bytesInBuffer = 0;
  5608. if (! wroteOk)
  5609. return false;
  5610. }
  5611. if (numBytes < bufferSize)
  5612. {
  5613. memcpy (buffer + bytesInBuffer, src, numBytes);
  5614. bytesInBuffer += numBytes;
  5615. currentPosition += numBytes;
  5616. }
  5617. else
  5618. {
  5619. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5620. currentPosition += bytesWritten;
  5621. return bytesWritten == numBytes;
  5622. }
  5623. }
  5624. return true;
  5625. }
  5626. END_JUCE_NAMESPACE
  5627. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5628. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5629. BEGIN_JUCE_NAMESPACE
  5630. FileSearchPath::FileSearchPath()
  5631. {
  5632. }
  5633. FileSearchPath::FileSearchPath (const String& path)
  5634. {
  5635. init (path);
  5636. }
  5637. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5638. : directories (other.directories)
  5639. {
  5640. }
  5641. FileSearchPath::~FileSearchPath()
  5642. {
  5643. }
  5644. FileSearchPath& FileSearchPath::operator= (const String& path)
  5645. {
  5646. init (path);
  5647. return *this;
  5648. }
  5649. void FileSearchPath::init (const String& path)
  5650. {
  5651. directories.clear();
  5652. directories.addTokens (path, ";", "\"");
  5653. directories.trim();
  5654. directories.removeEmptyStrings();
  5655. for (int i = directories.size(); --i >= 0;)
  5656. directories.set (i, directories[i].unquoted());
  5657. }
  5658. int FileSearchPath::getNumPaths() const
  5659. {
  5660. return directories.size();
  5661. }
  5662. const File FileSearchPath::operator[] (const int index) const
  5663. {
  5664. return File (directories [index]);
  5665. }
  5666. const String FileSearchPath::toString() const
  5667. {
  5668. StringArray directories2 (directories);
  5669. for (int i = directories2.size(); --i >= 0;)
  5670. if (directories2[i].containsChar (';'))
  5671. directories2.set (i, directories2[i].quoted());
  5672. return directories2.joinIntoString (";");
  5673. }
  5674. void FileSearchPath::add (const File& dir, const int insertIndex)
  5675. {
  5676. directories.insert (insertIndex, dir.getFullPathName());
  5677. }
  5678. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5679. {
  5680. for (int i = 0; i < directories.size(); ++i)
  5681. if (File (directories[i]) == dir)
  5682. return;
  5683. add (dir);
  5684. }
  5685. void FileSearchPath::remove (const int index)
  5686. {
  5687. directories.remove (index);
  5688. }
  5689. void FileSearchPath::addPath (const FileSearchPath& other)
  5690. {
  5691. for (int i = 0; i < other.getNumPaths(); ++i)
  5692. addIfNotAlreadyThere (other[i]);
  5693. }
  5694. void FileSearchPath::removeRedundantPaths()
  5695. {
  5696. for (int i = directories.size(); --i >= 0;)
  5697. {
  5698. const File d1 (directories[i]);
  5699. for (int j = directories.size(); --j >= 0;)
  5700. {
  5701. const File d2 (directories[j]);
  5702. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5703. {
  5704. directories.remove (i);
  5705. break;
  5706. }
  5707. }
  5708. }
  5709. }
  5710. void FileSearchPath::removeNonExistentPaths()
  5711. {
  5712. for (int i = directories.size(); --i >= 0;)
  5713. if (! File (directories[i]).isDirectory())
  5714. directories.remove (i);
  5715. }
  5716. int FileSearchPath::findChildFiles (Array<File>& results,
  5717. const int whatToLookFor,
  5718. const bool searchRecursively,
  5719. const String& wildCardPattern) const
  5720. {
  5721. int total = 0;
  5722. for (int i = 0; i < directories.size(); ++i)
  5723. total += operator[] (i).findChildFiles (results,
  5724. whatToLookFor,
  5725. searchRecursively,
  5726. wildCardPattern);
  5727. return total;
  5728. }
  5729. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5730. const bool checkRecursively) const
  5731. {
  5732. for (int i = directories.size(); --i >= 0;)
  5733. {
  5734. const File d (directories[i]);
  5735. if (checkRecursively)
  5736. {
  5737. if (fileToCheck.isAChildOf (d))
  5738. return true;
  5739. }
  5740. else
  5741. {
  5742. if (fileToCheck.getParentDirectory() == d)
  5743. return true;
  5744. }
  5745. }
  5746. return false;
  5747. }
  5748. END_JUCE_NAMESPACE
  5749. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5750. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5751. BEGIN_JUCE_NAMESPACE
  5752. NamedPipe::NamedPipe()
  5753. : internal (0)
  5754. {
  5755. }
  5756. NamedPipe::~NamedPipe()
  5757. {
  5758. close();
  5759. }
  5760. bool NamedPipe::openExisting (const String& pipeName)
  5761. {
  5762. currentPipeName = pipeName;
  5763. return openInternal (pipeName, false);
  5764. }
  5765. bool NamedPipe::createNewPipe (const String& pipeName)
  5766. {
  5767. currentPipeName = pipeName;
  5768. return openInternal (pipeName, true);
  5769. }
  5770. bool NamedPipe::isOpen() const
  5771. {
  5772. return internal != 0;
  5773. }
  5774. const String NamedPipe::getName() const
  5775. {
  5776. return currentPipeName;
  5777. }
  5778. // other methods for this class are implemented in the platform-specific files
  5779. END_JUCE_NAMESPACE
  5780. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5781. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5782. BEGIN_JUCE_NAMESPACE
  5783. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5784. {
  5785. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5786. "temp_" + String (Random::getSystemRandom().nextInt()),
  5787. suffix,
  5788. optionFlags);
  5789. }
  5790. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5791. : targetFile (targetFile_)
  5792. {
  5793. // If you use this constructor, you need to give it a valid target file!
  5794. jassert (targetFile != File::nonexistent);
  5795. createTempFile (targetFile.getParentDirectory(),
  5796. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5797. targetFile.getFileExtension(),
  5798. optionFlags);
  5799. }
  5800. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5801. const String& suffix, const int optionFlags)
  5802. {
  5803. if ((optionFlags & useHiddenFile) != 0)
  5804. name = "." + name;
  5805. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5806. }
  5807. TemporaryFile::~TemporaryFile()
  5808. {
  5809. // Have a few attempts at deleting the file before giving up..
  5810. for (int i = 5; --i >= 0;)
  5811. {
  5812. if (temporaryFile.deleteFile())
  5813. return;
  5814. Thread::sleep (50);
  5815. }
  5816. // Failed to delete our temporary file! Check that you've deleted all the
  5817. // file output streams that were using it!
  5818. jassertfalse;
  5819. }
  5820. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5821. {
  5822. // This method only works if you created this object with the constructor
  5823. // that takes a target file!
  5824. jassert (targetFile != File::nonexistent);
  5825. if (temporaryFile.exists())
  5826. {
  5827. // Have a few attempts at overwriting the file before giving up..
  5828. for (int i = 5; --i >= 0;)
  5829. {
  5830. if (temporaryFile.moveFileTo (targetFile))
  5831. return true;
  5832. Thread::sleep (100);
  5833. }
  5834. }
  5835. else
  5836. {
  5837. // There's no temporary file to use. If your write failed, you should
  5838. // probably check, and not bother calling this method.
  5839. jassertfalse
  5840. }
  5841. return false;
  5842. }
  5843. END_JUCE_NAMESPACE
  5844. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5845. /*** Start of inlined file: juce_Socket.cpp ***/
  5846. #if JUCE_WINDOWS
  5847. #include <winsock2.h>
  5848. #ifdef _MSC_VER
  5849. #pragma warning (disable : 4127 4389 4018)
  5850. #endif
  5851. #else
  5852. #if JUCE_LINUX
  5853. #include <sys/types.h>
  5854. #include <sys/socket.h>
  5855. #include <sys/errno.h>
  5856. #include <unistd.h>
  5857. #include <netinet/in.h>
  5858. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5859. #include <CoreServices/CoreServices.h>
  5860. #endif
  5861. #include <fcntl.h>
  5862. #include <netdb.h>
  5863. #include <arpa/inet.h>
  5864. #include <netinet/tcp.h>
  5865. #endif
  5866. BEGIN_JUCE_NAMESPACE
  5867. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5868. typedef socklen_t juce_socklen_t;
  5869. #else
  5870. typedef int juce_socklen_t;
  5871. #endif
  5872. #if JUCE_WINDOWS
  5873. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5874. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5875. static void initWin32Sockets()
  5876. {
  5877. static CriticalSection lock;
  5878. const ScopedLock sl (lock);
  5879. if (juce_CloseWin32SocketLib == 0)
  5880. {
  5881. WSADATA wsaData;
  5882. const WORD wVersionRequested = MAKEWORD (1, 1);
  5883. WSAStartup (wVersionRequested, &wsaData);
  5884. juce_CloseWin32SocketLib = &WSACleanup;
  5885. }
  5886. }
  5887. #endif
  5888. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5889. {
  5890. const int sndBufSize = 65536;
  5891. const int rcvBufSize = 65536;
  5892. const int one = 1;
  5893. return handle > 0
  5894. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5895. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5896. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5897. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5898. }
  5899. static bool bindSocketToPort (const int handle, const int port) throw()
  5900. {
  5901. if (handle <= 0 || port <= 0)
  5902. return false;
  5903. struct sockaddr_in servTmpAddr;
  5904. zerostruct (servTmpAddr);
  5905. servTmpAddr.sin_family = PF_INET;
  5906. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5907. servTmpAddr.sin_port = htons ((uint16) port);
  5908. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5909. }
  5910. static int readSocket (const int handle,
  5911. void* const destBuffer, const int maxBytesToRead,
  5912. bool volatile& connected,
  5913. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5914. {
  5915. int bytesRead = 0;
  5916. while (bytesRead < maxBytesToRead)
  5917. {
  5918. int bytesThisTime;
  5919. #if JUCE_WINDOWS
  5920. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5921. #else
  5922. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5923. && errno == EINTR
  5924. && connected)
  5925. {
  5926. }
  5927. #endif
  5928. if (bytesThisTime <= 0 || ! connected)
  5929. {
  5930. if (bytesRead == 0)
  5931. bytesRead = -1;
  5932. break;
  5933. }
  5934. bytesRead += bytesThisTime;
  5935. if (! blockUntilSpecifiedAmountHasArrived)
  5936. break;
  5937. }
  5938. return bytesRead;
  5939. }
  5940. static int waitForReadiness (const int handle, const bool forReading,
  5941. const int timeoutMsecs) throw()
  5942. {
  5943. struct timeval timeout;
  5944. struct timeval* timeoutp;
  5945. if (timeoutMsecs >= 0)
  5946. {
  5947. timeout.tv_sec = timeoutMsecs / 1000;
  5948. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5949. timeoutp = &timeout;
  5950. }
  5951. else
  5952. {
  5953. timeoutp = 0;
  5954. }
  5955. fd_set rset, wset;
  5956. FD_ZERO (&rset);
  5957. FD_SET (handle, &rset);
  5958. FD_ZERO (&wset);
  5959. FD_SET (handle, &wset);
  5960. fd_set* const prset = forReading ? &rset : 0;
  5961. fd_set* const pwset = forReading ? 0 : &wset;
  5962. #if JUCE_WINDOWS
  5963. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5964. return -1;
  5965. #else
  5966. {
  5967. int result;
  5968. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5969. && errno == EINTR)
  5970. {
  5971. }
  5972. if (result < 0)
  5973. return -1;
  5974. }
  5975. #endif
  5976. {
  5977. int opt;
  5978. juce_socklen_t len = sizeof (opt);
  5979. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5980. || opt != 0)
  5981. return -1;
  5982. }
  5983. if ((forReading && FD_ISSET (handle, &rset))
  5984. || ((! forReading) && FD_ISSET (handle, &wset)))
  5985. return 1;
  5986. return 0;
  5987. }
  5988. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5989. {
  5990. #if JUCE_WINDOWS
  5991. u_long nonBlocking = shouldBlock ? 0 : 1;
  5992. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5993. return false;
  5994. #else
  5995. int socketFlags = fcntl (handle, F_GETFL, 0);
  5996. if (socketFlags == -1)
  5997. return false;
  5998. if (shouldBlock)
  5999. socketFlags &= ~O_NONBLOCK;
  6000. else
  6001. socketFlags |= O_NONBLOCK;
  6002. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6003. return false;
  6004. #endif
  6005. return true;
  6006. }
  6007. static bool connectSocket (int volatile& handle,
  6008. const bool isDatagram,
  6009. void** serverAddress,
  6010. const String& hostName,
  6011. const int portNumber,
  6012. const int timeOutMillisecs) throw()
  6013. {
  6014. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6015. if (hostEnt == 0)
  6016. return false;
  6017. struct in_addr targetAddress;
  6018. memcpy (&targetAddress.s_addr,
  6019. *(hostEnt->h_addr_list),
  6020. sizeof (targetAddress.s_addr));
  6021. struct sockaddr_in servTmpAddr;
  6022. zerostruct (servTmpAddr);
  6023. servTmpAddr.sin_family = PF_INET;
  6024. servTmpAddr.sin_addr = targetAddress;
  6025. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6026. if (handle < 0)
  6027. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6028. if (handle < 0)
  6029. return false;
  6030. if (isDatagram)
  6031. {
  6032. *serverAddress = new struct sockaddr_in();
  6033. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6034. return true;
  6035. }
  6036. setSocketBlockingState (handle, false);
  6037. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6038. if (result < 0)
  6039. {
  6040. #if JUCE_WINDOWS
  6041. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6042. #else
  6043. if (errno == EINPROGRESS)
  6044. #endif
  6045. {
  6046. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6047. {
  6048. setSocketBlockingState (handle, true);
  6049. return false;
  6050. }
  6051. }
  6052. }
  6053. setSocketBlockingState (handle, true);
  6054. resetSocketOptions (handle, false, false);
  6055. return true;
  6056. }
  6057. StreamingSocket::StreamingSocket()
  6058. : portNumber (0),
  6059. handle (-1),
  6060. connected (false),
  6061. isListener (false)
  6062. {
  6063. #if JUCE_WINDOWS
  6064. initWin32Sockets();
  6065. #endif
  6066. }
  6067. StreamingSocket::StreamingSocket (const String& hostName_,
  6068. const int portNumber_,
  6069. const int handle_)
  6070. : hostName (hostName_),
  6071. portNumber (portNumber_),
  6072. handle (handle_),
  6073. connected (true),
  6074. isListener (false)
  6075. {
  6076. #if JUCE_WINDOWS
  6077. initWin32Sockets();
  6078. #endif
  6079. resetSocketOptions (handle_, false, false);
  6080. }
  6081. StreamingSocket::~StreamingSocket()
  6082. {
  6083. close();
  6084. }
  6085. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6086. {
  6087. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6088. : -1;
  6089. }
  6090. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6091. {
  6092. if (isListener || ! connected)
  6093. return -1;
  6094. #if JUCE_WINDOWS
  6095. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6096. #else
  6097. int result;
  6098. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6099. && errno == EINTR)
  6100. {
  6101. }
  6102. return result;
  6103. #endif
  6104. }
  6105. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6106. const int timeoutMsecs) const
  6107. {
  6108. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6109. : -1;
  6110. }
  6111. bool StreamingSocket::bindToPort (const int port)
  6112. {
  6113. return bindSocketToPort (handle, port);
  6114. }
  6115. bool StreamingSocket::connect (const String& remoteHostName,
  6116. const int remotePortNumber,
  6117. const int timeOutMillisecs)
  6118. {
  6119. if (isListener)
  6120. {
  6121. jassertfalse // a listener socket can't connect to another one!
  6122. return false;
  6123. }
  6124. if (connected)
  6125. close();
  6126. hostName = remoteHostName;
  6127. portNumber = remotePortNumber;
  6128. isListener = false;
  6129. connected = connectSocket (handle, false, 0, remoteHostName,
  6130. remotePortNumber, timeOutMillisecs);
  6131. if (! (connected && resetSocketOptions (handle, false, false)))
  6132. {
  6133. close();
  6134. return false;
  6135. }
  6136. return true;
  6137. }
  6138. void StreamingSocket::close()
  6139. {
  6140. #if JUCE_WINDOWS
  6141. if (handle != SOCKET_ERROR || connected)
  6142. closesocket (handle);
  6143. connected = false;
  6144. #else
  6145. if (connected)
  6146. {
  6147. connected = false;
  6148. if (isListener)
  6149. {
  6150. // need to do this to interrupt the accept() function..
  6151. StreamingSocket temp;
  6152. temp.connect ("localhost", portNumber, 1000);
  6153. }
  6154. }
  6155. if (handle != -1)
  6156. ::close (handle);
  6157. #endif
  6158. hostName = String::empty;
  6159. portNumber = 0;
  6160. handle = -1;
  6161. isListener = false;
  6162. }
  6163. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6164. {
  6165. if (connected)
  6166. close();
  6167. hostName = "listener";
  6168. portNumber = newPortNumber;
  6169. isListener = true;
  6170. struct sockaddr_in servTmpAddr;
  6171. zerostruct (servTmpAddr);
  6172. servTmpAddr.sin_family = PF_INET;
  6173. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6174. if (localHostName.isNotEmpty())
  6175. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6176. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6177. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6178. if (handle < 0)
  6179. return false;
  6180. const int reuse = 1;
  6181. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6182. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6183. || listen (handle, SOMAXCONN) < 0)
  6184. {
  6185. close();
  6186. return false;
  6187. }
  6188. connected = true;
  6189. return true;
  6190. }
  6191. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6192. {
  6193. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6194. // prepare this socket as a listener.
  6195. if (connected && isListener)
  6196. {
  6197. struct sockaddr address;
  6198. juce_socklen_t len = sizeof (sockaddr);
  6199. const int newSocket = (int) accept (handle, &address, &len);
  6200. if (newSocket >= 0 && connected)
  6201. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6202. portNumber, newSocket);
  6203. }
  6204. return 0;
  6205. }
  6206. bool StreamingSocket::isLocal() const throw()
  6207. {
  6208. return hostName == "127.0.0.1";
  6209. }
  6210. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6211. : portNumber (0),
  6212. handle (-1),
  6213. connected (true),
  6214. allowBroadcast (allowBroadcast_),
  6215. serverAddress (0)
  6216. {
  6217. #if JUCE_WINDOWS
  6218. initWin32Sockets();
  6219. #endif
  6220. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6221. bindToPort (localPortNumber);
  6222. }
  6223. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6224. const int handle_, const int localPortNumber)
  6225. : hostName (hostName_),
  6226. portNumber (portNumber_),
  6227. handle (handle_),
  6228. connected (true),
  6229. allowBroadcast (false),
  6230. serverAddress (0)
  6231. {
  6232. #if JUCE_WINDOWS
  6233. initWin32Sockets();
  6234. #endif
  6235. resetSocketOptions (handle_, true, allowBroadcast);
  6236. bindToPort (localPortNumber);
  6237. }
  6238. DatagramSocket::~DatagramSocket()
  6239. {
  6240. close();
  6241. delete ((struct sockaddr_in*) serverAddress);
  6242. serverAddress = 0;
  6243. }
  6244. void DatagramSocket::close()
  6245. {
  6246. #if JUCE_WINDOWS
  6247. closesocket (handle);
  6248. connected = false;
  6249. #else
  6250. connected = false;
  6251. ::close (handle);
  6252. #endif
  6253. hostName = String::empty;
  6254. portNumber = 0;
  6255. handle = -1;
  6256. }
  6257. bool DatagramSocket::bindToPort (const int port)
  6258. {
  6259. return bindSocketToPort (handle, port);
  6260. }
  6261. bool DatagramSocket::connect (const String& remoteHostName,
  6262. const int remotePortNumber,
  6263. const int timeOutMillisecs)
  6264. {
  6265. if (connected)
  6266. close();
  6267. hostName = remoteHostName;
  6268. portNumber = remotePortNumber;
  6269. connected = connectSocket (handle, true, &serverAddress,
  6270. remoteHostName, remotePortNumber,
  6271. timeOutMillisecs);
  6272. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6273. {
  6274. close();
  6275. return false;
  6276. }
  6277. return true;
  6278. }
  6279. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6280. {
  6281. struct sockaddr address;
  6282. juce_socklen_t len = sizeof (sockaddr);
  6283. while (waitUntilReady (true, -1) == 1)
  6284. {
  6285. char buf[1];
  6286. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6287. {
  6288. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6289. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6290. -1, -1);
  6291. }
  6292. }
  6293. return 0;
  6294. }
  6295. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6296. const int timeoutMsecs) const
  6297. {
  6298. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6299. : -1;
  6300. }
  6301. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6302. {
  6303. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6304. : -1;
  6305. }
  6306. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6307. {
  6308. // You need to call connect() first to set the server address..
  6309. jassert (serverAddress != 0 && connected);
  6310. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6311. numBytesToWrite, 0,
  6312. (const struct sockaddr*) serverAddress,
  6313. sizeof (struct sockaddr_in))
  6314. : -1;
  6315. }
  6316. bool DatagramSocket::isLocal() const throw()
  6317. {
  6318. return hostName == "127.0.0.1";
  6319. }
  6320. END_JUCE_NAMESPACE
  6321. /*** End of inlined file: juce_Socket.cpp ***/
  6322. /*** Start of inlined file: juce_URL.cpp ***/
  6323. BEGIN_JUCE_NAMESPACE
  6324. URL::URL()
  6325. {
  6326. }
  6327. URL::URL (const String& url_)
  6328. : url (url_)
  6329. {
  6330. int i = url.indexOfChar ('?');
  6331. if (i >= 0)
  6332. {
  6333. do
  6334. {
  6335. const int nextAmp = url.indexOfChar (i + 1, '&');
  6336. const int equalsPos = url.indexOfChar (i + 1, '=');
  6337. if (equalsPos > i + 1)
  6338. {
  6339. if (nextAmp < 0)
  6340. {
  6341. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6342. removeEscapeChars (url.substring (equalsPos + 1)));
  6343. }
  6344. else if (nextAmp > 0 && equalsPos < nextAmp)
  6345. {
  6346. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6347. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6348. }
  6349. }
  6350. i = nextAmp;
  6351. }
  6352. while (i >= 0);
  6353. url = url.upToFirstOccurrenceOf ("?", false, false);
  6354. }
  6355. }
  6356. URL::URL (const URL& other)
  6357. : url (other.url),
  6358. postData (other.postData),
  6359. parameters (other.parameters),
  6360. filesToUpload (other.filesToUpload),
  6361. mimeTypes (other.mimeTypes)
  6362. {
  6363. }
  6364. URL& URL::operator= (const URL& other)
  6365. {
  6366. url = other.url;
  6367. postData = other.postData;
  6368. parameters = other.parameters;
  6369. filesToUpload = other.filesToUpload;
  6370. mimeTypes = other.mimeTypes;
  6371. return *this;
  6372. }
  6373. URL::~URL()
  6374. {
  6375. }
  6376. static const String getMangledParameters (const StringPairArray& parameters)
  6377. {
  6378. String p;
  6379. for (int i = 0; i < parameters.size(); ++i)
  6380. {
  6381. if (i > 0)
  6382. p += '&';
  6383. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6384. << '='
  6385. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6386. }
  6387. return p;
  6388. }
  6389. const String URL::toString (const bool includeGetParameters) const
  6390. {
  6391. if (includeGetParameters && parameters.size() > 0)
  6392. return url + "?" + getMangledParameters (parameters);
  6393. else
  6394. return url;
  6395. }
  6396. bool URL::isWellFormed() const
  6397. {
  6398. //xxx TODO
  6399. return url.isNotEmpty();
  6400. }
  6401. static int findStartOfDomain (const String& url)
  6402. {
  6403. int i = 0;
  6404. while (CharacterFunctions::isLetterOrDigit (url[i])
  6405. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6406. ++i;
  6407. return url[i] == ':' ? i + 1 : 0;
  6408. }
  6409. const String URL::getDomain() const
  6410. {
  6411. int start = findStartOfDomain (url);
  6412. while (url[start] == '/')
  6413. ++start;
  6414. const int end1 = url.indexOfChar (start, '/');
  6415. const int end2 = url.indexOfChar (start, ':');
  6416. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6417. : jmin (end1, end2);
  6418. return url.substring (start, end);
  6419. }
  6420. const String URL::getSubPath() const
  6421. {
  6422. int start = findStartOfDomain (url);
  6423. while (url[start] == '/')
  6424. ++start;
  6425. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6426. return startOfPath <= 0 ? String::empty
  6427. : url.substring (startOfPath);
  6428. }
  6429. const String URL::getScheme() const
  6430. {
  6431. return url.substring (0, findStartOfDomain (url) - 1);
  6432. }
  6433. const URL URL::withNewSubPath (const String& newPath) const
  6434. {
  6435. int start = findStartOfDomain (url);
  6436. while (url[start] == '/')
  6437. ++start;
  6438. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6439. URL u (*this);
  6440. if (startOfPath > 0)
  6441. u.url = url.substring (0, startOfPath);
  6442. if (! u.url.endsWithChar ('/'))
  6443. u.url << '/';
  6444. if (newPath.startsWithChar ('/'))
  6445. u.url << newPath.substring (1);
  6446. else
  6447. u.url << newPath;
  6448. return u;
  6449. }
  6450. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6451. {
  6452. if (possibleURL.startsWithIgnoreCase ("http:")
  6453. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6454. return true;
  6455. if (possibleURL.startsWithIgnoreCase ("file:")
  6456. || possibleURL.containsChar ('@')
  6457. || possibleURL.endsWithChar ('.')
  6458. || (! possibleURL.containsChar ('.')))
  6459. return false;
  6460. if (possibleURL.startsWithIgnoreCase ("www.")
  6461. && possibleURL.substring (5).containsChar ('.'))
  6462. return true;
  6463. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6464. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6465. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6466. return true;
  6467. return false;
  6468. }
  6469. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6470. {
  6471. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6472. return atSign > 0
  6473. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6474. && (! possibleEmailAddress.endsWithChar ('.'));
  6475. }
  6476. void* juce_openInternetFile (const String& url,
  6477. const String& headers,
  6478. const MemoryBlock& optionalPostData,
  6479. const bool isPost,
  6480. URL::OpenStreamProgressCallback* callback,
  6481. void* callbackContext,
  6482. int timeOutMs);
  6483. void juce_closeInternetFile (void* handle);
  6484. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6485. int juce_seekInInternetFile (void* handle, int newPosition);
  6486. int64 juce_getInternetFileContentLength (void* handle);
  6487. class WebInputStream : public InputStream
  6488. {
  6489. public:
  6490. WebInputStream (const URL& url,
  6491. const bool isPost_,
  6492. URL::OpenStreamProgressCallback* const progressCallback_,
  6493. void* const progressCallbackContext_,
  6494. const String& extraHeaders,
  6495. int timeOutMs_)
  6496. : position (0),
  6497. finished (false),
  6498. isPost (isPost_),
  6499. progressCallback (progressCallback_),
  6500. progressCallbackContext (progressCallbackContext_),
  6501. timeOutMs (timeOutMs_)
  6502. {
  6503. server = url.toString (! isPost);
  6504. if (isPost_)
  6505. createHeadersAndPostData (url);
  6506. headers += extraHeaders;
  6507. if (! headers.endsWithChar ('\n'))
  6508. headers << "\r\n";
  6509. handle = juce_openInternetFile (server, headers, postData, isPost,
  6510. progressCallback_, progressCallbackContext_,
  6511. timeOutMs);
  6512. }
  6513. ~WebInputStream()
  6514. {
  6515. juce_closeInternetFile (handle);
  6516. }
  6517. bool isError() const { return handle == 0; }
  6518. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6519. bool isExhausted() { return finished; }
  6520. int64 getPosition() { return position; }
  6521. int read (void* dest, int bytes)
  6522. {
  6523. if (finished || isError())
  6524. {
  6525. return 0;
  6526. }
  6527. else
  6528. {
  6529. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6530. position += bytesRead;
  6531. if (bytesRead == 0)
  6532. finished = true;
  6533. return bytesRead;
  6534. }
  6535. }
  6536. bool setPosition (int64 wantedPos)
  6537. {
  6538. if (wantedPos != position)
  6539. {
  6540. finished = false;
  6541. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6542. if (actualPos == wantedPos)
  6543. {
  6544. position = wantedPos;
  6545. }
  6546. else
  6547. {
  6548. if (wantedPos < position)
  6549. {
  6550. juce_closeInternetFile (handle);
  6551. position = 0;
  6552. finished = false;
  6553. handle = juce_openInternetFile (server, headers, postData, isPost,
  6554. progressCallback, progressCallbackContext,
  6555. timeOutMs);
  6556. }
  6557. skipNextBytes (wantedPos - position);
  6558. }
  6559. }
  6560. return true;
  6561. }
  6562. juce_UseDebuggingNewOperator
  6563. private:
  6564. String server, headers;
  6565. MemoryBlock postData;
  6566. int64 position;
  6567. bool finished;
  6568. const bool isPost;
  6569. void* handle;
  6570. URL::OpenStreamProgressCallback* const progressCallback;
  6571. void* const progressCallbackContext;
  6572. const int timeOutMs;
  6573. void createHeadersAndPostData (const URL& url)
  6574. {
  6575. MemoryOutputStream data (256, 256, &postData);
  6576. if (url.getFilesToUpload().size() > 0)
  6577. {
  6578. // need to upload some files, so do it as multi-part...
  6579. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6580. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6581. data << "--" << boundary;
  6582. int i;
  6583. for (i = 0; i < url.getParameters().size(); ++i)
  6584. {
  6585. data << "\r\nContent-Disposition: form-data; name=\""
  6586. << url.getParameters().getAllKeys() [i]
  6587. << "\"\r\n\r\n"
  6588. << url.getParameters().getAllValues() [i]
  6589. << "\r\n--"
  6590. << boundary;
  6591. }
  6592. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6593. {
  6594. const File file (url.getFilesToUpload().getAllValues() [i]);
  6595. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6596. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6597. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6598. const String mimeType (url.getMimeTypesOfUploadFiles()
  6599. .getValue (paramName, String::empty));
  6600. if (mimeType.isNotEmpty())
  6601. data << "Content-Type: " << mimeType << "\r\n";
  6602. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6603. << file << "\r\n--" << boundary;
  6604. }
  6605. data << "--\r\n";
  6606. }
  6607. else
  6608. {
  6609. data << getMangledParameters (url.getParameters())
  6610. << url.getPostData();
  6611. // just a short text attachment, so use simple url encoding..
  6612. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6613. + String ((unsigned int) postData.getSize())
  6614. + "\r\n";
  6615. }
  6616. }
  6617. WebInputStream (const WebInputStream&);
  6618. WebInputStream& operator= (const WebInputStream&);
  6619. };
  6620. InputStream* URL::createInputStream (const bool usePostCommand,
  6621. OpenStreamProgressCallback* const progressCallback,
  6622. void* const progressCallbackContext,
  6623. const String& extraHeaders,
  6624. const int timeOutMs) const
  6625. {
  6626. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6627. progressCallback, progressCallbackContext,
  6628. extraHeaders,
  6629. timeOutMs));
  6630. return wi->isError() ? 0 : wi.release();
  6631. }
  6632. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6633. const bool usePostCommand) const
  6634. {
  6635. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6636. if (in != 0)
  6637. {
  6638. in->readIntoMemoryBlock (destData, -1);
  6639. return true;
  6640. }
  6641. return false;
  6642. }
  6643. const String URL::readEntireTextStream (const bool usePostCommand) const
  6644. {
  6645. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6646. if (in != 0)
  6647. return in->readEntireStreamAsString();
  6648. return String::empty;
  6649. }
  6650. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6651. {
  6652. XmlDocument doc (readEntireTextStream (usePostCommand));
  6653. return doc.getDocumentElement();
  6654. }
  6655. const URL URL::withParameter (const String& parameterName,
  6656. const String& parameterValue) const
  6657. {
  6658. URL u (*this);
  6659. u.parameters.set (parameterName, parameterValue);
  6660. return u;
  6661. }
  6662. const URL URL::withFileToUpload (const String& parameterName,
  6663. const File& fileToUpload,
  6664. const String& mimeType) const
  6665. {
  6666. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6667. URL u (*this);
  6668. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6669. u.mimeTypes.set (parameterName, mimeType);
  6670. return u;
  6671. }
  6672. const URL URL::withPOSTData (const String& postData_) const
  6673. {
  6674. URL u (*this);
  6675. u.postData = postData_;
  6676. return u;
  6677. }
  6678. const StringPairArray& URL::getParameters() const
  6679. {
  6680. return parameters;
  6681. }
  6682. const StringPairArray& URL::getFilesToUpload() const
  6683. {
  6684. return filesToUpload;
  6685. }
  6686. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6687. {
  6688. return mimeTypes;
  6689. }
  6690. const String URL::removeEscapeChars (const String& s)
  6691. {
  6692. String result (s.replaceCharacter ('+', ' '));
  6693. int nextPercent = 0;
  6694. for (;;)
  6695. {
  6696. nextPercent = result.indexOfChar (nextPercent, '%');
  6697. if (nextPercent < 0)
  6698. break;
  6699. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6700. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6701. ++nextPercent;
  6702. }
  6703. return result;
  6704. }
  6705. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6706. {
  6707. String result;
  6708. result.preallocateStorage (s.length() + 8);
  6709. const char* utf8 = s.toUTF8();
  6710. const char* legalChars = isParameter ? "_-.*!'()"
  6711. : "_-$.*!'(),";
  6712. while (*utf8 != 0)
  6713. {
  6714. const char c = *utf8++;
  6715. if (CharacterFunctions::isLetterOrDigit (c)
  6716. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6717. {
  6718. result << c;
  6719. }
  6720. else
  6721. {
  6722. const int v = (int) (uint8) c;
  6723. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6724. }
  6725. }
  6726. return result;
  6727. }
  6728. bool URL::launchInDefaultBrowser() const
  6729. {
  6730. String u (toString (true));
  6731. if (u.containsChar ('@') && ! u.containsChar (':'))
  6732. u = "mailto:" + u;
  6733. return PlatformUtilities::openDocument (u, String::empty);
  6734. }
  6735. END_JUCE_NAMESPACE
  6736. /*** End of inlined file: juce_URL.cpp ***/
  6737. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6738. BEGIN_JUCE_NAMESPACE
  6739. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6740. const int bufferSize_,
  6741. const bool deleteSourceWhenDestroyed)
  6742. : source (source_),
  6743. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6744. bufferSize (jmax (256, bufferSize_)),
  6745. position (source_->getPosition()),
  6746. lastReadPos (0),
  6747. bufferOverlap (128)
  6748. {
  6749. const int sourceSize = (int) source_->getTotalLength();
  6750. if (sourceSize >= 0)
  6751. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6752. bufferStart = position;
  6753. buffer.malloc (bufferSize);
  6754. }
  6755. BufferedInputStream::~BufferedInputStream()
  6756. {
  6757. }
  6758. int64 BufferedInputStream::getTotalLength()
  6759. {
  6760. return source->getTotalLength();
  6761. }
  6762. int64 BufferedInputStream::getPosition()
  6763. {
  6764. return position;
  6765. }
  6766. bool BufferedInputStream::setPosition (int64 newPosition)
  6767. {
  6768. position = jmax ((int64) 0, newPosition);
  6769. return true;
  6770. }
  6771. bool BufferedInputStream::isExhausted()
  6772. {
  6773. return (position >= lastReadPos)
  6774. && source->isExhausted();
  6775. }
  6776. void BufferedInputStream::ensureBuffered()
  6777. {
  6778. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6779. if (position < bufferStart || position >= bufferEndOverlap)
  6780. {
  6781. int bytesRead;
  6782. if (position < lastReadPos
  6783. && position >= bufferEndOverlap
  6784. && position >= bufferStart)
  6785. {
  6786. const int bytesToKeep = (int) (lastReadPos - position);
  6787. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6788. bufferStart = position;
  6789. bytesRead = source->read (buffer + bytesToKeep,
  6790. bufferSize - bytesToKeep);
  6791. lastReadPos += bytesRead;
  6792. bytesRead += bytesToKeep;
  6793. }
  6794. else
  6795. {
  6796. bufferStart = position;
  6797. source->setPosition (bufferStart);
  6798. bytesRead = source->read (buffer, bufferSize);
  6799. lastReadPos = bufferStart + bytesRead;
  6800. }
  6801. while (bytesRead < bufferSize)
  6802. buffer [bytesRead++] = 0;
  6803. }
  6804. }
  6805. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6806. {
  6807. if (position >= bufferStart
  6808. && position + maxBytesToRead <= lastReadPos)
  6809. {
  6810. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6811. position += maxBytesToRead;
  6812. return maxBytesToRead;
  6813. }
  6814. else
  6815. {
  6816. if (position < bufferStart || position >= lastReadPos)
  6817. ensureBuffered();
  6818. int bytesRead = 0;
  6819. while (maxBytesToRead > 0)
  6820. {
  6821. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6822. if (bytesAvailable > 0)
  6823. {
  6824. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6825. maxBytesToRead -= bytesAvailable;
  6826. bytesRead += bytesAvailable;
  6827. position += bytesAvailable;
  6828. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6829. }
  6830. const int64 oldLastReadPos = lastReadPos;
  6831. ensureBuffered();
  6832. if (oldLastReadPos == lastReadPos)
  6833. break; // if ensureBuffered() failed to read any more data, bail out
  6834. if (isExhausted())
  6835. break;
  6836. }
  6837. return bytesRead;
  6838. }
  6839. }
  6840. const String BufferedInputStream::readString()
  6841. {
  6842. if (position >= bufferStart
  6843. && position < lastReadPos)
  6844. {
  6845. const int maxChars = (int) (lastReadPos - position);
  6846. const char* const src = buffer + (int) (position - bufferStart);
  6847. for (int i = 0; i < maxChars; ++i)
  6848. {
  6849. if (src[i] == 0)
  6850. {
  6851. position += i + 1;
  6852. return String::fromUTF8 (src, i);
  6853. }
  6854. }
  6855. }
  6856. return InputStream::readString();
  6857. }
  6858. END_JUCE_NAMESPACE
  6859. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6860. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6861. BEGIN_JUCE_NAMESPACE
  6862. FileInputSource::FileInputSource (const File& file_)
  6863. : file (file_)
  6864. {
  6865. }
  6866. FileInputSource::~FileInputSource()
  6867. {
  6868. }
  6869. InputStream* FileInputSource::createInputStream()
  6870. {
  6871. return file.createInputStream();
  6872. }
  6873. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6874. {
  6875. return file.getSiblingFile (relatedItemPath).createInputStream();
  6876. }
  6877. int64 FileInputSource::hashCode() const
  6878. {
  6879. return file.hashCode();
  6880. }
  6881. END_JUCE_NAMESPACE
  6882. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6883. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6884. BEGIN_JUCE_NAMESPACE
  6885. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6886. const size_t sourceDataSize,
  6887. const bool keepInternalCopy)
  6888. : data (static_cast <const char*> (sourceData)),
  6889. dataSize (sourceDataSize),
  6890. position (0)
  6891. {
  6892. if (keepInternalCopy)
  6893. {
  6894. internalCopy.append (data, sourceDataSize);
  6895. data = static_cast <const char*> (internalCopy.getData());
  6896. }
  6897. }
  6898. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6899. const bool keepInternalCopy)
  6900. : data (static_cast <const char*> (sourceData.getData())),
  6901. dataSize (sourceData.getSize()),
  6902. position (0)
  6903. {
  6904. if (keepInternalCopy)
  6905. {
  6906. internalCopy = sourceData;
  6907. data = static_cast <const char*> (internalCopy.getData());
  6908. }
  6909. }
  6910. MemoryInputStream::~MemoryInputStream()
  6911. {
  6912. }
  6913. int64 MemoryInputStream::getTotalLength()
  6914. {
  6915. return dataSize;
  6916. }
  6917. int MemoryInputStream::read (void* const buffer, const int howMany)
  6918. {
  6919. jassert (howMany >= 0);
  6920. const int num = jmin (howMany, (int) (dataSize - position));
  6921. memcpy (buffer, data + position, num);
  6922. position += num;
  6923. return (int) num;
  6924. }
  6925. bool MemoryInputStream::isExhausted()
  6926. {
  6927. return (position >= dataSize);
  6928. }
  6929. bool MemoryInputStream::setPosition (const int64 pos)
  6930. {
  6931. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6932. return true;
  6933. }
  6934. int64 MemoryInputStream::getPosition()
  6935. {
  6936. return position;
  6937. }
  6938. END_JUCE_NAMESPACE
  6939. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  6940. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  6941. BEGIN_JUCE_NAMESPACE
  6942. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  6943. const size_t blockSizeToIncreaseBy,
  6944. MemoryBlock* const memoryBlockToWriteTo)
  6945. : data (memoryBlockToWriteTo),
  6946. position (0),
  6947. size (0),
  6948. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  6949. {
  6950. if (data == 0)
  6951. dataToDelete = data = new MemoryBlock (initialSize);
  6952. else
  6953. data->setSize (initialSize, false);
  6954. }
  6955. MemoryOutputStream::~MemoryOutputStream()
  6956. {
  6957. flush();
  6958. }
  6959. void MemoryOutputStream::flush()
  6960. {
  6961. if (dataToDelete == 0)
  6962. data->setSize (size, false);
  6963. }
  6964. void MemoryOutputStream::reset() throw()
  6965. {
  6966. position = 0;
  6967. size = 0;
  6968. }
  6969. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  6970. {
  6971. if (howMany > 0)
  6972. {
  6973. size_t storageNeeded = position + howMany;
  6974. if (storageNeeded >= data->getSize())
  6975. {
  6976. // if we need more space, increase the block by at least 10%..
  6977. storageNeeded += jmax (blockSize, storageNeeded / 10);
  6978. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  6979. data->ensureSize (storageNeeded);
  6980. }
  6981. data->copyFrom (buffer, (int) position, howMany);
  6982. position += howMany;
  6983. size = jmax (size, position);
  6984. }
  6985. return true;
  6986. }
  6987. const char* MemoryOutputStream::getData() const throw()
  6988. {
  6989. char* const d = static_cast <char*> (data->getData());
  6990. if (data->getSize() > size)
  6991. d [size] = 0;
  6992. return d;
  6993. }
  6994. bool MemoryOutputStream::setPosition (int64 newPosition)
  6995. {
  6996. if (newPosition <= (int64) size)
  6997. {
  6998. // ok to seek backwards
  6999. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7000. return true;
  7001. }
  7002. else
  7003. {
  7004. // trying to make it bigger isn't a good thing to do..
  7005. return false;
  7006. }
  7007. }
  7008. const String MemoryOutputStream::toUTF8() const
  7009. {
  7010. return String (getData(), getDataSize());
  7011. }
  7012. END_JUCE_NAMESPACE
  7013. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7014. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7015. BEGIN_JUCE_NAMESPACE
  7016. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7017. const int64 startPositionInSourceStream_,
  7018. const int64 lengthOfSourceStream_,
  7019. const bool deleteSourceWhenDestroyed) throw()
  7020. : source (sourceStream),
  7021. startPositionInSourceStream (startPositionInSourceStream_),
  7022. lengthOfSourceStream (lengthOfSourceStream_)
  7023. {
  7024. if (deleteSourceWhenDestroyed)
  7025. sourceToDelete = source;
  7026. setPosition (0);
  7027. }
  7028. SubregionStream::~SubregionStream() throw()
  7029. {
  7030. }
  7031. int64 SubregionStream::getTotalLength()
  7032. {
  7033. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7034. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7035. : srcLen;
  7036. }
  7037. int64 SubregionStream::getPosition()
  7038. {
  7039. return source->getPosition() - startPositionInSourceStream;
  7040. }
  7041. bool SubregionStream::setPosition (int64 newPosition)
  7042. {
  7043. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7044. }
  7045. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7046. {
  7047. if (lengthOfSourceStream < 0)
  7048. {
  7049. return source->read (destBuffer, maxBytesToRead);
  7050. }
  7051. else
  7052. {
  7053. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7054. if (maxBytesToRead <= 0)
  7055. return 0;
  7056. return source->read (destBuffer, maxBytesToRead);
  7057. }
  7058. }
  7059. bool SubregionStream::isExhausted()
  7060. {
  7061. if (lengthOfSourceStream >= 0)
  7062. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7063. else
  7064. return source->isExhausted();
  7065. }
  7066. END_JUCE_NAMESPACE
  7067. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7068. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7069. BEGIN_JUCE_NAMESPACE
  7070. PerformanceCounter::PerformanceCounter (const String& name_,
  7071. int runsPerPrintout,
  7072. const File& loggingFile)
  7073. : name (name_),
  7074. numRuns (0),
  7075. runsPerPrint (runsPerPrintout),
  7076. totalTime (0),
  7077. outputFile (loggingFile)
  7078. {
  7079. if (outputFile != File::nonexistent)
  7080. {
  7081. String s ("**** Counter for \"");
  7082. s << name_ << "\" started at: "
  7083. << Time::getCurrentTime().toString (true, true)
  7084. << "\r\n";
  7085. outputFile.appendText (s, false, false);
  7086. }
  7087. }
  7088. PerformanceCounter::~PerformanceCounter()
  7089. {
  7090. printStatistics();
  7091. }
  7092. void PerformanceCounter::start()
  7093. {
  7094. started = Time::getHighResolutionTicks();
  7095. }
  7096. void PerformanceCounter::stop()
  7097. {
  7098. const int64 now = Time::getHighResolutionTicks();
  7099. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7100. if (++numRuns == runsPerPrint)
  7101. printStatistics();
  7102. }
  7103. void PerformanceCounter::printStatistics()
  7104. {
  7105. if (numRuns > 0)
  7106. {
  7107. String s ("Performance count for \"");
  7108. s << name << "\" - average over " << numRuns << " run(s) = ";
  7109. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7110. if (micros > 10000)
  7111. s << (micros/1000) << " millisecs";
  7112. else
  7113. s << micros << " microsecs";
  7114. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7115. Logger::outputDebugString (s);
  7116. s << "\r\n";
  7117. if (outputFile != File::nonexistent)
  7118. outputFile.appendText (s, false, false);
  7119. numRuns = 0;
  7120. totalTime = 0;
  7121. }
  7122. }
  7123. END_JUCE_NAMESPACE
  7124. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7125. /*** Start of inlined file: juce_Uuid.cpp ***/
  7126. BEGIN_JUCE_NAMESPACE
  7127. Uuid::Uuid()
  7128. {
  7129. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7130. // to make it very very unlikely that two UUIDs will ever be the same..
  7131. static int64 macAddresses[2];
  7132. static bool hasCheckedMacAddresses = false;
  7133. if (! hasCheckedMacAddresses)
  7134. {
  7135. hasCheckedMacAddresses = true;
  7136. SystemStats::getMACAddresses (macAddresses, 2);
  7137. }
  7138. value.asInt64[0] = macAddresses[0];
  7139. value.asInt64[1] = macAddresses[1];
  7140. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7141. // whose seed will carry over between calls to this method.
  7142. Random r (macAddresses[0] ^ macAddresses[1]
  7143. ^ Random::getSystemRandom().nextInt64());
  7144. for (int i = 4; --i >= 0;)
  7145. {
  7146. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7147. value.asInt[i] ^= r.nextInt();
  7148. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7149. }
  7150. }
  7151. Uuid::~Uuid() throw()
  7152. {
  7153. }
  7154. Uuid::Uuid (const Uuid& other)
  7155. : value (other.value)
  7156. {
  7157. }
  7158. Uuid& Uuid::operator= (const Uuid& other)
  7159. {
  7160. value = other.value;
  7161. return *this;
  7162. }
  7163. bool Uuid::operator== (const Uuid& other) const
  7164. {
  7165. return value.asInt64[0] == other.value.asInt64[0]
  7166. && value.asInt64[1] == other.value.asInt64[1];
  7167. }
  7168. bool Uuid::operator!= (const Uuid& other) const
  7169. {
  7170. return ! operator== (other);
  7171. }
  7172. bool Uuid::isNull() const throw()
  7173. {
  7174. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7175. }
  7176. const String Uuid::toString() const
  7177. {
  7178. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7179. }
  7180. Uuid::Uuid (const String& uuidString)
  7181. {
  7182. operator= (uuidString);
  7183. }
  7184. Uuid& Uuid::operator= (const String& uuidString)
  7185. {
  7186. MemoryBlock mb;
  7187. mb.loadFromHexString (uuidString);
  7188. mb.ensureSize (sizeof (value.asBytes), true);
  7189. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7190. return *this;
  7191. }
  7192. Uuid::Uuid (const uint8* const rawData)
  7193. {
  7194. operator= (rawData);
  7195. }
  7196. Uuid& Uuid::operator= (const uint8* const rawData)
  7197. {
  7198. if (rawData != 0)
  7199. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7200. else
  7201. zeromem (value.asBytes, sizeof (value.asBytes));
  7202. return *this;
  7203. }
  7204. END_JUCE_NAMESPACE
  7205. /*** End of inlined file: juce_Uuid.cpp ***/
  7206. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7207. BEGIN_JUCE_NAMESPACE
  7208. class ZipFile::ZipEntryInfo
  7209. {
  7210. public:
  7211. ZipFile::ZipEntry entry;
  7212. int streamOffset;
  7213. int compressedSize;
  7214. bool compressed;
  7215. };
  7216. class ZipFile::ZipInputStream : public InputStream
  7217. {
  7218. public:
  7219. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7220. : file (file_),
  7221. zipEntryInfo (zei),
  7222. pos (0),
  7223. headerSize (0),
  7224. inputStream (0)
  7225. {
  7226. inputStream = file_.inputStream;
  7227. if (file_.inputSource != 0)
  7228. {
  7229. inputStream = file.inputSource->createInputStream();
  7230. }
  7231. else
  7232. {
  7233. #if JUCE_DEBUG
  7234. file_.numOpenStreams++;
  7235. #endif
  7236. }
  7237. char buffer [30];
  7238. if (inputStream != 0
  7239. && inputStream->setPosition (zei.streamOffset)
  7240. && inputStream->read (buffer, 30) == 30
  7241. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7242. {
  7243. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7244. + ByteOrder::littleEndianShort (buffer + 28);
  7245. }
  7246. }
  7247. ~ZipInputStream() throw()
  7248. {
  7249. #if JUCE_DEBUG
  7250. if (inputStream != 0 && inputStream == file.inputStream)
  7251. file.numOpenStreams--;
  7252. #endif
  7253. if (inputStream != file.inputStream)
  7254. delete inputStream;
  7255. }
  7256. int64 getTotalLength() throw()
  7257. {
  7258. return zipEntryInfo.compressedSize;
  7259. }
  7260. int read (void* buffer, int howMany) throw()
  7261. {
  7262. if (headerSize <= 0)
  7263. return 0;
  7264. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7265. if (inputStream == 0)
  7266. return 0;
  7267. int num;
  7268. if (inputStream == file.inputStream)
  7269. {
  7270. const ScopedLock sl (file.lock);
  7271. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7272. num = inputStream->read (buffer, howMany);
  7273. }
  7274. else
  7275. {
  7276. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7277. num = inputStream->read (buffer, howMany);
  7278. }
  7279. pos += num;
  7280. return num;
  7281. }
  7282. bool isExhausted() throw()
  7283. {
  7284. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7285. }
  7286. int64 getPosition() throw()
  7287. {
  7288. return pos;
  7289. }
  7290. bool setPosition (int64 newPos) throw()
  7291. {
  7292. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7293. return true;
  7294. }
  7295. private:
  7296. ZipFile& file;
  7297. ZipEntryInfo zipEntryInfo;
  7298. int64 pos;
  7299. int headerSize;
  7300. InputStream* inputStream;
  7301. ZipInputStream (const ZipInputStream&);
  7302. ZipInputStream& operator= (const ZipInputStream&);
  7303. };
  7304. ZipFile::ZipFile (InputStream* const source_,
  7305. const bool deleteStreamWhenDestroyed) throw()
  7306. : inputStream (source_)
  7307. #if JUCE_DEBUG
  7308. , numOpenStreams (0)
  7309. #endif
  7310. {
  7311. if (deleteStreamWhenDestroyed)
  7312. streamToDelete = inputStream;
  7313. init();
  7314. }
  7315. ZipFile::ZipFile (const File& file)
  7316. : inputStream (0)
  7317. #if JUCE_DEBUG
  7318. , numOpenStreams (0)
  7319. #endif
  7320. {
  7321. inputSource = new FileInputSource (file);
  7322. init();
  7323. }
  7324. ZipFile::ZipFile (InputSource* const inputSource_)
  7325. : inputStream (0),
  7326. inputSource (inputSource_)
  7327. #if JUCE_DEBUG
  7328. , numOpenStreams (0)
  7329. #endif
  7330. {
  7331. init();
  7332. }
  7333. ZipFile::~ZipFile() throw()
  7334. {
  7335. #if JUCE_DEBUG
  7336. entries.clear();
  7337. // If you hit this assertion, it means you've created a stream to read
  7338. // one of the items in the zipfile, but you've forgotten to delete that
  7339. // stream object before deleting the file.. Streams can't be kept open
  7340. // after the file is deleted because they need to share the input
  7341. // stream that the file uses to read itself.
  7342. jassert (numOpenStreams == 0);
  7343. #endif
  7344. }
  7345. int ZipFile::getNumEntries() const throw()
  7346. {
  7347. return entries.size();
  7348. }
  7349. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7350. {
  7351. ZipEntryInfo* const zei = entries [index];
  7352. return zei != 0 ? &(zei->entry) : 0;
  7353. }
  7354. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7355. {
  7356. for (int i = 0; i < entries.size(); ++i)
  7357. if (entries.getUnchecked (i)->entry.filename == fileName)
  7358. return i;
  7359. return -1;
  7360. }
  7361. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7362. {
  7363. return getEntry (getIndexOfFileName (fileName));
  7364. }
  7365. InputStream* ZipFile::createStreamForEntry (const int index)
  7366. {
  7367. ZipEntryInfo* const zei = entries[index];
  7368. InputStream* stream = 0;
  7369. if (zei != 0)
  7370. {
  7371. stream = new ZipInputStream (*this, *zei);
  7372. if (zei->compressed)
  7373. {
  7374. stream = new GZIPDecompressorInputStream (stream, true, true,
  7375. zei->entry.uncompressedSize);
  7376. // (much faster to unzip in big blocks using a buffer..)
  7377. stream = new BufferedInputStream (stream, 32768, true);
  7378. }
  7379. }
  7380. return stream;
  7381. }
  7382. class ZipFile::ZipFilenameComparator
  7383. {
  7384. public:
  7385. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7386. {
  7387. return first->entry.filename.compare (second->entry.filename);
  7388. }
  7389. };
  7390. void ZipFile::sortEntriesByFilename()
  7391. {
  7392. ZipFilenameComparator sorter;
  7393. entries.sort (sorter);
  7394. }
  7395. void ZipFile::init()
  7396. {
  7397. ScopedPointer <InputStream> toDelete;
  7398. InputStream* in = inputStream;
  7399. if (inputSource != 0)
  7400. {
  7401. in = inputSource->createInputStream();
  7402. toDelete = in;
  7403. }
  7404. if (in != 0)
  7405. {
  7406. int numEntries = 0;
  7407. int pos = findEndOfZipEntryTable (in, numEntries);
  7408. if (pos >= 0 && pos < in->getTotalLength())
  7409. {
  7410. const int size = (int) (in->getTotalLength() - pos);
  7411. in->setPosition (pos);
  7412. MemoryBlock headerData;
  7413. if (in->readIntoMemoryBlock (headerData, size) == size)
  7414. {
  7415. pos = 0;
  7416. for (int i = 0; i < numEntries; ++i)
  7417. {
  7418. if (pos + 46 > size)
  7419. break;
  7420. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7421. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7422. if (pos + 46 + fileNameLen > size)
  7423. break;
  7424. ZipEntryInfo* const zei = new ZipEntryInfo();
  7425. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7426. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7427. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7428. const int year = 1980 + (date >> 9);
  7429. const int month = ((date >> 5) & 15) - 1;
  7430. const int day = date & 31;
  7431. const int hours = time >> 11;
  7432. const int minutes = (time >> 5) & 63;
  7433. const int seconds = (time & 31) << 1;
  7434. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7435. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7436. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7437. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7438. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7439. entries.add (zei);
  7440. pos += 46 + fileNameLen
  7441. + ByteOrder::littleEndianShort (buffer + 30)
  7442. + ByteOrder::littleEndianShort (buffer + 32);
  7443. }
  7444. }
  7445. }
  7446. }
  7447. }
  7448. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7449. {
  7450. BufferedInputStream in (input, 8192, false);
  7451. in.setPosition (in.getTotalLength());
  7452. int64 pos = in.getPosition();
  7453. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7454. char buffer [32];
  7455. zeromem (buffer, sizeof (buffer));
  7456. while (pos > lowestPos)
  7457. {
  7458. in.setPosition (pos - 22);
  7459. pos = in.getPosition();
  7460. memcpy (buffer + 22, buffer, 4);
  7461. if (in.read (buffer, 22) != 22)
  7462. return 0;
  7463. for (int i = 0; i < 22; ++i)
  7464. {
  7465. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7466. {
  7467. in.setPosition (pos + i);
  7468. in.read (buffer, 22);
  7469. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7470. return ByteOrder::littleEndianInt (buffer + 16);
  7471. }
  7472. }
  7473. }
  7474. return 0;
  7475. }
  7476. void ZipFile::uncompressTo (const File& targetDirectory,
  7477. const bool shouldOverwriteFiles)
  7478. {
  7479. for (int i = 0; i < entries.size(); ++i)
  7480. {
  7481. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7482. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7483. if (zei.filename.endsWithChar ('/'))
  7484. {
  7485. targetFile.createDirectory(); // (entry is a directory, not a file)
  7486. }
  7487. else
  7488. {
  7489. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7490. if (in != 0)
  7491. {
  7492. if (shouldOverwriteFiles)
  7493. targetFile.deleteFile();
  7494. if ((! targetFile.exists())
  7495. && targetFile.getParentDirectory().createDirectory())
  7496. {
  7497. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7498. if (out != 0)
  7499. {
  7500. out->writeFromInputStream (*in, -1);
  7501. out = 0;
  7502. targetFile.setCreationTime (zei.fileTime);
  7503. targetFile.setLastModificationTime (zei.fileTime);
  7504. targetFile.setLastAccessTime (zei.fileTime);
  7505. }
  7506. }
  7507. }
  7508. }
  7509. }
  7510. }
  7511. END_JUCE_NAMESPACE
  7512. /*** End of inlined file: juce_ZipFile.cpp ***/
  7513. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7514. #ifdef _MSC_VER
  7515. #pragma warning (disable: 4514 4996)
  7516. #pragma warning (push)
  7517. #endif
  7518. #include <cwctype>
  7519. #include <cctype>
  7520. #include <ctime>
  7521. #ifdef _MSC_VER
  7522. #pragma warning (pop)
  7523. #endif
  7524. BEGIN_JUCE_NAMESPACE
  7525. int CharacterFunctions::length (const char* const s) throw()
  7526. {
  7527. return (int) strlen (s);
  7528. }
  7529. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7530. {
  7531. return (int) wcslen (s);
  7532. }
  7533. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7534. {
  7535. strncpy (dest, src, maxChars);
  7536. }
  7537. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7538. {
  7539. wcsncpy (dest, src, maxChars);
  7540. }
  7541. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7542. {
  7543. mbstowcs (dest, src, maxChars);
  7544. }
  7545. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7546. {
  7547. wcstombs (dest, src, maxChars);
  7548. }
  7549. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7550. {
  7551. return (int) wcstombs (0, src, 0);
  7552. }
  7553. void CharacterFunctions::append (char* dest, const char* src) throw()
  7554. {
  7555. strcat (dest, src);
  7556. }
  7557. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7558. {
  7559. wcscat (dest, src);
  7560. }
  7561. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7562. {
  7563. return strcmp (s1, s2);
  7564. }
  7565. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7566. {
  7567. jassert (s1 != 0 && s2 != 0);
  7568. return wcscmp (s1, s2);
  7569. }
  7570. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7571. {
  7572. jassert (s1 != 0 && s2 != 0);
  7573. return strncmp (s1, s2, maxChars);
  7574. }
  7575. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7576. {
  7577. jassert (s1 != 0 && s2 != 0);
  7578. return wcsncmp (s1, s2, maxChars);
  7579. }
  7580. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7581. {
  7582. jassert (s1 != 0 && s2 != 0);
  7583. for (;;)
  7584. {
  7585. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7586. if (diff != 0)
  7587. return diff;
  7588. else if (*s1 == 0)
  7589. break;
  7590. ++s1;
  7591. ++s2;
  7592. }
  7593. return 0;
  7594. }
  7595. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7596. {
  7597. return -compare (s2, s1);
  7598. }
  7599. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7600. {
  7601. jassert (s1 != 0 && s2 != 0);
  7602. #if JUCE_WIN32
  7603. return stricmp (s1, s2);
  7604. #else
  7605. return strcasecmp (s1, s2);
  7606. #endif
  7607. }
  7608. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7609. {
  7610. jassert (s1 != 0 && s2 != 0);
  7611. #if JUCE_WIN32
  7612. return _wcsicmp (s1, s2);
  7613. #else
  7614. for (;;)
  7615. {
  7616. if (*s1 != *s2)
  7617. {
  7618. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7619. if (diff != 0)
  7620. return diff < 0 ? -1 : 1;
  7621. }
  7622. else if (*s1 == 0)
  7623. break;
  7624. ++s1;
  7625. ++s2;
  7626. }
  7627. return 0;
  7628. #endif
  7629. }
  7630. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7631. {
  7632. jassert (s1 != 0 && s2 != 0);
  7633. for (;;)
  7634. {
  7635. if (*s1 != *s2)
  7636. {
  7637. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7638. if (diff != 0)
  7639. return diff < 0 ? -1 : 1;
  7640. }
  7641. else if (*s1 == 0)
  7642. break;
  7643. ++s1;
  7644. ++s2;
  7645. }
  7646. return 0;
  7647. }
  7648. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7649. {
  7650. jassert (s1 != 0 && s2 != 0);
  7651. #if JUCE_WIN32
  7652. return strnicmp (s1, s2, maxChars);
  7653. #else
  7654. return strncasecmp (s1, s2, maxChars);
  7655. #endif
  7656. }
  7657. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7658. {
  7659. jassert (s1 != 0 && s2 != 0);
  7660. #if JUCE_WIN32
  7661. return _wcsnicmp (s1, s2, maxChars);
  7662. #else
  7663. while (--maxChars >= 0)
  7664. {
  7665. if (*s1 != *s2)
  7666. {
  7667. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7668. if (diff != 0)
  7669. return diff < 0 ? -1 : 1;
  7670. }
  7671. else if (*s1 == 0)
  7672. break;
  7673. ++s1;
  7674. ++s2;
  7675. }
  7676. return 0;
  7677. #endif
  7678. }
  7679. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7680. {
  7681. return strstr (haystack, needle);
  7682. }
  7683. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7684. {
  7685. return wcsstr (haystack, needle);
  7686. }
  7687. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7688. {
  7689. if (haystack != 0)
  7690. {
  7691. int i = 0;
  7692. if (ignoreCase)
  7693. {
  7694. const char n1 = toLowerCase (needle);
  7695. const char n2 = toUpperCase (needle);
  7696. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7697. {
  7698. while (haystack[i] != 0)
  7699. {
  7700. if (haystack[i] == n1 || haystack[i] == n2)
  7701. return i;
  7702. ++i;
  7703. }
  7704. return -1;
  7705. }
  7706. jassert (n1 == needle);
  7707. }
  7708. while (haystack[i] != 0)
  7709. {
  7710. if (haystack[i] == needle)
  7711. return i;
  7712. ++i;
  7713. }
  7714. }
  7715. return -1;
  7716. }
  7717. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7718. {
  7719. if (haystack != 0)
  7720. {
  7721. int i = 0;
  7722. if (ignoreCase)
  7723. {
  7724. const juce_wchar n1 = toLowerCase (needle);
  7725. const juce_wchar n2 = toUpperCase (needle);
  7726. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7727. {
  7728. while (haystack[i] != 0)
  7729. {
  7730. if (haystack[i] == n1 || haystack[i] == n2)
  7731. return i;
  7732. ++i;
  7733. }
  7734. return -1;
  7735. }
  7736. jassert (n1 == needle);
  7737. }
  7738. while (haystack[i] != 0)
  7739. {
  7740. if (haystack[i] == needle)
  7741. return i;
  7742. ++i;
  7743. }
  7744. }
  7745. return -1;
  7746. }
  7747. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7748. {
  7749. jassert (haystack != 0);
  7750. int i = 0;
  7751. while (haystack[i] != 0)
  7752. {
  7753. if (haystack[i] == needle)
  7754. return i;
  7755. ++i;
  7756. }
  7757. return -1;
  7758. }
  7759. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7760. {
  7761. jassert (haystack != 0);
  7762. int i = 0;
  7763. while (haystack[i] != 0)
  7764. {
  7765. if (haystack[i] == needle)
  7766. return i;
  7767. ++i;
  7768. }
  7769. return -1;
  7770. }
  7771. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7772. {
  7773. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7774. }
  7775. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7776. {
  7777. if (allowedChars == 0)
  7778. return 0;
  7779. int i = 0;
  7780. for (;;)
  7781. {
  7782. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7783. break;
  7784. ++i;
  7785. }
  7786. return i;
  7787. }
  7788. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7789. {
  7790. return (int) strftime (dest, maxChars, format, tm);
  7791. }
  7792. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7793. {
  7794. return (int) wcsftime (dest, maxChars, format, tm);
  7795. }
  7796. int CharacterFunctions::getIntValue (const char* const s) throw()
  7797. {
  7798. return atoi (s);
  7799. }
  7800. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7801. {
  7802. #if JUCE_WIN32
  7803. return _wtoi (s);
  7804. #else
  7805. int v = 0;
  7806. while (isWhitespace (*s))
  7807. ++s;
  7808. const bool isNeg = *s == '-';
  7809. if (isNeg)
  7810. ++s;
  7811. for (;;)
  7812. {
  7813. const wchar_t c = *s++;
  7814. if (c >= '0' && c <= '9')
  7815. v = v * 10 + (int) (c - '0');
  7816. else
  7817. break;
  7818. }
  7819. return isNeg ? -v : v;
  7820. #endif
  7821. }
  7822. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7823. {
  7824. #if JUCE_LINUX
  7825. return atoll (s);
  7826. #elif defined (JUCE_WIN32)
  7827. return _atoi64 (s);
  7828. #else
  7829. int64 v = 0;
  7830. while (isWhitespace (*s))
  7831. ++s;
  7832. const bool isNeg = *s == '-';
  7833. if (isNeg)
  7834. ++s;
  7835. for (;;)
  7836. {
  7837. const char c = *s++;
  7838. if (c >= '0' && c <= '9')
  7839. v = v * 10 + (int64) (c - '0');
  7840. else
  7841. break;
  7842. }
  7843. return isNeg ? -v : v;
  7844. #endif
  7845. }
  7846. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7847. {
  7848. #if JUCE_WIN32
  7849. return _wtoi64 (s);
  7850. #else
  7851. int64 v = 0;
  7852. while (isWhitespace (*s))
  7853. ++s;
  7854. const bool isNeg = *s == '-';
  7855. if (isNeg)
  7856. ++s;
  7857. for (;;)
  7858. {
  7859. const juce_wchar c = *s++;
  7860. if (c >= '0' && c <= '9')
  7861. v = v * 10 + (int64) (c - '0');
  7862. else
  7863. break;
  7864. }
  7865. return isNeg ? -v : v;
  7866. #endif
  7867. }
  7868. static double juce_mulexp10 (const double value, int exponent) throw()
  7869. {
  7870. if (exponent == 0)
  7871. return value;
  7872. if (value == 0)
  7873. return 0;
  7874. const bool negative = (exponent < 0);
  7875. if (negative)
  7876. exponent = -exponent;
  7877. double result = 1.0, power = 10.0;
  7878. for (int bit = 1; exponent != 0; bit <<= 1)
  7879. {
  7880. if ((exponent & bit) != 0)
  7881. {
  7882. exponent ^= bit;
  7883. result *= power;
  7884. if (exponent == 0)
  7885. break;
  7886. }
  7887. power *= power;
  7888. }
  7889. return negative ? (value / result) : (value * result);
  7890. }
  7891. template <class CharType>
  7892. double juce_atof (const CharType* const original) throw()
  7893. {
  7894. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7895. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7896. int exponent = 0, decPointIndex = 0, digit = 0;
  7897. int lastDigit = 0, numSignificantDigits = 0;
  7898. bool isNegative = false, digitsFound = false;
  7899. const int maxSignificantDigits = 15 + 2;
  7900. const CharType* s = original;
  7901. while (CharacterFunctions::isWhitespace (*s))
  7902. ++s;
  7903. switch (*s)
  7904. {
  7905. case '-': isNegative = true; // fall-through..
  7906. case '+': ++s;
  7907. }
  7908. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7909. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  7910. for (;;)
  7911. {
  7912. if (CharacterFunctions::isDigit (*s))
  7913. {
  7914. lastDigit = digit;
  7915. digit = *s++ - '0';
  7916. digitsFound = true;
  7917. if (decPointIndex != 0)
  7918. exponentAdjustment[1]++;
  7919. if (numSignificantDigits == 0 && digit == 0)
  7920. continue;
  7921. if (++numSignificantDigits > maxSignificantDigits)
  7922. {
  7923. if (digit > 5)
  7924. ++accumulator [decPointIndex];
  7925. else if (digit == 5 && (lastDigit & 1) != 0)
  7926. ++accumulator [decPointIndex];
  7927. if (decPointIndex > 0)
  7928. exponentAdjustment[1]--;
  7929. else
  7930. exponentAdjustment[0]++;
  7931. while (CharacterFunctions::isDigit (*s))
  7932. {
  7933. ++s;
  7934. if (decPointIndex == 0)
  7935. exponentAdjustment[0]++;
  7936. }
  7937. }
  7938. else
  7939. {
  7940. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  7941. if (accumulator [decPointIndex] > maxAccumulatorValue)
  7942. {
  7943. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  7944. + accumulator [decPointIndex];
  7945. accumulator [decPointIndex] = 0;
  7946. exponentAccumulator [decPointIndex] = 0;
  7947. }
  7948. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  7949. exponentAccumulator [decPointIndex]++;
  7950. }
  7951. }
  7952. else if (decPointIndex == 0 && *s == '.')
  7953. {
  7954. ++s;
  7955. decPointIndex = 1;
  7956. if (numSignificantDigits > maxSignificantDigits)
  7957. {
  7958. while (CharacterFunctions::isDigit (*s))
  7959. ++s;
  7960. break;
  7961. }
  7962. }
  7963. else
  7964. {
  7965. break;
  7966. }
  7967. }
  7968. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  7969. if (decPointIndex != 0)
  7970. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  7971. if ((*s == 'e' || *s == 'E') && digitsFound)
  7972. {
  7973. bool negativeExponent = false;
  7974. switch (*++s)
  7975. {
  7976. case '-': negativeExponent = true; // fall-through..
  7977. case '+': ++s;
  7978. }
  7979. while (CharacterFunctions::isDigit (*s))
  7980. exponent = (exponent * 10) + (*s++ - '0');
  7981. if (negativeExponent)
  7982. exponent = -exponent;
  7983. }
  7984. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  7985. if (decPointIndex != 0)
  7986. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  7987. return isNegative ? -r : r;
  7988. }
  7989. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  7990. {
  7991. return juce_atof <char> (s);
  7992. }
  7993. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  7994. {
  7995. return juce_atof <juce_wchar> (s);
  7996. }
  7997. char CharacterFunctions::toUpperCase (const char character) throw()
  7998. {
  7999. return (char) toupper (character);
  8000. }
  8001. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8002. {
  8003. return towupper (character);
  8004. }
  8005. void CharacterFunctions::toUpperCase (char* s) throw()
  8006. {
  8007. #if JUCE_WIN32
  8008. strupr (s);
  8009. #else
  8010. while (*s != 0)
  8011. {
  8012. *s = toUpperCase (*s);
  8013. ++s;
  8014. }
  8015. #endif
  8016. }
  8017. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8018. {
  8019. #if JUCE_WIN32
  8020. _wcsupr (s);
  8021. #else
  8022. while (*s != 0)
  8023. {
  8024. *s = toUpperCase (*s);
  8025. ++s;
  8026. }
  8027. #endif
  8028. }
  8029. bool CharacterFunctions::isUpperCase (const char character) throw()
  8030. {
  8031. return isupper (character) != 0;
  8032. }
  8033. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8034. {
  8035. #if JUCE_WIN32
  8036. return iswupper (character) != 0;
  8037. #else
  8038. return toLowerCase (character) != character;
  8039. #endif
  8040. }
  8041. char CharacterFunctions::toLowerCase (const char character) throw()
  8042. {
  8043. return (char) tolower (character);
  8044. }
  8045. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8046. {
  8047. return towlower (character);
  8048. }
  8049. void CharacterFunctions::toLowerCase (char* s) throw()
  8050. {
  8051. #if JUCE_WIN32
  8052. strlwr (s);
  8053. #else
  8054. while (*s != 0)
  8055. {
  8056. *s = toLowerCase (*s);
  8057. ++s;
  8058. }
  8059. #endif
  8060. }
  8061. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8062. {
  8063. #if JUCE_WIN32
  8064. _wcslwr (s);
  8065. #else
  8066. while (*s != 0)
  8067. {
  8068. *s = toLowerCase (*s);
  8069. ++s;
  8070. }
  8071. #endif
  8072. }
  8073. bool CharacterFunctions::isLowerCase (const char character) throw()
  8074. {
  8075. return islower (character) != 0;
  8076. }
  8077. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8078. {
  8079. #if JUCE_WIN32
  8080. return iswlower (character) != 0;
  8081. #else
  8082. return toUpperCase (character) != character;
  8083. #endif
  8084. }
  8085. bool CharacterFunctions::isWhitespace (const char character) throw()
  8086. {
  8087. return character == ' ' || (character <= 13 && character >= 9);
  8088. }
  8089. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8090. {
  8091. return iswspace (character) != 0;
  8092. }
  8093. bool CharacterFunctions::isDigit (const char character) throw()
  8094. {
  8095. return (character >= '0' && character <= '9');
  8096. }
  8097. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8098. {
  8099. return iswdigit (character) != 0;
  8100. }
  8101. bool CharacterFunctions::isLetter (const char character) throw()
  8102. {
  8103. return (character >= 'a' && character <= 'z')
  8104. || (character >= 'A' && character <= 'Z');
  8105. }
  8106. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8107. {
  8108. return iswalpha (character) != 0;
  8109. }
  8110. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8111. {
  8112. return (character >= 'a' && character <= 'z')
  8113. || (character >= 'A' && character <= 'Z')
  8114. || (character >= '0' && character <= '9');
  8115. }
  8116. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8117. {
  8118. return iswalnum (character) != 0;
  8119. }
  8120. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8121. {
  8122. if (digit >= '0' && digit <= '9')
  8123. return digit - '0';
  8124. else if (digit >= 'a' && digit <= 'f')
  8125. return digit - ('a' - 10);
  8126. else if (digit >= 'A' && digit <= 'F')
  8127. return digit - ('A' - 10);
  8128. return -1;
  8129. }
  8130. END_JUCE_NAMESPACE
  8131. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8132. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8133. BEGIN_JUCE_NAMESPACE
  8134. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8135. {
  8136. loadFromText (fileContents);
  8137. }
  8138. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8139. {
  8140. loadFromText (fileToLoad.loadFileAsString());
  8141. }
  8142. LocalisedStrings::~LocalisedStrings()
  8143. {
  8144. }
  8145. const String LocalisedStrings::translate (const String& text) const
  8146. {
  8147. return translations.getValue (text, text);
  8148. }
  8149. static int findCloseQuote (const String& text, int startPos)
  8150. {
  8151. juce_wchar lastChar = 0;
  8152. for (;;)
  8153. {
  8154. const juce_wchar c = text [startPos];
  8155. if (c == 0 || (c == '"' && lastChar != '\\'))
  8156. break;
  8157. lastChar = c;
  8158. ++startPos;
  8159. }
  8160. return startPos;
  8161. }
  8162. static const String unescapeString (const String& s)
  8163. {
  8164. return s.replace ("\\\"", "\"")
  8165. .replace ("\\\'", "\'")
  8166. .replace ("\\t", "\t")
  8167. .replace ("\\r", "\r")
  8168. .replace ("\\n", "\n");
  8169. }
  8170. void LocalisedStrings::loadFromText (const String& fileContents)
  8171. {
  8172. StringArray lines;
  8173. lines.addLines (fileContents);
  8174. for (int i = 0; i < lines.size(); ++i)
  8175. {
  8176. String line (lines[i].trim());
  8177. if (line.startsWithChar ('"'))
  8178. {
  8179. int closeQuote = findCloseQuote (line, 1);
  8180. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8181. if (originalText.isNotEmpty())
  8182. {
  8183. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8184. closeQuote = findCloseQuote (line, openingQuote + 1);
  8185. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8186. if (newText.isNotEmpty())
  8187. translations.set (originalText, newText);
  8188. }
  8189. }
  8190. else if (line.startsWithIgnoreCase ("language:"))
  8191. {
  8192. languageName = line.substring (9).trim();
  8193. }
  8194. else if (line.startsWithIgnoreCase ("countries:"))
  8195. {
  8196. countryCodes.addTokens (line.substring (10).trim(), true);
  8197. countryCodes.trim();
  8198. countryCodes.removeEmptyStrings();
  8199. }
  8200. }
  8201. }
  8202. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8203. {
  8204. translations.setIgnoresCase (shouldIgnoreCase);
  8205. }
  8206. static CriticalSection currentMappingsLock;
  8207. static LocalisedStrings* currentMappings = 0;
  8208. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8209. {
  8210. const ScopedLock sl (currentMappingsLock);
  8211. delete currentMappings;
  8212. currentMappings = newTranslations;
  8213. }
  8214. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8215. {
  8216. return currentMappings;
  8217. }
  8218. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8219. {
  8220. const ScopedLock sl (currentMappingsLock);
  8221. if (currentMappings != 0)
  8222. return currentMappings->translate (text);
  8223. return text;
  8224. }
  8225. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8226. {
  8227. return translateWithCurrentMappings (String (text));
  8228. }
  8229. END_JUCE_NAMESPACE
  8230. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8231. /*** Start of inlined file: juce_String.cpp ***/
  8232. #ifdef _MSC_VER
  8233. #pragma warning (push)
  8234. #pragma warning (disable: 4514)
  8235. #endif
  8236. #include <locale>
  8237. #if JUCE_MSVC
  8238. #include <float.h>
  8239. #endif
  8240. BEGIN_JUCE_NAMESPACE
  8241. #ifdef _MSC_VER
  8242. #pragma warning (pop)
  8243. #endif
  8244. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8245. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8246. #endif
  8247. class StringHolder
  8248. {
  8249. public:
  8250. StringHolder()
  8251. : refCount (0x3fffffff), allocatedNumChars (0)
  8252. {
  8253. text[0] = 0;
  8254. }
  8255. static juce_wchar* createUninitialised (const size_t numChars)
  8256. {
  8257. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8258. s->refCount.value = 0;
  8259. s->allocatedNumChars = numChars;
  8260. return &(s->text[0]);
  8261. }
  8262. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8263. {
  8264. juce_wchar* const dest = createUninitialised (numChars);
  8265. copyChars (dest, src, numChars);
  8266. return dest;
  8267. }
  8268. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8269. {
  8270. juce_wchar* const dest = createUninitialised (numChars);
  8271. CharacterFunctions::copy (dest, src, (int) numChars);
  8272. dest [numChars] = 0;
  8273. return dest;
  8274. }
  8275. static inline juce_wchar* getEmpty() throw()
  8276. {
  8277. return &(empty.text[0]);
  8278. }
  8279. static void retain (juce_wchar* const text) throw()
  8280. {
  8281. ++(bufferFromText (text)->refCount);
  8282. }
  8283. static inline void release (StringHolder* const b) throw()
  8284. {
  8285. if (--(b->refCount) == -1 && b != &empty)
  8286. delete[] reinterpret_cast <char*> (b);
  8287. }
  8288. static void release (juce_wchar* const text) throw()
  8289. {
  8290. release (bufferFromText (text));
  8291. }
  8292. static juce_wchar* makeUnique (juce_wchar* const text)
  8293. {
  8294. StringHolder* const b = bufferFromText (text);
  8295. if (b->refCount.get() <= 0)
  8296. return text;
  8297. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8298. release (b);
  8299. return newText;
  8300. }
  8301. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8302. {
  8303. StringHolder* const b = bufferFromText (text);
  8304. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8305. return text;
  8306. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8307. copyChars (newText, text, b->allocatedNumChars);
  8308. release (b);
  8309. return newText;
  8310. }
  8311. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8312. {
  8313. return bufferFromText (text)->allocatedNumChars;
  8314. }
  8315. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8316. {
  8317. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8318. dest [numChars] = 0;
  8319. }
  8320. Atomic<int> refCount;
  8321. size_t allocatedNumChars;
  8322. juce_wchar text[1];
  8323. static StringHolder empty;
  8324. private:
  8325. static inline StringHolder* bufferFromText (void* const text) throw()
  8326. {
  8327. // (Can't use offsetof() here because of warnings about this not being a POD)
  8328. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8329. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8330. }
  8331. };
  8332. StringHolder StringHolder::empty;
  8333. const String String::empty;
  8334. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8335. {
  8336. jassert (t[numChars] == 0); // must have a null terminator
  8337. text = StringHolder::createCopy (t, numChars);
  8338. }
  8339. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8340. {
  8341. if (numExtraChars > 0)
  8342. {
  8343. const int oldLen = length();
  8344. const int newTotalLen = oldLen + numExtraChars;
  8345. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8346. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8347. }
  8348. }
  8349. void String::preallocateStorage (const size_t numChars)
  8350. {
  8351. text = StringHolder::makeUniqueWithSize (text, numChars);
  8352. }
  8353. String::String() throw()
  8354. : text (StringHolder::getEmpty())
  8355. {
  8356. }
  8357. String::~String() throw()
  8358. {
  8359. StringHolder::release (text);
  8360. }
  8361. String::String (const String& other) throw()
  8362. : text (other.text)
  8363. {
  8364. StringHolder::retain (text);
  8365. }
  8366. void String::swapWith (String& other) throw()
  8367. {
  8368. swapVariables (text, other.text);
  8369. }
  8370. String& String::operator= (const String& other) throw()
  8371. {
  8372. juce_wchar* const newText = other.text;
  8373. StringHolder::retain (newText);
  8374. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8375. return *this;
  8376. }
  8377. String::String (const size_t numChars, const int /*dummyVariable*/)
  8378. : text (StringHolder::createUninitialised (numChars))
  8379. {
  8380. }
  8381. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8382. {
  8383. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8384. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8385. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8386. }
  8387. String::String (const char* const t)
  8388. {
  8389. if (t != 0 && *t != 0)
  8390. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8391. else
  8392. text = StringHolder::getEmpty();
  8393. }
  8394. String::String (const juce_wchar* const t)
  8395. {
  8396. if (t != 0 && *t != 0)
  8397. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8398. else
  8399. text = StringHolder::getEmpty();
  8400. }
  8401. String::String (const char* const t, const size_t maxChars)
  8402. {
  8403. int i;
  8404. for (i = 0; (size_t) i < maxChars; ++i)
  8405. if (t[i] == 0)
  8406. break;
  8407. if (i > 0)
  8408. text = StringHolder::createCopy (t, i);
  8409. else
  8410. text = StringHolder::getEmpty();
  8411. }
  8412. String::String (const juce_wchar* const t, const size_t maxChars)
  8413. {
  8414. int i;
  8415. for (i = 0; (size_t) i < maxChars; ++i)
  8416. if (t[i] == 0)
  8417. break;
  8418. if (i > 0)
  8419. text = StringHolder::createCopy (t, i);
  8420. else
  8421. text = StringHolder::getEmpty();
  8422. }
  8423. const String String::charToString (const juce_wchar character)
  8424. {
  8425. String result ((size_t) 1, (int) 0);
  8426. result.text[0] = character;
  8427. result.text[1] = 0;
  8428. return result;
  8429. }
  8430. namespace NumberToStringConverters
  8431. {
  8432. // pass in a pointer to the END of a buffer..
  8433. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8434. {
  8435. *--t = 0;
  8436. int64 v = (n >= 0) ? n : -n;
  8437. do
  8438. {
  8439. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8440. v /= 10;
  8441. } while (v > 0);
  8442. if (n < 0)
  8443. *--t = '-';
  8444. return t;
  8445. }
  8446. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8447. {
  8448. *--t = 0;
  8449. do
  8450. {
  8451. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8452. v /= 10;
  8453. } while (v > 0);
  8454. return t;
  8455. }
  8456. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8457. {
  8458. if (n == (int) 0x80000000) // (would cause an overflow)
  8459. return int64ToString (t, n);
  8460. *--t = 0;
  8461. int v = abs (n);
  8462. do
  8463. {
  8464. *--t = (juce_wchar) ('0' + (v % 10));
  8465. v /= 10;
  8466. } while (v > 0);
  8467. if (n < 0)
  8468. *--t = '-';
  8469. return t;
  8470. }
  8471. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8472. {
  8473. *--t = 0;
  8474. do
  8475. {
  8476. *--t = (juce_wchar) ('0' + (v % 10));
  8477. v /= 10;
  8478. } while (v > 0);
  8479. return t;
  8480. }
  8481. static juce_wchar getDecimalPoint()
  8482. {
  8483. #if JUCE_WINDOWS && _MSC_VER < 1400
  8484. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8485. #else
  8486. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8487. #endif
  8488. return dp;
  8489. }
  8490. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8491. {
  8492. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8493. {
  8494. juce_wchar* const end = buffer + numChars;
  8495. juce_wchar* t = end;
  8496. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8497. *--t = (juce_wchar) 0;
  8498. while (numDecPlaces >= 0 || v > 0)
  8499. {
  8500. if (numDecPlaces == 0)
  8501. *--t = getDecimalPoint();
  8502. *--t = (juce_wchar) ('0' + (v % 10));
  8503. v /= 10;
  8504. --numDecPlaces;
  8505. }
  8506. if (n < 0)
  8507. *--t = '-';
  8508. len = end - t - 1;
  8509. return t;
  8510. }
  8511. else
  8512. {
  8513. #if JUCE_WIN32
  8514. #if _MSC_VER <= 1400
  8515. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8516. #else
  8517. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8518. #endif
  8519. #else
  8520. len = swprintf (buffer, numChars, L"%.9g", n);
  8521. #endif
  8522. return buffer;
  8523. }
  8524. }
  8525. }
  8526. String::String (const int number)
  8527. {
  8528. juce_wchar buffer [16];
  8529. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8530. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8531. createInternal (start, end - start - 1);
  8532. }
  8533. String::String (const unsigned int number)
  8534. {
  8535. juce_wchar buffer [16];
  8536. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8537. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8538. createInternal (start, end - start - 1);
  8539. }
  8540. String::String (const short number)
  8541. {
  8542. juce_wchar buffer [16];
  8543. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8544. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8545. createInternal (start, end - start - 1);
  8546. }
  8547. String::String (const unsigned short number)
  8548. {
  8549. juce_wchar buffer [16];
  8550. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8551. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8552. createInternal (start, end - start - 1);
  8553. }
  8554. String::String (const int64 number)
  8555. {
  8556. juce_wchar buffer [32];
  8557. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8558. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8559. createInternal (start, end - start - 1);
  8560. }
  8561. String::String (const uint64 number)
  8562. {
  8563. juce_wchar buffer [32];
  8564. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8565. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8566. createInternal (start, end - start - 1);
  8567. }
  8568. String::String (const float number, const int numberOfDecimalPlaces)
  8569. {
  8570. juce_wchar buffer [48];
  8571. size_t len;
  8572. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8573. createInternal (start, len);
  8574. }
  8575. String::String (const double number, const int numberOfDecimalPlaces)
  8576. {
  8577. juce_wchar buffer [48];
  8578. size_t len;
  8579. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8580. createInternal (start, len);
  8581. }
  8582. int String::length() const throw()
  8583. {
  8584. return CharacterFunctions::length (text);
  8585. }
  8586. int String::hashCode() const throw()
  8587. {
  8588. const juce_wchar* t = text;
  8589. int result = 0;
  8590. while (*t != (juce_wchar) 0)
  8591. result = 31 * result + *t++;
  8592. return result;
  8593. }
  8594. int64 String::hashCode64() const throw()
  8595. {
  8596. const juce_wchar* t = text;
  8597. int64 result = 0;
  8598. while (*t != (juce_wchar) 0)
  8599. result = 101 * result + *t++;
  8600. return result;
  8601. }
  8602. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8603. {
  8604. return string1.compare (string2) == 0;
  8605. }
  8606. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8607. {
  8608. return string1.compare (string2) == 0;
  8609. }
  8610. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8611. {
  8612. return string1.compare (string2) == 0;
  8613. }
  8614. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8615. {
  8616. return string1.compare (string2) != 0;
  8617. }
  8618. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8619. {
  8620. return string1.compare (string2) != 0;
  8621. }
  8622. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8623. {
  8624. return string1.compare (string2) != 0;
  8625. }
  8626. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8627. {
  8628. return string1.compare (string2) > 0;
  8629. }
  8630. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8631. {
  8632. return string1.compare (string2) < 0;
  8633. }
  8634. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8635. {
  8636. return string1.compare (string2) >= 0;
  8637. }
  8638. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8639. {
  8640. return string1.compare (string2) <= 0;
  8641. }
  8642. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8643. {
  8644. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8645. : isEmpty();
  8646. }
  8647. bool String::equalsIgnoreCase (const char* t) const throw()
  8648. {
  8649. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8650. : isEmpty();
  8651. }
  8652. bool String::equalsIgnoreCase (const String& other) const throw()
  8653. {
  8654. return text == other.text
  8655. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8656. }
  8657. int String::compare (const String& other) const throw()
  8658. {
  8659. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8660. }
  8661. int String::compare (const char* other) const throw()
  8662. {
  8663. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8664. }
  8665. int String::compare (const juce_wchar* other) const throw()
  8666. {
  8667. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8668. }
  8669. int String::compareIgnoreCase (const String& other) const throw()
  8670. {
  8671. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8672. }
  8673. int String::compareLexicographically (const String& other) const throw()
  8674. {
  8675. const juce_wchar* s1 = text;
  8676. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8677. ++s1;
  8678. const juce_wchar* s2 = other.text;
  8679. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8680. ++s2;
  8681. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8682. }
  8683. String& String::operator+= (const juce_wchar* const t)
  8684. {
  8685. if (t != 0)
  8686. appendInternal (t, CharacterFunctions::length (t));
  8687. return *this;
  8688. }
  8689. String& String::operator+= (const String& other)
  8690. {
  8691. if (isEmpty())
  8692. operator= (other);
  8693. else
  8694. appendInternal (other.text, other.length());
  8695. return *this;
  8696. }
  8697. String& String::operator+= (const char ch)
  8698. {
  8699. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8700. return operator+= (static_cast <const juce_wchar*> (asString));
  8701. }
  8702. String& String::operator+= (const juce_wchar ch)
  8703. {
  8704. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8705. return operator+= (static_cast <const juce_wchar*> (asString));
  8706. }
  8707. String& String::operator+= (const int number)
  8708. {
  8709. juce_wchar buffer [16];
  8710. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8711. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8712. appendInternal (start, (int) (end - start));
  8713. return *this;
  8714. }
  8715. String& String::operator+= (const unsigned int number)
  8716. {
  8717. juce_wchar buffer [16];
  8718. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8719. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8720. appendInternal (start, (int) (end - start));
  8721. return *this;
  8722. }
  8723. void String::append (const juce_wchar* const other, const int howMany)
  8724. {
  8725. if (howMany > 0)
  8726. {
  8727. int i;
  8728. for (i = 0; i < howMany; ++i)
  8729. if (other[i] == 0)
  8730. break;
  8731. appendInternal (other, i);
  8732. }
  8733. }
  8734. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8735. {
  8736. String s (string1);
  8737. return s += string2;
  8738. }
  8739. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8740. {
  8741. String s (string1);
  8742. return s += string2;
  8743. }
  8744. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8745. {
  8746. return String::charToString (string1) + string2;
  8747. }
  8748. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8749. {
  8750. return String::charToString (string1) + string2;
  8751. }
  8752. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8753. {
  8754. return string1 += string2;
  8755. }
  8756. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8757. {
  8758. return string1 += string2;
  8759. }
  8760. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8761. {
  8762. return string1 += string2;
  8763. }
  8764. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8765. {
  8766. return string1 += string2;
  8767. }
  8768. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8769. {
  8770. return string1 += string2;
  8771. }
  8772. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8773. {
  8774. return string1 += characterToAppend;
  8775. }
  8776. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8777. {
  8778. return string1 += characterToAppend;
  8779. }
  8780. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8781. {
  8782. return string1 += string2;
  8783. }
  8784. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8785. {
  8786. return string1 += string2;
  8787. }
  8788. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8789. {
  8790. return string1 += string2;
  8791. }
  8792. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8793. {
  8794. return string1 += (int) number;
  8795. }
  8796. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8797. {
  8798. return string1 += number;
  8799. }
  8800. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8801. {
  8802. return string1 += number;
  8803. }
  8804. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8805. {
  8806. return string1 += (int) number;
  8807. }
  8808. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8809. {
  8810. return string1 += (unsigned int) number;
  8811. }
  8812. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8813. {
  8814. return string1 += String (number);
  8815. }
  8816. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8817. {
  8818. return string1 += String (number);
  8819. }
  8820. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8821. {
  8822. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8823. // if lots of large, persistent strings were to be written to streams).
  8824. const int numBytes = text.getNumBytesAsUTF8();
  8825. HeapBlock<char> temp (numBytes + 1);
  8826. text.copyToUTF8 (temp, numBytes + 1);
  8827. stream.write (temp, numBytes);
  8828. return stream;
  8829. }
  8830. int String::indexOfChar (const juce_wchar character) const throw()
  8831. {
  8832. const juce_wchar* t = text;
  8833. for (;;)
  8834. {
  8835. if (*t == character)
  8836. return (int) (t - text);
  8837. if (*t++ == 0)
  8838. return -1;
  8839. }
  8840. }
  8841. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8842. {
  8843. for (int i = length(); --i >= 0;)
  8844. if (text[i] == character)
  8845. return i;
  8846. return -1;
  8847. }
  8848. int String::indexOf (const String& t) const throw()
  8849. {
  8850. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8851. return r == 0 ? -1 : (int) (r - text);
  8852. }
  8853. int String::indexOfChar (const int startIndex,
  8854. const juce_wchar character) const throw()
  8855. {
  8856. if (startIndex > 0 && startIndex >= length())
  8857. return -1;
  8858. const juce_wchar* t = text + jmax (0, startIndex);
  8859. for (;;)
  8860. {
  8861. if (*t == character)
  8862. return (int) (t - text);
  8863. if (*t == 0)
  8864. return -1;
  8865. ++t;
  8866. }
  8867. }
  8868. int String::indexOfAnyOf (const String& charactersToLookFor,
  8869. const int startIndex,
  8870. const bool ignoreCase) const throw()
  8871. {
  8872. if (startIndex > 0 && startIndex >= length())
  8873. return -1;
  8874. const juce_wchar* t = text + jmax (0, startIndex);
  8875. while (*t != 0)
  8876. {
  8877. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8878. return (int) (t - text);
  8879. ++t;
  8880. }
  8881. return -1;
  8882. }
  8883. int String::indexOf (const int startIndex, const String& other) const throw()
  8884. {
  8885. if (startIndex > 0 && startIndex >= length())
  8886. return -1;
  8887. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8888. return found == 0 ? -1 : (int) (found - text);
  8889. }
  8890. int String::indexOfIgnoreCase (const String& other) const throw()
  8891. {
  8892. if (other.isNotEmpty())
  8893. {
  8894. const int len = other.length();
  8895. const int end = length() - len;
  8896. for (int i = 0; i <= end; ++i)
  8897. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8898. return i;
  8899. }
  8900. return -1;
  8901. }
  8902. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8903. {
  8904. if (other.isNotEmpty())
  8905. {
  8906. const int len = other.length();
  8907. const int end = length() - len;
  8908. for (int i = jmax (0, startIndex); i <= end; ++i)
  8909. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8910. return i;
  8911. }
  8912. return -1;
  8913. }
  8914. int String::lastIndexOf (const String& other) const throw()
  8915. {
  8916. if (other.isNotEmpty())
  8917. {
  8918. const int len = other.length();
  8919. int i = length() - len;
  8920. if (i >= 0)
  8921. {
  8922. const juce_wchar* n = text + i;
  8923. while (i >= 0)
  8924. {
  8925. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  8926. return i;
  8927. --i;
  8928. }
  8929. }
  8930. }
  8931. return -1;
  8932. }
  8933. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  8934. {
  8935. if (other.isNotEmpty())
  8936. {
  8937. const int len = other.length();
  8938. int i = length() - len;
  8939. if (i >= 0)
  8940. {
  8941. const juce_wchar* n = text + i;
  8942. while (i >= 0)
  8943. {
  8944. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  8945. return i;
  8946. --i;
  8947. }
  8948. }
  8949. }
  8950. return -1;
  8951. }
  8952. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  8953. {
  8954. for (int i = length(); --i >= 0;)
  8955. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  8956. return i;
  8957. return -1;
  8958. }
  8959. bool String::contains (const String& other) const throw()
  8960. {
  8961. return indexOf (other) >= 0;
  8962. }
  8963. bool String::containsChar (const juce_wchar character) const throw()
  8964. {
  8965. const juce_wchar* t = text;
  8966. for (;;)
  8967. {
  8968. if (*t == 0)
  8969. return false;
  8970. if (*t == character)
  8971. return true;
  8972. ++t;
  8973. }
  8974. }
  8975. bool String::containsIgnoreCase (const String& t) const throw()
  8976. {
  8977. return indexOfIgnoreCase (t) >= 0;
  8978. }
  8979. int String::indexOfWholeWord (const String& word) const throw()
  8980. {
  8981. if (word.isNotEmpty())
  8982. {
  8983. const int wordLen = word.length();
  8984. const int end = length() - wordLen;
  8985. const juce_wchar* t = text;
  8986. for (int i = 0; i <= end; ++i)
  8987. {
  8988. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  8989. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8990. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8991. {
  8992. return i;
  8993. }
  8994. ++t;
  8995. }
  8996. }
  8997. return -1;
  8998. }
  8999. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9000. {
  9001. if (word.isNotEmpty())
  9002. {
  9003. const int wordLen = word.length();
  9004. const int end = length() - wordLen;
  9005. const juce_wchar* t = text;
  9006. for (int i = 0; i <= end; ++i)
  9007. {
  9008. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9009. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9010. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9011. {
  9012. return i;
  9013. }
  9014. ++t;
  9015. }
  9016. }
  9017. return -1;
  9018. }
  9019. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9020. {
  9021. return indexOfWholeWord (wordToLookFor) >= 0;
  9022. }
  9023. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9024. {
  9025. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9026. }
  9027. static int indexOfMatch (const juce_wchar* const wildcard,
  9028. const juce_wchar* const test,
  9029. const bool ignoreCase) throw()
  9030. {
  9031. int start = 0;
  9032. while (test [start] != 0)
  9033. {
  9034. int i = 0;
  9035. for (;;)
  9036. {
  9037. const juce_wchar wc = wildcard [i];
  9038. const juce_wchar c = test [i + start];
  9039. if (wc == c
  9040. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9041. || (wc == '?' && c != 0))
  9042. {
  9043. if (wc == 0)
  9044. return start;
  9045. ++i;
  9046. }
  9047. else
  9048. {
  9049. if (wc == '*' && (wildcard [i + 1] == 0
  9050. || indexOfMatch (wildcard + i + 1,
  9051. test + start + i,
  9052. ignoreCase) >= 0))
  9053. {
  9054. return start;
  9055. }
  9056. break;
  9057. }
  9058. }
  9059. ++start;
  9060. }
  9061. return -1;
  9062. }
  9063. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9064. {
  9065. int i = 0;
  9066. for (;;)
  9067. {
  9068. const juce_wchar wc = wildcard.text [i];
  9069. const juce_wchar c = text [i];
  9070. if (wc == c
  9071. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9072. || (wc == '?' && c != 0))
  9073. {
  9074. if (wc == 0)
  9075. return true;
  9076. ++i;
  9077. }
  9078. else
  9079. {
  9080. return wc == '*' && (wildcard [i + 1] == 0
  9081. || indexOfMatch (wildcard.text + i + 1,
  9082. text + i,
  9083. ignoreCase) >= 0);
  9084. }
  9085. }
  9086. }
  9087. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9088. {
  9089. const int len = stringToRepeat.length();
  9090. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9091. juce_wchar* n = result.text;
  9092. *n = 0;
  9093. while (--numberOfTimesToRepeat >= 0)
  9094. {
  9095. StringHolder::copyChars (n, stringToRepeat.text, len);
  9096. n += len;
  9097. }
  9098. return result;
  9099. }
  9100. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9101. {
  9102. jassert (padCharacter != 0);
  9103. const int len = length();
  9104. if (len >= minimumLength || padCharacter == 0)
  9105. return *this;
  9106. String result ((size_t) minimumLength + 1, (int) 0);
  9107. juce_wchar* n = result.text;
  9108. minimumLength -= len;
  9109. while (--minimumLength >= 0)
  9110. *n++ = padCharacter;
  9111. StringHolder::copyChars (n, text, len);
  9112. return result;
  9113. }
  9114. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9115. {
  9116. jassert (padCharacter != 0);
  9117. const int len = length();
  9118. if (len >= minimumLength || padCharacter == 0)
  9119. return *this;
  9120. String result (*this, (size_t) minimumLength);
  9121. juce_wchar* n = result.text + len;
  9122. minimumLength -= len;
  9123. while (--minimumLength >= 0)
  9124. *n++ = padCharacter;
  9125. *n = 0;
  9126. return result;
  9127. }
  9128. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9129. {
  9130. if (index < 0)
  9131. {
  9132. // a negative index to replace from?
  9133. jassertfalse
  9134. index = 0;
  9135. }
  9136. if (numCharsToReplace < 0)
  9137. {
  9138. // replacing a negative number of characters?
  9139. numCharsToReplace = 0;
  9140. jassertfalse;
  9141. }
  9142. const int len = length();
  9143. if (index + numCharsToReplace > len)
  9144. {
  9145. if (index > len)
  9146. {
  9147. // replacing beyond the end of the string?
  9148. index = len;
  9149. jassertfalse
  9150. }
  9151. numCharsToReplace = len - index;
  9152. }
  9153. const int newStringLen = stringToInsert.length();
  9154. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9155. if (newTotalLen <= 0)
  9156. return String::empty;
  9157. String result ((size_t) newTotalLen, (int) 0);
  9158. StringHolder::copyChars (result.text, text, index);
  9159. if (newStringLen > 0)
  9160. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9161. const int endStringLen = newTotalLen - (index + newStringLen);
  9162. if (endStringLen > 0)
  9163. StringHolder::copyChars (result.text + (index + newStringLen),
  9164. text + (index + numCharsToReplace),
  9165. endStringLen);
  9166. return result;
  9167. }
  9168. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9169. {
  9170. const int stringToReplaceLen = stringToReplace.length();
  9171. const int stringToInsertLen = stringToInsert.length();
  9172. int i = 0;
  9173. String result (*this);
  9174. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9175. : result.indexOf (i, stringToReplace))) >= 0)
  9176. {
  9177. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9178. i += stringToInsertLen;
  9179. }
  9180. return result;
  9181. }
  9182. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9183. {
  9184. const int index = indexOfChar (charToReplace);
  9185. if (index < 0)
  9186. return *this;
  9187. String result (*this, size_t());
  9188. juce_wchar* t = result.text + index;
  9189. while (*t != 0)
  9190. {
  9191. if (*t == charToReplace)
  9192. *t = charToInsert;
  9193. ++t;
  9194. }
  9195. return result;
  9196. }
  9197. const String String::replaceCharacters (const String& charactersToReplace,
  9198. const String& charactersToInsertInstead) const
  9199. {
  9200. String result (*this, size_t());
  9201. juce_wchar* t = result.text;
  9202. const int len2 = charactersToInsertInstead.length();
  9203. // the two strings passed in are supposed to be the same length!
  9204. jassert (len2 == charactersToReplace.length());
  9205. while (*t != 0)
  9206. {
  9207. const int index = charactersToReplace.indexOfChar (*t);
  9208. if (((unsigned int) index) < (unsigned int) len2)
  9209. *t = charactersToInsertInstead [index];
  9210. ++t;
  9211. }
  9212. return result;
  9213. }
  9214. bool String::startsWith (const String& other) const throw()
  9215. {
  9216. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9217. }
  9218. bool String::startsWithIgnoreCase (const String& other) const throw()
  9219. {
  9220. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9221. }
  9222. bool String::startsWithChar (const juce_wchar character) const throw()
  9223. {
  9224. jassert (character != 0); // strings can't contain a null character!
  9225. return text[0] == character;
  9226. }
  9227. bool String::endsWithChar (const juce_wchar character) const throw()
  9228. {
  9229. jassert (character != 0); // strings can't contain a null character!
  9230. return text[0] != 0
  9231. && text [length() - 1] == character;
  9232. }
  9233. bool String::endsWith (const String& other) const throw()
  9234. {
  9235. const int thisLen = length();
  9236. const int otherLen = other.length();
  9237. return thisLen >= otherLen
  9238. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9239. }
  9240. bool String::endsWithIgnoreCase (const String& other) const throw()
  9241. {
  9242. const int thisLen = length();
  9243. const int otherLen = other.length();
  9244. return thisLen >= otherLen
  9245. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9246. }
  9247. const String String::toUpperCase() const
  9248. {
  9249. String result (*this, size_t());
  9250. CharacterFunctions::toUpperCase (result.text);
  9251. return result;
  9252. }
  9253. const String String::toLowerCase() const
  9254. {
  9255. String result (*this, size_t());
  9256. CharacterFunctions::toLowerCase (result.text);
  9257. return result;
  9258. }
  9259. juce_wchar& String::operator[] (const int index)
  9260. {
  9261. jassert (((unsigned int) index) <= (unsigned int) length());
  9262. text = StringHolder::makeUnique (text);
  9263. return text [index];
  9264. }
  9265. juce_wchar String::getLastCharacter() const throw()
  9266. {
  9267. return isEmpty() ? juce_wchar() : text [length() - 1];
  9268. }
  9269. const String String::substring (int start, int end) const
  9270. {
  9271. if (start < 0)
  9272. start = 0;
  9273. else if (end <= start)
  9274. return empty;
  9275. int len = 0;
  9276. while (len <= end && text [len] != 0)
  9277. ++len;
  9278. if (end >= len)
  9279. {
  9280. if (start == 0)
  9281. return *this;
  9282. end = len;
  9283. }
  9284. return String (text + start, end - start);
  9285. }
  9286. const String String::substring (const int start) const
  9287. {
  9288. if (start <= 0)
  9289. return *this;
  9290. const int len = length();
  9291. if (start >= len)
  9292. return empty;
  9293. return String (text + start, len - start);
  9294. }
  9295. const String String::dropLastCharacters (const int numberToDrop) const
  9296. {
  9297. return String (text, jmax (0, length() - numberToDrop));
  9298. }
  9299. const String String::getLastCharacters (const int numCharacters) const
  9300. {
  9301. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9302. }
  9303. const String String::fromFirstOccurrenceOf (const String& sub,
  9304. const bool includeSubString,
  9305. const bool ignoreCase) const
  9306. {
  9307. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9308. : indexOf (sub);
  9309. if (i < 0)
  9310. return empty;
  9311. return substring (includeSubString ? i : i + sub.length());
  9312. }
  9313. const String String::fromLastOccurrenceOf (const String& sub,
  9314. const bool includeSubString,
  9315. const bool ignoreCase) const
  9316. {
  9317. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9318. : lastIndexOf (sub);
  9319. if (i < 0)
  9320. return *this;
  9321. return substring (includeSubString ? i : i + sub.length());
  9322. }
  9323. const String String::upToFirstOccurrenceOf (const String& sub,
  9324. const bool includeSubString,
  9325. const bool ignoreCase) const
  9326. {
  9327. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9328. : indexOf (sub);
  9329. if (i < 0)
  9330. return *this;
  9331. return substring (0, includeSubString ? i + sub.length() : i);
  9332. }
  9333. const String String::upToLastOccurrenceOf (const String& sub,
  9334. const bool includeSubString,
  9335. const bool ignoreCase) const
  9336. {
  9337. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9338. : lastIndexOf (sub);
  9339. if (i < 0)
  9340. return *this;
  9341. return substring (0, includeSubString ? i + sub.length() : i);
  9342. }
  9343. bool String::isQuotedString() const
  9344. {
  9345. const String trimmed (trimStart());
  9346. return trimmed[0] == '"'
  9347. || trimmed[0] == '\'';
  9348. }
  9349. const String String::unquoted() const
  9350. {
  9351. String s (*this);
  9352. if (s.text[0] == '"' || s.text[0] == '\'')
  9353. s = s.substring (1);
  9354. const int lastCharIndex = s.length() - 1;
  9355. if (lastCharIndex >= 0
  9356. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9357. s [lastCharIndex] = 0;
  9358. return s;
  9359. }
  9360. const String String::quoted (const juce_wchar quoteCharacter) const
  9361. {
  9362. if (isEmpty())
  9363. return charToString (quoteCharacter) + quoteCharacter;
  9364. String t (*this);
  9365. if (! t.startsWithChar (quoteCharacter))
  9366. t = charToString (quoteCharacter) + t;
  9367. if (! t.endsWithChar (quoteCharacter))
  9368. t += quoteCharacter;
  9369. return t;
  9370. }
  9371. const String String::trim() const
  9372. {
  9373. if (isEmpty())
  9374. return empty;
  9375. int start = 0;
  9376. while (CharacterFunctions::isWhitespace (text [start]))
  9377. ++start;
  9378. const int len = length();
  9379. int end = len - 1;
  9380. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9381. --end;
  9382. ++end;
  9383. if (end <= start)
  9384. return empty;
  9385. else if (start > 0 || end < len)
  9386. return String (text + start, end - start);
  9387. return *this;
  9388. }
  9389. const String String::trimStart() const
  9390. {
  9391. if (isEmpty())
  9392. return empty;
  9393. const juce_wchar* t = text;
  9394. while (CharacterFunctions::isWhitespace (*t))
  9395. ++t;
  9396. if (t == text)
  9397. return *this;
  9398. return String (t);
  9399. }
  9400. const String String::trimEnd() const
  9401. {
  9402. if (isEmpty())
  9403. return empty;
  9404. const juce_wchar* endT = text + (length() - 1);
  9405. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9406. --endT;
  9407. return String (text, (int) (++endT - text));
  9408. }
  9409. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9410. {
  9411. const juce_wchar* t = text;
  9412. while (charactersToTrim.containsChar (*t))
  9413. ++t;
  9414. return t == text ? *this : String (t);
  9415. }
  9416. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9417. {
  9418. if (isEmpty())
  9419. return empty;
  9420. const int len = length();
  9421. const juce_wchar* endT = text + (len - 1);
  9422. int numToRemove = 0;
  9423. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9424. {
  9425. ++numToRemove;
  9426. --endT;
  9427. }
  9428. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9429. }
  9430. const String String::retainCharacters (const String& charactersToRetain) const
  9431. {
  9432. if (isEmpty())
  9433. return empty;
  9434. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9435. juce_wchar* dst = result.text;
  9436. const juce_wchar* src = text;
  9437. while (*src != 0)
  9438. {
  9439. if (charactersToRetain.containsChar (*src))
  9440. *dst++ = *src;
  9441. ++src;
  9442. }
  9443. *dst = 0;
  9444. return result;
  9445. }
  9446. const String String::removeCharacters (const String& charactersToRemove) const
  9447. {
  9448. if (isEmpty())
  9449. return empty;
  9450. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9451. juce_wchar* dst = result.text;
  9452. const juce_wchar* src = text;
  9453. while (*src != 0)
  9454. {
  9455. if (! charactersToRemove.containsChar (*src))
  9456. *dst++ = *src;
  9457. ++src;
  9458. }
  9459. *dst = 0;
  9460. return result;
  9461. }
  9462. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9463. {
  9464. int i = 0;
  9465. for (;;)
  9466. {
  9467. if (! permittedCharacters.containsChar (text[i]))
  9468. break;
  9469. ++i;
  9470. }
  9471. return substring (0, i);
  9472. }
  9473. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9474. {
  9475. const juce_wchar* const t = text;
  9476. int i = 0;
  9477. while (t[i] != 0)
  9478. {
  9479. if (charactersToStopAt.containsChar (t[i]))
  9480. return String (text, i);
  9481. ++i;
  9482. }
  9483. return empty;
  9484. }
  9485. bool String::containsOnly (const String& chars) const throw()
  9486. {
  9487. const juce_wchar* t = text;
  9488. while (*t != 0)
  9489. if (! chars.containsChar (*t++))
  9490. return false;
  9491. return true;
  9492. }
  9493. bool String::containsAnyOf (const String& chars) const throw()
  9494. {
  9495. const juce_wchar* t = text;
  9496. while (*t != 0)
  9497. if (chars.containsChar (*t++))
  9498. return true;
  9499. return false;
  9500. }
  9501. bool String::containsNonWhitespaceChars() const throw()
  9502. {
  9503. const juce_wchar* t = text;
  9504. while (*t != 0)
  9505. if (! CharacterFunctions::isWhitespace (*t++))
  9506. return true;
  9507. return false;
  9508. }
  9509. const String String::formatted (const juce_wchar* const pf, ... )
  9510. {
  9511. jassert (pf != 0);
  9512. va_list args;
  9513. va_start (args, pf);
  9514. size_t bufferSize = 256;
  9515. String result (bufferSize, (int) 0);
  9516. result.text[0] = 0;
  9517. for (;;)
  9518. {
  9519. #if JUCE_LINUX && JUCE_64BIT
  9520. va_list tempArgs;
  9521. va_copy (tempArgs, args);
  9522. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9523. va_end (tempArgs);
  9524. #elif JUCE_WINDOWS
  9525. #ifdef _MSC_VER
  9526. #pragma warning (push)
  9527. #pragma warning (disable: 4996)
  9528. #endif
  9529. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9530. #ifdef _MSC_VER
  9531. #pragma warning (pop)
  9532. #endif
  9533. #else
  9534. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9535. #endif
  9536. if (num > 0)
  9537. return result;
  9538. bufferSize += 256;
  9539. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9540. break; // returns -1 because of an error rather than because it needs more space.
  9541. result.preallocateStorage (bufferSize);
  9542. }
  9543. return empty;
  9544. }
  9545. int String::getIntValue() const throw()
  9546. {
  9547. return CharacterFunctions::getIntValue (text);
  9548. }
  9549. int String::getTrailingIntValue() const throw()
  9550. {
  9551. int n = 0;
  9552. int mult = 1;
  9553. const juce_wchar* t = text + length();
  9554. while (--t >= text)
  9555. {
  9556. const juce_wchar c = *t;
  9557. if (! CharacterFunctions::isDigit (c))
  9558. {
  9559. if (c == '-')
  9560. n = -n;
  9561. break;
  9562. }
  9563. n += mult * (c - '0');
  9564. mult *= 10;
  9565. }
  9566. return n;
  9567. }
  9568. int64 String::getLargeIntValue() const throw()
  9569. {
  9570. return CharacterFunctions::getInt64Value (text);
  9571. }
  9572. float String::getFloatValue() const throw()
  9573. {
  9574. return (float) CharacterFunctions::getDoubleValue (text);
  9575. }
  9576. double String::getDoubleValue() const throw()
  9577. {
  9578. return CharacterFunctions::getDoubleValue (text);
  9579. }
  9580. static const juce_wchar* const hexDigits = T("0123456789abcdef");
  9581. const String String::toHexString (const int number)
  9582. {
  9583. juce_wchar buffer[32];
  9584. juce_wchar* const end = buffer + 32;
  9585. juce_wchar* t = end;
  9586. *--t = 0;
  9587. unsigned int v = (unsigned int) number;
  9588. do
  9589. {
  9590. *--t = hexDigits [v & 15];
  9591. v >>= 4;
  9592. } while (v != 0);
  9593. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9594. }
  9595. const String String::toHexString (const int64 number)
  9596. {
  9597. juce_wchar buffer[32];
  9598. juce_wchar* const end = buffer + 32;
  9599. juce_wchar* t = end;
  9600. *--t = 0;
  9601. uint64 v = (uint64) number;
  9602. do
  9603. {
  9604. *--t = hexDigits [(int) (v & 15)];
  9605. v >>= 4;
  9606. } while (v != 0);
  9607. return String (t, (int) (((char*) end) - (char*) t));
  9608. }
  9609. const String String::toHexString (const short number)
  9610. {
  9611. return toHexString ((int) (unsigned short) number);
  9612. }
  9613. const String String::toHexString (const unsigned char* data,
  9614. const int size,
  9615. const int groupSize)
  9616. {
  9617. if (size <= 0)
  9618. return empty;
  9619. int numChars = (size * 2) + 2;
  9620. if (groupSize > 0)
  9621. numChars += size / groupSize;
  9622. String s ((size_t) numChars, (int) 0);
  9623. juce_wchar* d = s.text;
  9624. for (int i = 0; i < size; ++i)
  9625. {
  9626. *d++ = hexDigits [(*data) >> 4];
  9627. *d++ = hexDigits [(*data) & 0xf];
  9628. ++data;
  9629. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9630. *d++ = ' ';
  9631. }
  9632. *d = 0;
  9633. return s;
  9634. }
  9635. int String::getHexValue32() const throw()
  9636. {
  9637. int result = 0;
  9638. const juce_wchar* c = text;
  9639. for (;;)
  9640. {
  9641. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9642. if (hexValue >= 0)
  9643. result = (result << 4) | hexValue;
  9644. else if (*c == 0)
  9645. break;
  9646. ++c;
  9647. }
  9648. return result;
  9649. }
  9650. int64 String::getHexValue64() const throw()
  9651. {
  9652. int64 result = 0;
  9653. const juce_wchar* c = text;
  9654. for (;;)
  9655. {
  9656. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9657. if (hexValue >= 0)
  9658. result = (result << 4) | hexValue;
  9659. else if (*c == 0)
  9660. break;
  9661. ++c;
  9662. }
  9663. return result;
  9664. }
  9665. const String String::createStringFromData (const void* const data_, const int size)
  9666. {
  9667. const char* const data = static_cast <const char*> (data_);
  9668. if (size <= 0 || data == 0)
  9669. {
  9670. return empty;
  9671. }
  9672. else if (size < 2)
  9673. {
  9674. return charToString (data[0]);
  9675. }
  9676. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9677. || (data[0] == (char)-1 && data[1] == (char)-2))
  9678. {
  9679. // assume it's 16-bit unicode
  9680. const bool bigEndian = (data[0] == (char)-2);
  9681. const int numChars = size / 2 - 1;
  9682. String result;
  9683. result.preallocateStorage (numChars + 2);
  9684. const uint16* const src = (const uint16*) (data + 2);
  9685. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9686. if (bigEndian)
  9687. {
  9688. for (int i = 0; i < numChars; ++i)
  9689. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9690. }
  9691. else
  9692. {
  9693. for (int i = 0; i < numChars; ++i)
  9694. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9695. }
  9696. dst [numChars] = 0;
  9697. return result;
  9698. }
  9699. else
  9700. {
  9701. return String::fromUTF8 (data, size);
  9702. }
  9703. }
  9704. const char* String::toUTF8() const
  9705. {
  9706. if (isEmpty())
  9707. {
  9708. return reinterpret_cast <const char*> (text);
  9709. }
  9710. else
  9711. {
  9712. const int currentLen = length() + 1;
  9713. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9714. String* const mutableThis = const_cast <String*> (this);
  9715. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9716. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9717. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9718. return otherCopy;
  9719. }
  9720. }
  9721. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9722. {
  9723. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9724. int num = 0, index = 0;
  9725. for (;;)
  9726. {
  9727. const uint32 c = (uint32) text [index++];
  9728. if (c >= 0x80)
  9729. {
  9730. int numExtraBytes = 1;
  9731. if (c >= 0x800)
  9732. {
  9733. ++numExtraBytes;
  9734. if (c >= 0x10000)
  9735. {
  9736. ++numExtraBytes;
  9737. if (c >= 0x200000)
  9738. {
  9739. ++numExtraBytes;
  9740. if (c >= 0x4000000)
  9741. ++numExtraBytes;
  9742. }
  9743. }
  9744. }
  9745. if (buffer != 0)
  9746. {
  9747. if (num + numExtraBytes >= maxBufferSizeBytes)
  9748. {
  9749. buffer [num++] = 0;
  9750. break;
  9751. }
  9752. else
  9753. {
  9754. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9755. while (--numExtraBytes >= 0)
  9756. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9757. }
  9758. }
  9759. else
  9760. {
  9761. num += numExtraBytes + 1;
  9762. }
  9763. }
  9764. else
  9765. {
  9766. if (buffer != 0)
  9767. {
  9768. if (num + 1 >= maxBufferSizeBytes)
  9769. {
  9770. buffer [num++] = 0;
  9771. break;
  9772. }
  9773. buffer [num] = (uint8) c;
  9774. }
  9775. ++num;
  9776. }
  9777. if (c == 0)
  9778. break;
  9779. }
  9780. return num;
  9781. }
  9782. int String::getNumBytesAsUTF8() const throw()
  9783. {
  9784. int num = 0;
  9785. const juce_wchar* t = text;
  9786. for (;;)
  9787. {
  9788. const uint32 c = (uint32) *t;
  9789. if (c >= 0x80)
  9790. {
  9791. ++num;
  9792. if (c >= 0x800)
  9793. {
  9794. ++num;
  9795. if (c >= 0x10000)
  9796. {
  9797. ++num;
  9798. if (c >= 0x200000)
  9799. {
  9800. ++num;
  9801. if (c >= 0x4000000)
  9802. ++num;
  9803. }
  9804. }
  9805. }
  9806. }
  9807. else if (c == 0)
  9808. break;
  9809. ++num;
  9810. ++t;
  9811. }
  9812. return num;
  9813. }
  9814. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9815. {
  9816. if (buffer == 0)
  9817. return empty;
  9818. if (bufferSizeBytes < 0)
  9819. bufferSizeBytes = std::numeric_limits<int>::max();
  9820. size_t numBytes;
  9821. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9822. if (buffer [numBytes] == 0)
  9823. break;
  9824. String result ((size_t) numBytes + 1, (int) 0);
  9825. juce_wchar* dest = result.text;
  9826. size_t i = 0;
  9827. while (i < numBytes)
  9828. {
  9829. const char c = buffer [i++];
  9830. if (c < 0)
  9831. {
  9832. unsigned int mask = 0x7f;
  9833. int bit = 0x40;
  9834. int numExtraValues = 0;
  9835. while (bit != 0 && (c & bit) != 0)
  9836. {
  9837. bit >>= 1;
  9838. mask >>= 1;
  9839. ++numExtraValues;
  9840. }
  9841. int n = (mask & (unsigned char) c);
  9842. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9843. {
  9844. const char nextByte = buffer[i];
  9845. if ((nextByte & 0xc0) != 0x80)
  9846. break;
  9847. n <<= 6;
  9848. n |= (nextByte & 0x3f);
  9849. ++i;
  9850. }
  9851. *dest++ = (juce_wchar) n;
  9852. }
  9853. else
  9854. {
  9855. *dest++ = (juce_wchar) c;
  9856. }
  9857. }
  9858. *dest = 0;
  9859. return result;
  9860. }
  9861. const char* String::toCString() const
  9862. {
  9863. if (isEmpty())
  9864. {
  9865. return reinterpret_cast <const char*> (text);
  9866. }
  9867. else
  9868. {
  9869. const int len = length();
  9870. String* const mutableThis = const_cast <String*> (this);
  9871. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9872. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9873. CharacterFunctions::copy (otherCopy, text, len);
  9874. otherCopy [len] = 0;
  9875. return otherCopy;
  9876. }
  9877. }
  9878. #ifdef _MSC_VER
  9879. #pragma warning (disable: 4514 4996)
  9880. #pragma warning (push)
  9881. #endif
  9882. int String::getNumBytesAsCString() const throw()
  9883. {
  9884. return (int) wcstombs (0, text, 0);
  9885. }
  9886. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9887. {
  9888. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9889. if (destBuffer != 0 && numBytes >= 0)
  9890. destBuffer [numBytes] = 0;
  9891. return numBytes;
  9892. }
  9893. #ifdef _MSC_VER
  9894. #pragma warning (pop)
  9895. #endif
  9896. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9897. {
  9898. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9899. }
  9900. String::Concatenator::Concatenator (String& stringToAppendTo)
  9901. : result (stringToAppendTo),
  9902. nextIndex (stringToAppendTo.length())
  9903. {
  9904. }
  9905. String::Concatenator::~Concatenator()
  9906. {
  9907. }
  9908. void String::Concatenator::append (const String& s)
  9909. {
  9910. const int len = s.length();
  9911. if (len > 0)
  9912. {
  9913. result.preallocateStorage (nextIndex + len);
  9914. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  9915. nextIndex += len;
  9916. }
  9917. }
  9918. END_JUCE_NAMESPACE
  9919. /*** End of inlined file: juce_String.cpp ***/
  9920. /*** Start of inlined file: juce_StringArray.cpp ***/
  9921. BEGIN_JUCE_NAMESPACE
  9922. StringArray::StringArray() throw()
  9923. {
  9924. }
  9925. StringArray::StringArray (const StringArray& other)
  9926. : strings (other.strings)
  9927. {
  9928. }
  9929. StringArray::StringArray (const String& firstValue)
  9930. {
  9931. strings.add (firstValue);
  9932. }
  9933. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  9934. const int numberOfStrings)
  9935. {
  9936. for (int i = 0; i < numberOfStrings; ++i)
  9937. strings.add (initialStrings [i]);
  9938. }
  9939. StringArray::StringArray (const char* const* const initialStrings,
  9940. const int numberOfStrings)
  9941. {
  9942. for (int i = 0; i < numberOfStrings; ++i)
  9943. strings.add (initialStrings [i]);
  9944. }
  9945. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  9946. {
  9947. int i = 0;
  9948. while (initialStrings[i] != 0)
  9949. strings.add (initialStrings [i++]);
  9950. }
  9951. StringArray::StringArray (const char* const* const initialStrings)
  9952. {
  9953. int i = 0;
  9954. while (initialStrings[i] != 0)
  9955. strings.add (initialStrings [i++]);
  9956. }
  9957. StringArray& StringArray::operator= (const StringArray& other)
  9958. {
  9959. strings = other.strings;
  9960. return *this;
  9961. }
  9962. StringArray::~StringArray()
  9963. {
  9964. }
  9965. bool StringArray::operator== (const StringArray& other) const throw()
  9966. {
  9967. if (other.size() != size())
  9968. return false;
  9969. for (int i = size(); --i >= 0;)
  9970. if (other.strings.getReference(i) != strings.getReference(i))
  9971. return false;
  9972. return true;
  9973. }
  9974. bool StringArray::operator!= (const StringArray& other) const throw()
  9975. {
  9976. return ! operator== (other);
  9977. }
  9978. void StringArray::clear()
  9979. {
  9980. strings.clear();
  9981. }
  9982. const String& StringArray::operator[] (const int index) const throw()
  9983. {
  9984. if (((unsigned int) index) < (unsigned int) strings.size())
  9985. return strings.getReference (index);
  9986. return String::empty;
  9987. }
  9988. String& StringArray::getReference (const int index) throw()
  9989. {
  9990. jassert (((unsigned int) index) < (unsigned int) strings.size());
  9991. return strings.getReference (index);
  9992. }
  9993. void StringArray::add (const String& newString)
  9994. {
  9995. strings.add (newString);
  9996. }
  9997. void StringArray::insert (const int index, const String& newString)
  9998. {
  9999. strings.insert (index, newString);
  10000. }
  10001. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10002. {
  10003. if (! contains (newString, ignoreCase))
  10004. add (newString);
  10005. }
  10006. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10007. {
  10008. if (startIndex < 0)
  10009. {
  10010. jassertfalse
  10011. startIndex = 0;
  10012. }
  10013. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10014. numElementsToAdd = otherArray.size() - startIndex;
  10015. while (--numElementsToAdd >= 0)
  10016. strings.add (otherArray.strings.getReference (startIndex++));
  10017. }
  10018. void StringArray::set (const int index, const String& newString)
  10019. {
  10020. strings.set (index, newString);
  10021. }
  10022. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10023. {
  10024. if (ignoreCase)
  10025. {
  10026. for (int i = size(); --i >= 0;)
  10027. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10028. return true;
  10029. }
  10030. else
  10031. {
  10032. for (int i = size(); --i >= 0;)
  10033. if (stringToLookFor == strings.getReference(i))
  10034. return true;
  10035. }
  10036. return false;
  10037. }
  10038. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10039. {
  10040. if (i < 0)
  10041. i = 0;
  10042. const int numElements = size();
  10043. if (ignoreCase)
  10044. {
  10045. while (i < numElements)
  10046. {
  10047. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10048. return i;
  10049. ++i;
  10050. }
  10051. }
  10052. else
  10053. {
  10054. while (i < numElements)
  10055. {
  10056. if (stringToLookFor == strings.getReference (i))
  10057. return i;
  10058. ++i;
  10059. }
  10060. }
  10061. return -1;
  10062. }
  10063. void StringArray::remove (const int index)
  10064. {
  10065. strings.remove (index);
  10066. }
  10067. void StringArray::removeString (const String& stringToRemove,
  10068. const bool ignoreCase)
  10069. {
  10070. if (ignoreCase)
  10071. {
  10072. for (int i = size(); --i >= 0;)
  10073. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10074. strings.remove (i);
  10075. }
  10076. else
  10077. {
  10078. for (int i = size(); --i >= 0;)
  10079. if (stringToRemove == strings.getReference (i))
  10080. strings.remove (i);
  10081. }
  10082. }
  10083. void StringArray::removeRange (int startIndex, int numberToRemove)
  10084. {
  10085. strings.removeRange (startIndex, numberToRemove);
  10086. }
  10087. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10088. {
  10089. if (removeWhitespaceStrings)
  10090. {
  10091. for (int i = size(); --i >= 0;)
  10092. if (! strings.getReference(i).containsNonWhitespaceChars())
  10093. strings.remove (i);
  10094. }
  10095. else
  10096. {
  10097. for (int i = size(); --i >= 0;)
  10098. if (strings.getReference(i).isEmpty())
  10099. strings.remove (i);
  10100. }
  10101. }
  10102. void StringArray::trim()
  10103. {
  10104. for (int i = size(); --i >= 0;)
  10105. {
  10106. String& s = strings.getReference(i);
  10107. s = s.trim();
  10108. }
  10109. }
  10110. class InternalStringArrayComparator_CaseSensitive
  10111. {
  10112. public:
  10113. static int compareElements (String& first, String& second) { return first.compare (second); }
  10114. };
  10115. class InternalStringArrayComparator_CaseInsensitive
  10116. {
  10117. public:
  10118. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10119. };
  10120. void StringArray::sort (const bool ignoreCase)
  10121. {
  10122. if (ignoreCase)
  10123. {
  10124. InternalStringArrayComparator_CaseInsensitive comp;
  10125. strings.sort (comp);
  10126. }
  10127. else
  10128. {
  10129. InternalStringArrayComparator_CaseSensitive comp;
  10130. strings.sort (comp);
  10131. }
  10132. }
  10133. void StringArray::move (const int currentIndex, int newIndex) throw()
  10134. {
  10135. strings.move (currentIndex, newIndex);
  10136. }
  10137. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10138. {
  10139. const int last = (numberToJoin < 0) ? size()
  10140. : jmin (size(), start + numberToJoin);
  10141. if (start < 0)
  10142. start = 0;
  10143. if (start >= last)
  10144. return String::empty;
  10145. if (start == last - 1)
  10146. return strings.getReference (start);
  10147. const int separatorLen = separator.length();
  10148. int charsNeeded = separatorLen * (last - start - 1);
  10149. for (int i = start; i < last; ++i)
  10150. charsNeeded += strings.getReference(i).length();
  10151. String result;
  10152. result.preallocateStorage (charsNeeded);
  10153. juce_wchar* dest = result;
  10154. while (start < last)
  10155. {
  10156. const String& s = strings.getReference (start);
  10157. const int len = s.length();
  10158. if (len > 0)
  10159. {
  10160. s.copyToUnicode (dest, len);
  10161. dest += len;
  10162. }
  10163. if (++start < last && separatorLen > 0)
  10164. {
  10165. separator.copyToUnicode (dest, separatorLen);
  10166. dest += separatorLen;
  10167. }
  10168. }
  10169. *dest = 0;
  10170. return result;
  10171. }
  10172. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10173. {
  10174. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10175. }
  10176. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10177. {
  10178. int num = 0;
  10179. if (text.isNotEmpty())
  10180. {
  10181. bool insideQuotes = false;
  10182. juce_wchar currentQuoteChar = 0;
  10183. int i = 0;
  10184. int tokenStart = 0;
  10185. for (;;)
  10186. {
  10187. const juce_wchar c = text[i];
  10188. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10189. if (! isBreak)
  10190. {
  10191. if (quoteCharacters.containsChar (c))
  10192. {
  10193. if (insideQuotes)
  10194. {
  10195. // only break out of quotes-mode if we find a matching quote to the
  10196. // one that we opened with..
  10197. if (currentQuoteChar == c)
  10198. insideQuotes = false;
  10199. }
  10200. else
  10201. {
  10202. insideQuotes = true;
  10203. currentQuoteChar = c;
  10204. }
  10205. }
  10206. }
  10207. else
  10208. {
  10209. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10210. ++num;
  10211. tokenStart = i + 1;
  10212. }
  10213. if (c == 0)
  10214. break;
  10215. ++i;
  10216. }
  10217. }
  10218. return num;
  10219. }
  10220. int StringArray::addLines (const String& sourceText)
  10221. {
  10222. int numLines = 0;
  10223. const juce_wchar* text = sourceText;
  10224. while (*text != 0)
  10225. {
  10226. const juce_wchar* const startOfLine = text;
  10227. while (*text != 0)
  10228. {
  10229. if (*text == '\r')
  10230. {
  10231. ++text;
  10232. if (*text == '\n')
  10233. ++text;
  10234. break;
  10235. }
  10236. if (*text == '\n')
  10237. {
  10238. ++text;
  10239. break;
  10240. }
  10241. ++text;
  10242. }
  10243. const juce_wchar* endOfLine = text;
  10244. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10245. --endOfLine;
  10246. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10247. --endOfLine;
  10248. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10249. ++numLines;
  10250. }
  10251. return numLines;
  10252. }
  10253. void StringArray::removeDuplicates (const bool ignoreCase)
  10254. {
  10255. for (int i = 0; i < size() - 1; ++i)
  10256. {
  10257. const String s (strings.getReference(i));
  10258. int nextIndex = i + 1;
  10259. for (;;)
  10260. {
  10261. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10262. if (nextIndex < 0)
  10263. break;
  10264. strings.remove (nextIndex);
  10265. }
  10266. }
  10267. }
  10268. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10269. const bool appendNumberToFirstInstance,
  10270. const juce_wchar* preNumberString,
  10271. const juce_wchar* postNumberString)
  10272. {
  10273. if (preNumberString == 0)
  10274. preNumberString = L" (";
  10275. if (postNumberString == 0)
  10276. postNumberString = L")";
  10277. for (int i = 0; i < size() - 1; ++i)
  10278. {
  10279. String& s = strings.getReference(i);
  10280. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10281. if (nextIndex >= 0)
  10282. {
  10283. const String original (s);
  10284. int number = 0;
  10285. if (appendNumberToFirstInstance)
  10286. s = original + preNumberString + String (++number) + postNumberString;
  10287. else
  10288. ++number;
  10289. while (nextIndex >= 0)
  10290. {
  10291. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10292. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10293. }
  10294. }
  10295. }
  10296. }
  10297. void StringArray::minimiseStorageOverheads()
  10298. {
  10299. strings.minimiseStorageOverheads();
  10300. }
  10301. END_JUCE_NAMESPACE
  10302. /*** End of inlined file: juce_StringArray.cpp ***/
  10303. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10304. BEGIN_JUCE_NAMESPACE
  10305. StringPairArray::StringPairArray (const bool ignoreCase_)
  10306. : ignoreCase (ignoreCase_)
  10307. {
  10308. }
  10309. StringPairArray::StringPairArray (const StringPairArray& other)
  10310. : keys (other.keys),
  10311. values (other.values),
  10312. ignoreCase (other.ignoreCase)
  10313. {
  10314. }
  10315. StringPairArray::~StringPairArray()
  10316. {
  10317. }
  10318. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10319. {
  10320. keys = other.keys;
  10321. values = other.values;
  10322. return *this;
  10323. }
  10324. bool StringPairArray::operator== (const StringPairArray& other) const
  10325. {
  10326. for (int i = keys.size(); --i >= 0;)
  10327. if (other [keys[i]] != values[i])
  10328. return false;
  10329. return true;
  10330. }
  10331. bool StringPairArray::operator!= (const StringPairArray& other) const
  10332. {
  10333. return ! operator== (other);
  10334. }
  10335. const String& StringPairArray::operator[] (const String& key) const
  10336. {
  10337. return values [keys.indexOf (key, ignoreCase)];
  10338. }
  10339. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10340. {
  10341. const int i = keys.indexOf (key, ignoreCase);
  10342. if (i >= 0)
  10343. return values[i];
  10344. return defaultReturnValue;
  10345. }
  10346. void StringPairArray::set (const String& key, const String& value)
  10347. {
  10348. const int i = keys.indexOf (key, ignoreCase);
  10349. if (i >= 0)
  10350. {
  10351. values.set (i, value);
  10352. }
  10353. else
  10354. {
  10355. keys.add (key);
  10356. values.add (value);
  10357. }
  10358. }
  10359. void StringPairArray::addArray (const StringPairArray& other)
  10360. {
  10361. for (int i = 0; i < other.size(); ++i)
  10362. set (other.keys[i], other.values[i]);
  10363. }
  10364. void StringPairArray::clear()
  10365. {
  10366. keys.clear();
  10367. values.clear();
  10368. }
  10369. void StringPairArray::remove (const String& key)
  10370. {
  10371. remove (keys.indexOf (key, ignoreCase));
  10372. }
  10373. void StringPairArray::remove (const int index)
  10374. {
  10375. keys.remove (index);
  10376. values.remove (index);
  10377. }
  10378. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10379. {
  10380. ignoreCase = shouldIgnoreCase;
  10381. }
  10382. const String StringPairArray::getDescription() const
  10383. {
  10384. String s;
  10385. for (int i = 0; i < keys.size(); ++i)
  10386. {
  10387. s << keys[i] << " = " << values[i];
  10388. if (i < keys.size())
  10389. s << ", ";
  10390. }
  10391. return s;
  10392. }
  10393. void StringPairArray::minimiseStorageOverheads()
  10394. {
  10395. keys.minimiseStorageOverheads();
  10396. values.minimiseStorageOverheads();
  10397. }
  10398. END_JUCE_NAMESPACE
  10399. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10400. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10401. BEGIN_JUCE_NAMESPACE
  10402. XmlDocument::XmlDocument (const String& documentText)
  10403. : originalText (documentText),
  10404. ignoreEmptyTextElements (true)
  10405. {
  10406. }
  10407. XmlDocument::XmlDocument (const File& file)
  10408. : ignoreEmptyTextElements (true)
  10409. {
  10410. inputSource = new FileInputSource (file);
  10411. }
  10412. XmlDocument::~XmlDocument()
  10413. {
  10414. }
  10415. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10416. {
  10417. inputSource = newSource;
  10418. }
  10419. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10420. {
  10421. ignoreEmptyTextElements = shouldBeIgnored;
  10422. }
  10423. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10424. {
  10425. return CharacterFunctions::isLetterOrDigit (c)
  10426. || c == '_' || c == '-' || c == ':' || c == '.';
  10427. }
  10428. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10429. {
  10430. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10431. : isXmlIdentifierCharSlow (c);
  10432. }
  10433. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10434. {
  10435. String textToParse (originalText);
  10436. if (textToParse.isEmpty() && inputSource != 0)
  10437. {
  10438. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10439. if (in != 0)
  10440. {
  10441. MemoryBlock data;
  10442. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10443. if (data.getSize() >= 2
  10444. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10445. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10446. {
  10447. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10448. }
  10449. else
  10450. {
  10451. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10452. }
  10453. if (! onlyReadOuterDocumentElement)
  10454. originalText = textToParse;
  10455. }
  10456. }
  10457. input = textToParse;
  10458. lastError = String::empty;
  10459. errorOccurred = false;
  10460. outOfData = false;
  10461. needToLoadDTD = true;
  10462. for (int i = 0; i < 128; ++i)
  10463. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10464. if (textToParse.isEmpty())
  10465. {
  10466. lastError = "not enough input";
  10467. }
  10468. else
  10469. {
  10470. skipHeader();
  10471. if (input != 0)
  10472. {
  10473. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10474. if (! errorOccurred)
  10475. return result.release();
  10476. }
  10477. else
  10478. {
  10479. lastError = "incorrect xml header";
  10480. }
  10481. }
  10482. return 0;
  10483. }
  10484. const String& XmlDocument::getLastParseError() const throw()
  10485. {
  10486. return lastError;
  10487. }
  10488. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10489. {
  10490. lastError = desc;
  10491. errorOccurred = ! carryOn;
  10492. }
  10493. const String XmlDocument::getFileContents (const String& filename) const
  10494. {
  10495. if (inputSource != 0)
  10496. {
  10497. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10498. if (in != 0)
  10499. return in->readEntireStreamAsString();
  10500. }
  10501. return String::empty;
  10502. }
  10503. juce_wchar XmlDocument::readNextChar() throw()
  10504. {
  10505. if (*input != 0)
  10506. {
  10507. return *input++;
  10508. }
  10509. else
  10510. {
  10511. outOfData = true;
  10512. return 0;
  10513. }
  10514. }
  10515. int XmlDocument::findNextTokenLength() throw()
  10516. {
  10517. int len = 0;
  10518. juce_wchar c = *input;
  10519. while (isXmlIdentifierChar (c))
  10520. c = input [++len];
  10521. return len;
  10522. }
  10523. void XmlDocument::skipHeader()
  10524. {
  10525. const juce_wchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10526. if (found != 0)
  10527. {
  10528. input = found;
  10529. input = CharacterFunctions::find (input, T("?>"));
  10530. if (input == 0)
  10531. return;
  10532. input += 2;
  10533. }
  10534. skipNextWhiteSpace();
  10535. const juce_wchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10536. if (docType == 0)
  10537. return;
  10538. input = docType + 9;
  10539. int n = 1;
  10540. while (n > 0)
  10541. {
  10542. const juce_wchar c = readNextChar();
  10543. if (outOfData)
  10544. return;
  10545. if (c == '<')
  10546. ++n;
  10547. else if (c == '>')
  10548. --n;
  10549. }
  10550. docType += 9;
  10551. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10552. }
  10553. void XmlDocument::skipNextWhiteSpace()
  10554. {
  10555. for (;;)
  10556. {
  10557. juce_wchar c = *input;
  10558. while (CharacterFunctions::isWhitespace (c))
  10559. c = *++input;
  10560. if (c == 0)
  10561. {
  10562. outOfData = true;
  10563. break;
  10564. }
  10565. else if (c == '<')
  10566. {
  10567. if (input[1] == '!'
  10568. && input[2] == '-'
  10569. && input[3] == '-')
  10570. {
  10571. const juce_wchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10572. if (closeComment == 0)
  10573. {
  10574. outOfData = true;
  10575. break;
  10576. }
  10577. input = closeComment + 3;
  10578. continue;
  10579. }
  10580. else if (input[1] == '?')
  10581. {
  10582. const juce_wchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10583. if (closeBracket == 0)
  10584. {
  10585. outOfData = true;
  10586. break;
  10587. }
  10588. input = closeBracket + 2;
  10589. continue;
  10590. }
  10591. }
  10592. break;
  10593. }
  10594. }
  10595. void XmlDocument::readQuotedString (String& result)
  10596. {
  10597. const juce_wchar quote = readNextChar();
  10598. while (! outOfData)
  10599. {
  10600. const juce_wchar c = readNextChar();
  10601. if (c == quote)
  10602. break;
  10603. if (c == '&')
  10604. {
  10605. --input;
  10606. readEntity (result);
  10607. }
  10608. else
  10609. {
  10610. --input;
  10611. const juce_wchar* const start = input;
  10612. for (;;)
  10613. {
  10614. const juce_wchar character = *input;
  10615. if (character == quote)
  10616. {
  10617. result.append (start, (int) (input - start));
  10618. ++input;
  10619. return;
  10620. }
  10621. else if (character == '&')
  10622. {
  10623. result.append (start, (int) (input - start));
  10624. break;
  10625. }
  10626. else if (character == 0)
  10627. {
  10628. outOfData = true;
  10629. setLastError ("unmatched quotes", false);
  10630. break;
  10631. }
  10632. ++input;
  10633. }
  10634. }
  10635. }
  10636. }
  10637. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10638. {
  10639. XmlElement* node = 0;
  10640. skipNextWhiteSpace();
  10641. if (outOfData)
  10642. return 0;
  10643. input = CharacterFunctions::find (input, T("<"));
  10644. if (input != 0)
  10645. {
  10646. ++input;
  10647. int tagLen = findNextTokenLength();
  10648. if (tagLen == 0)
  10649. {
  10650. // no tag name - but allow for a gap after the '<' before giving an error
  10651. skipNextWhiteSpace();
  10652. tagLen = findNextTokenLength();
  10653. if (tagLen == 0)
  10654. {
  10655. setLastError ("tag name missing", false);
  10656. return node;
  10657. }
  10658. }
  10659. node = new XmlElement (String (input, tagLen));
  10660. input += tagLen;
  10661. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10662. // look for attributes
  10663. for (;;)
  10664. {
  10665. skipNextWhiteSpace();
  10666. const juce_wchar c = *input;
  10667. // empty tag..
  10668. if (c == '/' && input[1] == '>')
  10669. {
  10670. input += 2;
  10671. break;
  10672. }
  10673. // parse the guts of the element..
  10674. if (c == '>')
  10675. {
  10676. ++input;
  10677. skipNextWhiteSpace();
  10678. if (alsoParseSubElements)
  10679. readChildElements (node);
  10680. break;
  10681. }
  10682. // get an attribute..
  10683. if (isXmlIdentifierChar (c))
  10684. {
  10685. const int attNameLen = findNextTokenLength();
  10686. if (attNameLen > 0)
  10687. {
  10688. const juce_wchar* attNameStart = input;
  10689. input += attNameLen;
  10690. skipNextWhiteSpace();
  10691. if (readNextChar() == '=')
  10692. {
  10693. skipNextWhiteSpace();
  10694. const juce_wchar nextChar = *input;
  10695. if (nextChar == '"' || nextChar == '\'')
  10696. {
  10697. XmlElement::XmlAttributeNode* const newAtt
  10698. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10699. String::empty);
  10700. readQuotedString (newAtt->value);
  10701. if (lastAttribute == 0)
  10702. node->attributes = newAtt;
  10703. else
  10704. lastAttribute->next = newAtt;
  10705. lastAttribute = newAtt;
  10706. continue;
  10707. }
  10708. }
  10709. }
  10710. }
  10711. else
  10712. {
  10713. if (! outOfData)
  10714. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10715. }
  10716. break;
  10717. }
  10718. }
  10719. return node;
  10720. }
  10721. void XmlDocument::readChildElements (XmlElement* parent)
  10722. {
  10723. XmlElement* lastChildNode = 0;
  10724. for (;;)
  10725. {
  10726. skipNextWhiteSpace();
  10727. if (outOfData)
  10728. {
  10729. setLastError ("unmatched tags", false);
  10730. break;
  10731. }
  10732. if (*input == '<')
  10733. {
  10734. if (input[1] == '/')
  10735. {
  10736. // our close tag..
  10737. input = CharacterFunctions::find (input, T(">"));
  10738. ++input;
  10739. break;
  10740. }
  10741. else if (input[1] == '!'
  10742. && input[2] == '['
  10743. && input[3] == 'C'
  10744. && input[4] == 'D'
  10745. && input[5] == 'A'
  10746. && input[6] == 'T'
  10747. && input[7] == 'A'
  10748. && input[8] == '[')
  10749. {
  10750. input += 9;
  10751. const juce_wchar* const inputStart = input;
  10752. int len = 0;
  10753. for (;;)
  10754. {
  10755. if (*input == 0)
  10756. {
  10757. setLastError ("unterminated CDATA section", false);
  10758. outOfData = true;
  10759. break;
  10760. }
  10761. else if (input[0] == ']'
  10762. && input[1] == ']'
  10763. && input[2] == '>')
  10764. {
  10765. input += 3;
  10766. break;
  10767. }
  10768. ++input;
  10769. ++len;
  10770. }
  10771. XmlElement* const e = new XmlElement ((int) 0);
  10772. e->setText (String (inputStart, len));
  10773. if (lastChildNode != 0)
  10774. lastChildNode->nextElement = e;
  10775. else
  10776. parent->addChildElement (e);
  10777. lastChildNode = e;
  10778. }
  10779. else
  10780. {
  10781. // this is some other element, so parse and add it..
  10782. XmlElement* const n = readNextElement (true);
  10783. if (n != 0)
  10784. {
  10785. if (lastChildNode == 0)
  10786. parent->addChildElement (n);
  10787. else
  10788. lastChildNode->nextElement = n;
  10789. lastChildNode = n;
  10790. }
  10791. else
  10792. {
  10793. return;
  10794. }
  10795. }
  10796. }
  10797. else
  10798. {
  10799. // read character block..
  10800. XmlElement* const e = new XmlElement ((int)0);
  10801. if (lastChildNode != 0)
  10802. lastChildNode->nextElement = e;
  10803. else
  10804. parent->addChildElement (e);
  10805. lastChildNode = e;
  10806. String textElementContent;
  10807. for (;;)
  10808. {
  10809. const juce_wchar c = *input;
  10810. if (c == '<')
  10811. break;
  10812. if (c == 0)
  10813. {
  10814. setLastError ("unmatched tags", false);
  10815. outOfData = true;
  10816. return;
  10817. }
  10818. if (c == '&')
  10819. {
  10820. String entity;
  10821. readEntity (entity);
  10822. if (entity.startsWithChar ('<') && entity [1] != 0)
  10823. {
  10824. const juce_wchar* const oldInput = input;
  10825. const bool oldOutOfData = outOfData;
  10826. input = entity;
  10827. outOfData = false;
  10828. for (;;)
  10829. {
  10830. XmlElement* const n = readNextElement (true);
  10831. if (n == 0)
  10832. break;
  10833. if (lastChildNode == 0)
  10834. parent->addChildElement (n);
  10835. else
  10836. lastChildNode->nextElement = n;
  10837. lastChildNode = n;
  10838. }
  10839. input = oldInput;
  10840. outOfData = oldOutOfData;
  10841. }
  10842. else
  10843. {
  10844. textElementContent += entity;
  10845. }
  10846. }
  10847. else
  10848. {
  10849. const juce_wchar* start = input;
  10850. int len = 0;
  10851. for (;;)
  10852. {
  10853. const juce_wchar nextChar = *input;
  10854. if (nextChar == '<' || nextChar == '&')
  10855. {
  10856. break;
  10857. }
  10858. else if (nextChar == 0)
  10859. {
  10860. setLastError ("unmatched tags", false);
  10861. outOfData = true;
  10862. return;
  10863. }
  10864. ++input;
  10865. ++len;
  10866. }
  10867. textElementContent.append (start, len);
  10868. }
  10869. }
  10870. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  10871. : textElementContent.isNotEmpty())
  10872. e->setText (textElementContent);
  10873. }
  10874. }
  10875. }
  10876. void XmlDocument::readEntity (String& result)
  10877. {
  10878. // skip over the ampersand
  10879. ++input;
  10880. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  10881. {
  10882. input += 4;
  10883. result += '&';
  10884. }
  10885. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  10886. {
  10887. input += 5;
  10888. result += '"';
  10889. }
  10890. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  10891. {
  10892. input += 5;
  10893. result += '\'';
  10894. }
  10895. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  10896. {
  10897. input += 3;
  10898. result += '<';
  10899. }
  10900. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  10901. {
  10902. input += 3;
  10903. result += '>';
  10904. }
  10905. else if (*input == '#')
  10906. {
  10907. int charCode = 0;
  10908. ++input;
  10909. if (*input == 'x' || *input == 'X')
  10910. {
  10911. ++input;
  10912. int numChars = 0;
  10913. while (input[0] != ';')
  10914. {
  10915. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  10916. if (hexValue < 0 || ++numChars > 8)
  10917. {
  10918. setLastError ("illegal escape sequence", true);
  10919. break;
  10920. }
  10921. charCode = (charCode << 4) | hexValue;
  10922. ++input;
  10923. }
  10924. ++input;
  10925. }
  10926. else if (input[0] >= '0' && input[0] <= '9')
  10927. {
  10928. int numChars = 0;
  10929. while (input[0] != ';')
  10930. {
  10931. if (++numChars > 12)
  10932. {
  10933. setLastError ("illegal escape sequence", true);
  10934. break;
  10935. }
  10936. charCode = charCode * 10 + (input[0] - '0');
  10937. ++input;
  10938. }
  10939. ++input;
  10940. }
  10941. else
  10942. {
  10943. setLastError ("illegal escape sequence", true);
  10944. result += '&';
  10945. return;
  10946. }
  10947. result << (juce_wchar) charCode;
  10948. }
  10949. else
  10950. {
  10951. const juce_wchar* const entityNameStart = input;
  10952. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10953. if (closingSemiColon == 0)
  10954. {
  10955. outOfData = true;
  10956. result += '&';
  10957. }
  10958. else
  10959. {
  10960. input = closingSemiColon + 1;
  10961. result += expandExternalEntity (String (entityNameStart,
  10962. (int) (closingSemiColon - entityNameStart)));
  10963. }
  10964. }
  10965. }
  10966. const String XmlDocument::expandEntity (const String& ent)
  10967. {
  10968. if (ent.equalsIgnoreCase ("amp"))
  10969. return String::charToString ('&');
  10970. if (ent.equalsIgnoreCase ("quot"))
  10971. return String::charToString ('"');
  10972. if (ent.equalsIgnoreCase ("apos"))
  10973. return String::charToString ('\'');
  10974. if (ent.equalsIgnoreCase ("lt"))
  10975. return String::charToString ('<');
  10976. if (ent.equalsIgnoreCase ("gt"))
  10977. return String::charToString ('>');
  10978. if (ent[0] == '#')
  10979. {
  10980. if (ent[1] == 'x' || ent[1] == 'X')
  10981. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  10982. if (ent[1] >= '0' && ent[1] <= '9')
  10983. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  10984. setLastError ("illegal escape sequence", false);
  10985. return String::charToString ('&');
  10986. }
  10987. return expandExternalEntity (ent);
  10988. }
  10989. const String XmlDocument::expandExternalEntity (const String& entity)
  10990. {
  10991. if (needToLoadDTD)
  10992. {
  10993. if (dtdText.isNotEmpty())
  10994. {
  10995. dtdText = dtdText.trimCharactersAtEnd (">");
  10996. tokenisedDTD.addTokens (dtdText, true);
  10997. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  10998. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10999. {
  11000. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11001. tokenisedDTD.clear();
  11002. tokenisedDTD.addTokens (getFileContents (fn), true);
  11003. }
  11004. else
  11005. {
  11006. tokenisedDTD.clear();
  11007. const int openBracket = dtdText.indexOfChar ('[');
  11008. if (openBracket > 0)
  11009. {
  11010. const int closeBracket = dtdText.lastIndexOfChar (']');
  11011. if (closeBracket > openBracket)
  11012. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11013. closeBracket), true);
  11014. }
  11015. }
  11016. for (int i = tokenisedDTD.size(); --i >= 0;)
  11017. {
  11018. if (tokenisedDTD[i].startsWithChar ('%')
  11019. && tokenisedDTD[i].endsWithChar (';'))
  11020. {
  11021. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11022. StringArray newToks;
  11023. newToks.addTokens (parsed, true);
  11024. tokenisedDTD.remove (i);
  11025. for (int j = newToks.size(); --j >= 0;)
  11026. tokenisedDTD.insert (i, newToks[j]);
  11027. }
  11028. }
  11029. }
  11030. needToLoadDTD = false;
  11031. }
  11032. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11033. {
  11034. if (tokenisedDTD[i] == entity)
  11035. {
  11036. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11037. {
  11038. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11039. // check for sub-entities..
  11040. int ampersand = ent.indexOfChar ('&');
  11041. while (ampersand >= 0)
  11042. {
  11043. const int semiColon = ent.indexOf (i + 1, ";");
  11044. if (semiColon < 0)
  11045. {
  11046. setLastError ("entity without terminating semi-colon", false);
  11047. break;
  11048. }
  11049. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11050. ent = ent.substring (0, ampersand)
  11051. + resolved
  11052. + ent.substring (semiColon + 1);
  11053. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11054. }
  11055. return ent;
  11056. }
  11057. }
  11058. }
  11059. setLastError ("unknown entity", true);
  11060. return entity;
  11061. }
  11062. const String XmlDocument::getParameterEntity (const String& entity)
  11063. {
  11064. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11065. {
  11066. if (tokenisedDTD[i] == entity)
  11067. {
  11068. if (tokenisedDTD [i - 1] == "%"
  11069. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11070. {
  11071. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11072. if (ent.equalsIgnoreCase ("system"))
  11073. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11074. else
  11075. return ent.trim().unquoted();
  11076. }
  11077. }
  11078. }
  11079. return entity;
  11080. }
  11081. END_JUCE_NAMESPACE
  11082. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11083. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11084. BEGIN_JUCE_NAMESPACE
  11085. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11086. : name (other.name),
  11087. value (other.value),
  11088. next (0)
  11089. {
  11090. }
  11091. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11092. : name (name_),
  11093. value (value_),
  11094. next (0)
  11095. {
  11096. }
  11097. XmlElement::XmlElement (const String& tagName_) throw()
  11098. : tagName (tagName_),
  11099. firstChildElement (0),
  11100. nextElement (0),
  11101. attributes (0)
  11102. {
  11103. // the tag name mustn't be empty, or it'll look like a text element!
  11104. jassert (tagName_.containsNonWhitespaceChars())
  11105. // The tag can't contain spaces or other characters that would create invalid XML!
  11106. jassert (! tagName_.containsAnyOf (" <>/&"));
  11107. }
  11108. XmlElement::XmlElement (int /*dummy*/) throw()
  11109. : firstChildElement (0),
  11110. nextElement (0),
  11111. attributes (0)
  11112. {
  11113. }
  11114. XmlElement::XmlElement (const XmlElement& other) throw()
  11115. : tagName (other.tagName),
  11116. firstChildElement (0),
  11117. nextElement (0),
  11118. attributes (0)
  11119. {
  11120. copyChildrenAndAttributesFrom (other);
  11121. }
  11122. XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11123. {
  11124. if (this != &other)
  11125. {
  11126. removeAllAttributes();
  11127. deleteAllChildElements();
  11128. tagName = other.tagName;
  11129. copyChildrenAndAttributesFrom (other);
  11130. }
  11131. return *this;
  11132. }
  11133. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11134. {
  11135. XmlElement* child = other.firstChildElement;
  11136. XmlElement* lastChild = 0;
  11137. while (child != 0)
  11138. {
  11139. XmlElement* const copiedChild = new XmlElement (*child);
  11140. if (lastChild != 0)
  11141. lastChild->nextElement = copiedChild;
  11142. else
  11143. firstChildElement = copiedChild;
  11144. lastChild = copiedChild;
  11145. child = child->nextElement;
  11146. }
  11147. const XmlAttributeNode* att = other.attributes;
  11148. XmlAttributeNode* lastAtt = 0;
  11149. while (att != 0)
  11150. {
  11151. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11152. if (lastAtt != 0)
  11153. lastAtt->next = newAtt;
  11154. else
  11155. attributes = newAtt;
  11156. lastAtt = newAtt;
  11157. att = att->next;
  11158. }
  11159. }
  11160. XmlElement::~XmlElement() throw()
  11161. {
  11162. XmlElement* child = firstChildElement;
  11163. while (child != 0)
  11164. {
  11165. XmlElement* const nextChild = child->nextElement;
  11166. delete child;
  11167. child = nextChild;
  11168. }
  11169. XmlAttributeNode* att = attributes;
  11170. while (att != 0)
  11171. {
  11172. XmlAttributeNode* const nextAtt = att->next;
  11173. delete att;
  11174. att = nextAtt;
  11175. }
  11176. }
  11177. namespace XmlOutputFunctions
  11178. {
  11179. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11180. {
  11181. if ((character >= 'a' && character <= 'z')
  11182. || (character >= 'A' && character <= 'Z')
  11183. || (character >= '0' && character <= '9'))
  11184. return true;
  11185. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11186. do
  11187. {
  11188. if (((juce_wchar) (uint8) *t) == character)
  11189. return true;
  11190. }
  11191. while (*++t != 0);
  11192. return false;
  11193. }
  11194. static void generateLegalCharConstants()
  11195. {
  11196. uint8 n[32];
  11197. zerostruct (n);
  11198. for (int i = 0; i < 256; ++i)
  11199. if (isLegalXmlCharSlow (i))
  11200. n[i >> 3] |= (1 << (i & 7));
  11201. String s;
  11202. for (int i = 0; i < 32; ++i)
  11203. s << (int) n[i] << ", ";
  11204. DBG (s);
  11205. }*/
  11206. static bool isLegalXmlChar (const uint32 c) throw()
  11207. {
  11208. static const unsigned char legalChars[] = { 0, 0, 0, 0, 171, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 111 };
  11209. return c < sizeof (legalChars) * 8
  11210. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11211. }
  11212. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11213. {
  11214. const juce_wchar* t = text;
  11215. for (;;)
  11216. {
  11217. const juce_wchar character = *t++;
  11218. if (character == 0)
  11219. {
  11220. break;
  11221. }
  11222. else if (isLegalXmlChar ((uint32) character))
  11223. {
  11224. outputStream << (char) character;
  11225. }
  11226. else
  11227. {
  11228. switch (character)
  11229. {
  11230. case '&': outputStream << "&amp;"; break;
  11231. case '"': outputStream << "&quot;"; break;
  11232. case '>': outputStream << "&gt;"; break;
  11233. case '<': outputStream << "&lt;"; break;
  11234. case '\n':
  11235. if (changeNewLines)
  11236. outputStream << "&#10;";
  11237. else
  11238. outputStream << (char) character;
  11239. break;
  11240. case '\r':
  11241. if (changeNewLines)
  11242. outputStream << "&#13;";
  11243. else
  11244. outputStream << (char) character;
  11245. break;
  11246. default:
  11247. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11248. break;
  11249. }
  11250. }
  11251. }
  11252. }
  11253. static void writeSpaces (OutputStream& out, int numSpaces)
  11254. {
  11255. if (numSpaces > 0)
  11256. {
  11257. const char* const blanks = " ";
  11258. const int blankSize = (int) sizeof (blanks) - 1;
  11259. while (numSpaces > blankSize)
  11260. {
  11261. out.write (blanks, blankSize);
  11262. numSpaces -= blankSize;
  11263. }
  11264. out.write (blanks, numSpaces);
  11265. }
  11266. }
  11267. }
  11268. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11269. const int indentationLevel,
  11270. const int lineWrapLength) const
  11271. {
  11272. using namespace XmlOutputFunctions;
  11273. writeSpaces (outputStream, indentationLevel);
  11274. if (! isTextElement())
  11275. {
  11276. outputStream.writeByte ('<');
  11277. outputStream << tagName;
  11278. const int attIndent = indentationLevel + tagName.length() + 1;
  11279. int lineLen = 0;
  11280. const XmlAttributeNode* att = attributes;
  11281. while (att != 0)
  11282. {
  11283. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11284. {
  11285. outputStream.write ("\r\n", 2);
  11286. writeSpaces (outputStream, attIndent);
  11287. lineLen = 0;
  11288. }
  11289. const int64 startPos = outputStream.getPosition();
  11290. outputStream.writeByte (' ');
  11291. outputStream << att->name;
  11292. outputStream.write ("=\"", 2);
  11293. escapeIllegalXmlChars (outputStream, att->value, true);
  11294. outputStream.writeByte ('"');
  11295. lineLen += (int) (outputStream.getPosition() - startPos);
  11296. att = att->next;
  11297. }
  11298. if (firstChildElement != 0)
  11299. {
  11300. XmlElement* child = firstChildElement;
  11301. if (child->nextElement == 0 && child->isTextElement())
  11302. {
  11303. outputStream.writeByte ('>');
  11304. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11305. }
  11306. else
  11307. {
  11308. if (indentationLevel >= 0)
  11309. outputStream.write (">\r\n", 3);
  11310. else
  11311. outputStream.writeByte ('>');
  11312. bool lastWasTextNode = false;
  11313. while (child != 0)
  11314. {
  11315. if (child->isTextElement())
  11316. {
  11317. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11318. writeSpaces (outputStream, indentationLevel + 2);
  11319. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11320. lastWasTextNode = true;
  11321. }
  11322. else
  11323. {
  11324. if (indentationLevel >= 0)
  11325. {
  11326. if (lastWasTextNode)
  11327. outputStream.write ("\r\n", 2);
  11328. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11329. }
  11330. else
  11331. {
  11332. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11333. }
  11334. lastWasTextNode = false;
  11335. }
  11336. child = child->nextElement;
  11337. }
  11338. if (indentationLevel >= 0)
  11339. {
  11340. if (lastWasTextNode)
  11341. outputStream.write ("\r\n", 2);
  11342. writeSpaces (outputStream, indentationLevel);
  11343. }
  11344. }
  11345. outputStream.write ("</", 2);
  11346. outputStream << tagName;
  11347. if (indentationLevel >= 0)
  11348. outputStream.write (">\r\n", 3);
  11349. else
  11350. outputStream.writeByte ('>');
  11351. }
  11352. else
  11353. {
  11354. if (indentationLevel >= 0)
  11355. outputStream.write ("/>\r\n", 4);
  11356. else
  11357. outputStream.write ("/>", 2);
  11358. }
  11359. }
  11360. else
  11361. {
  11362. if (indentationLevel >= 0)
  11363. writeSpaces (outputStream, indentationLevel + 2);
  11364. escapeIllegalXmlChars (outputStream, getText(), false);
  11365. }
  11366. }
  11367. const String XmlElement::createDocument (const String& dtdToUse,
  11368. const bool allOnOneLine,
  11369. const bool includeXmlHeader,
  11370. const String& encodingType,
  11371. const int lineWrapLength) const
  11372. {
  11373. MemoryOutputStream mem (2048, 4096);
  11374. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11375. return mem.toUTF8();
  11376. }
  11377. void XmlElement::writeToStream (OutputStream& output,
  11378. const String& dtdToUse,
  11379. const bool allOnOneLine,
  11380. const bool includeXmlHeader,
  11381. const String& encodingType,
  11382. const int lineWrapLength) const
  11383. {
  11384. if (includeXmlHeader)
  11385. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11386. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11387. if (dtdToUse.isNotEmpty())
  11388. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11389. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11390. }
  11391. bool XmlElement::writeToFile (const File& file,
  11392. const String& dtdToUse,
  11393. const String& encodingType,
  11394. const int lineWrapLength) const
  11395. {
  11396. if (file.hasWriteAccess())
  11397. {
  11398. TemporaryFile tempFile (file);
  11399. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11400. if (out != 0)
  11401. {
  11402. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11403. out = 0;
  11404. return tempFile.overwriteTargetFileWithTemporary();
  11405. }
  11406. }
  11407. return false;
  11408. }
  11409. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11410. {
  11411. #if JUCE_DEBUG
  11412. // if debugging, check that the case is actually the same, because
  11413. // valid xml is case-sensitive, and although this lets it pass, it's
  11414. // better not to..
  11415. if (tagName.equalsIgnoreCase (tagNameWanted))
  11416. {
  11417. jassert (tagName == tagNameWanted);
  11418. return true;
  11419. }
  11420. else
  11421. {
  11422. return false;
  11423. }
  11424. #else
  11425. return tagName.equalsIgnoreCase (tagNameWanted);
  11426. #endif
  11427. }
  11428. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11429. {
  11430. XmlElement* e = nextElement;
  11431. while (e != 0 && ! e->hasTagName (requiredTagName))
  11432. e = e->nextElement;
  11433. return e;
  11434. }
  11435. int XmlElement::getNumAttributes() const throw()
  11436. {
  11437. const XmlAttributeNode* att = attributes;
  11438. int count = 0;
  11439. while (att != 0)
  11440. {
  11441. att = att->next;
  11442. ++count;
  11443. }
  11444. return count;
  11445. }
  11446. const String& XmlElement::getAttributeName (const int index) const throw()
  11447. {
  11448. const XmlAttributeNode* att = attributes;
  11449. int count = 0;
  11450. while (att != 0)
  11451. {
  11452. if (count == index)
  11453. return att->name;
  11454. att = att->next;
  11455. ++count;
  11456. }
  11457. return String::empty;
  11458. }
  11459. const String& XmlElement::getAttributeValue (const int index) const throw()
  11460. {
  11461. const XmlAttributeNode* att = attributes;
  11462. int count = 0;
  11463. while (att != 0)
  11464. {
  11465. if (count == index)
  11466. return att->value;
  11467. att = att->next;
  11468. ++count;
  11469. }
  11470. return String::empty;
  11471. }
  11472. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11473. {
  11474. const XmlAttributeNode* att = attributes;
  11475. while (att != 0)
  11476. {
  11477. if (att->name.equalsIgnoreCase (attributeName))
  11478. return true;
  11479. att = att->next;
  11480. }
  11481. return false;
  11482. }
  11483. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11484. {
  11485. const XmlAttributeNode* att = attributes;
  11486. while (att != 0)
  11487. {
  11488. if (att->name.equalsIgnoreCase (attributeName))
  11489. return att->value;
  11490. att = att->next;
  11491. }
  11492. return String::empty;
  11493. }
  11494. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11495. {
  11496. const XmlAttributeNode* att = attributes;
  11497. while (att != 0)
  11498. {
  11499. if (att->name.equalsIgnoreCase (attributeName))
  11500. return att->value;
  11501. att = att->next;
  11502. }
  11503. return defaultReturnValue;
  11504. }
  11505. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11506. {
  11507. const XmlAttributeNode* att = attributes;
  11508. while (att != 0)
  11509. {
  11510. if (att->name.equalsIgnoreCase (attributeName))
  11511. return att->value.getIntValue();
  11512. att = att->next;
  11513. }
  11514. return defaultReturnValue;
  11515. }
  11516. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11517. {
  11518. const XmlAttributeNode* att = attributes;
  11519. while (att != 0)
  11520. {
  11521. if (att->name.equalsIgnoreCase (attributeName))
  11522. return att->value.getDoubleValue();
  11523. att = att->next;
  11524. }
  11525. return defaultReturnValue;
  11526. }
  11527. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11528. {
  11529. const XmlAttributeNode* att = attributes;
  11530. while (att != 0)
  11531. {
  11532. if (att->name.equalsIgnoreCase (attributeName))
  11533. {
  11534. juce_wchar firstChar = att->value[0];
  11535. if (CharacterFunctions::isWhitespace (firstChar))
  11536. firstChar = att->value.trimStart() [0];
  11537. return firstChar == '1'
  11538. || firstChar == 't'
  11539. || firstChar == 'y'
  11540. || firstChar == 'T'
  11541. || firstChar == 'Y';
  11542. }
  11543. att = att->next;
  11544. }
  11545. return defaultReturnValue;
  11546. }
  11547. bool XmlElement::compareAttribute (const String& attributeName,
  11548. const String& stringToCompareAgainst,
  11549. const bool ignoreCase) const throw()
  11550. {
  11551. const XmlAttributeNode* att = attributes;
  11552. while (att != 0)
  11553. {
  11554. if (att->name.equalsIgnoreCase (attributeName))
  11555. {
  11556. if (ignoreCase)
  11557. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11558. else
  11559. return att->value == stringToCompareAgainst;
  11560. }
  11561. att = att->next;
  11562. }
  11563. return false;
  11564. }
  11565. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11566. {
  11567. #if JUCE_DEBUG
  11568. // check the identifier being passed in is legal..
  11569. const juce_wchar* t = attributeName;
  11570. while (*t != 0)
  11571. {
  11572. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11573. || *t == '_'
  11574. || *t == '-'
  11575. || *t == ':');
  11576. ++t;
  11577. }
  11578. #endif
  11579. if (attributes == 0)
  11580. {
  11581. attributes = new XmlAttributeNode (attributeName, value);
  11582. }
  11583. else
  11584. {
  11585. XmlAttributeNode* att = attributes;
  11586. for (;;)
  11587. {
  11588. if (att->name.equalsIgnoreCase (attributeName))
  11589. {
  11590. att->value = value;
  11591. break;
  11592. }
  11593. else if (att->next == 0)
  11594. {
  11595. att->next = new XmlAttributeNode (attributeName, value);
  11596. break;
  11597. }
  11598. att = att->next;
  11599. }
  11600. }
  11601. }
  11602. void XmlElement::setAttribute (const String& attributeName, const int number)
  11603. {
  11604. setAttribute (attributeName, String (number));
  11605. }
  11606. void XmlElement::setAttribute (const String& attributeName, const double number)
  11607. {
  11608. setAttribute (attributeName, String (number));
  11609. }
  11610. void XmlElement::removeAttribute (const String& attributeName) throw()
  11611. {
  11612. XmlAttributeNode* att = attributes;
  11613. XmlAttributeNode* lastAtt = 0;
  11614. while (att != 0)
  11615. {
  11616. if (att->name.equalsIgnoreCase (attributeName))
  11617. {
  11618. if (lastAtt == 0)
  11619. attributes = att->next;
  11620. else
  11621. lastAtt->next = att->next;
  11622. delete att;
  11623. break;
  11624. }
  11625. lastAtt = att;
  11626. att = att->next;
  11627. }
  11628. }
  11629. void XmlElement::removeAllAttributes() throw()
  11630. {
  11631. while (attributes != 0)
  11632. {
  11633. XmlAttributeNode* const nextAtt = attributes->next;
  11634. delete attributes;
  11635. attributes = nextAtt;
  11636. }
  11637. }
  11638. int XmlElement::getNumChildElements() const throw()
  11639. {
  11640. int count = 0;
  11641. const XmlElement* child = firstChildElement;
  11642. while (child != 0)
  11643. {
  11644. ++count;
  11645. child = child->nextElement;
  11646. }
  11647. return count;
  11648. }
  11649. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11650. {
  11651. int count = 0;
  11652. XmlElement* child = firstChildElement;
  11653. while (child != 0 && count < index)
  11654. {
  11655. child = child->nextElement;
  11656. ++count;
  11657. }
  11658. return child;
  11659. }
  11660. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11661. {
  11662. XmlElement* child = firstChildElement;
  11663. while (child != 0)
  11664. {
  11665. if (child->hasTagName (childName))
  11666. break;
  11667. child = child->nextElement;
  11668. }
  11669. return child;
  11670. }
  11671. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11672. {
  11673. if (newNode != 0)
  11674. {
  11675. if (firstChildElement == 0)
  11676. {
  11677. firstChildElement = newNode;
  11678. }
  11679. else
  11680. {
  11681. XmlElement* child = firstChildElement;
  11682. while (child->nextElement != 0)
  11683. child = child->nextElement;
  11684. child->nextElement = newNode;
  11685. // if this is non-zero, then something's probably
  11686. // gone wrong..
  11687. jassert (newNode->nextElement == 0);
  11688. }
  11689. }
  11690. }
  11691. void XmlElement::insertChildElement (XmlElement* const newNode,
  11692. int indexToInsertAt) throw()
  11693. {
  11694. if (newNode != 0)
  11695. {
  11696. removeChildElement (newNode, false);
  11697. if (indexToInsertAt == 0)
  11698. {
  11699. newNode->nextElement = firstChildElement;
  11700. firstChildElement = newNode;
  11701. }
  11702. else
  11703. {
  11704. if (firstChildElement == 0)
  11705. {
  11706. firstChildElement = newNode;
  11707. }
  11708. else
  11709. {
  11710. if (indexToInsertAt < 0)
  11711. indexToInsertAt = std::numeric_limits<int>::max();
  11712. XmlElement* child = firstChildElement;
  11713. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11714. child = child->nextElement;
  11715. newNode->nextElement = child->nextElement;
  11716. child->nextElement = newNode;
  11717. }
  11718. }
  11719. }
  11720. }
  11721. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11722. {
  11723. XmlElement* const newElement = new XmlElement (childTagName);
  11724. addChildElement (newElement);
  11725. return newElement;
  11726. }
  11727. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11728. XmlElement* const newNode) throw()
  11729. {
  11730. if (newNode != 0)
  11731. {
  11732. XmlElement* child = firstChildElement;
  11733. XmlElement* previousNode = 0;
  11734. while (child != 0)
  11735. {
  11736. if (child == currentChildElement)
  11737. {
  11738. if (child != newNode)
  11739. {
  11740. if (previousNode == 0)
  11741. firstChildElement = newNode;
  11742. else
  11743. previousNode->nextElement = newNode;
  11744. newNode->nextElement = child->nextElement;
  11745. delete child;
  11746. }
  11747. return true;
  11748. }
  11749. previousNode = child;
  11750. child = child->nextElement;
  11751. }
  11752. }
  11753. return false;
  11754. }
  11755. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11756. const bool shouldDeleteTheChild) throw()
  11757. {
  11758. if (childToRemove != 0)
  11759. {
  11760. if (firstChildElement == childToRemove)
  11761. {
  11762. firstChildElement = childToRemove->nextElement;
  11763. childToRemove->nextElement = 0;
  11764. }
  11765. else
  11766. {
  11767. XmlElement* child = firstChildElement;
  11768. XmlElement* last = 0;
  11769. while (child != 0)
  11770. {
  11771. if (child == childToRemove)
  11772. {
  11773. if (last == 0)
  11774. firstChildElement = child->nextElement;
  11775. else
  11776. last->nextElement = child->nextElement;
  11777. childToRemove->nextElement = 0;
  11778. break;
  11779. }
  11780. last = child;
  11781. child = child->nextElement;
  11782. }
  11783. }
  11784. if (shouldDeleteTheChild)
  11785. delete childToRemove;
  11786. }
  11787. }
  11788. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11789. const bool ignoreOrderOfAttributes) const throw()
  11790. {
  11791. if (this != other)
  11792. {
  11793. if (other == 0 || tagName != other->tagName)
  11794. {
  11795. return false;
  11796. }
  11797. if (ignoreOrderOfAttributes)
  11798. {
  11799. int totalAtts = 0;
  11800. const XmlAttributeNode* att = attributes;
  11801. while (att != 0)
  11802. {
  11803. if (! other->compareAttribute (att->name, att->value))
  11804. return false;
  11805. att = att->next;
  11806. ++totalAtts;
  11807. }
  11808. if (totalAtts != other->getNumAttributes())
  11809. return false;
  11810. }
  11811. else
  11812. {
  11813. const XmlAttributeNode* thisAtt = attributes;
  11814. const XmlAttributeNode* otherAtt = other->attributes;
  11815. for (;;)
  11816. {
  11817. if (thisAtt == 0 || otherAtt == 0)
  11818. {
  11819. if (thisAtt == otherAtt) // both 0, so it's a match
  11820. break;
  11821. return false;
  11822. }
  11823. if (thisAtt->name != otherAtt->name
  11824. || thisAtt->value != otherAtt->value)
  11825. {
  11826. return false;
  11827. }
  11828. thisAtt = thisAtt->next;
  11829. otherAtt = otherAtt->next;
  11830. }
  11831. }
  11832. const XmlElement* thisChild = firstChildElement;
  11833. const XmlElement* otherChild = other->firstChildElement;
  11834. for (;;)
  11835. {
  11836. if (thisChild == 0 || otherChild == 0)
  11837. {
  11838. if (thisChild == otherChild) // both 0, so it's a match
  11839. break;
  11840. return false;
  11841. }
  11842. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11843. return false;
  11844. thisChild = thisChild->nextElement;
  11845. otherChild = otherChild->nextElement;
  11846. }
  11847. }
  11848. return true;
  11849. }
  11850. void XmlElement::deleteAllChildElements() throw()
  11851. {
  11852. while (firstChildElement != 0)
  11853. {
  11854. XmlElement* const nextChild = firstChildElement->nextElement;
  11855. delete firstChildElement;
  11856. firstChildElement = nextChild;
  11857. }
  11858. }
  11859. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  11860. {
  11861. XmlElement* child = firstChildElement;
  11862. while (child != 0)
  11863. {
  11864. if (child->hasTagName (name))
  11865. {
  11866. XmlElement* const nextChild = child->nextElement;
  11867. removeChildElement (child, true);
  11868. child = nextChild;
  11869. }
  11870. else
  11871. {
  11872. child = child->nextElement;
  11873. }
  11874. }
  11875. }
  11876. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  11877. {
  11878. const XmlElement* child = firstChildElement;
  11879. while (child != 0)
  11880. {
  11881. if (child == possibleChild)
  11882. return true;
  11883. child = child->nextElement;
  11884. }
  11885. return false;
  11886. }
  11887. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  11888. {
  11889. if (this == elementToLookFor || elementToLookFor == 0)
  11890. return 0;
  11891. XmlElement* child = firstChildElement;
  11892. while (child != 0)
  11893. {
  11894. if (elementToLookFor == child)
  11895. return this;
  11896. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  11897. if (found != 0)
  11898. return found;
  11899. child = child->nextElement;
  11900. }
  11901. return 0;
  11902. }
  11903. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  11904. {
  11905. XmlElement* e = firstChildElement;
  11906. while (e != 0)
  11907. {
  11908. *elems++ = e;
  11909. e = e->nextElement;
  11910. }
  11911. }
  11912. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11913. {
  11914. XmlElement* e = firstChildElement = elems[0];
  11915. for (int i = 1; i < num; ++i)
  11916. {
  11917. e->nextElement = elems[i];
  11918. e = e->nextElement;
  11919. }
  11920. e->nextElement = 0;
  11921. }
  11922. bool XmlElement::isTextElement() const throw()
  11923. {
  11924. return tagName.isEmpty();
  11925. }
  11926. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  11927. const String XmlElement::getText() const throw()
  11928. {
  11929. jassert (isTextElement()); // you're trying to get the text from an element that
  11930. // isn't actually a text element.. If this contains text sub-nodes, you
  11931. // probably want to use getAllSubText instead.
  11932. return getStringAttribute (juce_xmltextContentAttributeName);
  11933. }
  11934. void XmlElement::setText (const String& newText) throw()
  11935. {
  11936. if (isTextElement())
  11937. {
  11938. setAttribute (juce_xmltextContentAttributeName, newText);
  11939. }
  11940. else
  11941. {
  11942. jassertfalse // you can only change the text in a text element, not a normal one.
  11943. }
  11944. }
  11945. const String XmlElement::getAllSubText() const throw()
  11946. {
  11947. String result;
  11948. String::Concatenator concatenator (result);
  11949. const XmlElement* child = firstChildElement;
  11950. while (child != 0)
  11951. {
  11952. if (child->isTextElement())
  11953. concatenator.append (child->getText());
  11954. child = child->nextElement;
  11955. }
  11956. return result;
  11957. }
  11958. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  11959. const String& defaultReturnValue) const throw()
  11960. {
  11961. const XmlElement* const child = getChildByName (childTagName);
  11962. if (child != 0)
  11963. return child->getAllSubText();
  11964. return defaultReturnValue;
  11965. }
  11966. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11967. {
  11968. XmlElement* const e = new XmlElement ((int) 0);
  11969. e->setAttribute (juce_xmltextContentAttributeName, text);
  11970. return e;
  11971. }
  11972. void XmlElement::addTextElement (const String& text) throw()
  11973. {
  11974. addChildElement (createTextElement (text));
  11975. }
  11976. void XmlElement::deleteAllTextElements() throw()
  11977. {
  11978. XmlElement* child = firstChildElement;
  11979. while (child != 0)
  11980. {
  11981. XmlElement* const next = child->nextElement;
  11982. if (child->isTextElement())
  11983. removeChildElement (child, true);
  11984. child = next;
  11985. }
  11986. }
  11987. END_JUCE_NAMESPACE
  11988. /*** End of inlined file: juce_XmlElement.cpp ***/
  11989. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  11990. BEGIN_JUCE_NAMESPACE
  11991. ReadWriteLock::ReadWriteLock() throw()
  11992. : numWaitingWriters (0),
  11993. numWriters (0),
  11994. writerThreadId (0)
  11995. {
  11996. }
  11997. ReadWriteLock::~ReadWriteLock() throw()
  11998. {
  11999. jassert (readerThreads.size() == 0);
  12000. jassert (numWriters == 0);
  12001. }
  12002. void ReadWriteLock::enterRead() const throw()
  12003. {
  12004. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12005. const ScopedLock sl (accessLock);
  12006. for (;;)
  12007. {
  12008. jassert (readerThreads.size() % 2 == 0);
  12009. int i;
  12010. for (i = 0; i < readerThreads.size(); i += 2)
  12011. if (readerThreads.getUnchecked(i) == threadId)
  12012. break;
  12013. if (i < readerThreads.size()
  12014. || numWriters + numWaitingWriters == 0
  12015. || (threadId == writerThreadId && numWriters > 0))
  12016. {
  12017. if (i < readerThreads.size())
  12018. {
  12019. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12020. }
  12021. else
  12022. {
  12023. readerThreads.add (threadId);
  12024. readerThreads.add ((Thread::ThreadID) 1);
  12025. }
  12026. return;
  12027. }
  12028. const ScopedUnlock ul (accessLock);
  12029. waitEvent.wait (100);
  12030. }
  12031. }
  12032. void ReadWriteLock::exitRead() const throw()
  12033. {
  12034. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12035. const ScopedLock sl (accessLock);
  12036. for (int i = 0; i < readerThreads.size(); i += 2)
  12037. {
  12038. if (readerThreads.getUnchecked(i) == threadId)
  12039. {
  12040. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12041. if (newCount == 0)
  12042. {
  12043. readerThreads.removeRange (i, 2);
  12044. waitEvent.signal();
  12045. }
  12046. else
  12047. {
  12048. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12049. }
  12050. return;
  12051. }
  12052. }
  12053. jassertfalse // unlocking a lock that wasn't locked..
  12054. }
  12055. void ReadWriteLock::enterWrite() const throw()
  12056. {
  12057. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12058. const ScopedLock sl (accessLock);
  12059. for (;;)
  12060. {
  12061. if (readerThreads.size() + numWriters == 0
  12062. || threadId == writerThreadId
  12063. || (readerThreads.size() == 2
  12064. && readerThreads.getUnchecked(0) == threadId))
  12065. {
  12066. writerThreadId = threadId;
  12067. ++numWriters;
  12068. break;
  12069. }
  12070. ++numWaitingWriters;
  12071. accessLock.exit();
  12072. waitEvent.wait (100);
  12073. accessLock.enter();
  12074. --numWaitingWriters;
  12075. }
  12076. }
  12077. bool ReadWriteLock::tryEnterWrite() const throw()
  12078. {
  12079. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12080. const ScopedLock sl (accessLock);
  12081. if (readerThreads.size() + numWriters == 0
  12082. || threadId == writerThreadId
  12083. || (readerThreads.size() == 2
  12084. && readerThreads.getUnchecked(0) == threadId))
  12085. {
  12086. writerThreadId = threadId;
  12087. ++numWriters;
  12088. return true;
  12089. }
  12090. return false;
  12091. }
  12092. void ReadWriteLock::exitWrite() const throw()
  12093. {
  12094. const ScopedLock sl (accessLock);
  12095. // check this thread actually had the lock..
  12096. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12097. if (--numWriters == 0)
  12098. {
  12099. writerThreadId = 0;
  12100. waitEvent.signal();
  12101. }
  12102. }
  12103. END_JUCE_NAMESPACE
  12104. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12105. /*** Start of inlined file: juce_Thread.cpp ***/
  12106. BEGIN_JUCE_NAMESPACE
  12107. // these functions are implemented in the platform-specific code.
  12108. void* juce_createThread (void* userData);
  12109. void juce_killThread (void* handle);
  12110. bool juce_setThreadPriority (void* handle, int priority);
  12111. void juce_setCurrentThreadName (const String& name);
  12112. #if JUCE_WIN32
  12113. void juce_CloseThreadHandle (void* handle);
  12114. #endif
  12115. void Thread::threadEntryPoint (Thread* const thread)
  12116. {
  12117. {
  12118. const ScopedLock sl (runningThreadsLock);
  12119. runningThreads.add (thread);
  12120. }
  12121. JUCE_TRY
  12122. {
  12123. thread->threadId_ = Thread::getCurrentThreadId();
  12124. if (thread->threadName_.isNotEmpty())
  12125. juce_setCurrentThreadName (thread->threadName_);
  12126. if (thread->startSuspensionEvent_.wait (10000))
  12127. {
  12128. if (thread->affinityMask_ != 0)
  12129. setCurrentThreadAffinityMask (thread->affinityMask_);
  12130. thread->run();
  12131. }
  12132. }
  12133. JUCE_CATCH_ALL_ASSERT
  12134. {
  12135. const ScopedLock sl (runningThreadsLock);
  12136. jassert (runningThreads.contains (thread));
  12137. runningThreads.removeValue (thread);
  12138. }
  12139. #if JUCE_WIN32
  12140. juce_CloseThreadHandle (thread->threadHandle_);
  12141. #endif
  12142. thread->threadHandle_ = 0;
  12143. thread->threadId_ = 0;
  12144. }
  12145. // used to wrap the incoming call from the platform-specific code
  12146. void JUCE_API juce_threadEntryPoint (void* userData)
  12147. {
  12148. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12149. }
  12150. Thread::Thread (const String& threadName)
  12151. : threadName_ (threadName),
  12152. threadHandle_ (0),
  12153. threadPriority_ (5),
  12154. threadId_ (0),
  12155. affinityMask_ (0),
  12156. threadShouldExit_ (false)
  12157. {
  12158. }
  12159. Thread::~Thread()
  12160. {
  12161. stopThread (100);
  12162. }
  12163. void Thread::startThread()
  12164. {
  12165. const ScopedLock sl (startStopLock);
  12166. threadShouldExit_ = false;
  12167. if (threadHandle_ == 0)
  12168. {
  12169. threadHandle_ = juce_createThread (this);
  12170. juce_setThreadPriority (threadHandle_, threadPriority_);
  12171. startSuspensionEvent_.signal();
  12172. }
  12173. }
  12174. void Thread::startThread (const int priority)
  12175. {
  12176. const ScopedLock sl (startStopLock);
  12177. if (threadHandle_ == 0)
  12178. {
  12179. threadPriority_ = priority;
  12180. startThread();
  12181. }
  12182. else
  12183. {
  12184. setPriority (priority);
  12185. }
  12186. }
  12187. bool Thread::isThreadRunning() const
  12188. {
  12189. return threadHandle_ != 0;
  12190. }
  12191. void Thread::signalThreadShouldExit()
  12192. {
  12193. threadShouldExit_ = true;
  12194. }
  12195. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12196. {
  12197. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12198. jassert (getThreadId() != getCurrentThreadId());
  12199. const int sleepMsPerIteration = 5;
  12200. int count = timeOutMilliseconds / sleepMsPerIteration;
  12201. while (isThreadRunning())
  12202. {
  12203. if (timeOutMilliseconds > 0 && --count < 0)
  12204. return false;
  12205. sleep (sleepMsPerIteration);
  12206. }
  12207. return true;
  12208. }
  12209. void Thread::stopThread (const int timeOutMilliseconds)
  12210. {
  12211. // agh! You can't stop the thread that's calling this method! How on earth
  12212. // would that work??
  12213. jassert (getCurrentThreadId() != getThreadId());
  12214. const ScopedLock sl (startStopLock);
  12215. if (isThreadRunning())
  12216. {
  12217. signalThreadShouldExit();
  12218. notify();
  12219. if (timeOutMilliseconds != 0)
  12220. waitForThreadToExit (timeOutMilliseconds);
  12221. if (isThreadRunning())
  12222. {
  12223. // very bad karma if this point is reached, as
  12224. // there are bound to be locks and events left in
  12225. // silly states when a thread is killed by force..
  12226. jassertfalse
  12227. Logger::writeToLog ("!! killing thread by force !!");
  12228. juce_killThread (threadHandle_);
  12229. threadHandle_ = 0;
  12230. threadId_ = 0;
  12231. const ScopedLock sl2 (runningThreadsLock);
  12232. runningThreads.removeValue (this);
  12233. }
  12234. }
  12235. }
  12236. bool Thread::setPriority (const int priority)
  12237. {
  12238. const ScopedLock sl (startStopLock);
  12239. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12240. if (worked)
  12241. threadPriority_ = priority;
  12242. return worked;
  12243. }
  12244. bool Thread::setCurrentThreadPriority (const int priority)
  12245. {
  12246. return juce_setThreadPriority (0, priority);
  12247. }
  12248. void Thread::setAffinityMask (const uint32 affinityMask)
  12249. {
  12250. affinityMask_ = affinityMask;
  12251. }
  12252. bool Thread::wait (const int timeOutMilliseconds) const
  12253. {
  12254. return defaultEvent_.wait (timeOutMilliseconds);
  12255. }
  12256. void Thread::notify() const
  12257. {
  12258. defaultEvent_.signal();
  12259. }
  12260. int Thread::getNumRunningThreads()
  12261. {
  12262. return runningThreads.size();
  12263. }
  12264. Thread* Thread::getCurrentThread()
  12265. {
  12266. const ThreadID thisId = getCurrentThreadId();
  12267. const ScopedLock sl (runningThreadsLock);
  12268. for (int i = runningThreads.size(); --i >= 0;)
  12269. {
  12270. Thread* const t = runningThreads.getUnchecked(i);
  12271. if (t->threadId_ == thisId)
  12272. return t;
  12273. }
  12274. return 0;
  12275. }
  12276. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12277. {
  12278. {
  12279. const ScopedLock sl (runningThreadsLock);
  12280. for (int i = runningThreads.size(); --i >= 0;)
  12281. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12282. }
  12283. for (;;)
  12284. {
  12285. Thread* firstThread;
  12286. {
  12287. const ScopedLock sl (runningThreadsLock);
  12288. firstThread = runningThreads.getFirst();
  12289. }
  12290. if (firstThread == 0)
  12291. break;
  12292. firstThread->stopThread (timeOutMilliseconds);
  12293. }
  12294. }
  12295. Array<Thread*> Thread::runningThreads;
  12296. CriticalSection Thread::runningThreadsLock;
  12297. END_JUCE_NAMESPACE
  12298. /*** End of inlined file: juce_Thread.cpp ***/
  12299. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12300. BEGIN_JUCE_NAMESPACE
  12301. ThreadPoolJob::ThreadPoolJob (const String& name)
  12302. : jobName (name),
  12303. pool (0),
  12304. shouldStop (false),
  12305. isActive (false),
  12306. shouldBeDeleted (false)
  12307. {
  12308. }
  12309. ThreadPoolJob::~ThreadPoolJob()
  12310. {
  12311. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12312. // to remove it first!
  12313. jassert (pool == 0 || ! pool->contains (this));
  12314. }
  12315. const String ThreadPoolJob::getJobName() const
  12316. {
  12317. return jobName;
  12318. }
  12319. void ThreadPoolJob::setJobName (const String& newName)
  12320. {
  12321. jobName = newName;
  12322. }
  12323. void ThreadPoolJob::signalJobShouldExit()
  12324. {
  12325. shouldStop = true;
  12326. }
  12327. class ThreadPool::ThreadPoolThread : public Thread
  12328. {
  12329. public:
  12330. ThreadPoolThread (ThreadPool& pool_)
  12331. : Thread ("Pool"),
  12332. pool (pool_),
  12333. busy (false)
  12334. {
  12335. }
  12336. ~ThreadPoolThread()
  12337. {
  12338. }
  12339. void run()
  12340. {
  12341. while (! threadShouldExit())
  12342. {
  12343. if (! pool.runNextJob())
  12344. wait (500);
  12345. }
  12346. }
  12347. private:
  12348. ThreadPool& pool;
  12349. bool volatile busy;
  12350. ThreadPoolThread (const ThreadPoolThread&);
  12351. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12352. };
  12353. ThreadPool::ThreadPool (const int numThreads,
  12354. const bool startThreadsOnlyWhenNeeded,
  12355. const int stopThreadsWhenNotUsedTimeoutMs)
  12356. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12357. priority (5)
  12358. {
  12359. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12360. for (int i = jmax (1, numThreads); --i >= 0;)
  12361. threads.add (new ThreadPoolThread (*this));
  12362. if (! startThreadsOnlyWhenNeeded)
  12363. for (int i = threads.size(); --i >= 0;)
  12364. threads.getUnchecked(i)->startThread (priority);
  12365. }
  12366. ThreadPool::~ThreadPool()
  12367. {
  12368. removeAllJobs (true, 4000);
  12369. int i;
  12370. for (i = threads.size(); --i >= 0;)
  12371. threads.getUnchecked(i)->signalThreadShouldExit();
  12372. for (i = threads.size(); --i >= 0;)
  12373. threads.getUnchecked(i)->stopThread (500);
  12374. }
  12375. void ThreadPool::addJob (ThreadPoolJob* const job)
  12376. {
  12377. jassert (job != 0);
  12378. jassert (job->pool == 0);
  12379. if (job->pool == 0)
  12380. {
  12381. job->pool = this;
  12382. job->shouldStop = false;
  12383. job->isActive = false;
  12384. {
  12385. const ScopedLock sl (lock);
  12386. jobs.add (job);
  12387. int numRunning = 0;
  12388. for (int i = threads.size(); --i >= 0;)
  12389. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12390. ++numRunning;
  12391. if (numRunning < threads.size())
  12392. {
  12393. bool startedOne = false;
  12394. int n = 1000;
  12395. while (--n >= 0 && ! startedOne)
  12396. {
  12397. for (int i = threads.size(); --i >= 0;)
  12398. {
  12399. if (! threads.getUnchecked(i)->isThreadRunning())
  12400. {
  12401. threads.getUnchecked(i)->startThread (priority);
  12402. startedOne = true;
  12403. break;
  12404. }
  12405. }
  12406. if (! startedOne)
  12407. Thread::sleep (2);
  12408. }
  12409. }
  12410. }
  12411. for (int i = threads.size(); --i >= 0;)
  12412. threads.getUnchecked(i)->notify();
  12413. }
  12414. }
  12415. int ThreadPool::getNumJobs() const
  12416. {
  12417. return jobs.size();
  12418. }
  12419. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12420. {
  12421. const ScopedLock sl (lock);
  12422. return jobs [index];
  12423. }
  12424. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12425. {
  12426. const ScopedLock sl (lock);
  12427. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12428. }
  12429. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12430. {
  12431. const ScopedLock sl (lock);
  12432. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12433. }
  12434. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12435. const int timeOutMs) const
  12436. {
  12437. if (job != 0)
  12438. {
  12439. const uint32 start = Time::getMillisecondCounter();
  12440. while (contains (job))
  12441. {
  12442. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12443. return false;
  12444. jobFinishedSignal.wait (2);
  12445. }
  12446. }
  12447. return true;
  12448. }
  12449. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12450. const bool interruptIfRunning,
  12451. const int timeOutMs)
  12452. {
  12453. bool dontWait = true;
  12454. if (job != 0)
  12455. {
  12456. const ScopedLock sl (lock);
  12457. if (jobs.contains (job))
  12458. {
  12459. if (job->isActive)
  12460. {
  12461. if (interruptIfRunning)
  12462. job->signalJobShouldExit();
  12463. dontWait = false;
  12464. }
  12465. else
  12466. {
  12467. jobs.removeValue (job);
  12468. }
  12469. }
  12470. }
  12471. return dontWait || waitForJobToFinish (job, timeOutMs);
  12472. }
  12473. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12474. const int timeOutMs,
  12475. const bool deleteInactiveJobs,
  12476. ThreadPool::JobSelector* selectedJobsToRemove)
  12477. {
  12478. Array <ThreadPoolJob*> jobsToWaitFor;
  12479. {
  12480. const ScopedLock sl (lock);
  12481. for (int i = jobs.size(); --i >= 0;)
  12482. {
  12483. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12484. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12485. {
  12486. if (job->isActive)
  12487. {
  12488. jobsToWaitFor.add (job);
  12489. if (interruptRunningJobs)
  12490. job->signalJobShouldExit();
  12491. }
  12492. else
  12493. {
  12494. jobs.remove (i);
  12495. if (deleteInactiveJobs)
  12496. delete job;
  12497. }
  12498. }
  12499. }
  12500. }
  12501. const uint32 start = Time::getMillisecondCounter();
  12502. for (;;)
  12503. {
  12504. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12505. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12506. jobsToWaitFor.remove (i);
  12507. if (jobsToWaitFor.size() == 0)
  12508. break;
  12509. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12510. return false;
  12511. jobFinishedSignal.wait (20);
  12512. }
  12513. return true;
  12514. }
  12515. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12516. {
  12517. StringArray s;
  12518. const ScopedLock sl (lock);
  12519. for (int i = 0; i < jobs.size(); ++i)
  12520. {
  12521. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12522. if (job->isActive || ! onlyReturnActiveJobs)
  12523. s.add (job->getJobName());
  12524. }
  12525. return s;
  12526. }
  12527. bool ThreadPool::setThreadPriorities (const int newPriority)
  12528. {
  12529. bool ok = true;
  12530. if (priority != newPriority)
  12531. {
  12532. priority = newPriority;
  12533. for (int i = threads.size(); --i >= 0;)
  12534. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12535. ok = false;
  12536. }
  12537. return ok;
  12538. }
  12539. bool ThreadPool::runNextJob()
  12540. {
  12541. ThreadPoolJob* job = 0;
  12542. {
  12543. const ScopedLock sl (lock);
  12544. for (int i = 0; i < jobs.size(); ++i)
  12545. {
  12546. job = jobs[i];
  12547. if (job != 0 && ! (job->isActive || job->shouldStop))
  12548. break;
  12549. job = 0;
  12550. }
  12551. if (job != 0)
  12552. job->isActive = true;
  12553. }
  12554. if (job != 0)
  12555. {
  12556. JUCE_TRY
  12557. {
  12558. ThreadPoolJob::JobStatus result = job->runJob();
  12559. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12560. const ScopedLock sl (lock);
  12561. if (jobs.contains (job))
  12562. {
  12563. job->isActive = false;
  12564. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12565. {
  12566. job->pool = 0;
  12567. job->shouldStop = true;
  12568. jobs.removeValue (job);
  12569. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12570. delete job;
  12571. jobFinishedSignal.signal();
  12572. }
  12573. else
  12574. {
  12575. // move the job to the end of the queue if it wants another go
  12576. jobs.move (jobs.indexOf (job), -1);
  12577. }
  12578. }
  12579. }
  12580. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12581. catch (...)
  12582. {
  12583. const ScopedLock sl (lock);
  12584. jobs.removeValue (job);
  12585. }
  12586. #endif
  12587. }
  12588. else
  12589. {
  12590. if (threadStopTimeout > 0
  12591. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12592. {
  12593. const ScopedLock sl (lock);
  12594. if (jobs.size() == 0)
  12595. for (int i = threads.size(); --i >= 0;)
  12596. threads.getUnchecked(i)->signalThreadShouldExit();
  12597. }
  12598. else
  12599. {
  12600. return false;
  12601. }
  12602. }
  12603. return true;
  12604. }
  12605. END_JUCE_NAMESPACE
  12606. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12607. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12608. BEGIN_JUCE_NAMESPACE
  12609. TimeSliceThread::TimeSliceThread (const String& threadName)
  12610. : Thread (threadName),
  12611. index (0),
  12612. clientBeingCalled (0),
  12613. clientsChanged (false)
  12614. {
  12615. }
  12616. TimeSliceThread::~TimeSliceThread()
  12617. {
  12618. stopThread (2000);
  12619. }
  12620. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12621. {
  12622. const ScopedLock sl (listLock);
  12623. clients.addIfNotAlreadyThere (client);
  12624. clientsChanged = true;
  12625. notify();
  12626. }
  12627. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12628. {
  12629. const ScopedLock sl1 (listLock);
  12630. clientsChanged = true;
  12631. // if there's a chance we're in the middle of calling this client, we need to
  12632. // also lock the outer lock..
  12633. if (clientBeingCalled == client)
  12634. {
  12635. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12636. const ScopedLock sl2 (callbackLock);
  12637. const ScopedLock sl3 (listLock);
  12638. clients.removeValue (client);
  12639. }
  12640. else
  12641. {
  12642. clients.removeValue (client);
  12643. }
  12644. }
  12645. int TimeSliceThread::getNumClients() const
  12646. {
  12647. return clients.size();
  12648. }
  12649. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12650. {
  12651. const ScopedLock sl (listLock);
  12652. return clients [i];
  12653. }
  12654. void TimeSliceThread::run()
  12655. {
  12656. int numCallsSinceBusy = 0;
  12657. while (! threadShouldExit())
  12658. {
  12659. int timeToWait = 500;
  12660. {
  12661. const ScopedLock sl (callbackLock);
  12662. {
  12663. const ScopedLock sl2 (listLock);
  12664. if (clients.size() > 0)
  12665. {
  12666. index = (index + 1) % clients.size();
  12667. clientBeingCalled = clients [index];
  12668. }
  12669. else
  12670. {
  12671. index = 0;
  12672. clientBeingCalled = 0;
  12673. }
  12674. if (clientsChanged)
  12675. {
  12676. clientsChanged = false;
  12677. numCallsSinceBusy = 0;
  12678. }
  12679. }
  12680. if (clientBeingCalled != 0)
  12681. {
  12682. if (clientBeingCalled->useTimeSlice())
  12683. numCallsSinceBusy = 0;
  12684. else
  12685. ++numCallsSinceBusy;
  12686. if (numCallsSinceBusy >= clients.size())
  12687. timeToWait = 500;
  12688. else if (index == 0)
  12689. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12690. else
  12691. timeToWait = 0;
  12692. }
  12693. }
  12694. if (timeToWait > 0)
  12695. wait (timeToWait);
  12696. }
  12697. }
  12698. END_JUCE_NAMESPACE
  12699. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12700. #endif
  12701. #if JUCE_BUILD_MISC
  12702. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12703. BEGIN_JUCE_NAMESPACE
  12704. class ValueTree::SetPropertyAction : public UndoableAction
  12705. {
  12706. public:
  12707. SetPropertyAction (const SharedObjectPtr& target_, const var::identifier& name_,
  12708. const var& newValue_, const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12709. : target (target_), name (name_), newValue (newValue_),
  12710. isAddingNewProperty (isAddingNewProperty_),
  12711. isDeletingProperty (isDeletingProperty_)
  12712. {
  12713. if (! isAddingNewProperty)
  12714. oldValue = target_->getProperty (name_);
  12715. }
  12716. ~SetPropertyAction() {}
  12717. bool perform()
  12718. {
  12719. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12720. if (isDeletingProperty)
  12721. target->removeProperty (name, 0);
  12722. else
  12723. target->setProperty (name, newValue, 0);
  12724. return true;
  12725. }
  12726. bool undo()
  12727. {
  12728. if (isAddingNewProperty)
  12729. target->removeProperty (name, 0);
  12730. else
  12731. target->setProperty (name, oldValue, 0);
  12732. return true;
  12733. }
  12734. int getSizeInUnits()
  12735. {
  12736. return (int) sizeof (*this); //xxx should be more accurate
  12737. }
  12738. private:
  12739. const SharedObjectPtr target;
  12740. const var::identifier name;
  12741. const var newValue;
  12742. var oldValue;
  12743. const bool isAddingNewProperty, isDeletingProperty;
  12744. SetPropertyAction (const SetPropertyAction&);
  12745. SetPropertyAction& operator= (const SetPropertyAction&);
  12746. };
  12747. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12748. {
  12749. public:
  12750. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12751. const SharedObjectPtr& newChild_)
  12752. : target (target_),
  12753. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12754. childIndex (childIndex_),
  12755. isDeleting (newChild_ == 0)
  12756. {
  12757. jassert (child != 0);
  12758. }
  12759. ~AddOrRemoveChildAction() {}
  12760. bool perform()
  12761. {
  12762. if (isDeleting)
  12763. target->removeChild (childIndex, 0);
  12764. else
  12765. target->addChild (child, childIndex, 0);
  12766. return true;
  12767. }
  12768. bool undo()
  12769. {
  12770. if (isDeleting)
  12771. {
  12772. target->addChild (child, childIndex, 0);
  12773. }
  12774. else
  12775. {
  12776. // If you hit this, it seems that your object's state is getting confused - probably
  12777. // because you've interleaved some undoable and non-undoable operations?
  12778. jassert (childIndex < target->children.size());
  12779. target->removeChild (childIndex, 0);
  12780. }
  12781. return true;
  12782. }
  12783. int getSizeInUnits()
  12784. {
  12785. return (int) sizeof (*this); //xxx should be more accurate
  12786. }
  12787. private:
  12788. const SharedObjectPtr target, child;
  12789. const int childIndex;
  12790. const bool isDeleting;
  12791. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  12792. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  12793. };
  12794. class ValueTree::MoveChildAction : public UndoableAction
  12795. {
  12796. public:
  12797. MoveChildAction (const SharedObjectPtr& target_,
  12798. const int startIndex_, const int endIndex_)
  12799. : target (target_),
  12800. startIndex (startIndex_),
  12801. endIndex (endIndex_)
  12802. {
  12803. }
  12804. ~MoveChildAction() {}
  12805. bool perform()
  12806. {
  12807. target->moveChild (startIndex, endIndex, 0);
  12808. return true;
  12809. }
  12810. bool undo()
  12811. {
  12812. target->moveChild (endIndex, startIndex, 0);
  12813. return true;
  12814. }
  12815. int getSizeInUnits()
  12816. {
  12817. return (int) sizeof (*this); //xxx should be more accurate
  12818. }
  12819. private:
  12820. const SharedObjectPtr target, child;
  12821. const int startIndex, endIndex;
  12822. MoveChildAction (const MoveChildAction&);
  12823. MoveChildAction& operator= (const MoveChildAction&);
  12824. };
  12825. ValueTree::SharedObject::SharedObject (const String& type_)
  12826. : type (type_), parent (0)
  12827. {
  12828. }
  12829. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  12830. : type (other.type), properties (other.properties), parent (0)
  12831. {
  12832. for (int i = 0; i < other.children.size(); ++i)
  12833. {
  12834. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  12835. child->parent = this;
  12836. children.add (child);
  12837. }
  12838. }
  12839. ValueTree::SharedObject::~SharedObject()
  12840. {
  12841. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  12842. for (int i = children.size(); --i >= 0;)
  12843. {
  12844. const SharedObjectPtr c (children.getUnchecked(i));
  12845. c->parent = 0;
  12846. children.remove (i);
  12847. c->sendParentChangeMessage();
  12848. }
  12849. }
  12850. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const var::identifier& property)
  12851. {
  12852. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12853. {
  12854. ValueTree* const v = valueTreesWithListeners[i];
  12855. if (v != 0)
  12856. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  12857. }
  12858. }
  12859. void ValueTree::SharedObject::sendPropertyChangeMessage (const var::identifier& property)
  12860. {
  12861. ValueTree tree (this);
  12862. ValueTree::SharedObject* t = this;
  12863. while (t != 0)
  12864. {
  12865. t->sendPropertyChangeMessage (tree, property);
  12866. t = t->parent;
  12867. }
  12868. }
  12869. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  12870. {
  12871. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12872. {
  12873. ValueTree* const v = valueTreesWithListeners[i];
  12874. if (v != 0)
  12875. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  12876. }
  12877. }
  12878. void ValueTree::SharedObject::sendChildChangeMessage()
  12879. {
  12880. ValueTree tree (this);
  12881. ValueTree::SharedObject* t = this;
  12882. while (t != 0)
  12883. {
  12884. t->sendChildChangeMessage (tree);
  12885. t = t->parent;
  12886. }
  12887. }
  12888. void ValueTree::SharedObject::sendParentChangeMessage()
  12889. {
  12890. ValueTree tree (this);
  12891. int i;
  12892. for (i = children.size(); --i >= 0;)
  12893. {
  12894. SharedObject* const t = children[i];
  12895. if (t != 0)
  12896. t->sendParentChangeMessage();
  12897. }
  12898. for (i = valueTreesWithListeners.size(); --i >= 0;)
  12899. {
  12900. ValueTree* const v = valueTreesWithListeners[i];
  12901. if (v != 0)
  12902. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  12903. }
  12904. }
  12905. const var& ValueTree::SharedObject::getProperty (const var::identifier& name) const
  12906. {
  12907. return properties [name];
  12908. }
  12909. const var ValueTree::SharedObject::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  12910. {
  12911. return properties.getWithDefault (name, defaultReturnValue);
  12912. }
  12913. void ValueTree::SharedObject::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  12914. {
  12915. if (undoManager == 0)
  12916. {
  12917. if (properties.set (name, newValue))
  12918. sendPropertyChangeMessage (name);
  12919. }
  12920. else
  12921. {
  12922. var* const existingValue = properties.getItem (name);
  12923. if (existingValue != 0)
  12924. {
  12925. if (*existingValue != newValue)
  12926. undoManager->perform (new SetPropertyAction (this, name, newValue, false, false));
  12927. }
  12928. else
  12929. {
  12930. undoManager->perform (new SetPropertyAction (this, name, newValue, true, false));
  12931. }
  12932. }
  12933. }
  12934. bool ValueTree::SharedObject::hasProperty (const var::identifier& name) const
  12935. {
  12936. return properties.contains (name);
  12937. }
  12938. void ValueTree::SharedObject::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  12939. {
  12940. if (undoManager == 0)
  12941. {
  12942. if (properties.remove (name))
  12943. sendPropertyChangeMessage (name);
  12944. }
  12945. else
  12946. {
  12947. if (properties.contains (name))
  12948. undoManager->perform (new SetPropertyAction (this, name, var::null, false, true));
  12949. }
  12950. }
  12951. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  12952. {
  12953. if (undoManager == 0)
  12954. {
  12955. while (properties.size() > 0)
  12956. {
  12957. const var::identifier name (properties.getName (properties.size() - 1));
  12958. properties.remove (name);
  12959. sendPropertyChangeMessage (name);
  12960. }
  12961. }
  12962. else
  12963. {
  12964. for (int i = properties.size(); --i >= 0;)
  12965. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, false, true));
  12966. }
  12967. }
  12968. ValueTree ValueTree::SharedObject::getChildWithName (const String& typeToMatch) const
  12969. {
  12970. for (int i = 0; i < children.size(); ++i)
  12971. if (children.getUnchecked(i)->type == typeToMatch)
  12972. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12973. return ValueTree::invalid;
  12974. }
  12975. ValueTree ValueTree::SharedObject::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  12976. {
  12977. for (int i = 0; i < children.size(); ++i)
  12978. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  12979. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12980. return ValueTree::invalid;
  12981. }
  12982. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  12983. {
  12984. const SharedObject* p = parent;
  12985. while (p != 0)
  12986. {
  12987. if (p == possibleParent)
  12988. return true;
  12989. p = p->parent;
  12990. }
  12991. return false;
  12992. }
  12993. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  12994. {
  12995. return children.indexOf (child.object);
  12996. }
  12997. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  12998. {
  12999. if (child != 0 && child->parent != this)
  13000. {
  13001. if (child != this && ! isAChildOf (child))
  13002. {
  13003. // You should always make sure that a child is removed from its previous parent before
  13004. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13005. // undomanager should be used when removing it from its current parent..
  13006. jassert (child->parent == 0);
  13007. if (child->parent != 0)
  13008. {
  13009. jassert (child->parent->children.indexOf (child) >= 0);
  13010. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13011. }
  13012. if (undoManager == 0)
  13013. {
  13014. children.insert (index, child);
  13015. child->parent = this;
  13016. sendChildChangeMessage();
  13017. child->sendParentChangeMessage();
  13018. }
  13019. else
  13020. {
  13021. if (index < 0)
  13022. index = children.size();
  13023. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13024. }
  13025. }
  13026. else
  13027. {
  13028. // You're attempting to create a recursive loop! A node
  13029. // can't be a child of one of its own children!
  13030. jassertfalse
  13031. }
  13032. }
  13033. }
  13034. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13035. {
  13036. const SharedObjectPtr child (children [childIndex]);
  13037. if (child != 0)
  13038. {
  13039. if (undoManager == 0)
  13040. {
  13041. children.remove (childIndex);
  13042. child->parent = 0;
  13043. sendChildChangeMessage();
  13044. child->sendParentChangeMessage();
  13045. }
  13046. else
  13047. {
  13048. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13049. }
  13050. }
  13051. }
  13052. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13053. {
  13054. while (children.size() > 0)
  13055. removeChild (children.size() - 1, undoManager);
  13056. }
  13057. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13058. {
  13059. // The source index must be a valid index!
  13060. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13061. if (currentIndex != newIndex
  13062. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13063. {
  13064. if (undoManager == 0)
  13065. {
  13066. children.move (currentIndex, newIndex);
  13067. sendChildChangeMessage();
  13068. }
  13069. else
  13070. {
  13071. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13072. newIndex = children.size() - 1;
  13073. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13074. }
  13075. }
  13076. }
  13077. ValueTree::ValueTree() throw()
  13078. : object (0)
  13079. {
  13080. }
  13081. const ValueTree ValueTree::invalid;
  13082. ValueTree::ValueTree (const String& type_)
  13083. : object (new ValueTree::SharedObject (type_))
  13084. {
  13085. jassert (type_.isNotEmpty()); // All objects should be given a sensible type name!
  13086. }
  13087. ValueTree::ValueTree (SharedObject* const object_)
  13088. : object (object_)
  13089. {
  13090. }
  13091. ValueTree::ValueTree (const ValueTree& other)
  13092. : object (other.object)
  13093. {
  13094. }
  13095. ValueTree& ValueTree::operator= (const ValueTree& other)
  13096. {
  13097. if (listeners.size() > 0)
  13098. {
  13099. if (object != 0)
  13100. object->valueTreesWithListeners.removeValue (this);
  13101. if (other.object != 0)
  13102. other.object->valueTreesWithListeners.add (this);
  13103. }
  13104. object = other.object;
  13105. return *this;
  13106. }
  13107. ValueTree::~ValueTree()
  13108. {
  13109. if (listeners.size() > 0 && object != 0)
  13110. object->valueTreesWithListeners.removeValue (this);
  13111. }
  13112. bool ValueTree::operator== (const ValueTree& other) const
  13113. {
  13114. return object == other.object;
  13115. }
  13116. bool ValueTree::operator!= (const ValueTree& other) const
  13117. {
  13118. return object != other.object;
  13119. }
  13120. ValueTree ValueTree::createCopy() const
  13121. {
  13122. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13123. }
  13124. bool ValueTree::hasType (const String& typeName) const
  13125. {
  13126. return object != 0 && object->type == typeName;
  13127. }
  13128. const String ValueTree::getType() const
  13129. {
  13130. return object != 0 ? object->type : String::empty;
  13131. }
  13132. ValueTree ValueTree::getParent() const
  13133. {
  13134. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13135. }
  13136. const var& ValueTree::operator[] (const var::identifier& name) const
  13137. {
  13138. return object == 0 ? var::null : object->getProperty (name);
  13139. }
  13140. const var& ValueTree::getProperty (const var::identifier& name) const
  13141. {
  13142. return object == 0 ? var::null : object->getProperty (name);
  13143. }
  13144. const var ValueTree::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  13145. {
  13146. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13147. }
  13148. void ValueTree::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  13149. {
  13150. jassert (name.name.isNotEmpty());
  13151. if (object != 0 && name.name.isNotEmpty())
  13152. object->setProperty (name, newValue, undoManager);
  13153. }
  13154. bool ValueTree::hasProperty (const var::identifier& name) const
  13155. {
  13156. return object != 0 && object->hasProperty (name);
  13157. }
  13158. void ValueTree::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  13159. {
  13160. if (object != 0)
  13161. object->removeProperty (name, undoManager);
  13162. }
  13163. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13164. {
  13165. if (object != 0)
  13166. object->removeAllProperties (undoManager);
  13167. }
  13168. int ValueTree::getNumProperties() const
  13169. {
  13170. return object == 0 ? 0 : object->properties.size();
  13171. }
  13172. const var::identifier ValueTree::getPropertyName (const int index) const
  13173. {
  13174. return object == 0 ? var::identifier()
  13175. : object->properties.getName (index);
  13176. }
  13177. class ValueTreePropertyValueSource : public Value::ValueSource,
  13178. public ValueTree::Listener
  13179. {
  13180. public:
  13181. ValueTreePropertyValueSource (const ValueTree& tree_,
  13182. const var::identifier& property_,
  13183. UndoManager* const undoManager_)
  13184. : tree (tree_),
  13185. property (property_),
  13186. undoManager (undoManager_)
  13187. {
  13188. tree.addListener (this);
  13189. }
  13190. ~ValueTreePropertyValueSource()
  13191. {
  13192. tree.removeListener (this);
  13193. }
  13194. const var getValue() const
  13195. {
  13196. return tree [property];
  13197. }
  13198. void setValue (const var& newValue)
  13199. {
  13200. tree.setProperty (property, newValue, undoManager);
  13201. }
  13202. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const var::identifier& changedProperty)
  13203. {
  13204. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13205. sendChangeMessage (false);
  13206. }
  13207. void valueTreeChildrenChanged (ValueTree&) {}
  13208. void valueTreeParentChanged (ValueTree&) {}
  13209. private:
  13210. ValueTree tree;
  13211. const var::identifier property;
  13212. UndoManager* const undoManager;
  13213. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13214. };
  13215. Value ValueTree::getPropertyAsValue (const var::identifier& name, UndoManager* const undoManager) const
  13216. {
  13217. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13218. }
  13219. int ValueTree::getNumChildren() const
  13220. {
  13221. return object == 0 ? 0 : object->children.size();
  13222. }
  13223. ValueTree ValueTree::getChild (int index) const
  13224. {
  13225. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13226. }
  13227. ValueTree ValueTree::getChildWithName (const String& type) const
  13228. {
  13229. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13230. }
  13231. ValueTree ValueTree::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  13232. {
  13233. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13234. }
  13235. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13236. {
  13237. return object != 0 && object->isAChildOf (possibleParent.object);
  13238. }
  13239. int ValueTree::indexOf (const ValueTree& child) const
  13240. {
  13241. return object != 0 ? object->indexOf (child) : -1;
  13242. }
  13243. void ValueTree::addChild (ValueTree child, int index, UndoManager* const undoManager)
  13244. {
  13245. if (object != 0)
  13246. object->addChild (child.object, index, undoManager);
  13247. }
  13248. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13249. {
  13250. if (object != 0)
  13251. object->removeChild (childIndex, undoManager);
  13252. }
  13253. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13254. {
  13255. if (object != 0)
  13256. object->removeChild (object->children.indexOf (child.object), undoManager);
  13257. }
  13258. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13259. {
  13260. if (object != 0)
  13261. object->removeAllChildren (undoManager);
  13262. }
  13263. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13264. {
  13265. if (object != 0)
  13266. object->moveChild (currentIndex, newIndex, undoManager);
  13267. }
  13268. void ValueTree::addListener (Listener* listener)
  13269. {
  13270. if (listener != 0)
  13271. {
  13272. if (listeners.size() == 0 && object != 0)
  13273. object->valueTreesWithListeners.add (this);
  13274. listeners.add (listener);
  13275. }
  13276. }
  13277. void ValueTree::removeListener (Listener* listener)
  13278. {
  13279. listeners.remove (listener);
  13280. if (listeners.size() == 0 && object != 0)
  13281. object->valueTreesWithListeners.removeValue (this);
  13282. }
  13283. XmlElement* ValueTree::SharedObject::createXml() const
  13284. {
  13285. XmlElement* xml = new XmlElement (type);
  13286. int i;
  13287. for (i = 0; i < properties.size(); ++i)
  13288. {
  13289. var::identifier name (properties.getName(i));
  13290. const var& v = properties [name];
  13291. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13292. xml->setAttribute (name.name, v.toString());
  13293. }
  13294. for (i = 0; i < children.size(); ++i)
  13295. xml->addChildElement (children.getUnchecked(i)->createXml());
  13296. return xml;
  13297. }
  13298. XmlElement* ValueTree::createXml() const
  13299. {
  13300. return object != 0 ? object->createXml() : 0;
  13301. }
  13302. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13303. {
  13304. ValueTree v (xml.getTagName());
  13305. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13306. for (int i = 0; i < numAtts; ++i)
  13307. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13308. forEachXmlChildElement (xml, e)
  13309. {
  13310. v.addChild (fromXml (*e), -1, 0);
  13311. }
  13312. return v;
  13313. }
  13314. void ValueTree::writeToStream (OutputStream& output)
  13315. {
  13316. output.writeString (getType());
  13317. const int numProps = getNumProperties();
  13318. output.writeCompressedInt (numProps);
  13319. int i;
  13320. for (i = 0; i < numProps; ++i)
  13321. {
  13322. const var::identifier name (getPropertyName(i));
  13323. output.writeString (name.name);
  13324. getProperty(name).writeToStream (output);
  13325. }
  13326. const int numChildren = getNumChildren();
  13327. output.writeCompressedInt (numChildren);
  13328. for (i = 0; i < numChildren; ++i)
  13329. getChild (i).writeToStream (output);
  13330. }
  13331. ValueTree ValueTree::readFromStream (InputStream& input)
  13332. {
  13333. String type (input.readString());
  13334. if (type.isEmpty())
  13335. return ValueTree::invalid;
  13336. ValueTree v (type);
  13337. const int numProps = input.readCompressedInt();
  13338. if (numProps < 0)
  13339. {
  13340. jassertfalse // trying to read corrupted data!
  13341. return v;
  13342. }
  13343. int i;
  13344. for (i = 0; i < numProps; ++i)
  13345. {
  13346. const String name (input.readString());
  13347. jassert (name.isNotEmpty());
  13348. const var value (var::readFromStream (input));
  13349. v.setProperty (name, value, 0);
  13350. }
  13351. const int numChildren = input.readCompressedInt();
  13352. for (i = 0; i < numChildren; ++i)
  13353. v.addChild (readFromStream (input), -1, 0);
  13354. return v;
  13355. }
  13356. END_JUCE_NAMESPACE
  13357. /*** End of inlined file: juce_ValueTree.cpp ***/
  13358. /*** Start of inlined file: juce_Value.cpp ***/
  13359. BEGIN_JUCE_NAMESPACE
  13360. Value::ValueSource::ValueSource()
  13361. {
  13362. }
  13363. Value::ValueSource::~ValueSource()
  13364. {
  13365. }
  13366. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13367. {
  13368. if (synchronous)
  13369. {
  13370. for (int i = valuesWithListeners.size(); --i >= 0;)
  13371. {
  13372. Value* const v = valuesWithListeners[i];
  13373. if (v != 0)
  13374. v->callListeners();
  13375. }
  13376. }
  13377. else
  13378. {
  13379. triggerAsyncUpdate();
  13380. }
  13381. }
  13382. void Value::ValueSource::handleAsyncUpdate()
  13383. {
  13384. sendChangeMessage (true);
  13385. }
  13386. class SimpleValueSource : public Value::ValueSource
  13387. {
  13388. public:
  13389. SimpleValueSource()
  13390. {
  13391. }
  13392. SimpleValueSource (const var& initialValue)
  13393. : value (initialValue)
  13394. {
  13395. }
  13396. ~SimpleValueSource()
  13397. {
  13398. }
  13399. const var getValue() const
  13400. {
  13401. return value;
  13402. }
  13403. void setValue (const var& newValue)
  13404. {
  13405. if (newValue != value)
  13406. {
  13407. value = newValue;
  13408. sendChangeMessage (false);
  13409. }
  13410. }
  13411. private:
  13412. var value;
  13413. SimpleValueSource (const SimpleValueSource&);
  13414. SimpleValueSource& operator= (const SimpleValueSource&);
  13415. };
  13416. Value::Value()
  13417. : value (new SimpleValueSource())
  13418. {
  13419. }
  13420. Value::Value (ValueSource* const value_)
  13421. : value (value_)
  13422. {
  13423. jassert (value_ != 0);
  13424. }
  13425. Value::Value (const var& initialValue)
  13426. : value (new SimpleValueSource (initialValue))
  13427. {
  13428. }
  13429. Value::Value (const Value& other)
  13430. : value (other.value)
  13431. {
  13432. }
  13433. Value& Value::operator= (const Value& other)
  13434. {
  13435. value = other.value;
  13436. return *this;
  13437. }
  13438. Value::~Value()
  13439. {
  13440. if (listeners.size() > 0)
  13441. value->valuesWithListeners.removeValue (this);
  13442. }
  13443. const var Value::getValue() const
  13444. {
  13445. return value->getValue();
  13446. }
  13447. Value::operator const var() const
  13448. {
  13449. return getValue();
  13450. }
  13451. void Value::setValue (const var& newValue)
  13452. {
  13453. value->setValue (newValue);
  13454. }
  13455. const String Value::toString() const
  13456. {
  13457. return value->getValue().toString();
  13458. }
  13459. Value& Value::operator= (const var& newValue)
  13460. {
  13461. value->setValue (newValue);
  13462. return *this;
  13463. }
  13464. void Value::referTo (const Value& valueToReferTo)
  13465. {
  13466. if (valueToReferTo.value != value)
  13467. {
  13468. if (listeners.size() > 0)
  13469. {
  13470. value->valuesWithListeners.removeValue (this);
  13471. valueToReferTo.value->valuesWithListeners.add (this);
  13472. }
  13473. value = valueToReferTo.value;
  13474. callListeners();
  13475. }
  13476. }
  13477. bool Value::refersToSameSourceAs (const Value& other) const
  13478. {
  13479. return value == other.value;
  13480. }
  13481. bool Value::operator== (const Value& other) const
  13482. {
  13483. return value == other.value || value->getValue() == other.getValue();
  13484. }
  13485. bool Value::operator!= (const Value& other) const
  13486. {
  13487. return value != other.value && value->getValue() != other.getValue();
  13488. }
  13489. void Value::addListener (Listener* const listener)
  13490. {
  13491. if (listener != 0)
  13492. {
  13493. if (listeners.size() == 0)
  13494. value->valuesWithListeners.add (this);
  13495. listeners.add (listener);
  13496. }
  13497. }
  13498. void Value::removeListener (Listener* const listener)
  13499. {
  13500. listeners.remove (listener);
  13501. if (listeners.size() == 0)
  13502. value->valuesWithListeners.removeValue (this);
  13503. }
  13504. void Value::callListeners()
  13505. {
  13506. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13507. listeners.call (&Listener::valueChanged, v);
  13508. }
  13509. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13510. {
  13511. return stream << value.toString();
  13512. }
  13513. END_JUCE_NAMESPACE
  13514. /*** End of inlined file: juce_Value.cpp ***/
  13515. /*** Start of inlined file: juce_Application.cpp ***/
  13516. #if JUCE_MSVC
  13517. #pragma warning (push)
  13518. #pragma warning (disable: 4245 4514 4100)
  13519. #include <crtdbg.h>
  13520. #pragma warning (pop)
  13521. #endif
  13522. BEGIN_JUCE_NAMESPACE
  13523. void juce_setCurrentThreadName (const String& name);
  13524. static JUCEApplication* appInstance = 0;
  13525. JUCEApplication::JUCEApplication()
  13526. : appReturnValue (0),
  13527. stillInitialising (true)
  13528. {
  13529. }
  13530. JUCEApplication::~JUCEApplication()
  13531. {
  13532. if (appLock != 0)
  13533. {
  13534. appLock->exit();
  13535. appLock = 0;
  13536. }
  13537. }
  13538. JUCEApplication* JUCEApplication::getInstance() throw()
  13539. {
  13540. return appInstance;
  13541. }
  13542. bool JUCEApplication::isInitialising() const throw()
  13543. {
  13544. return stillInitialising;
  13545. }
  13546. const String JUCEApplication::getApplicationVersion()
  13547. {
  13548. return String::empty;
  13549. }
  13550. bool JUCEApplication::moreThanOneInstanceAllowed()
  13551. {
  13552. return true;
  13553. }
  13554. void JUCEApplication::anotherInstanceStarted (const String&)
  13555. {
  13556. }
  13557. void JUCEApplication::systemRequestedQuit()
  13558. {
  13559. quit();
  13560. }
  13561. void JUCEApplication::quit()
  13562. {
  13563. MessageManager::getInstance()->stopDispatchLoop();
  13564. }
  13565. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13566. {
  13567. appReturnValue = newReturnValue;
  13568. }
  13569. void JUCEApplication::unhandledException (const std::exception*,
  13570. const String&,
  13571. const int)
  13572. {
  13573. jassertfalse
  13574. }
  13575. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13576. const char* const sourceFile,
  13577. const int lineNumber)
  13578. {
  13579. if (appInstance != 0)
  13580. appInstance->unhandledException (e, sourceFile, lineNumber);
  13581. }
  13582. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13583. {
  13584. return 0;
  13585. }
  13586. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13587. {
  13588. commands.add (StandardApplicationCommandIDs::quit);
  13589. }
  13590. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13591. {
  13592. if (commandID == StandardApplicationCommandIDs::quit)
  13593. {
  13594. result.setInfo (TRANS("Quit"),
  13595. TRANS("Quits the application"),
  13596. "Application",
  13597. 0);
  13598. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13599. }
  13600. }
  13601. bool JUCEApplication::perform (const InvocationInfo& info)
  13602. {
  13603. if (info.commandID == StandardApplicationCommandIDs::quit)
  13604. {
  13605. systemRequestedQuit();
  13606. return true;
  13607. }
  13608. return false;
  13609. }
  13610. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13611. {
  13612. if (! app->initialiseApp (commandLine))
  13613. return 0;
  13614. // now loop until a quit message is received..
  13615. JUCE_TRY
  13616. {
  13617. MessageManager::getInstance()->runDispatchLoop();
  13618. }
  13619. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13620. catch (const std::exception& e)
  13621. {
  13622. app->unhandledException (&e, __FILE__, __LINE__);
  13623. }
  13624. catch (...)
  13625. {
  13626. app->unhandledException (0, __FILE__, __LINE__);
  13627. }
  13628. #endif
  13629. return shutdownAppAndClearUp();
  13630. }
  13631. bool JUCEApplication::initialiseApp (String& commandLine)
  13632. {
  13633. jassert (appInstance == 0);
  13634. appInstance = this;
  13635. commandLineParameters = commandLine.trim();
  13636. commandLine = String::empty;
  13637. initialiseJuce_GUI();
  13638. #if ! JUCE_IPHONE
  13639. jassert (appLock == 0); // initialiseApp must only be called once!
  13640. if (! moreThanOneInstanceAllowed())
  13641. {
  13642. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13643. if (! appLock->enter(0))
  13644. {
  13645. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13646. delete appInstance;
  13647. appInstance = 0;
  13648. DBG ("Another instance is running - quitting...");
  13649. return false;
  13650. }
  13651. }
  13652. #endif
  13653. // let the app do its setting-up..
  13654. initialise (commandLineParameters);
  13655. // register for broadcast new app messages
  13656. MessageManager::getInstance()->registerBroadcastListener (this);
  13657. stillInitialising = false;
  13658. return true;
  13659. }
  13660. int JUCEApplication::shutdownAppAndClearUp()
  13661. {
  13662. jassert (appInstance != 0);
  13663. ScopedPointer<JUCEApplication> app (appInstance);
  13664. int returnValue = 0;
  13665. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13666. static bool reentrancyCheck = false;
  13667. if (! reentrancyCheck)
  13668. {
  13669. reentrancyCheck = true;
  13670. JUCE_TRY
  13671. {
  13672. // give the app a chance to clean up..
  13673. app->shutdown();
  13674. }
  13675. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13676. catch (const std::exception& e)
  13677. {
  13678. app->unhandledException (&e, __FILE__, __LINE__);
  13679. }
  13680. catch (...)
  13681. {
  13682. app->unhandledException (0, __FILE__, __LINE__);
  13683. }
  13684. #endif
  13685. JUCE_TRY
  13686. {
  13687. shutdownJuce_GUI();
  13688. returnValue = app->getApplicationReturnValue();
  13689. appInstance = 0;
  13690. app = 0;
  13691. }
  13692. JUCE_CATCH_ALL_ASSERT
  13693. reentrancyCheck = false;
  13694. }
  13695. return returnValue;
  13696. }
  13697. #if JUCE_IPHONE
  13698. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13699. #endif
  13700. #if ! JUCE_WINDOWS
  13701. extern const char* juce_Argv0;
  13702. #endif
  13703. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13704. {
  13705. #if ! JUCE_WINDOWS
  13706. juce_Argv0 = argv[0];
  13707. #endif
  13708. #if JUCE_IPHONE
  13709. const ScopedAutoReleasePool pool;
  13710. return juce_IPhoneMain (argc, argv, newApp);
  13711. #else
  13712. #if JUCE_MAC
  13713. const ScopedAutoReleasePool pool;
  13714. #endif
  13715. String cmd;
  13716. for (int i = 1; i < argc; ++i)
  13717. cmd << argv[i] << ' ';
  13718. return JUCEApplication::main (cmd, newApp);
  13719. #endif
  13720. }
  13721. void JUCEApplication::actionListenerCallback (const String& message)
  13722. {
  13723. if (message.startsWith (getApplicationName() + "/"))
  13724. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13725. }
  13726. static bool juceInitialisedGUI = false;
  13727. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13728. {
  13729. if (! juceInitialisedGUI)
  13730. {
  13731. #if JUCE_MAC || JUCE_IPHONE
  13732. const ScopedAutoReleasePool pool;
  13733. #endif
  13734. juceInitialisedGUI = true;
  13735. initialiseJuce_NonGUI();
  13736. MessageManager::getInstance();
  13737. LookAndFeel::setDefaultLookAndFeel (0);
  13738. juce_setCurrentThreadName ("Juce Message Thread");
  13739. #if JUCE_WINDOWS && JUCE_DEBUG
  13740. // This section is just for catching people who mess up their project settings and
  13741. // turn RTTI off..
  13742. try
  13743. {
  13744. TextButton tb (String::empty);
  13745. Component* c = &tb;
  13746. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13747. c = dynamic_cast <Button*> (c);
  13748. }
  13749. catch (...)
  13750. {
  13751. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13752. // got as far as this catch statement, then why haven't you got exception catching
  13753. // turned on in the debugger???
  13754. jassertfalse
  13755. }
  13756. #endif
  13757. }
  13758. }
  13759. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13760. {
  13761. if (juceInitialisedGUI)
  13762. {
  13763. #if JUCE_MAC
  13764. const ScopedAutoReleasePool pool;
  13765. #endif
  13766. {
  13767. DeletedAtShutdown::deleteAll();
  13768. LookAndFeel::clearDefaultLookAndFeel();
  13769. }
  13770. delete MessageManager::getInstance();
  13771. shutdownJuce_NonGUI();
  13772. juceInitialisedGUI = false;
  13773. }
  13774. }
  13775. END_JUCE_NAMESPACE
  13776. /*** End of inlined file: juce_Application.cpp ***/
  13777. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13778. BEGIN_JUCE_NAMESPACE
  13779. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13780. : commandID (commandID_),
  13781. flags (0)
  13782. {
  13783. }
  13784. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13785. const String& description_,
  13786. const String& categoryName_,
  13787. const int flags_) throw()
  13788. {
  13789. shortName = shortName_;
  13790. description = description_;
  13791. categoryName = categoryName_;
  13792. flags = flags_;
  13793. }
  13794. void ApplicationCommandInfo::setActive (const bool b) throw()
  13795. {
  13796. if (b)
  13797. flags &= ~isDisabled;
  13798. else
  13799. flags |= isDisabled;
  13800. }
  13801. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13802. {
  13803. if (b)
  13804. flags |= isTicked;
  13805. else
  13806. flags &= ~isTicked;
  13807. }
  13808. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13809. {
  13810. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13811. }
  13812. END_JUCE_NAMESPACE
  13813. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13814. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  13815. BEGIN_JUCE_NAMESPACE
  13816. ApplicationCommandManager::ApplicationCommandManager()
  13817. : firstTarget (0)
  13818. {
  13819. keyMappings = new KeyPressMappingSet (this);
  13820. Desktop::getInstance().addFocusChangeListener (this);
  13821. }
  13822. ApplicationCommandManager::~ApplicationCommandManager()
  13823. {
  13824. Desktop::getInstance().removeFocusChangeListener (this);
  13825. keyMappings = 0;
  13826. }
  13827. void ApplicationCommandManager::clearCommands()
  13828. {
  13829. commands.clear();
  13830. keyMappings->clearAllKeyPresses();
  13831. triggerAsyncUpdate();
  13832. }
  13833. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13834. {
  13835. // zero isn't a valid command ID!
  13836. jassert (newCommand.commandID != 0);
  13837. // the name isn't optional!
  13838. jassert (newCommand.shortName.isNotEmpty());
  13839. if (getCommandForID (newCommand.commandID) == 0)
  13840. {
  13841. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13842. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13843. commands.add (newInfo);
  13844. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13845. triggerAsyncUpdate();
  13846. }
  13847. else
  13848. {
  13849. // trying to re-register the same command with different parameters?
  13850. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13851. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13852. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13853. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13854. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13855. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13856. }
  13857. }
  13858. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13859. {
  13860. if (target != 0)
  13861. {
  13862. Array <CommandID> commandIDs;
  13863. target->getAllCommands (commandIDs);
  13864. for (int i = 0; i < commandIDs.size(); ++i)
  13865. {
  13866. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13867. target->getCommandInfo (info.commandID, info);
  13868. registerCommand (info);
  13869. }
  13870. }
  13871. }
  13872. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13873. {
  13874. for (int i = commands.size(); --i >= 0;)
  13875. {
  13876. if (commands.getUnchecked (i)->commandID == commandID)
  13877. {
  13878. commands.remove (i);
  13879. triggerAsyncUpdate();
  13880. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13881. for (int j = keys.size(); --j >= 0;)
  13882. keyMappings->removeKeyPress (keys.getReference (j));
  13883. }
  13884. }
  13885. }
  13886. void ApplicationCommandManager::commandStatusChanged()
  13887. {
  13888. triggerAsyncUpdate();
  13889. }
  13890. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13891. {
  13892. for (int i = commands.size(); --i >= 0;)
  13893. if (commands.getUnchecked(i)->commandID == commandID)
  13894. return commands.getUnchecked(i);
  13895. return 0;
  13896. }
  13897. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13898. {
  13899. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13900. return (ci != 0) ? ci->shortName : String::empty;
  13901. }
  13902. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13903. {
  13904. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13905. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13906. : String::empty;
  13907. }
  13908. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13909. {
  13910. StringArray s;
  13911. for (int i = 0; i < commands.size(); ++i)
  13912. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13913. return s;
  13914. }
  13915. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13916. {
  13917. Array <CommandID> results;
  13918. for (int i = 0; i < commands.size(); ++i)
  13919. if (commands.getUnchecked(i)->categoryName == categoryName)
  13920. results.add (commands.getUnchecked(i)->commandID);
  13921. return results;
  13922. }
  13923. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13924. {
  13925. ApplicationCommandTarget::InvocationInfo info (commandID);
  13926. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13927. return invoke (info, asynchronously);
  13928. }
  13929. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13930. {
  13931. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13932. // manager first..
  13933. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13934. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13935. if (target == 0)
  13936. return false;
  13937. ApplicationCommandInfo commandInfo (0);
  13938. target->getCommandInfo (info_.commandID, commandInfo);
  13939. ApplicationCommandTarget::InvocationInfo info (info_);
  13940. info.commandFlags = commandInfo.flags;
  13941. sendListenerInvokeCallback (info);
  13942. const bool ok = target->invoke (info, asynchronously);
  13943. commandStatusChanged();
  13944. return ok;
  13945. }
  13946. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13947. {
  13948. return firstTarget != 0 ? firstTarget
  13949. : findDefaultComponentTarget();
  13950. }
  13951. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13952. {
  13953. firstTarget = newTarget;
  13954. }
  13955. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13956. ApplicationCommandInfo& upToDateInfo)
  13957. {
  13958. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13959. if (target == 0)
  13960. target = JUCEApplication::getInstance();
  13961. if (target != 0)
  13962. target = target->getTargetForCommand (commandID);
  13963. if (target != 0)
  13964. target->getCommandInfo (commandID, upToDateInfo);
  13965. return target;
  13966. }
  13967. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13968. {
  13969. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13970. if (target == 0 && c != 0)
  13971. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13972. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13973. return target;
  13974. }
  13975. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13976. {
  13977. Component* c = Component::getCurrentlyFocusedComponent();
  13978. if (c == 0)
  13979. {
  13980. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13981. if (activeWindow != 0)
  13982. {
  13983. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13984. if (c == 0)
  13985. c = activeWindow;
  13986. }
  13987. }
  13988. if (c == 0 && Process::isForegroundProcess())
  13989. {
  13990. // getting a bit desperate now - try all desktop comps..
  13991. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13992. {
  13993. ApplicationCommandTarget* const target
  13994. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13995. ->getPeer()->getLastFocusedSubcomponent());
  13996. if (target != 0)
  13997. return target;
  13998. }
  13999. }
  14000. if (c != 0)
  14001. {
  14002. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14003. // if we're focused on a ResizableWindow, chances are that it's the content
  14004. // component that really should get the event. And if not, the event will
  14005. // still be passed up to the top level window anyway, so let's send it to the
  14006. // content comp.
  14007. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14008. c = resizableWindow->getContentComponent();
  14009. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14010. if (target != 0)
  14011. return target;
  14012. }
  14013. return JUCEApplication::getInstance();
  14014. }
  14015. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14016. {
  14017. listeners.add (listener);
  14018. }
  14019. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14020. {
  14021. listeners.remove (listener);
  14022. }
  14023. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14024. {
  14025. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14026. }
  14027. void ApplicationCommandManager::handleAsyncUpdate()
  14028. {
  14029. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14030. }
  14031. void ApplicationCommandManager::globalFocusChanged (Component*)
  14032. {
  14033. commandStatusChanged();
  14034. }
  14035. END_JUCE_NAMESPACE
  14036. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14037. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14038. BEGIN_JUCE_NAMESPACE
  14039. ApplicationCommandTarget::ApplicationCommandTarget()
  14040. {
  14041. }
  14042. ApplicationCommandTarget::~ApplicationCommandTarget()
  14043. {
  14044. messageInvoker = 0;
  14045. }
  14046. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14047. {
  14048. if (isCommandActive (info.commandID))
  14049. {
  14050. if (async)
  14051. {
  14052. if (messageInvoker == 0)
  14053. messageInvoker = new CommandTargetMessageInvoker (this);
  14054. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14055. return true;
  14056. }
  14057. else
  14058. {
  14059. const bool success = perform (info);
  14060. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14061. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14062. // returns the command's info.
  14063. return success;
  14064. }
  14065. }
  14066. return false;
  14067. }
  14068. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14069. {
  14070. Component* c = dynamic_cast <Component*> (this);
  14071. if (c != 0)
  14072. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14073. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14074. return 0;
  14075. }
  14076. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14077. {
  14078. ApplicationCommandTarget* target = this;
  14079. int depth = 0;
  14080. while (target != 0)
  14081. {
  14082. Array <CommandID> commandIDs;
  14083. target->getAllCommands (commandIDs);
  14084. if (commandIDs.contains (commandID))
  14085. return target;
  14086. target = target->getNextCommandTarget();
  14087. ++depth;
  14088. jassert (depth < 100); // could be a recursive command chain??
  14089. jassert (target != this); // definitely a recursive command chain!
  14090. if (depth > 100 || target == this)
  14091. break;
  14092. }
  14093. if (target == 0)
  14094. {
  14095. target = JUCEApplication::getInstance();
  14096. if (target != 0)
  14097. {
  14098. Array <CommandID> commandIDs;
  14099. target->getAllCommands (commandIDs);
  14100. if (commandIDs.contains (commandID))
  14101. return target;
  14102. }
  14103. }
  14104. return 0;
  14105. }
  14106. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14107. {
  14108. ApplicationCommandInfo info (commandID);
  14109. info.flags = ApplicationCommandInfo::isDisabled;
  14110. getCommandInfo (commandID, info);
  14111. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14112. }
  14113. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14114. {
  14115. ApplicationCommandTarget* target = this;
  14116. int depth = 0;
  14117. while (target != 0)
  14118. {
  14119. if (target->tryToInvoke (info, async))
  14120. return true;
  14121. target = target->getNextCommandTarget();
  14122. ++depth;
  14123. jassert (depth < 100); // could be a recursive command chain??
  14124. jassert (target != this); // definitely a recursive command chain!
  14125. if (depth > 100 || target == this)
  14126. break;
  14127. }
  14128. if (target == 0)
  14129. {
  14130. target = JUCEApplication::getInstance();
  14131. if (target != 0)
  14132. return target->tryToInvoke (info, async);
  14133. }
  14134. return false;
  14135. }
  14136. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14137. {
  14138. ApplicationCommandTarget::InvocationInfo info (commandID);
  14139. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14140. return invoke (info, asynchronously);
  14141. }
  14142. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14143. : commandID (commandID_),
  14144. commandFlags (0),
  14145. invocationMethod (direct),
  14146. originatingComponent (0),
  14147. isKeyDown (false),
  14148. millisecsSinceKeyPressed (0)
  14149. {
  14150. }
  14151. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14152. : owner (owner_)
  14153. {
  14154. }
  14155. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14156. {
  14157. }
  14158. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14159. {
  14160. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14161. owner->tryToInvoke (*info, false);
  14162. }
  14163. END_JUCE_NAMESPACE
  14164. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14165. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14166. BEGIN_JUCE_NAMESPACE
  14167. juce_ImplementSingleton (ApplicationProperties)
  14168. ApplicationProperties::ApplicationProperties() throw()
  14169. : msBeforeSaving (3000),
  14170. options (PropertiesFile::storeAsBinary),
  14171. commonSettingsAreReadOnly (0)
  14172. {
  14173. }
  14174. ApplicationProperties::~ApplicationProperties()
  14175. {
  14176. closeFiles();
  14177. clearSingletonInstance();
  14178. }
  14179. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14180. const String& fileNameSuffix,
  14181. const String& folderName_,
  14182. const int millisecondsBeforeSaving,
  14183. const int propertiesFileOptions) throw()
  14184. {
  14185. appName = applicationName;
  14186. fileSuffix = fileNameSuffix;
  14187. folderName = folderName_;
  14188. msBeforeSaving = millisecondsBeforeSaving;
  14189. options = propertiesFileOptions;
  14190. }
  14191. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14192. const bool testCommonSettings,
  14193. const bool showWarningDialogOnFailure)
  14194. {
  14195. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14196. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14197. if (! (userOk && commonOk))
  14198. {
  14199. if (showWarningDialogOnFailure)
  14200. {
  14201. String filenames;
  14202. if (userProps != 0 && ! userOk)
  14203. filenames << '\n' << userProps->getFile().getFullPathName();
  14204. if (commonProps != 0 && ! commonOk)
  14205. filenames << '\n' << commonProps->getFile().getFullPathName();
  14206. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14207. appName + TRANS(" - Unable to save settings"),
  14208. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14209. + appName + TRANS(" needs to be able to write to the following files:\n")
  14210. + filenames
  14211. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14212. }
  14213. return false;
  14214. }
  14215. return true;
  14216. }
  14217. void ApplicationProperties::openFiles() throw()
  14218. {
  14219. // You need to call setStorageParameters() before trying to get hold of the
  14220. // properties!
  14221. jassert (appName.isNotEmpty());
  14222. if (appName.isNotEmpty())
  14223. {
  14224. if (userProps == 0)
  14225. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14226. false, msBeforeSaving, options);
  14227. if (commonProps == 0)
  14228. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14229. true, msBeforeSaving, options);
  14230. userProps->setFallbackPropertySet (commonProps);
  14231. }
  14232. }
  14233. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14234. {
  14235. if (userProps == 0)
  14236. openFiles();
  14237. return userProps;
  14238. }
  14239. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14240. {
  14241. if (commonProps == 0)
  14242. openFiles();
  14243. if (returnUserPropsIfReadOnly)
  14244. {
  14245. if (commonSettingsAreReadOnly == 0)
  14246. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14247. if (commonSettingsAreReadOnly > 0)
  14248. return userProps;
  14249. }
  14250. return commonProps;
  14251. }
  14252. bool ApplicationProperties::saveIfNeeded()
  14253. {
  14254. return (userProps == 0 || userProps->saveIfNeeded())
  14255. && (commonProps == 0 || commonProps->saveIfNeeded());
  14256. }
  14257. void ApplicationProperties::closeFiles()
  14258. {
  14259. userProps = 0;
  14260. commonProps = 0;
  14261. }
  14262. END_JUCE_NAMESPACE
  14263. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14264. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14265. BEGIN_JUCE_NAMESPACE
  14266. static VoidArray objectsToDelete;
  14267. static CriticalSection lock;
  14268. DeletedAtShutdown::DeletedAtShutdown()
  14269. {
  14270. const ScopedLock sl (lock);
  14271. objectsToDelete.add (this);
  14272. }
  14273. DeletedAtShutdown::~DeletedAtShutdown()
  14274. {
  14275. const ScopedLock sl (lock);
  14276. objectsToDelete.removeValue (this);
  14277. }
  14278. void DeletedAtShutdown::deleteAll()
  14279. {
  14280. // make a local copy of the array, so it can't get into a loop if something
  14281. // creates another DeletedAtShutdown object during its destructor.
  14282. VoidArray localCopy;
  14283. {
  14284. const ScopedLock sl (lock);
  14285. localCopy = objectsToDelete;
  14286. }
  14287. for (int i = localCopy.size(); --i >= 0;)
  14288. {
  14289. JUCE_TRY
  14290. {
  14291. DeletedAtShutdown* deletee = static_cast <DeletedAtShutdown*> (localCopy.getUnchecked(i));
  14292. // double-check that it's not already been deleted during another object's destructor.
  14293. {
  14294. const ScopedLock sl (lock);
  14295. if (! objectsToDelete.contains (deletee))
  14296. deletee = 0;
  14297. }
  14298. delete deletee;
  14299. }
  14300. JUCE_CATCH_EXCEPTION
  14301. }
  14302. // if no objects got re-created during shutdown, this should have been emptied by their
  14303. // destructors
  14304. jassert (objectsToDelete.size() == 0);
  14305. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  14306. }
  14307. END_JUCE_NAMESPACE
  14308. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14309. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14310. BEGIN_JUCE_NAMESPACE
  14311. namespace PropertyFileConstants
  14312. {
  14313. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14314. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14315. static const char* const fileTag = "PROPERTIES";
  14316. static const char* const valueTag = "VALUE";
  14317. static const char* const nameAttribute = "name";
  14318. static const char* const valueAttribute = "val";
  14319. }
  14320. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14321. const int options_, InterProcessLock* const processLock_)
  14322. : PropertySet (ignoreCaseOfKeyNames),
  14323. file (f),
  14324. timerInterval (millisecondsBeforeSaving),
  14325. options (options_),
  14326. loadedOk (false),
  14327. needsWriting (false),
  14328. processLock (processLock_)
  14329. {
  14330. // You need to correctly specify just one storage format for the file
  14331. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14332. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14333. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14334. ProcessScopedLock pl (createProcessLock());
  14335. if (pl != 0 && ! pl->isLocked())
  14336. return; // locking failure..
  14337. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14338. if (fileStream != 0)
  14339. {
  14340. int magicNumber = fileStream->readInt();
  14341. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14342. {
  14343. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14344. magicNumber = PropertyFileConstants::magicNumber;
  14345. }
  14346. if (magicNumber == PropertyFileConstants::magicNumber)
  14347. {
  14348. loadedOk = true;
  14349. BufferedInputStream in (fileStream.release(), 2048, true);
  14350. int numValues = in.readInt();
  14351. while (--numValues >= 0 && ! in.isExhausted())
  14352. {
  14353. const String key (in.readString());
  14354. const String value (in.readString());
  14355. jassert (key.isNotEmpty());
  14356. if (key.isNotEmpty())
  14357. getAllProperties().set (key, value);
  14358. }
  14359. }
  14360. else
  14361. {
  14362. // Not a binary props file - let's see if it's XML..
  14363. fileStream = 0;
  14364. XmlDocument parser (f);
  14365. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14366. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14367. {
  14368. doc = parser.getDocumentElement();
  14369. if (doc != 0)
  14370. {
  14371. loadedOk = true;
  14372. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14373. {
  14374. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14375. if (name.isNotEmpty())
  14376. {
  14377. getAllProperties().set (name,
  14378. e->getFirstChildElement() != 0
  14379. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14380. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14381. }
  14382. }
  14383. }
  14384. else
  14385. {
  14386. // must be a pretty broken XML file we're trying to parse here,
  14387. // or a sign that this object needs an InterProcessLock,
  14388. // or just a failure reading the file. This last reason is why
  14389. // we don't jassertfalse here.
  14390. }
  14391. }
  14392. }
  14393. }
  14394. else
  14395. {
  14396. loadedOk = ! f.exists();
  14397. }
  14398. }
  14399. PropertiesFile::~PropertiesFile()
  14400. {
  14401. if (! saveIfNeeded())
  14402. jassertfalse;
  14403. }
  14404. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14405. {
  14406. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14407. }
  14408. bool PropertiesFile::saveIfNeeded()
  14409. {
  14410. const ScopedLock sl (getLock());
  14411. return (! needsWriting) || save();
  14412. }
  14413. bool PropertiesFile::needsToBeSaved() const
  14414. {
  14415. const ScopedLock sl (getLock());
  14416. return needsWriting;
  14417. }
  14418. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14419. {
  14420. const ScopedLock sl (getLock());
  14421. needsWriting = needsToBeSaved_;
  14422. }
  14423. bool PropertiesFile::save()
  14424. {
  14425. const ScopedLock sl (getLock());
  14426. stopTimer();
  14427. if (file == File::nonexistent
  14428. || file.isDirectory()
  14429. || ! file.getParentDirectory().createDirectory())
  14430. return false;
  14431. if ((options & storeAsXML) != 0)
  14432. {
  14433. XmlElement doc (PropertyFileConstants::fileTag);
  14434. for (int i = 0; i < getAllProperties().size(); ++i)
  14435. {
  14436. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14437. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14438. // if the value seems to contain xml, store it as such..
  14439. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14440. XmlElement* const childElement = xmlContent.getDocumentElement();
  14441. if (childElement != 0)
  14442. e->addChildElement (childElement);
  14443. else
  14444. e->setAttribute (PropertyFileConstants::valueAttribute,
  14445. getAllProperties().getAllValues() [i]);
  14446. }
  14447. ProcessScopedLock pl (createProcessLock());
  14448. if (pl != 0 && ! pl->isLocked())
  14449. return false; // locking failure..
  14450. if (doc.writeToFile (file, String::empty))
  14451. {
  14452. needsWriting = false;
  14453. return true;
  14454. }
  14455. }
  14456. else
  14457. {
  14458. ProcessScopedLock pl (createProcessLock());
  14459. if (pl != 0 && ! pl->isLocked())
  14460. return false; // locking failure..
  14461. TemporaryFile tempFile (file);
  14462. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14463. if (out != 0)
  14464. {
  14465. if ((options & storeAsCompressedBinary) != 0)
  14466. {
  14467. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14468. out->flush();
  14469. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14470. }
  14471. else
  14472. {
  14473. // have you set up the storage option flags correctly?
  14474. jassert ((options & storeAsBinary) != 0);
  14475. out->writeInt (PropertyFileConstants::magicNumber);
  14476. }
  14477. const int numProperties = getAllProperties().size();
  14478. out->writeInt (numProperties);
  14479. for (int i = 0; i < numProperties; ++i)
  14480. {
  14481. out->writeString (getAllProperties().getAllKeys() [i]);
  14482. out->writeString (getAllProperties().getAllValues() [i]);
  14483. }
  14484. out = 0;
  14485. if (tempFile.overwriteTargetFileWithTemporary())
  14486. {
  14487. needsWriting = false;
  14488. return true;
  14489. }
  14490. }
  14491. }
  14492. return false;
  14493. }
  14494. void PropertiesFile::timerCallback()
  14495. {
  14496. saveIfNeeded();
  14497. }
  14498. void PropertiesFile::propertyChanged()
  14499. {
  14500. sendChangeMessage (this);
  14501. needsWriting = true;
  14502. if (timerInterval > 0)
  14503. startTimer (timerInterval);
  14504. else if (timerInterval == 0)
  14505. saveIfNeeded();
  14506. }
  14507. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14508. const String& fileNameSuffix,
  14509. const String& folderName,
  14510. const bool commonToAllUsers)
  14511. {
  14512. // mustn't have illegal characters in this name..
  14513. jassert (applicationName == File::createLegalFileName (applicationName));
  14514. #if JUCE_MAC || JUCE_IPHONE
  14515. File dir (commonToAllUsers ? "/Library/Preferences"
  14516. : "~/Library/Preferences");
  14517. if (folderName.isNotEmpty())
  14518. dir = dir.getChildFile (folderName);
  14519. #endif
  14520. #ifdef JUCE_LINUX
  14521. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14522. + (folderName.isNotEmpty() ? folderName
  14523. : ("." + applicationName)));
  14524. #endif
  14525. #if JUCE_WIN32
  14526. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14527. : File::userApplicationDataDirectory));
  14528. if (dir == File::nonexistent)
  14529. return File::nonexistent;
  14530. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14531. : applicationName);
  14532. #endif
  14533. return dir.getChildFile (applicationName)
  14534. .withFileExtension (fileNameSuffix);
  14535. }
  14536. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14537. const String& fileNameSuffix,
  14538. const String& folderName,
  14539. const bool commonToAllUsers,
  14540. const int millisecondsBeforeSaving,
  14541. const int propertiesFileOptions,
  14542. InterProcessLock* processLock_)
  14543. {
  14544. const File file (getDefaultAppSettingsFile (applicationName,
  14545. fileNameSuffix,
  14546. folderName,
  14547. commonToAllUsers));
  14548. jassert (file != File::nonexistent);
  14549. if (file == File::nonexistent)
  14550. return 0;
  14551. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14552. }
  14553. END_JUCE_NAMESPACE
  14554. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14555. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14556. BEGIN_JUCE_NAMESPACE
  14557. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14558. const String& fileWildcard_,
  14559. const String& openFileDialogTitle_,
  14560. const String& saveFileDialogTitle_)
  14561. : changedSinceSave (false),
  14562. fileExtension (fileExtension_),
  14563. fileWildcard (fileWildcard_),
  14564. openFileDialogTitle (openFileDialogTitle_),
  14565. saveFileDialogTitle (saveFileDialogTitle_)
  14566. {
  14567. }
  14568. FileBasedDocument::~FileBasedDocument()
  14569. {
  14570. }
  14571. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14572. {
  14573. if (changedSinceSave != hasChanged)
  14574. {
  14575. changedSinceSave = hasChanged;
  14576. sendChangeMessage (this);
  14577. }
  14578. }
  14579. void FileBasedDocument::changed()
  14580. {
  14581. changedSinceSave = true;
  14582. sendChangeMessage (this);
  14583. }
  14584. void FileBasedDocument::setFile (const File& newFile)
  14585. {
  14586. if (documentFile != newFile)
  14587. {
  14588. documentFile = newFile;
  14589. changed();
  14590. }
  14591. }
  14592. bool FileBasedDocument::loadFrom (const File& newFile,
  14593. const bool showMessageOnFailure)
  14594. {
  14595. MouseCursor::showWaitCursor();
  14596. const File oldFile (documentFile);
  14597. documentFile = newFile;
  14598. String error;
  14599. if (newFile.existsAsFile())
  14600. {
  14601. error = loadDocument (newFile);
  14602. if (error.isEmpty())
  14603. {
  14604. setChangedFlag (false);
  14605. MouseCursor::hideWaitCursor();
  14606. setLastDocumentOpened (newFile);
  14607. return true;
  14608. }
  14609. }
  14610. else
  14611. {
  14612. error = "The file doesn't exist";
  14613. }
  14614. documentFile = oldFile;
  14615. MouseCursor::hideWaitCursor();
  14616. if (showMessageOnFailure)
  14617. {
  14618. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14619. TRANS("Failed to open file..."),
  14620. TRANS("There was an error while trying to load the file:\n\n")
  14621. + newFile.getFullPathName()
  14622. + "\n\n"
  14623. + error);
  14624. }
  14625. return false;
  14626. }
  14627. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14628. {
  14629. FileChooser fc (openFileDialogTitle,
  14630. getLastDocumentOpened(),
  14631. fileWildcard);
  14632. if (fc.browseForFileToOpen())
  14633. return loadFrom (fc.getResult(), showMessageOnFailure);
  14634. return false;
  14635. }
  14636. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14637. const bool showMessageOnFailure)
  14638. {
  14639. return saveAs (documentFile,
  14640. false,
  14641. askUserForFileIfNotSpecified,
  14642. showMessageOnFailure);
  14643. }
  14644. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14645. const bool warnAboutOverwritingExistingFiles,
  14646. const bool askUserForFileIfNotSpecified,
  14647. const bool showMessageOnFailure)
  14648. {
  14649. if (newFile == File::nonexistent)
  14650. {
  14651. if (askUserForFileIfNotSpecified)
  14652. {
  14653. return saveAsInteractive (true);
  14654. }
  14655. else
  14656. {
  14657. // can't save to an unspecified file
  14658. jassertfalse
  14659. return failedToWriteToFile;
  14660. }
  14661. }
  14662. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14663. {
  14664. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14665. TRANS("File already exists"),
  14666. TRANS("There's already a file called:\n\n")
  14667. + newFile.getFullPathName()
  14668. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14669. TRANS("overwrite"),
  14670. TRANS("cancel")))
  14671. {
  14672. return userCancelledSave;
  14673. }
  14674. }
  14675. MouseCursor::showWaitCursor();
  14676. const File oldFile (documentFile);
  14677. documentFile = newFile;
  14678. String error (saveDocument (newFile));
  14679. if (error.isEmpty())
  14680. {
  14681. setChangedFlag (false);
  14682. MouseCursor::hideWaitCursor();
  14683. return savedOk;
  14684. }
  14685. documentFile = oldFile;
  14686. MouseCursor::hideWaitCursor();
  14687. if (showMessageOnFailure)
  14688. {
  14689. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14690. TRANS("Error writing to file..."),
  14691. TRANS("An error occurred while trying to save \"")
  14692. + getDocumentTitle()
  14693. + TRANS("\" to the file:\n\n")
  14694. + newFile.getFullPathName()
  14695. + "\n\n"
  14696. + error);
  14697. }
  14698. return failedToWriteToFile;
  14699. }
  14700. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14701. {
  14702. if (! hasChangedSinceSaved())
  14703. return savedOk;
  14704. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14705. TRANS("Closing document..."),
  14706. TRANS("Do you want to save the changes to \"")
  14707. + getDocumentTitle() + "\"?",
  14708. TRANS("save"),
  14709. TRANS("discard changes"),
  14710. TRANS("cancel"));
  14711. if (r == 1)
  14712. {
  14713. // save changes
  14714. return save (true, true);
  14715. }
  14716. else if (r == 2)
  14717. {
  14718. // discard changes
  14719. return savedOk;
  14720. }
  14721. return userCancelledSave;
  14722. }
  14723. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14724. {
  14725. File f;
  14726. if (documentFile.existsAsFile())
  14727. f = documentFile;
  14728. else
  14729. f = getLastDocumentOpened();
  14730. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14731. if (legalFilename.isEmpty())
  14732. legalFilename = "unnamed";
  14733. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14734. f = f.getSiblingFile (legalFilename);
  14735. else
  14736. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14737. f = f.withFileExtension (fileExtension)
  14738. .getNonexistentSibling (true);
  14739. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14740. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14741. {
  14742. setLastDocumentOpened (fc.getResult());
  14743. File chosen (fc.getResult());
  14744. if (chosen.getFileExtension().isEmpty())
  14745. {
  14746. chosen = chosen.withFileExtension (fileExtension);
  14747. if (chosen.exists())
  14748. {
  14749. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14750. TRANS("File already exists"),
  14751. TRANS("There's already a file called:")
  14752. + "\n\n" + chosen.getFullPathName()
  14753. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14754. TRANS("overwrite"),
  14755. TRANS("cancel")))
  14756. {
  14757. return userCancelledSave;
  14758. }
  14759. }
  14760. }
  14761. return saveAs (chosen, false, false, true);
  14762. }
  14763. return userCancelledSave;
  14764. }
  14765. END_JUCE_NAMESPACE
  14766. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14767. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14768. BEGIN_JUCE_NAMESPACE
  14769. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14770. : maxNumberOfItems (10)
  14771. {
  14772. }
  14773. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14774. {
  14775. }
  14776. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14777. {
  14778. maxNumberOfItems = jmax (1, newMaxNumber);
  14779. while (getNumFiles() > maxNumberOfItems)
  14780. files.remove (getNumFiles() - 1);
  14781. }
  14782. int RecentlyOpenedFilesList::getNumFiles() const
  14783. {
  14784. return files.size();
  14785. }
  14786. const File RecentlyOpenedFilesList::getFile (const int index) const
  14787. {
  14788. return File (files [index]);
  14789. }
  14790. void RecentlyOpenedFilesList::clear()
  14791. {
  14792. files.clear();
  14793. }
  14794. void RecentlyOpenedFilesList::addFile (const File& file)
  14795. {
  14796. const String path (file.getFullPathName());
  14797. files.removeString (path, true);
  14798. files.insert (0, path);
  14799. setMaxNumberOfItems (maxNumberOfItems);
  14800. }
  14801. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14802. {
  14803. for (int i = getNumFiles(); --i >= 0;)
  14804. if (! getFile(i).exists())
  14805. files.remove (i);
  14806. }
  14807. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14808. const int baseItemId,
  14809. const bool showFullPaths,
  14810. const bool dontAddNonExistentFiles,
  14811. const File** filesToAvoid)
  14812. {
  14813. int num = 0;
  14814. for (int i = 0; i < getNumFiles(); ++i)
  14815. {
  14816. const File f (getFile(i));
  14817. if ((! dontAddNonExistentFiles) || f.exists())
  14818. {
  14819. bool needsAvoiding = false;
  14820. if (filesToAvoid != 0)
  14821. {
  14822. const File** avoid = filesToAvoid;
  14823. while (*avoid != 0)
  14824. {
  14825. if (f == **avoid)
  14826. {
  14827. needsAvoiding = true;
  14828. break;
  14829. }
  14830. ++avoid;
  14831. }
  14832. }
  14833. if (! needsAvoiding)
  14834. {
  14835. menuToAddTo.addItem (baseItemId + i,
  14836. showFullPaths ? f.getFullPathName()
  14837. : f.getFileName());
  14838. ++num;
  14839. }
  14840. }
  14841. }
  14842. return num;
  14843. }
  14844. const String RecentlyOpenedFilesList::toString() const
  14845. {
  14846. return files.joinIntoString ("\n");
  14847. }
  14848. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14849. {
  14850. clear();
  14851. files.addLines (stringifiedVersion);
  14852. setMaxNumberOfItems (maxNumberOfItems);
  14853. }
  14854. END_JUCE_NAMESPACE
  14855. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14856. /*** Start of inlined file: juce_UndoManager.cpp ***/
  14857. BEGIN_JUCE_NAMESPACE
  14858. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14859. const int minimumTransactions)
  14860. : totalUnitsStored (0),
  14861. nextIndex (0),
  14862. newTransaction (true),
  14863. reentrancyCheck (false)
  14864. {
  14865. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14866. minimumTransactions);
  14867. }
  14868. UndoManager::~UndoManager()
  14869. {
  14870. clearUndoHistory();
  14871. }
  14872. void UndoManager::clearUndoHistory()
  14873. {
  14874. transactions.clear();
  14875. transactionNames.clear();
  14876. totalUnitsStored = 0;
  14877. nextIndex = 0;
  14878. sendChangeMessage (this);
  14879. }
  14880. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14881. {
  14882. return totalUnitsStored;
  14883. }
  14884. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14885. const int minimumTransactions)
  14886. {
  14887. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14888. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14889. }
  14890. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14891. {
  14892. if (command != 0)
  14893. {
  14894. if (actionName.isNotEmpty())
  14895. currentTransactionName = actionName;
  14896. if (reentrancyCheck)
  14897. {
  14898. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14899. // undo() methods, or else these actions won't actually get done.
  14900. return false;
  14901. }
  14902. else
  14903. {
  14904. bool success = false;
  14905. JUCE_TRY
  14906. {
  14907. success = command->perform();
  14908. }
  14909. JUCE_CATCH_EXCEPTION
  14910. jassert (success);
  14911. if (success)
  14912. {
  14913. if (nextIndex > 0 && ! newTransaction)
  14914. {
  14915. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14916. jassert (commandSet != 0);
  14917. if (commandSet == 0)
  14918. return false;
  14919. commandSet->add (command);
  14920. }
  14921. else
  14922. {
  14923. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14924. commandSet->add (command);
  14925. transactions.insert (nextIndex, commandSet);
  14926. transactionNames.insert (nextIndex, currentTransactionName);
  14927. ++nextIndex;
  14928. }
  14929. totalUnitsStored += command->getSizeInUnits();
  14930. newTransaction = false;
  14931. }
  14932. while (nextIndex < transactions.size())
  14933. {
  14934. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14935. for (int i = lastSet->size(); --i >= 0;)
  14936. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14937. transactions.removeLast();
  14938. transactionNames.remove (transactionNames.size() - 1);
  14939. }
  14940. while (nextIndex > 0
  14941. && totalUnitsStored > maxNumUnitsToKeep
  14942. && transactions.size() > minimumTransactionsToKeep)
  14943. {
  14944. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14945. for (int i = firstSet->size(); --i >= 0;)
  14946. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14947. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14948. transactions.remove (0);
  14949. transactionNames.remove (0);
  14950. --nextIndex;
  14951. }
  14952. sendChangeMessage (this);
  14953. return success;
  14954. }
  14955. }
  14956. return false;
  14957. }
  14958. void UndoManager::beginNewTransaction (const String& actionName)
  14959. {
  14960. newTransaction = true;
  14961. currentTransactionName = actionName;
  14962. }
  14963. void UndoManager::setCurrentTransactionName (const String& newName)
  14964. {
  14965. currentTransactionName = newName;
  14966. }
  14967. bool UndoManager::canUndo() const
  14968. {
  14969. return nextIndex > 0;
  14970. }
  14971. bool UndoManager::canRedo() const
  14972. {
  14973. return nextIndex < transactions.size();
  14974. }
  14975. const String UndoManager::getUndoDescription() const
  14976. {
  14977. return transactionNames [nextIndex - 1];
  14978. }
  14979. const String UndoManager::getRedoDescription() const
  14980. {
  14981. return transactionNames [nextIndex];
  14982. }
  14983. bool UndoManager::undo()
  14984. {
  14985. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14986. if (commandSet == 0)
  14987. return false;
  14988. reentrancyCheck = true;
  14989. bool failed = false;
  14990. for (int i = commandSet->size(); --i >= 0;)
  14991. {
  14992. if (! commandSet->getUnchecked(i)->undo())
  14993. {
  14994. jassertfalse
  14995. failed = true;
  14996. break;
  14997. }
  14998. }
  14999. reentrancyCheck = false;
  15000. if (failed)
  15001. {
  15002. clearUndoHistory();
  15003. }
  15004. else
  15005. {
  15006. --nextIndex;
  15007. }
  15008. beginNewTransaction();
  15009. sendChangeMessage (this);
  15010. return true;
  15011. }
  15012. bool UndoManager::redo()
  15013. {
  15014. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15015. if (commandSet == 0)
  15016. return false;
  15017. reentrancyCheck = true;
  15018. bool failed = false;
  15019. for (int i = 0; i < commandSet->size(); ++i)
  15020. {
  15021. if (! commandSet->getUnchecked(i)->perform())
  15022. {
  15023. jassertfalse
  15024. failed = true;
  15025. break;
  15026. }
  15027. }
  15028. reentrancyCheck = false;
  15029. if (failed)
  15030. {
  15031. clearUndoHistory();
  15032. }
  15033. else
  15034. {
  15035. ++nextIndex;
  15036. }
  15037. beginNewTransaction();
  15038. sendChangeMessage (this);
  15039. return true;
  15040. }
  15041. bool UndoManager::undoCurrentTransactionOnly()
  15042. {
  15043. return newTransaction ? false
  15044. : undo();
  15045. }
  15046. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15047. {
  15048. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15049. if (commandSet != 0 && ! newTransaction)
  15050. {
  15051. for (int i = 0; i < commandSet->size(); ++i)
  15052. actionsFound.add (commandSet->getUnchecked(i));
  15053. }
  15054. }
  15055. int UndoManager::getNumActionsInCurrentTransaction() const
  15056. {
  15057. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15058. if (commandSet != 0 && ! newTransaction)
  15059. return commandSet->size();
  15060. return 0;
  15061. }
  15062. END_JUCE_NAMESPACE
  15063. /*** End of inlined file: juce_UndoManager.cpp ***/
  15064. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15065. BEGIN_JUCE_NAMESPACE
  15066. static const char* const aiffFormatName = "AIFF file";
  15067. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15068. class AiffAudioFormatReader : public AudioFormatReader
  15069. {
  15070. public:
  15071. int bytesPerFrame;
  15072. int64 dataChunkStart;
  15073. bool littleEndian;
  15074. AiffAudioFormatReader (InputStream* in)
  15075. : AudioFormatReader (in, TRANS (aiffFormatName))
  15076. {
  15077. if (input->readInt() == chunkName ("FORM"))
  15078. {
  15079. const int len = input->readIntBigEndian();
  15080. const int64 end = input->getPosition() + len;
  15081. const int nextType = input->readInt();
  15082. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15083. {
  15084. bool hasGotVer = false;
  15085. bool hasGotData = false;
  15086. bool hasGotType = false;
  15087. while (input->getPosition() < end)
  15088. {
  15089. const int type = input->readInt();
  15090. const uint32 length = (uint32) input->readIntBigEndian();
  15091. const int64 chunkEnd = input->getPosition() + length;
  15092. if (type == chunkName ("FVER"))
  15093. {
  15094. hasGotVer = true;
  15095. const int ver = input->readIntBigEndian();
  15096. if (ver != 0 && ver != (int)0xa2805140)
  15097. break;
  15098. }
  15099. else if (type == chunkName ("COMM"))
  15100. {
  15101. hasGotType = true;
  15102. numChannels = (unsigned int)input->readShortBigEndian();
  15103. lengthInSamples = input->readIntBigEndian();
  15104. bitsPerSample = input->readShortBigEndian();
  15105. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15106. unsigned char sampleRateBytes[10];
  15107. input->read (sampleRateBytes, 10);
  15108. const int byte0 = sampleRateBytes[0];
  15109. if ((byte0 & 0x80) != 0
  15110. || byte0 <= 0x3F || byte0 > 0x40
  15111. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15112. break;
  15113. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15114. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15115. sampleRate = (int) sampRate;
  15116. if (length <= 18)
  15117. {
  15118. // some types don't have a chunk large enough to include a compression
  15119. // type, so assume it's just big-endian pcm
  15120. littleEndian = false;
  15121. }
  15122. else
  15123. {
  15124. const int compType = input->readInt();
  15125. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15126. {
  15127. littleEndian = false;
  15128. }
  15129. else if (compType == chunkName ("sowt"))
  15130. {
  15131. littleEndian = true;
  15132. }
  15133. else
  15134. {
  15135. sampleRate = 0;
  15136. break;
  15137. }
  15138. }
  15139. }
  15140. else if (type == chunkName ("SSND"))
  15141. {
  15142. hasGotData = true;
  15143. const int offset = input->readIntBigEndian();
  15144. dataChunkStart = input->getPosition() + 4 + offset;
  15145. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15146. }
  15147. else if ((hasGotVer && hasGotData && hasGotType)
  15148. || chunkEnd < input->getPosition()
  15149. || input->isExhausted())
  15150. {
  15151. break;
  15152. }
  15153. input->setPosition (chunkEnd);
  15154. }
  15155. }
  15156. }
  15157. }
  15158. ~AiffAudioFormatReader()
  15159. {
  15160. }
  15161. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15162. int64 startSampleInFile, int numSamples)
  15163. {
  15164. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15165. if (samplesAvailable < numSamples)
  15166. {
  15167. for (int i = numDestChannels; --i >= 0;)
  15168. if (destSamples[i] != 0)
  15169. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15170. numSamples = (int) samplesAvailable;
  15171. }
  15172. if (numSamples <= 0)
  15173. return true;
  15174. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15175. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15176. char tempBuffer [tempBufSize];
  15177. while (numSamples > 0)
  15178. {
  15179. int* left = destSamples[0];
  15180. if (left != 0)
  15181. left += startOffsetInDestBuffer;
  15182. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15183. if (right != 0)
  15184. right += startOffsetInDestBuffer;
  15185. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15186. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15187. if (bytesRead < numThisTime * bytesPerFrame)
  15188. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15189. if (bitsPerSample == 16)
  15190. {
  15191. if (littleEndian)
  15192. {
  15193. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15194. if (numChannels > 1)
  15195. {
  15196. if (left == 0)
  15197. {
  15198. for (int i = numThisTime; --i >= 0;)
  15199. {
  15200. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15201. ++src;
  15202. }
  15203. }
  15204. else if (right == 0)
  15205. {
  15206. for (int i = numThisTime; --i >= 0;)
  15207. {
  15208. ++src;
  15209. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15210. }
  15211. }
  15212. else
  15213. {
  15214. for (int i = numThisTime; --i >= 0;)
  15215. {
  15216. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15217. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15218. }
  15219. }
  15220. }
  15221. else
  15222. {
  15223. for (int i = numThisTime; --i >= 0;)
  15224. {
  15225. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15226. }
  15227. }
  15228. }
  15229. else
  15230. {
  15231. const char* src = tempBuffer;
  15232. if (numChannels > 1)
  15233. {
  15234. if (left == 0)
  15235. {
  15236. for (int i = numThisTime; --i >= 0;)
  15237. {
  15238. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15239. src += 4;
  15240. }
  15241. }
  15242. else if (right == 0)
  15243. {
  15244. for (int i = numThisTime; --i >= 0;)
  15245. {
  15246. src += 2;
  15247. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15248. src += 2;
  15249. }
  15250. }
  15251. else
  15252. {
  15253. for (int i = numThisTime; --i >= 0;)
  15254. {
  15255. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15256. src += 2;
  15257. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15258. src += 2;
  15259. }
  15260. }
  15261. }
  15262. else
  15263. {
  15264. for (int i = numThisTime; --i >= 0;)
  15265. {
  15266. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15267. src += 2;
  15268. }
  15269. }
  15270. }
  15271. }
  15272. else if (bitsPerSample == 24)
  15273. {
  15274. const char* src = (const char*)tempBuffer;
  15275. if (littleEndian)
  15276. {
  15277. if (numChannels > 1)
  15278. {
  15279. if (left == 0)
  15280. {
  15281. for (int i = numThisTime; --i >= 0;)
  15282. {
  15283. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15284. src += 6;
  15285. }
  15286. }
  15287. else if (right == 0)
  15288. {
  15289. for (int i = numThisTime; --i >= 0;)
  15290. {
  15291. src += 3;
  15292. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15293. src += 3;
  15294. }
  15295. }
  15296. else
  15297. {
  15298. for (int i = numThisTime; --i >= 0;)
  15299. {
  15300. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15301. src += 3;
  15302. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15303. src += 3;
  15304. }
  15305. }
  15306. }
  15307. else
  15308. {
  15309. for (int i = numThisTime; --i >= 0;)
  15310. {
  15311. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15312. src += 3;
  15313. }
  15314. }
  15315. }
  15316. else
  15317. {
  15318. if (numChannels > 1)
  15319. {
  15320. if (left == 0)
  15321. {
  15322. for (int i = numThisTime; --i >= 0;)
  15323. {
  15324. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15325. src += 6;
  15326. }
  15327. }
  15328. else if (right == 0)
  15329. {
  15330. for (int i = numThisTime; --i >= 0;)
  15331. {
  15332. src += 3;
  15333. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15334. src += 3;
  15335. }
  15336. }
  15337. else
  15338. {
  15339. for (int i = numThisTime; --i >= 0;)
  15340. {
  15341. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15342. src += 3;
  15343. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15344. src += 3;
  15345. }
  15346. }
  15347. }
  15348. else
  15349. {
  15350. for (int i = numThisTime; --i >= 0;)
  15351. {
  15352. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15353. src += 3;
  15354. }
  15355. }
  15356. }
  15357. }
  15358. else if (bitsPerSample == 32)
  15359. {
  15360. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15361. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15362. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15363. if (littleEndian)
  15364. {
  15365. if (numChannels > 1)
  15366. {
  15367. if (l == 0)
  15368. {
  15369. for (int i = numThisTime; --i >= 0;)
  15370. {
  15371. ++src;
  15372. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15373. }
  15374. }
  15375. else if (r == 0)
  15376. {
  15377. for (int i = numThisTime; --i >= 0;)
  15378. {
  15379. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15380. ++src;
  15381. }
  15382. }
  15383. else
  15384. {
  15385. for (int i = numThisTime; --i >= 0;)
  15386. {
  15387. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15388. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15389. }
  15390. }
  15391. }
  15392. else
  15393. {
  15394. for (int i = numThisTime; --i >= 0;)
  15395. {
  15396. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15397. }
  15398. }
  15399. }
  15400. else
  15401. {
  15402. if (numChannels > 1)
  15403. {
  15404. if (l == 0)
  15405. {
  15406. for (int i = numThisTime; --i >= 0;)
  15407. {
  15408. ++src;
  15409. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15410. }
  15411. }
  15412. else if (r == 0)
  15413. {
  15414. for (int i = numThisTime; --i >= 0;)
  15415. {
  15416. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15417. ++src;
  15418. }
  15419. }
  15420. else
  15421. {
  15422. for (int i = numThisTime; --i >= 0;)
  15423. {
  15424. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15425. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15426. }
  15427. }
  15428. }
  15429. else
  15430. {
  15431. for (int i = numThisTime; --i >= 0;)
  15432. {
  15433. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15434. }
  15435. }
  15436. }
  15437. left = reinterpret_cast <int*> (l);
  15438. right = reinterpret_cast <int*> (r);
  15439. }
  15440. else if (bitsPerSample == 8)
  15441. {
  15442. const char* src = tempBuffer;
  15443. if (numChannels > 1)
  15444. {
  15445. if (left == 0)
  15446. {
  15447. for (int i = numThisTime; --i >= 0;)
  15448. {
  15449. *right++ = ((int) *src++) << 24;
  15450. ++src;
  15451. }
  15452. }
  15453. else if (right == 0)
  15454. {
  15455. for (int i = numThisTime; --i >= 0;)
  15456. {
  15457. ++src;
  15458. *left++ = ((int) *src++) << 24;
  15459. }
  15460. }
  15461. else
  15462. {
  15463. for (int i = numThisTime; --i >= 0;)
  15464. {
  15465. *left++ = ((int) *src++) << 24;
  15466. *right++ = ((int) *src++) << 24;
  15467. }
  15468. }
  15469. }
  15470. else
  15471. {
  15472. for (int i = numThisTime; --i >= 0;)
  15473. {
  15474. *left++ = ((int) *src++) << 24;
  15475. }
  15476. }
  15477. }
  15478. startOffsetInDestBuffer += numThisTime;
  15479. numSamples -= numThisTime;
  15480. }
  15481. if (numSamples > 0)
  15482. {
  15483. for (int i = numDestChannels; --i >= 0;)
  15484. if (destSamples[i] != 0)
  15485. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15486. sizeof (int) * numSamples);
  15487. }
  15488. return true;
  15489. }
  15490. juce_UseDebuggingNewOperator
  15491. private:
  15492. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15493. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15494. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15495. };
  15496. class AiffAudioFormatWriter : public AudioFormatWriter
  15497. {
  15498. MemoryBlock tempBlock;
  15499. uint32 lengthInSamples, bytesWritten;
  15500. int64 headerPosition;
  15501. bool writeFailed;
  15502. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15503. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15504. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15505. void writeHeader()
  15506. {
  15507. const bool couldSeekOk = output->setPosition (headerPosition);
  15508. (void) couldSeekOk;
  15509. // if this fails, you've given it an output stream that can't seek! It needs
  15510. // to be able to seek back to write the header
  15511. jassert (couldSeekOk);
  15512. const int headerLen = 54;
  15513. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15514. audioBytes += (audioBytes & 1);
  15515. output->writeInt (chunkName ("FORM"));
  15516. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15517. output->writeInt (chunkName ("AIFF"));
  15518. output->writeInt (chunkName ("COMM"));
  15519. output->writeIntBigEndian (18);
  15520. output->writeShortBigEndian ((short) numChannels);
  15521. output->writeIntBigEndian (lengthInSamples);
  15522. output->writeShortBigEndian ((short) bitsPerSample);
  15523. uint8 sampleRateBytes[10];
  15524. zeromem (sampleRateBytes, 10);
  15525. if (sampleRate <= 1)
  15526. {
  15527. sampleRateBytes[0] = 0x3f;
  15528. sampleRateBytes[1] = 0xff;
  15529. sampleRateBytes[2] = 0x80;
  15530. }
  15531. else
  15532. {
  15533. int mask = 0x40000000;
  15534. sampleRateBytes[0] = 0x40;
  15535. if (sampleRate >= mask)
  15536. {
  15537. jassertfalse
  15538. sampleRateBytes[1] = 0x1d;
  15539. }
  15540. else
  15541. {
  15542. int n = (int) sampleRate;
  15543. int i;
  15544. for (i = 0; i <= 32 ; ++i)
  15545. {
  15546. if ((n & mask) != 0)
  15547. break;
  15548. mask >>= 1;
  15549. }
  15550. n = n << (i + 1);
  15551. sampleRateBytes[1] = (uint8) (29 - i);
  15552. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15553. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15554. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15555. sampleRateBytes[5] = (uint8) (n & 0xff);
  15556. }
  15557. }
  15558. output->write (sampleRateBytes, 10);
  15559. output->writeInt (chunkName ("SSND"));
  15560. output->writeIntBigEndian (audioBytes + 8);
  15561. output->writeInt (0);
  15562. output->writeInt (0);
  15563. jassert (output->getPosition() == headerLen);
  15564. }
  15565. public:
  15566. AiffAudioFormatWriter (OutputStream* out,
  15567. const double sampleRate_,
  15568. const unsigned int chans,
  15569. const int bits)
  15570. : AudioFormatWriter (out,
  15571. TRANS (aiffFormatName),
  15572. sampleRate_,
  15573. chans,
  15574. bits),
  15575. lengthInSamples (0),
  15576. bytesWritten (0),
  15577. writeFailed (false)
  15578. {
  15579. headerPosition = out->getPosition();
  15580. writeHeader();
  15581. }
  15582. ~AiffAudioFormatWriter()
  15583. {
  15584. if ((bytesWritten & 1) != 0)
  15585. output->writeByte (0);
  15586. writeHeader();
  15587. }
  15588. bool write (const int** data, int numSamples)
  15589. {
  15590. if (writeFailed)
  15591. return false;
  15592. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15593. tempBlock.ensureSize (bytes, false);
  15594. char* buffer = static_cast <char*> (tempBlock.getData());
  15595. const int* left = data[0];
  15596. const int* right = data[1];
  15597. if (right == 0)
  15598. right = left;
  15599. if (bitsPerSample == 16)
  15600. {
  15601. short* b = reinterpret_cast <short*> (buffer);
  15602. if (numChannels > 1)
  15603. {
  15604. for (int i = numSamples; --i >= 0;)
  15605. {
  15606. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15607. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15608. }
  15609. }
  15610. else
  15611. {
  15612. for (int i = numSamples; --i >= 0;)
  15613. {
  15614. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15615. }
  15616. }
  15617. }
  15618. else if (bitsPerSample == 24)
  15619. {
  15620. char* b = buffer;
  15621. if (numChannels > 1)
  15622. {
  15623. for (int i = numSamples; --i >= 0;)
  15624. {
  15625. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15626. b += 3;
  15627. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15628. b += 3;
  15629. }
  15630. }
  15631. else
  15632. {
  15633. for (int i = numSamples; --i >= 0;)
  15634. {
  15635. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15636. b += 3;
  15637. }
  15638. }
  15639. }
  15640. else if (bitsPerSample == 32)
  15641. {
  15642. uint32* b = reinterpret_cast <uint32*> (buffer);
  15643. if (numChannels > 1)
  15644. {
  15645. for (int i = numSamples; --i >= 0;)
  15646. {
  15647. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15648. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15649. }
  15650. }
  15651. else
  15652. {
  15653. for (int i = numSamples; --i >= 0;)
  15654. {
  15655. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15656. }
  15657. }
  15658. }
  15659. else if (bitsPerSample == 8)
  15660. {
  15661. char* b = buffer;
  15662. if (numChannels > 1)
  15663. {
  15664. for (int i = numSamples; --i >= 0;)
  15665. {
  15666. *b++ = (char) (*left++ >> 24);
  15667. *b++ = (char) (*right++ >> 24);
  15668. }
  15669. }
  15670. else
  15671. {
  15672. for (int i = numSamples; --i >= 0;)
  15673. {
  15674. *b++ = (char) (*left++ >> 24);
  15675. }
  15676. }
  15677. }
  15678. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15679. || ! output->write (buffer, bytes))
  15680. {
  15681. // failed to write to disk, so let's try writing the header.
  15682. // If it's just run out of disk space, then if it does manage
  15683. // to write the header, we'll still have a useable file..
  15684. writeHeader();
  15685. writeFailed = true;
  15686. return false;
  15687. }
  15688. else
  15689. {
  15690. bytesWritten += bytes;
  15691. lengthInSamples += numSamples;
  15692. return true;
  15693. }
  15694. }
  15695. juce_UseDebuggingNewOperator
  15696. };
  15697. AiffAudioFormat::AiffAudioFormat()
  15698. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15699. {
  15700. }
  15701. AiffAudioFormat::~AiffAudioFormat()
  15702. {
  15703. }
  15704. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15705. {
  15706. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15707. return Array <int> (rates);
  15708. }
  15709. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15710. {
  15711. const int depths[] = { 8, 16, 24, 0 };
  15712. return Array <int> (depths);
  15713. }
  15714. bool AiffAudioFormat::canDoStereo()
  15715. {
  15716. return true;
  15717. }
  15718. bool AiffAudioFormat::canDoMono()
  15719. {
  15720. return true;
  15721. }
  15722. #if JUCE_MAC
  15723. bool AiffAudioFormat::canHandleFile (const File& f)
  15724. {
  15725. if (AudioFormat::canHandleFile (f))
  15726. return true;
  15727. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15728. return type == 'AIFF' || type == 'AIFC'
  15729. || type == 'aiff' || type == 'aifc';
  15730. }
  15731. #endif
  15732. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15733. const bool deleteStreamIfOpeningFails)
  15734. {
  15735. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15736. if (w->sampleRate != 0)
  15737. return w.release();
  15738. if (! deleteStreamIfOpeningFails)
  15739. w->input = 0;
  15740. return 0;
  15741. }
  15742. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15743. double sampleRate,
  15744. unsigned int chans,
  15745. int bitsPerSample,
  15746. const StringPairArray& /*metadataValues*/,
  15747. int /*qualityOptionIndex*/)
  15748. {
  15749. if (getPossibleBitDepths().contains (bitsPerSample))
  15750. {
  15751. return new AiffAudioFormatWriter (out,
  15752. sampleRate,
  15753. chans,
  15754. bitsPerSample);
  15755. }
  15756. return 0;
  15757. }
  15758. END_JUCE_NAMESPACE
  15759. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15760. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  15761. BEGIN_JUCE_NAMESPACE
  15762. #if JUCE_MAC && JUCE_USE_CDREADER
  15763. // Mac version doesn't need any native code because it's all done with files..
  15764. // Windows + Linux versions are in the platform-dependent code sections.
  15765. static void findCDs (Array<File>& cds)
  15766. {
  15767. File volumes ("/Volumes");
  15768. volumes.findChildFiles (cds, File::findDirectories, false);
  15769. for (int i = cds.size(); --i >= 0;)
  15770. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  15771. cds.remove (i);
  15772. }
  15773. const StringArray AudioCDReader::getAvailableCDNames()
  15774. {
  15775. Array<File> cds;
  15776. findCDs (cds);
  15777. StringArray names;
  15778. for (int i = 0; i < cds.size(); ++i)
  15779. names.add (cds.getReference(i).getFileName());
  15780. return names;
  15781. }
  15782. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15783. {
  15784. Array<File> cds;
  15785. findCDs (cds);
  15786. if (cds[index] != File::nonexistent)
  15787. return new AudioCDReader (cds[index]);
  15788. else
  15789. return 0;
  15790. }
  15791. AudioCDReader::AudioCDReader (const File& volume)
  15792. : AudioFormatReader (0, "CD Audio"),
  15793. volumeDir (volume),
  15794. currentReaderTrack (-1),
  15795. reader (0)
  15796. {
  15797. sampleRate = 44100.0;
  15798. bitsPerSample = 16;
  15799. numChannels = 2;
  15800. usesFloatingPointData = false;
  15801. refreshTrackLengths();
  15802. }
  15803. AudioCDReader::~AudioCDReader()
  15804. {
  15805. }
  15806. static int getTrackNumber (const File& file)
  15807. {
  15808. return file.getFileName()
  15809. .initialSectionContainingOnly ("0123456789")
  15810. .getIntValue();
  15811. }
  15812. int AudioCDReader::compareElements (const File& first, const File& second)
  15813. {
  15814. const int firstTrack = getTrackNumber (first);
  15815. const int secondTrack = getTrackNumber (second);
  15816. jassert (firstTrack > 0 && secondTrack > 0);
  15817. return firstTrack - secondTrack;
  15818. }
  15819. void AudioCDReader::refreshTrackLengths()
  15820. {
  15821. tracks.clear();
  15822. trackStartSamples.clear();
  15823. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  15824. tracks.sort (*this);
  15825. AiffAudioFormat format;
  15826. int sample = 0;
  15827. for (int i = 0; i < tracks.size(); ++i)
  15828. {
  15829. trackStartSamples.add (sample);
  15830. FileInputStream* const in = tracks.getReference(i).createInputStream();
  15831. if (in != 0)
  15832. {
  15833. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  15834. if (r != 0)
  15835. sample += (int) r->lengthInSamples;
  15836. }
  15837. }
  15838. trackStartSamples.add (sample);
  15839. lengthInSamples = sample;
  15840. }
  15841. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15842. int64 startSampleInFile, int numSamples)
  15843. {
  15844. while (numSamples > 0)
  15845. {
  15846. int track = -1;
  15847. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15848. {
  15849. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15850. {
  15851. track = i;
  15852. break;
  15853. }
  15854. }
  15855. if (track < 0)
  15856. return false;
  15857. if (track != currentReaderTrack)
  15858. {
  15859. reader = 0;
  15860. FileInputStream* const in = tracks [track].createInputStream();
  15861. if (in != 0)
  15862. {
  15863. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15864. AiffAudioFormat format;
  15865. reader = format.createReaderFor (bin, true);
  15866. if (reader == 0)
  15867. currentReaderTrack = -1;
  15868. else
  15869. currentReaderTrack = track;
  15870. }
  15871. }
  15872. if (reader == 0)
  15873. return false;
  15874. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15875. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15876. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15877. numSamples -= numAvailable;
  15878. startSampleInFile += numAvailable;
  15879. }
  15880. return true;
  15881. }
  15882. bool AudioCDReader::isCDStillPresent() const
  15883. {
  15884. return volumeDir.exists();
  15885. }
  15886. int AudioCDReader::getNumTracks() const
  15887. {
  15888. return tracks.size();
  15889. }
  15890. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15891. {
  15892. return trackStartSamples [trackNum];
  15893. }
  15894. bool AudioCDReader::isTrackAudio (int trackNum) const
  15895. {
  15896. return tracks [trackNum] != File::nonexistent;
  15897. }
  15898. void AudioCDReader::enableIndexScanning (bool b)
  15899. {
  15900. // any way to do this on a Mac??
  15901. }
  15902. int AudioCDReader::getLastIndex() const
  15903. {
  15904. return 0;
  15905. }
  15906. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15907. {
  15908. return Array <int>();
  15909. }
  15910. int AudioCDReader::getCDDBId()
  15911. {
  15912. return 0; //xxx
  15913. }
  15914. #endif
  15915. END_JUCE_NAMESPACE
  15916. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  15917. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15918. BEGIN_JUCE_NAMESPACE
  15919. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15920. const String& formatName_)
  15921. : sampleRate (0),
  15922. bitsPerSample (0),
  15923. lengthInSamples (0),
  15924. numChannels (0),
  15925. usesFloatingPointData (false),
  15926. input (in),
  15927. formatName (formatName_)
  15928. {
  15929. }
  15930. AudioFormatReader::~AudioFormatReader()
  15931. {
  15932. delete input;
  15933. }
  15934. bool AudioFormatReader::read (int** destSamples,
  15935. int numDestChannels,
  15936. int64 startSampleInSource,
  15937. int numSamplesToRead,
  15938. const bool fillLeftoverChannelsWithCopies)
  15939. {
  15940. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15941. int startOffsetInDestBuffer = 0;
  15942. if (startSampleInSource < 0)
  15943. {
  15944. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15945. for (int i = numDestChannels; --i >= 0;)
  15946. if (destSamples[i] != 0)
  15947. zeromem (destSamples[i], sizeof (int) * silence);
  15948. startOffsetInDestBuffer += silence;
  15949. numSamplesToRead -= silence;
  15950. startSampleInSource = 0;
  15951. }
  15952. if (numSamplesToRead <= 0)
  15953. return true;
  15954. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  15955. startSampleInSource, numSamplesToRead))
  15956. return false;
  15957. if (numDestChannels > (int) numChannels)
  15958. {
  15959. if (fillLeftoverChannelsWithCopies)
  15960. {
  15961. int* lastFullChannel = destSamples[0];
  15962. for (int i = numDestChannels; --i > 0;)
  15963. {
  15964. if (destSamples[i] != 0)
  15965. {
  15966. lastFullChannel = destSamples[i];
  15967. break;
  15968. }
  15969. }
  15970. if (lastFullChannel != 0)
  15971. for (int i = numChannels; i < numDestChannels; ++i)
  15972. if (destSamples[i] != 0)
  15973. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15974. }
  15975. else
  15976. {
  15977. for (int i = numChannels; i < numDestChannels; ++i)
  15978. if (destSamples[i] != 0)
  15979. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15980. }
  15981. }
  15982. return true;
  15983. }
  15984. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  15985. {
  15986. float mn = buffer[0];
  15987. float mx = mn;
  15988. for (int i = 1; i < num; ++i)
  15989. {
  15990. const float s = buffer[i];
  15991. if (s > mx) mx = s;
  15992. if (s < mn) mn = s;
  15993. }
  15994. maxVal = mx;
  15995. minVal = mn;
  15996. }
  15997. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15998. int64 numSamples,
  15999. float& lowestLeft, float& highestLeft,
  16000. float& lowestRight, float& highestRight)
  16001. {
  16002. if (numSamples <= 0)
  16003. {
  16004. lowestLeft = 0;
  16005. lowestRight = 0;
  16006. highestLeft = 0;
  16007. highestRight = 0;
  16008. return;
  16009. }
  16010. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16011. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16012. int* tempBuffer[3];
  16013. tempBuffer[0] = (int*) tempSpace.getData();
  16014. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16015. tempBuffer[2] = 0;
  16016. if (usesFloatingPointData)
  16017. {
  16018. float lmin = 1.0e6f;
  16019. float lmax = -lmin;
  16020. float rmin = lmin;
  16021. float rmax = lmax;
  16022. while (numSamples > 0)
  16023. {
  16024. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16025. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16026. numSamples -= numToDo;
  16027. startSampleInFile += numToDo;
  16028. float bufmin, bufmax;
  16029. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16030. lmin = jmin (lmin, bufmin);
  16031. lmax = jmax (lmax, bufmax);
  16032. if (numChannels > 1)
  16033. {
  16034. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16035. rmin = jmin (rmin, bufmin);
  16036. rmax = jmax (rmax, bufmax);
  16037. }
  16038. }
  16039. if (numChannels <= 1)
  16040. {
  16041. rmax = lmax;
  16042. rmin = lmin;
  16043. }
  16044. lowestLeft = lmin;
  16045. highestLeft = lmax;
  16046. lowestRight = rmin;
  16047. highestRight = rmax;
  16048. }
  16049. else
  16050. {
  16051. int lmax = std::numeric_limits<int>::min();
  16052. int lmin = std::numeric_limits<int>::max();
  16053. int rmax = std::numeric_limits<int>::min();
  16054. int rmin = std::numeric_limits<int>::max();
  16055. while (numSamples > 0)
  16056. {
  16057. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16058. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16059. numSamples -= numToDo;
  16060. startSampleInFile += numToDo;
  16061. for (int j = numChannels; --j >= 0;)
  16062. {
  16063. int bufMax = std::numeric_limits<int>::min();
  16064. int bufMin = std::numeric_limits<int>::max();
  16065. const int* const b = tempBuffer[j];
  16066. for (int i = 0; i < numToDo; ++i)
  16067. {
  16068. const int samp = b[i];
  16069. if (samp < bufMin)
  16070. bufMin = samp;
  16071. if (samp > bufMax)
  16072. bufMax = samp;
  16073. }
  16074. if (j == 0)
  16075. {
  16076. lmax = jmax (lmax, bufMax);
  16077. lmin = jmin (lmin, bufMin);
  16078. }
  16079. else
  16080. {
  16081. rmax = jmax (rmax, bufMax);
  16082. rmin = jmin (rmin, bufMin);
  16083. }
  16084. }
  16085. }
  16086. if (numChannels <= 1)
  16087. {
  16088. rmax = lmax;
  16089. rmin = lmin;
  16090. }
  16091. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16092. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16093. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16094. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16095. }
  16096. }
  16097. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16098. int64 numSamplesToSearch,
  16099. const double magnitudeRangeMinimum,
  16100. const double magnitudeRangeMaximum,
  16101. const int minimumConsecutiveSamples)
  16102. {
  16103. if (numSamplesToSearch == 0)
  16104. return -1;
  16105. const int bufferSize = 4096;
  16106. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16107. int* tempBuffer[3];
  16108. tempBuffer[0] = (int*) tempSpace.getData();
  16109. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16110. tempBuffer[2] = 0;
  16111. int consecutive = 0;
  16112. int64 firstMatchPos = -1;
  16113. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16114. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16115. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16116. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16117. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16118. while (numSamplesToSearch != 0)
  16119. {
  16120. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16121. int64 bufferStart = startSample;
  16122. if (numSamplesToSearch < 0)
  16123. bufferStart -= numThisTime;
  16124. if (bufferStart >= (int) lengthInSamples)
  16125. break;
  16126. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16127. int num = numThisTime;
  16128. while (--num >= 0)
  16129. {
  16130. if (numSamplesToSearch < 0)
  16131. --startSample;
  16132. bool matches = false;
  16133. const int index = (int) (startSample - bufferStart);
  16134. if (usesFloatingPointData)
  16135. {
  16136. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  16137. if (sample1 >= magnitudeRangeMinimum
  16138. && sample1 <= magnitudeRangeMaximum)
  16139. {
  16140. matches = true;
  16141. }
  16142. else if (numChannels > 1)
  16143. {
  16144. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  16145. matches = (sample2 >= magnitudeRangeMinimum
  16146. && sample2 <= magnitudeRangeMaximum);
  16147. }
  16148. }
  16149. else
  16150. {
  16151. const int sample1 = abs (tempBuffer[0] [index]);
  16152. if (sample1 >= intMagnitudeRangeMinimum
  16153. && sample1 <= intMagnitudeRangeMaximum)
  16154. {
  16155. matches = true;
  16156. }
  16157. else if (numChannels > 1)
  16158. {
  16159. const int sample2 = abs (tempBuffer[1][index]);
  16160. matches = (sample2 >= intMagnitudeRangeMinimum
  16161. && sample2 <= intMagnitudeRangeMaximum);
  16162. }
  16163. }
  16164. if (matches)
  16165. {
  16166. if (firstMatchPos < 0)
  16167. firstMatchPos = startSample;
  16168. if (++consecutive >= minimumConsecutiveSamples)
  16169. {
  16170. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16171. return -1;
  16172. return firstMatchPos;
  16173. }
  16174. }
  16175. else
  16176. {
  16177. consecutive = 0;
  16178. firstMatchPos = -1;
  16179. }
  16180. if (numSamplesToSearch > 0)
  16181. ++startSample;
  16182. }
  16183. if (numSamplesToSearch > 0)
  16184. numSamplesToSearch -= numThisTime;
  16185. else
  16186. numSamplesToSearch += numThisTime;
  16187. }
  16188. return -1;
  16189. }
  16190. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16191. const String& formatName_,
  16192. const double rate,
  16193. const unsigned int numChannels_,
  16194. const unsigned int bitsPerSample_)
  16195. : sampleRate (rate),
  16196. numChannels (numChannels_),
  16197. bitsPerSample (bitsPerSample_),
  16198. usesFloatingPointData (false),
  16199. output (out),
  16200. formatName (formatName_)
  16201. {
  16202. }
  16203. AudioFormatWriter::~AudioFormatWriter()
  16204. {
  16205. delete output;
  16206. }
  16207. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16208. int64 startSample,
  16209. int64 numSamplesToRead)
  16210. {
  16211. const int bufferSize = 16384;
  16212. const int maxChans = 128;
  16213. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  16214. int* buffers [maxChans];
  16215. for (int i = maxChans; --i >= 0;)
  16216. buffers[i] = 0;
  16217. if (numSamplesToRead < 0)
  16218. numSamplesToRead = reader.lengthInSamples;
  16219. while (numSamplesToRead > 0)
  16220. {
  16221. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16222. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16223. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16224. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  16225. return false;
  16226. if (reader.usesFloatingPointData != isFloatingPoint())
  16227. {
  16228. int** bufferChan = buffers;
  16229. while (*bufferChan != 0)
  16230. {
  16231. int* b = *bufferChan++;
  16232. if (isFloatingPoint())
  16233. {
  16234. // int -> float
  16235. const double factor = 1.0 / std::numeric_limits<int>::max();
  16236. for (int i = 0; i < numToDo; ++i)
  16237. ((float*) b)[i] = (float) (factor * b[i]);
  16238. }
  16239. else
  16240. {
  16241. // float -> int
  16242. for (int i = 0; i < numToDo; ++i)
  16243. {
  16244. const double samp = *(const float*) b;
  16245. if (samp <= -1.0)
  16246. *b++ = std::numeric_limits<int>::min();
  16247. else if (samp >= 1.0)
  16248. *b++ = std::numeric_limits<int>::max();
  16249. else
  16250. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16251. }
  16252. }
  16253. }
  16254. }
  16255. if (! write ((const int**) buffers, numToDo))
  16256. return false;
  16257. numSamplesToRead -= numToDo;
  16258. startSample += numToDo;
  16259. }
  16260. return true;
  16261. }
  16262. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16263. int numSamplesToRead,
  16264. const int samplesPerBlock)
  16265. {
  16266. const int maxChans = 128;
  16267. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16268. int* buffers [maxChans];
  16269. while (numSamplesToRead > 0)
  16270. {
  16271. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16272. AudioSourceChannelInfo info;
  16273. info.buffer = &tempBuffer;
  16274. info.startSample = 0;
  16275. info.numSamples = numToDo;
  16276. info.clearActiveBufferRegion();
  16277. source.getNextAudioBlock (info);
  16278. int i;
  16279. for (i = maxChans; --i >= 0;)
  16280. buffers[i] = 0;
  16281. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  16282. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16283. if (! isFloatingPoint())
  16284. {
  16285. int** bufferChan = buffers;
  16286. while (*bufferChan != 0)
  16287. {
  16288. int* b = *bufferChan++;
  16289. // float -> int
  16290. for (int j = numToDo; --j >= 0;)
  16291. {
  16292. const double samp = *(const float*) b;
  16293. if (samp <= -1.0)
  16294. *b++ = std::numeric_limits<int>::min();
  16295. else if (samp >= 1.0)
  16296. *b++ = std::numeric_limits<int>::max();
  16297. else
  16298. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16299. }
  16300. }
  16301. }
  16302. if (! write ((const int**) buffers, numToDo))
  16303. return false;
  16304. numSamplesToRead -= numToDo;
  16305. }
  16306. return true;
  16307. }
  16308. AudioFormat::AudioFormat (const String& name,
  16309. const StringArray& extensions)
  16310. : formatName (name),
  16311. fileExtensions (extensions)
  16312. {
  16313. }
  16314. AudioFormat::~AudioFormat()
  16315. {
  16316. }
  16317. const String& AudioFormat::getFormatName() const
  16318. {
  16319. return formatName;
  16320. }
  16321. const StringArray& AudioFormat::getFileExtensions() const
  16322. {
  16323. return fileExtensions;
  16324. }
  16325. bool AudioFormat::canHandleFile (const File& f)
  16326. {
  16327. for (int i = 0; i < fileExtensions.size(); ++i)
  16328. if (f.hasFileExtension (fileExtensions[i]))
  16329. return true;
  16330. return false;
  16331. }
  16332. bool AudioFormat::isCompressed()
  16333. {
  16334. return false;
  16335. }
  16336. const StringArray AudioFormat::getQualityOptions()
  16337. {
  16338. return StringArray();
  16339. }
  16340. END_JUCE_NAMESPACE
  16341. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16342. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16343. BEGIN_JUCE_NAMESPACE
  16344. AudioFormatManager::AudioFormatManager()
  16345. : defaultFormatIndex (0)
  16346. {
  16347. }
  16348. AudioFormatManager::~AudioFormatManager()
  16349. {
  16350. clearFormats();
  16351. clearSingletonInstance();
  16352. }
  16353. juce_ImplementSingleton (AudioFormatManager);
  16354. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16355. const bool makeThisTheDefaultFormat)
  16356. {
  16357. jassert (newFormat != 0);
  16358. if (newFormat != 0)
  16359. {
  16360. #if JUCE_DEBUG
  16361. for (int i = getNumKnownFormats(); --i >= 0;)
  16362. {
  16363. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16364. {
  16365. jassertfalse // trying to add the same format twice!
  16366. }
  16367. }
  16368. #endif
  16369. if (makeThisTheDefaultFormat)
  16370. defaultFormatIndex = getNumKnownFormats();
  16371. knownFormats.add (newFormat);
  16372. }
  16373. }
  16374. void AudioFormatManager::registerBasicFormats()
  16375. {
  16376. #if JUCE_MAC
  16377. registerFormat (new AiffAudioFormat(), true);
  16378. registerFormat (new WavAudioFormat(), false);
  16379. #else
  16380. registerFormat (new WavAudioFormat(), true);
  16381. registerFormat (new AiffAudioFormat(), false);
  16382. #endif
  16383. #if JUCE_USE_FLAC
  16384. registerFormat (new FlacAudioFormat(), false);
  16385. #endif
  16386. #if JUCE_USE_OGGVORBIS
  16387. registerFormat (new OggVorbisAudioFormat(), false);
  16388. #endif
  16389. }
  16390. void AudioFormatManager::clearFormats()
  16391. {
  16392. knownFormats.clear();
  16393. defaultFormatIndex = 0;
  16394. }
  16395. int AudioFormatManager::getNumKnownFormats() const
  16396. {
  16397. return knownFormats.size();
  16398. }
  16399. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16400. {
  16401. return knownFormats [index];
  16402. }
  16403. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16404. {
  16405. return getKnownFormat (defaultFormatIndex);
  16406. }
  16407. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16408. {
  16409. String e (fileExtension);
  16410. if (! e.startsWithChar ('.'))
  16411. e = "." + e;
  16412. for (int i = 0; i < getNumKnownFormats(); ++i)
  16413. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16414. return getKnownFormat(i);
  16415. return 0;
  16416. }
  16417. const String AudioFormatManager::getWildcardForAllFormats() const
  16418. {
  16419. StringArray allExtensions;
  16420. int i;
  16421. for (i = 0; i < getNumKnownFormats(); ++i)
  16422. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16423. allExtensions.trim();
  16424. allExtensions.removeEmptyStrings();
  16425. String s;
  16426. for (i = 0; i < allExtensions.size(); ++i)
  16427. {
  16428. s << '*';
  16429. if (! allExtensions[i].startsWithChar ('.'))
  16430. s << '.';
  16431. s << allExtensions[i];
  16432. if (i < allExtensions.size() - 1)
  16433. s << ';';
  16434. }
  16435. return s;
  16436. }
  16437. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16438. {
  16439. // you need to actually register some formats before the manager can
  16440. // use them to open a file!
  16441. jassert (getNumKnownFormats() > 0);
  16442. for (int i = 0; i < getNumKnownFormats(); ++i)
  16443. {
  16444. AudioFormat* const af = getKnownFormat(i);
  16445. if (af->canHandleFile (file))
  16446. {
  16447. InputStream* const in = file.createInputStream();
  16448. if (in != 0)
  16449. {
  16450. AudioFormatReader* const r = af->createReaderFor (in, true);
  16451. if (r != 0)
  16452. return r;
  16453. }
  16454. }
  16455. }
  16456. return 0;
  16457. }
  16458. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16459. {
  16460. // you need to actually register some formats before the manager can
  16461. // use them to open a file!
  16462. jassert (getNumKnownFormats() > 0);
  16463. ScopedPointer <InputStream> in (audioFileStream);
  16464. if (in != 0)
  16465. {
  16466. const int64 originalStreamPos = in->getPosition();
  16467. for (int i = 0; i < getNumKnownFormats(); ++i)
  16468. {
  16469. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16470. if (r != 0)
  16471. {
  16472. in.release();
  16473. return r;
  16474. }
  16475. in->setPosition (originalStreamPos);
  16476. // the stream that is passed-in must be capable of being repositioned so
  16477. // that all the formats can have a go at opening it.
  16478. jassert (in->getPosition() == originalStreamPos);
  16479. }
  16480. }
  16481. return 0;
  16482. }
  16483. END_JUCE_NAMESPACE
  16484. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16485. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16486. BEGIN_JUCE_NAMESPACE
  16487. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16488. const int64 startSample_,
  16489. const int64 length_,
  16490. const bool deleteSourceWhenDeleted_)
  16491. : AudioFormatReader (0, source_->getFormatName()),
  16492. source (source_),
  16493. startSample (startSample_),
  16494. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16495. {
  16496. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16497. sampleRate = source->sampleRate;
  16498. bitsPerSample = source->bitsPerSample;
  16499. lengthInSamples = length;
  16500. numChannels = source->numChannels;
  16501. usesFloatingPointData = source->usesFloatingPointData;
  16502. }
  16503. AudioSubsectionReader::~AudioSubsectionReader()
  16504. {
  16505. if (deleteSourceWhenDeleted)
  16506. delete source;
  16507. }
  16508. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16509. int64 startSampleInFile, int numSamples)
  16510. {
  16511. if (startSampleInFile + numSamples > length)
  16512. {
  16513. for (int i = numDestChannels; --i >= 0;)
  16514. if (destSamples[i] != 0)
  16515. zeromem (destSamples[i], sizeof (int) * numSamples);
  16516. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16517. if (numSamples <= 0)
  16518. return true;
  16519. }
  16520. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16521. startSampleInFile + startSample, numSamples);
  16522. }
  16523. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16524. int64 numSamples,
  16525. float& lowestLeft,
  16526. float& highestLeft,
  16527. float& lowestRight,
  16528. float& highestRight)
  16529. {
  16530. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16531. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16532. source->readMaxLevels (startSampleInFile + startSample,
  16533. numSamples,
  16534. lowestLeft,
  16535. highestLeft,
  16536. lowestRight,
  16537. highestRight);
  16538. }
  16539. END_JUCE_NAMESPACE
  16540. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16541. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16542. BEGIN_JUCE_NAMESPACE
  16543. const int timeBeforeDeletingReader = 2000;
  16544. struct AudioThumbnailDataFormat
  16545. {
  16546. char thumbnailMagic[4];
  16547. int samplesPerThumbSample;
  16548. int64 totalSamples; // source samples
  16549. int64 numFinishedSamples; // source samples
  16550. int numThumbnailSamples;
  16551. int numChannels;
  16552. int sampleRate;
  16553. char future[16];
  16554. char data[1];
  16555. void swapEndiannessIfNeeded() throw()
  16556. {
  16557. #if JUCE_BIG_ENDIAN
  16558. flip (samplesPerThumbSample);
  16559. flip (totalSamples);
  16560. flip (numFinishedSamples);
  16561. flip (numThumbnailSamples);
  16562. flip (numChannels);
  16563. flip (sampleRate);
  16564. #endif
  16565. }
  16566. private:
  16567. #if JUCE_BIG_ENDIAN
  16568. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16569. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16570. #endif
  16571. };
  16572. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16573. AudioFormatManager& formatManagerToUse_,
  16574. AudioThumbnailCache& cacheToUse)
  16575. : formatManagerToUse (formatManagerToUse_),
  16576. cache (cacheToUse),
  16577. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16578. {
  16579. clear();
  16580. }
  16581. AudioThumbnail::~AudioThumbnail()
  16582. {
  16583. cache.removeThumbnail (this);
  16584. const ScopedLock sl (readerLock);
  16585. reader = 0;
  16586. }
  16587. void AudioThumbnail::setSource (InputSource* const newSource)
  16588. {
  16589. cache.removeThumbnail (this);
  16590. timerCallback(); // stops the timer and deletes the reader
  16591. source = newSource;
  16592. clear();
  16593. if (newSource != 0
  16594. && ! (cache.loadThumb (*this, newSource->hashCode())
  16595. && isFullyLoaded()))
  16596. {
  16597. {
  16598. const ScopedLock sl (readerLock);
  16599. reader = createReader();
  16600. }
  16601. if (reader != 0)
  16602. {
  16603. initialiseFromAudioFile (*reader);
  16604. cache.addThumbnail (this);
  16605. }
  16606. }
  16607. sendChangeMessage (this);
  16608. }
  16609. bool AudioThumbnail::useTimeSlice()
  16610. {
  16611. const ScopedLock sl (readerLock);
  16612. if (isFullyLoaded())
  16613. {
  16614. if (reader != 0)
  16615. startTimer (timeBeforeDeletingReader);
  16616. cache.removeThumbnail (this);
  16617. return false;
  16618. }
  16619. if (reader == 0)
  16620. reader = createReader();
  16621. if (reader != 0)
  16622. {
  16623. readNextBlockFromAudioFile (*reader);
  16624. stopTimer();
  16625. sendChangeMessage (this);
  16626. const bool justFinished = isFullyLoaded();
  16627. if (justFinished)
  16628. cache.storeThumb (*this, source->hashCode());
  16629. return ! justFinished;
  16630. }
  16631. return false;
  16632. }
  16633. AudioFormatReader* AudioThumbnail::createReader() const
  16634. {
  16635. if (source != 0)
  16636. {
  16637. InputStream* const audioFileStream = source->createInputStream();
  16638. if (audioFileStream != 0)
  16639. return formatManagerToUse.createReaderFor (audioFileStream);
  16640. }
  16641. return 0;
  16642. }
  16643. void AudioThumbnail::timerCallback()
  16644. {
  16645. stopTimer();
  16646. const ScopedLock sl (readerLock);
  16647. reader = 0;
  16648. }
  16649. void AudioThumbnail::clear()
  16650. {
  16651. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16652. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16653. d->thumbnailMagic[0] = 'j';
  16654. d->thumbnailMagic[1] = 'a';
  16655. d->thumbnailMagic[2] = 't';
  16656. d->thumbnailMagic[3] = 'm';
  16657. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16658. d->totalSamples = 0;
  16659. d->numFinishedSamples = 0;
  16660. d->numThumbnailSamples = 0;
  16661. d->numChannels = 0;
  16662. d->sampleRate = 0;
  16663. numSamplesCached = 0;
  16664. cacheNeedsRefilling = true;
  16665. }
  16666. void AudioThumbnail::loadFrom (InputStream& input)
  16667. {
  16668. const ScopedLock sl (readerLock);
  16669. data.setSize (0);
  16670. input.readIntoMemoryBlock (data);
  16671. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16672. d->swapEndiannessIfNeeded();
  16673. if (! (d->thumbnailMagic[0] == 'j'
  16674. && d->thumbnailMagic[1] == 'a'
  16675. && d->thumbnailMagic[2] == 't'
  16676. && d->thumbnailMagic[3] == 'm'))
  16677. {
  16678. clear();
  16679. }
  16680. numSamplesCached = 0;
  16681. cacheNeedsRefilling = true;
  16682. }
  16683. void AudioThumbnail::saveTo (OutputStream& output) const
  16684. {
  16685. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16686. d->swapEndiannessIfNeeded();
  16687. output.write (data.getData(), (int) data.getSize());
  16688. d->swapEndiannessIfNeeded();
  16689. }
  16690. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16691. {
  16692. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16693. d->totalSamples = fileReader.lengthInSamples;
  16694. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16695. d->numFinishedSamples = 0;
  16696. d->sampleRate = roundToInt (fileReader.sampleRate);
  16697. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16698. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16699. d = (AudioThumbnailDataFormat*) data.getData();
  16700. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16701. return d->totalSamples > 0;
  16702. }
  16703. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16704. {
  16705. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16706. if (d->numFinishedSamples < d->totalSamples)
  16707. {
  16708. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16709. generateSection (fileReader,
  16710. d->numFinishedSamples,
  16711. numToDo);
  16712. d->numFinishedSamples += numToDo;
  16713. }
  16714. cacheNeedsRefilling = true;
  16715. return (d->numFinishedSamples < d->totalSamples);
  16716. }
  16717. int AudioThumbnail::getNumChannels() const throw()
  16718. {
  16719. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16720. jassert (d != 0);
  16721. return d->numChannels;
  16722. }
  16723. double AudioThumbnail::getTotalLength() const throw()
  16724. {
  16725. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16726. jassert (d != 0);
  16727. if (d->sampleRate > 0)
  16728. return d->totalSamples / (double)d->sampleRate;
  16729. else
  16730. return 0.0;
  16731. }
  16732. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16733. int64 startSample,
  16734. int numSamples)
  16735. {
  16736. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16737. jassert (d != 0);
  16738. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16739. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16740. char* l = getChannelData (0);
  16741. char* r = getChannelData (1);
  16742. for (int i = firstDataPos; i < lastDataPos; ++i)
  16743. {
  16744. const int sourceStart = i * d->samplesPerThumbSample;
  16745. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16746. float lowestLeft, highestLeft, lowestRight, highestRight;
  16747. fileReader.readMaxLevels (sourceStart,
  16748. sourceEnd - sourceStart,
  16749. lowestLeft,
  16750. highestLeft,
  16751. lowestRight,
  16752. highestRight);
  16753. int n = i * 2;
  16754. if (r != 0)
  16755. {
  16756. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16757. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16758. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16759. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16760. }
  16761. else
  16762. {
  16763. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16764. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16765. }
  16766. }
  16767. }
  16768. char* AudioThumbnail::getChannelData (int channel) const
  16769. {
  16770. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16771. jassert (d != 0);
  16772. if (channel >= 0 && channel < d->numChannels)
  16773. return d->data + (channel * 2 * d->numThumbnailSamples);
  16774. return 0;
  16775. }
  16776. bool AudioThumbnail::isFullyLoaded() const throw()
  16777. {
  16778. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16779. jassert (d != 0);
  16780. return d->numFinishedSamples >= d->totalSamples;
  16781. }
  16782. void AudioThumbnail::refillCache (const int numSamples,
  16783. double startTime,
  16784. const double timePerPixel)
  16785. {
  16786. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16787. jassert (d != 0);
  16788. if (numSamples <= 0
  16789. || timePerPixel <= 0.0
  16790. || d->sampleRate <= 0)
  16791. {
  16792. numSamplesCached = 0;
  16793. cacheNeedsRefilling = true;
  16794. return;
  16795. }
  16796. if (numSamples == numSamplesCached
  16797. && numChannelsCached == d->numChannels
  16798. && startTime == cachedStart
  16799. && timePerPixel == cachedTimePerPixel
  16800. && ! cacheNeedsRefilling)
  16801. {
  16802. return;
  16803. }
  16804. numSamplesCached = numSamples;
  16805. numChannelsCached = d->numChannels;
  16806. cachedStart = startTime;
  16807. cachedTimePerPixel = timePerPixel;
  16808. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16809. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16810. const ScopedLock sl (readerLock);
  16811. cacheNeedsRefilling = false;
  16812. if (needExtraDetail && reader == 0)
  16813. reader = createReader();
  16814. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16815. {
  16816. startTimer (timeBeforeDeletingReader);
  16817. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16818. int sample = roundToInt (startTime * d->sampleRate);
  16819. for (int i = numSamples; --i >= 0;)
  16820. {
  16821. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16822. if (sample >= 0)
  16823. {
  16824. if (sample >= reader->lengthInSamples)
  16825. break;
  16826. float lmin, lmax, rmin, rmax;
  16827. reader->readMaxLevels (sample,
  16828. jmax (1, nextSample - sample),
  16829. lmin, lmax, rmin, rmax);
  16830. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16831. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16832. if (numChannelsCached > 1)
  16833. {
  16834. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16835. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16836. }
  16837. cacheData += 2 * numChannelsCached;
  16838. }
  16839. startTime += timePerPixel;
  16840. sample = nextSample;
  16841. }
  16842. }
  16843. else
  16844. {
  16845. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16846. {
  16847. char* const channelData = getChannelData (channelNum);
  16848. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16849. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16850. startTime = cachedStart;
  16851. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16852. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16853. for (int i = numSamples; --i >= 0;)
  16854. {
  16855. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16856. if (sample >= 0 && channelData != 0)
  16857. {
  16858. char mx = -128;
  16859. char mn = 127;
  16860. while (sample <= nextSample)
  16861. {
  16862. if (sample >= numFinished)
  16863. break;
  16864. const int n = sample << 1;
  16865. const char sampMin = channelData [n];
  16866. const char sampMax = channelData [n + 1];
  16867. if (sampMin < mn)
  16868. mn = sampMin;
  16869. if (sampMax > mx)
  16870. mx = sampMax;
  16871. ++sample;
  16872. }
  16873. if (mn <= mx)
  16874. {
  16875. cacheData[0] = mn;
  16876. cacheData[1] = mx;
  16877. }
  16878. else
  16879. {
  16880. cacheData[0] = 1;
  16881. cacheData[1] = 0;
  16882. }
  16883. }
  16884. else
  16885. {
  16886. cacheData[0] = 1;
  16887. cacheData[1] = 0;
  16888. }
  16889. cacheData += numChannelsCached * 2;
  16890. startTime += timePerPixel;
  16891. sample = nextSample;
  16892. }
  16893. }
  16894. }
  16895. }
  16896. void AudioThumbnail::drawChannel (Graphics& g,
  16897. int x, int y, int w, int h,
  16898. double startTime,
  16899. double endTime,
  16900. int channelNum,
  16901. const float verticalZoomFactor)
  16902. {
  16903. refillCache (w, startTime, (endTime - startTime) / w);
  16904. if (numSamplesCached >= w
  16905. && channelNum >= 0
  16906. && channelNum < numChannelsCached)
  16907. {
  16908. const float topY = (float) y;
  16909. const float bottomY = topY + h;
  16910. const float midY = topY + h * 0.5f;
  16911. const float vscale = verticalZoomFactor * h / 256.0f;
  16912. const Rectangle<int> clip (g.getClipBounds());
  16913. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16914. w -= skipLeft;
  16915. x += skipLeft;
  16916. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16917. + (channelNum << 1)
  16918. + skipLeft * (numChannelsCached << 1);
  16919. while (--w >= 0)
  16920. {
  16921. const char mn = cacheData[0];
  16922. const char mx = cacheData[1];
  16923. cacheData += numChannelsCached << 1;
  16924. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16925. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16926. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16927. ++x;
  16928. if (x >= clip.getRight())
  16929. break;
  16930. }
  16931. }
  16932. }
  16933. END_JUCE_NAMESPACE
  16934. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16935. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16936. BEGIN_JUCE_NAMESPACE
  16937. struct ThumbnailCacheEntry
  16938. {
  16939. int64 hash;
  16940. uint32 lastUsed;
  16941. MemoryBlock data;
  16942. juce_UseDebuggingNewOperator
  16943. };
  16944. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16945. : TimeSliceThread ("thumb cache"),
  16946. maxNumThumbsToStore (maxNumThumbsToStore_)
  16947. {
  16948. startThread (2);
  16949. }
  16950. AudioThumbnailCache::~AudioThumbnailCache()
  16951. {
  16952. }
  16953. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16954. {
  16955. for (int i = thumbs.size(); --i >= 0;)
  16956. {
  16957. if (thumbs[i]->hash == hashCode)
  16958. {
  16959. MemoryInputStream in (thumbs[i]->data, false);
  16960. thumb.loadFrom (in);
  16961. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16962. return true;
  16963. }
  16964. }
  16965. return false;
  16966. }
  16967. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16968. const int64 hashCode)
  16969. {
  16970. MemoryOutputStream out;
  16971. thumb.saveTo (out);
  16972. ThumbnailCacheEntry* te = 0;
  16973. for (int i = thumbs.size(); --i >= 0;)
  16974. {
  16975. if (thumbs[i]->hash == hashCode)
  16976. {
  16977. te = thumbs[i];
  16978. break;
  16979. }
  16980. }
  16981. if (te == 0)
  16982. {
  16983. te = new ThumbnailCacheEntry();
  16984. te->hash = hashCode;
  16985. if (thumbs.size() < maxNumThumbsToStore)
  16986. {
  16987. thumbs.add (te);
  16988. }
  16989. else
  16990. {
  16991. int oldest = 0;
  16992. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16993. int i;
  16994. for (i = thumbs.size(); --i >= 0;)
  16995. if (thumbs[i]->lastUsed < oldestTime)
  16996. oldest = i;
  16997. thumbs.set (i, te);
  16998. }
  16999. }
  17000. te->lastUsed = Time::getMillisecondCounter();
  17001. te->data.setSize (0);
  17002. te->data.append (out.getData(), out.getDataSize());
  17003. }
  17004. void AudioThumbnailCache::clear()
  17005. {
  17006. thumbs.clear();
  17007. }
  17008. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17009. {
  17010. addTimeSliceClient (thumb);
  17011. }
  17012. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17013. {
  17014. removeTimeSliceClient (thumb);
  17015. }
  17016. END_JUCE_NAMESPACE
  17017. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17018. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17019. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17020. #if ! JUCE_WINDOWS
  17021. #include <QuickTime/Movies.h>
  17022. #include <QuickTime/QTML.h>
  17023. #include <QuickTime/QuickTimeComponents.h>
  17024. #include <QuickTime/MediaHandlers.h>
  17025. #include <QuickTime/ImageCodec.h>
  17026. #else
  17027. #if JUCE_MSVC
  17028. #pragma warning (push)
  17029. #pragma warning (disable : 4100)
  17030. #endif
  17031. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17032. add its header directory to your include path.
  17033. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17034. flag in juce_Config.h
  17035. */
  17036. #include <Movies.h>
  17037. #include <QTML.h>
  17038. #include <QuickTimeComponents.h>
  17039. #include <MediaHandlers.h>
  17040. #include <ImageCodec.h>
  17041. #if JUCE_MSVC
  17042. #pragma warning (pop)
  17043. #endif
  17044. #endif
  17045. BEGIN_JUCE_NAMESPACE
  17046. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17047. static const char* const quickTimeFormatName = "QuickTime file";
  17048. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17049. class QTAudioReader : public AudioFormatReader
  17050. {
  17051. public:
  17052. QTAudioReader (InputStream* const input_, const int trackNum_)
  17053. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17054. ok (false),
  17055. movie (0),
  17056. trackNum (trackNum_),
  17057. lastSampleRead (0),
  17058. lastThreadId (0),
  17059. extractor (0),
  17060. dataHandle (0)
  17061. {
  17062. bufferList.calloc (256, 1);
  17063. #ifdef WIN32
  17064. if (InitializeQTML (0) != noErr)
  17065. return;
  17066. #endif
  17067. if (EnterMovies() != noErr)
  17068. return;
  17069. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17070. if (! opened)
  17071. return;
  17072. {
  17073. const int numTracks = GetMovieTrackCount (movie);
  17074. int trackCount = 0;
  17075. for (int i = 1; i <= numTracks; ++i)
  17076. {
  17077. track = GetMovieIndTrack (movie, i);
  17078. media = GetTrackMedia (track);
  17079. OSType mediaType;
  17080. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17081. if (mediaType == SoundMediaType
  17082. && trackCount++ == trackNum_)
  17083. {
  17084. ok = true;
  17085. break;
  17086. }
  17087. }
  17088. }
  17089. if (! ok)
  17090. return;
  17091. ok = false;
  17092. lengthInSamples = GetMediaDecodeDuration (media);
  17093. usesFloatingPointData = false;
  17094. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17095. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17096. / GetMediaTimeScale (media);
  17097. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17098. unsigned long output_layout_size;
  17099. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17100. kQTPropertyClass_MovieAudioExtraction_Audio,
  17101. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17102. 0, &output_layout_size, 0);
  17103. if (err != noErr)
  17104. return;
  17105. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17106. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17107. err = MovieAudioExtractionGetProperty (extractor,
  17108. kQTPropertyClass_MovieAudioExtraction_Audio,
  17109. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17110. output_layout_size, qt_audio_channel_layout, 0);
  17111. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17112. err = MovieAudioExtractionSetProperty (extractor,
  17113. kQTPropertyClass_MovieAudioExtraction_Audio,
  17114. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17115. output_layout_size,
  17116. qt_audio_channel_layout);
  17117. err = MovieAudioExtractionGetProperty (extractor,
  17118. kQTPropertyClass_MovieAudioExtraction_Audio,
  17119. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17120. sizeof (inputStreamDesc),
  17121. &inputStreamDesc, 0);
  17122. if (err != noErr)
  17123. return;
  17124. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17125. | kAudioFormatFlagIsPacked
  17126. | kAudioFormatFlagsNativeEndian;
  17127. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17128. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17129. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17130. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17131. err = MovieAudioExtractionSetProperty (extractor,
  17132. kQTPropertyClass_MovieAudioExtraction_Audio,
  17133. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17134. sizeof (inputStreamDesc),
  17135. &inputStreamDesc);
  17136. if (err != noErr)
  17137. return;
  17138. Boolean allChannelsDiscrete = false;
  17139. err = MovieAudioExtractionSetProperty (extractor,
  17140. kQTPropertyClass_MovieAudioExtraction_Movie,
  17141. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17142. sizeof (allChannelsDiscrete),
  17143. &allChannelsDiscrete);
  17144. if (err != noErr)
  17145. return;
  17146. bufferList->mNumberBuffers = 1;
  17147. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17148. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17149. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17150. bufferList->mBuffers[0].mData = dataBuffer;
  17151. sampleRate = inputStreamDesc.mSampleRate;
  17152. bitsPerSample = 16;
  17153. numChannels = inputStreamDesc.mChannelsPerFrame;
  17154. detachThread();
  17155. ok = true;
  17156. }
  17157. ~QTAudioReader()
  17158. {
  17159. if (dataHandle != 0)
  17160. DisposeHandle (dataHandle);
  17161. if (extractor != 0)
  17162. {
  17163. MovieAudioExtractionEnd (extractor);
  17164. extractor = 0;
  17165. }
  17166. checkThreadIsAttached();
  17167. DisposeMovie (movie);
  17168. #if JUCE_MAC
  17169. ExitMoviesOnThread ();
  17170. #endif
  17171. }
  17172. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17173. int64 startSampleInFile, int numSamples)
  17174. {
  17175. checkThreadIsAttached();
  17176. while (numSamples > 0)
  17177. {
  17178. if (! loadFrame ((int) startSampleInFile))
  17179. return false;
  17180. const int numToDo = jmin (numSamples, samplesPerFrame);
  17181. for (int j = numDestChannels; --j >= 0;)
  17182. {
  17183. if (destSamples[j] != 0)
  17184. {
  17185. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17186. for (int i = 0; i < numToDo; ++i)
  17187. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17188. }
  17189. }
  17190. startOffsetInDestBuffer += numToDo;
  17191. startSampleInFile += numToDo;
  17192. numSamples -= numToDo;
  17193. }
  17194. detachThread();
  17195. return true;
  17196. }
  17197. bool loadFrame (const int sampleNum)
  17198. {
  17199. if (lastSampleRead != sampleNum)
  17200. {
  17201. TimeRecord time;
  17202. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17203. time.base = 0;
  17204. time.value.hi = 0;
  17205. time.value.lo = (UInt32) sampleNum;
  17206. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17207. kQTPropertyClass_MovieAudioExtraction_Movie,
  17208. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17209. sizeof (time), &time);
  17210. if (err != noErr)
  17211. return false;
  17212. }
  17213. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17214. UInt32 outFlags = 0;
  17215. UInt32 actualNumSamples = samplesPerFrame;
  17216. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17217. bufferList, &outFlags);
  17218. lastSampleRead = sampleNum + samplesPerFrame;
  17219. return err == noErr;
  17220. }
  17221. juce_UseDebuggingNewOperator
  17222. bool ok;
  17223. private:
  17224. Movie movie;
  17225. Media media;
  17226. Track track;
  17227. const int trackNum;
  17228. double trackUnitsPerFrame;
  17229. int samplesPerFrame;
  17230. int lastSampleRead;
  17231. Thread::ThreadID lastThreadId;
  17232. MovieAudioExtractionRef extractor;
  17233. AudioStreamBasicDescription inputStreamDesc;
  17234. HeapBlock <AudioBufferList> bufferList;
  17235. HeapBlock <char> dataBuffer;
  17236. Handle dataHandle;
  17237. void checkThreadIsAttached()
  17238. {
  17239. #if JUCE_MAC
  17240. if (Thread::getCurrentThreadId() != lastThreadId)
  17241. EnterMoviesOnThread (0);
  17242. AttachMovieToCurrentThread (movie);
  17243. #endif
  17244. }
  17245. void detachThread()
  17246. {
  17247. #if JUCE_MAC
  17248. DetachMovieFromCurrentThread (movie);
  17249. #endif
  17250. }
  17251. QTAudioReader (const QTAudioReader&);
  17252. QTAudioReader& operator= (const QTAudioReader&);
  17253. };
  17254. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17255. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17256. {
  17257. }
  17258. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17259. {
  17260. }
  17261. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17262. {
  17263. return Array<int>();
  17264. }
  17265. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17266. {
  17267. return Array<int>();
  17268. }
  17269. bool QuickTimeAudioFormat::canDoStereo()
  17270. {
  17271. return true;
  17272. }
  17273. bool QuickTimeAudioFormat::canDoMono()
  17274. {
  17275. return true;
  17276. }
  17277. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17278. const bool deleteStreamIfOpeningFails)
  17279. {
  17280. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17281. if (r->ok)
  17282. return r.release();
  17283. if (! deleteStreamIfOpeningFails)
  17284. r->input = 0;
  17285. return 0;
  17286. }
  17287. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17288. double /*sampleRateToUse*/,
  17289. unsigned int /*numberOfChannels*/,
  17290. int /*bitsPerSample*/,
  17291. const StringPairArray& /*metadataValues*/,
  17292. int /*qualityOptionIndex*/)
  17293. {
  17294. jassertfalse // not yet implemented!
  17295. return 0;
  17296. }
  17297. END_JUCE_NAMESPACE
  17298. #endif
  17299. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17300. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17301. BEGIN_JUCE_NAMESPACE
  17302. static const char* const wavFormatName = "WAV file";
  17303. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17304. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17305. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17306. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17307. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17308. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17309. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17310. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17311. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17312. const String& originator,
  17313. const String& originatorRef,
  17314. const Time& date,
  17315. const int64 timeReferenceSamples,
  17316. const String& codingHistory)
  17317. {
  17318. StringPairArray m;
  17319. m.set (bwavDescription, description);
  17320. m.set (bwavOriginator, originator);
  17321. m.set (bwavOriginatorRef, originatorRef);
  17322. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17323. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17324. m.set (bwavTimeReference, String (timeReferenceSamples));
  17325. m.set (bwavCodingHistory, codingHistory);
  17326. return m;
  17327. }
  17328. #if JUCE_MSVC
  17329. #pragma pack (push, 1)
  17330. #define PACKED
  17331. #elif JUCE_GCC
  17332. #define PACKED __attribute__((packed))
  17333. #else
  17334. #define PACKED
  17335. #endif
  17336. struct BWAVChunk
  17337. {
  17338. char description [256];
  17339. char originator [32];
  17340. char originatorRef [32];
  17341. char originationDate [10];
  17342. char originationTime [8];
  17343. uint32 timeRefLow;
  17344. uint32 timeRefHigh;
  17345. uint16 version;
  17346. uint8 umid[64];
  17347. uint8 reserved[190];
  17348. char codingHistory[1];
  17349. void copyTo (StringPairArray& values) const
  17350. {
  17351. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17352. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17353. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17354. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17355. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17356. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17357. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17358. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17359. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17360. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17361. }
  17362. static MemoryBlock createFrom (const StringPairArray& values)
  17363. {
  17364. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17365. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17366. data.fillWith (0);
  17367. BWAVChunk* b = (BWAVChunk*) data.getData();
  17368. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17369. // as they get called in the right order..
  17370. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17371. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17372. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17373. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17374. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17375. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17376. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17377. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17378. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17379. if (b->description[0] != 0
  17380. || b->originator[0] != 0
  17381. || b->originationDate[0] != 0
  17382. || b->originationTime[0] != 0
  17383. || b->codingHistory[0] != 0
  17384. || time != 0)
  17385. {
  17386. return data;
  17387. }
  17388. return MemoryBlock();
  17389. }
  17390. } PACKED;
  17391. struct SMPLChunk
  17392. {
  17393. struct SampleLoop
  17394. {
  17395. uint32 identifier;
  17396. uint32 type;
  17397. uint32 start;
  17398. uint32 end;
  17399. uint32 fraction;
  17400. uint32 playCount;
  17401. } PACKED;
  17402. uint32 manufacturer;
  17403. uint32 product;
  17404. uint32 samplePeriod;
  17405. uint32 midiUnityNote;
  17406. uint32 midiPitchFraction;
  17407. uint32 smpteFormat;
  17408. uint32 smpteOffset;
  17409. uint32 numSampleLoops;
  17410. uint32 samplerData;
  17411. SampleLoop loops[1];
  17412. void copyTo (StringPairArray& values, const int totalSize) const
  17413. {
  17414. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17415. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17416. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17417. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17418. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17419. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17420. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17421. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17422. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17423. for (uint32 i = 0; i < numSampleLoops; ++i)
  17424. {
  17425. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17426. break;
  17427. const String prefix ("Loop" + String(i));
  17428. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17429. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17430. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17431. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17432. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17433. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17434. }
  17435. }
  17436. static MemoryBlock createFrom (const StringPairArray& values)
  17437. {
  17438. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17439. if (numLoops <= 0)
  17440. return MemoryBlock();
  17441. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17442. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17443. data.fillWith (0);
  17444. SMPLChunk* s = (SMPLChunk*) data.getData();
  17445. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17446. // as they get called in the right order..
  17447. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17448. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17449. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17450. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17451. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17452. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17453. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17454. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17455. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17456. for (int i = 0; i < numLoops; ++i)
  17457. {
  17458. const String prefix ("Loop" + String(i));
  17459. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17460. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17461. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17462. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17463. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17464. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17465. }
  17466. return data;
  17467. }
  17468. } PACKED;
  17469. struct ExtensibleWavSubFormat
  17470. {
  17471. uint32 data1;
  17472. uint16 data2;
  17473. uint16 data3;
  17474. uint8 data4[8];
  17475. } PACKED;
  17476. #if JUCE_MSVC
  17477. #pragma pack (pop)
  17478. #endif
  17479. #undef PACKED
  17480. class WavAudioFormatReader : public AudioFormatReader
  17481. {
  17482. int bytesPerFrame;
  17483. int64 dataChunkStart, dataLength;
  17484. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17485. WavAudioFormatReader (const WavAudioFormatReader&);
  17486. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17487. public:
  17488. int64 bwavChunkStart, bwavSize;
  17489. WavAudioFormatReader (InputStream* const in)
  17490. : AudioFormatReader (in, TRANS (wavFormatName)),
  17491. dataLength (0),
  17492. bwavChunkStart (0),
  17493. bwavSize (0)
  17494. {
  17495. if (input->readInt() == chunkName ("RIFF"))
  17496. {
  17497. const uint32 len = (uint32) input->readInt();
  17498. const int64 end = input->getPosition() + len;
  17499. bool hasGotType = false;
  17500. bool hasGotData = false;
  17501. if (input->readInt() == chunkName ("WAVE"))
  17502. {
  17503. while (input->getPosition() < end
  17504. && ! input->isExhausted())
  17505. {
  17506. const int chunkType = input->readInt();
  17507. uint32 length = (uint32) input->readInt();
  17508. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17509. if (chunkType == chunkName ("fmt "))
  17510. {
  17511. // read the format chunk
  17512. const unsigned short format = input->readShort();
  17513. const short numChans = input->readShort();
  17514. sampleRate = input->readInt();
  17515. const int bytesPerSec = input->readInt();
  17516. numChannels = numChans;
  17517. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17518. bitsPerSample = 8 * bytesPerFrame / numChans;
  17519. if (format == 3)
  17520. {
  17521. usesFloatingPointData = true;
  17522. }
  17523. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17524. {
  17525. if (length < 40) // too short
  17526. {
  17527. bytesPerFrame = 0;
  17528. }
  17529. else
  17530. {
  17531. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17532. ExtensibleWavSubFormat subFormat;
  17533. subFormat.data1 = input->readInt();
  17534. subFormat.data2 = input->readShort();
  17535. subFormat.data3 = input->readShort();
  17536. input->read (subFormat.data4, sizeof (subFormat.data4));
  17537. const ExtensibleWavSubFormat pcmFormat
  17538. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17539. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17540. {
  17541. const ExtensibleWavSubFormat ambisonicFormat
  17542. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17543. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17544. bytesPerFrame = 0;
  17545. }
  17546. }
  17547. }
  17548. else if (format != 1)
  17549. {
  17550. bytesPerFrame = 0;
  17551. }
  17552. hasGotType = true;
  17553. }
  17554. else if (chunkType == chunkName ("data"))
  17555. {
  17556. // get the data chunk's position
  17557. dataLength = length;
  17558. dataChunkStart = input->getPosition();
  17559. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17560. hasGotData = true;
  17561. }
  17562. else if (chunkType == chunkName ("bext"))
  17563. {
  17564. bwavChunkStart = input->getPosition();
  17565. bwavSize = length;
  17566. // Broadcast-wav extension chunk..
  17567. HeapBlock <BWAVChunk> bwav;
  17568. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17569. input->read (bwav, length);
  17570. bwav->copyTo (metadataValues);
  17571. }
  17572. else if (chunkType == chunkName ("smpl"))
  17573. {
  17574. HeapBlock <SMPLChunk> smpl;
  17575. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17576. input->read (smpl, length);
  17577. smpl->copyTo (metadataValues, length);
  17578. }
  17579. else if (chunkEnd <= input->getPosition())
  17580. {
  17581. break;
  17582. }
  17583. input->setPosition (chunkEnd);
  17584. }
  17585. }
  17586. }
  17587. }
  17588. ~WavAudioFormatReader()
  17589. {
  17590. }
  17591. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17592. int64 startSampleInFile, int numSamples)
  17593. {
  17594. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17595. if (samplesAvailable < numSamples)
  17596. {
  17597. for (int i = numDestChannels; --i >= 0;)
  17598. if (destSamples[i] != 0)
  17599. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17600. numSamples = (int) samplesAvailable;
  17601. }
  17602. if (numSamples <= 0)
  17603. return true;
  17604. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17605. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17606. char tempBuffer [tempBufSize];
  17607. while (numSamples > 0)
  17608. {
  17609. int* left = destSamples[0];
  17610. if (left != 0)
  17611. left += startOffsetInDestBuffer;
  17612. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17613. if (right != 0)
  17614. right += startOffsetInDestBuffer;
  17615. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17616. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17617. if (bytesRead < numThisTime * bytesPerFrame)
  17618. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17619. if (bitsPerSample == 16)
  17620. {
  17621. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17622. if (numChannels > 1)
  17623. {
  17624. if (left == 0)
  17625. {
  17626. for (int i = numThisTime; --i >= 0;)
  17627. {
  17628. ++src;
  17629. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17630. }
  17631. }
  17632. else if (right == 0)
  17633. {
  17634. for (int i = numThisTime; --i >= 0;)
  17635. {
  17636. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17637. ++src;
  17638. }
  17639. }
  17640. else
  17641. {
  17642. for (int i = numThisTime; --i >= 0;)
  17643. {
  17644. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17645. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17646. }
  17647. }
  17648. }
  17649. else
  17650. {
  17651. for (int i = numThisTime; --i >= 0;)
  17652. {
  17653. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17654. }
  17655. }
  17656. }
  17657. else if (bitsPerSample == 24)
  17658. {
  17659. const char* src = tempBuffer;
  17660. if (numChannels > 1)
  17661. {
  17662. if (left == 0)
  17663. {
  17664. for (int i = numThisTime; --i >= 0;)
  17665. {
  17666. src += 3;
  17667. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17668. src += 3;
  17669. }
  17670. }
  17671. else if (right == 0)
  17672. {
  17673. for (int i = numThisTime; --i >= 0;)
  17674. {
  17675. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17676. src += 6;
  17677. }
  17678. }
  17679. else
  17680. {
  17681. for (int i = 0; i < numThisTime; ++i)
  17682. {
  17683. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17684. src += 3;
  17685. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17686. src += 3;
  17687. }
  17688. }
  17689. }
  17690. else
  17691. {
  17692. for (int i = 0; i < numThisTime; ++i)
  17693. {
  17694. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17695. src += 3;
  17696. }
  17697. }
  17698. }
  17699. else if (bitsPerSample == 32)
  17700. {
  17701. const unsigned int* src = (const unsigned int*) tempBuffer;
  17702. unsigned int* l = (unsigned int*) left;
  17703. unsigned int* r = (unsigned int*) right;
  17704. if (numChannels > 1)
  17705. {
  17706. if (l == 0)
  17707. {
  17708. for (int i = numThisTime; --i >= 0;)
  17709. {
  17710. ++src;
  17711. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17712. }
  17713. }
  17714. else if (r == 0)
  17715. {
  17716. for (int i = numThisTime; --i >= 0;)
  17717. {
  17718. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17719. ++src;
  17720. }
  17721. }
  17722. else
  17723. {
  17724. for (int i = numThisTime; --i >= 0;)
  17725. {
  17726. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17727. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17728. }
  17729. }
  17730. }
  17731. else
  17732. {
  17733. for (int i = numThisTime; --i >= 0;)
  17734. {
  17735. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17736. }
  17737. }
  17738. left = (int*)l;
  17739. right = (int*)r;
  17740. }
  17741. else if (bitsPerSample == 8)
  17742. {
  17743. const unsigned char* src = (const unsigned char*) tempBuffer;
  17744. if (numChannels > 1)
  17745. {
  17746. if (left == 0)
  17747. {
  17748. for (int i = numThisTime; --i >= 0;)
  17749. {
  17750. ++src;
  17751. *right++ = ((int) *src++ - 128) << 24;
  17752. }
  17753. }
  17754. else if (right == 0)
  17755. {
  17756. for (int i = numThisTime; --i >= 0;)
  17757. {
  17758. *left++ = ((int) *src++ - 128) << 24;
  17759. ++src;
  17760. }
  17761. }
  17762. else
  17763. {
  17764. for (int i = numThisTime; --i >= 0;)
  17765. {
  17766. *left++ = ((int) *src++ - 128) << 24;
  17767. *right++ = ((int) *src++ - 128) << 24;
  17768. }
  17769. }
  17770. }
  17771. else
  17772. {
  17773. for (int i = numThisTime; --i >= 0;)
  17774. {
  17775. *left++ = ((int)*src++ - 128) << 24;
  17776. }
  17777. }
  17778. }
  17779. startOffsetInDestBuffer += numThisTime;
  17780. numSamples -= numThisTime;
  17781. }
  17782. if (numSamples > 0)
  17783. {
  17784. for (int i = numDestChannels; --i >= 0;)
  17785. if (destSamples[i] != 0)
  17786. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17787. sizeof (int) * numSamples);
  17788. }
  17789. return true;
  17790. }
  17791. juce_UseDebuggingNewOperator
  17792. };
  17793. class WavAudioFormatWriter : public AudioFormatWriter
  17794. {
  17795. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17796. uint32 lengthInSamples, bytesWritten;
  17797. int64 headerPosition;
  17798. bool writeFailed;
  17799. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17800. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17801. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17802. void writeHeader()
  17803. {
  17804. const bool seekedOk = output->setPosition (headerPosition);
  17805. (void) seekedOk;
  17806. // if this fails, you've given it an output stream that can't seek! It needs
  17807. // to be able to seek back to write the header
  17808. jassert (seekedOk);
  17809. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17810. output->writeInt (chunkName ("RIFF"));
  17811. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17812. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17813. output->writeInt (chunkName ("WAVE"));
  17814. output->writeInt (chunkName ("fmt "));
  17815. output->writeInt (16);
  17816. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17817. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17818. output->writeShort ((short) numChannels);
  17819. output->writeInt ((int) sampleRate);
  17820. output->writeInt (bytesPerFrame * (int) sampleRate);
  17821. output->writeShort ((short) bytesPerFrame);
  17822. output->writeShort ((short) bitsPerSample);
  17823. if (bwavChunk.getSize() > 0)
  17824. {
  17825. output->writeInt (chunkName ("bext"));
  17826. output->writeInt ((int) bwavChunk.getSize());
  17827. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17828. }
  17829. if (smplChunk.getSize() > 0)
  17830. {
  17831. output->writeInt (chunkName ("smpl"));
  17832. output->writeInt ((int) smplChunk.getSize());
  17833. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17834. }
  17835. output->writeInt (chunkName ("data"));
  17836. output->writeInt (lengthInSamples * bytesPerFrame);
  17837. usesFloatingPointData = (bitsPerSample == 32);
  17838. }
  17839. public:
  17840. WavAudioFormatWriter (OutputStream* const out,
  17841. const double sampleRate_,
  17842. const unsigned int numChannels_,
  17843. const int bits,
  17844. const StringPairArray& metadataValues)
  17845. : AudioFormatWriter (out,
  17846. TRANS (wavFormatName),
  17847. sampleRate_,
  17848. numChannels_,
  17849. bits),
  17850. lengthInSamples (0),
  17851. bytesWritten (0),
  17852. writeFailed (false)
  17853. {
  17854. if (metadataValues.size() > 0)
  17855. {
  17856. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17857. smplChunk = SMPLChunk::createFrom (metadataValues);
  17858. }
  17859. headerPosition = out->getPosition();
  17860. writeHeader();
  17861. }
  17862. ~WavAudioFormatWriter()
  17863. {
  17864. writeHeader();
  17865. }
  17866. bool write (const int** data, int numSamples)
  17867. {
  17868. if (writeFailed)
  17869. return false;
  17870. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17871. tempBlock.ensureSize (bytes, false);
  17872. char* buffer = static_cast <char*> (tempBlock.getData());
  17873. const int* left = data[0];
  17874. const int* right = data[1];
  17875. if (right == 0)
  17876. right = left;
  17877. if (bitsPerSample == 16)
  17878. {
  17879. short* b = (short*) buffer;
  17880. if (numChannels > 1)
  17881. {
  17882. for (int i = numSamples; --i >= 0;)
  17883. {
  17884. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17885. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17886. }
  17887. }
  17888. else
  17889. {
  17890. for (int i = numSamples; --i >= 0;)
  17891. {
  17892. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17893. }
  17894. }
  17895. }
  17896. else if (bitsPerSample == 24)
  17897. {
  17898. char* b = buffer;
  17899. if (numChannels > 1)
  17900. {
  17901. for (int i = numSamples; --i >= 0;)
  17902. {
  17903. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17904. b += 3;
  17905. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17906. b += 3;
  17907. }
  17908. }
  17909. else
  17910. {
  17911. for (int i = numSamples; --i >= 0;)
  17912. {
  17913. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17914. b += 3;
  17915. }
  17916. }
  17917. }
  17918. else if (bitsPerSample == 32)
  17919. {
  17920. unsigned int* b = (unsigned int*) buffer;
  17921. if (numChannels > 1)
  17922. {
  17923. for (int i = numSamples; --i >= 0;)
  17924. {
  17925. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17926. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17927. }
  17928. }
  17929. else
  17930. {
  17931. for (int i = numSamples; --i >= 0;)
  17932. {
  17933. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17934. }
  17935. }
  17936. }
  17937. else if (bitsPerSample == 8)
  17938. {
  17939. unsigned char* b = (unsigned char*) buffer;
  17940. if (numChannels > 1)
  17941. {
  17942. for (int i = numSamples; --i >= 0;)
  17943. {
  17944. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17945. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17946. }
  17947. }
  17948. else
  17949. {
  17950. for (int i = numSamples; --i >= 0;)
  17951. {
  17952. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17953. }
  17954. }
  17955. }
  17956. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17957. || ! output->write (buffer, bytes))
  17958. {
  17959. // failed to write to disk, so let's try writing the header.
  17960. // If it's just run out of disk space, then if it does manage
  17961. // to write the header, we'll still have a useable file..
  17962. writeHeader();
  17963. writeFailed = true;
  17964. return false;
  17965. }
  17966. else
  17967. {
  17968. bytesWritten += bytes;
  17969. lengthInSamples += numSamples;
  17970. return true;
  17971. }
  17972. }
  17973. juce_UseDebuggingNewOperator
  17974. };
  17975. WavAudioFormat::WavAudioFormat()
  17976. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  17977. {
  17978. }
  17979. WavAudioFormat::~WavAudioFormat()
  17980. {
  17981. }
  17982. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17983. {
  17984. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17985. return Array <int> (rates);
  17986. }
  17987. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17988. {
  17989. const int depths[] = { 8, 16, 24, 32, 0 };
  17990. return Array <int> (depths);
  17991. }
  17992. bool WavAudioFormat::canDoStereo()
  17993. {
  17994. return true;
  17995. }
  17996. bool WavAudioFormat::canDoMono()
  17997. {
  17998. return true;
  17999. }
  18000. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18001. const bool deleteStreamIfOpeningFails)
  18002. {
  18003. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18004. if (r->sampleRate != 0)
  18005. return r.release();
  18006. if (! deleteStreamIfOpeningFails)
  18007. r->input = 0;
  18008. return 0;
  18009. }
  18010. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18011. double sampleRate,
  18012. unsigned int numChannels,
  18013. int bitsPerSample,
  18014. const StringPairArray& metadataValues,
  18015. int /*qualityOptionIndex*/)
  18016. {
  18017. if (getPossibleBitDepths().contains (bitsPerSample))
  18018. {
  18019. return new WavAudioFormatWriter (out,
  18020. sampleRate,
  18021. numChannels,
  18022. bitsPerSample,
  18023. metadataValues);
  18024. }
  18025. return 0;
  18026. }
  18027. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18028. {
  18029. TemporaryFile tempFile (file);
  18030. WavAudioFormat wav;
  18031. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18032. if (reader != 0)
  18033. {
  18034. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18035. if (outStream != 0)
  18036. {
  18037. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18038. reader->numChannels, reader->bitsPerSample,
  18039. metadata, 0));
  18040. if (writer != 0)
  18041. {
  18042. outStream.release();
  18043. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18044. writer = 0;
  18045. reader = 0;
  18046. return ok && tempFile.overwriteTargetFileWithTemporary();
  18047. }
  18048. }
  18049. }
  18050. return false;
  18051. }
  18052. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18053. {
  18054. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18055. if (reader != 0)
  18056. {
  18057. const int64 bwavPos = reader->bwavChunkStart;
  18058. const int64 bwavSize = reader->bwavSize;
  18059. reader = 0;
  18060. if (bwavSize > 0)
  18061. {
  18062. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18063. if (chunk.getSize() <= (size_t) bwavSize)
  18064. {
  18065. // the new one will fit in the space available, so write it directly..
  18066. const int64 oldSize = wavFile.getSize();
  18067. {
  18068. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18069. out->setPosition (bwavPos);
  18070. out->write (chunk.getData(), (int) chunk.getSize());
  18071. out->setPosition (oldSize);
  18072. }
  18073. jassert (wavFile.getSize() == oldSize);
  18074. return true;
  18075. }
  18076. }
  18077. }
  18078. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18079. }
  18080. END_JUCE_NAMESPACE
  18081. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18082. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18083. BEGIN_JUCE_NAMESPACE
  18084. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18085. const bool deleteReaderWhenThisIsDeleted)
  18086. : reader (reader_),
  18087. deleteReader (deleteReaderWhenThisIsDeleted),
  18088. nextPlayPos (0),
  18089. looping (false)
  18090. {
  18091. jassert (reader != 0);
  18092. }
  18093. AudioFormatReaderSource::~AudioFormatReaderSource()
  18094. {
  18095. releaseResources();
  18096. if (deleteReader)
  18097. delete reader;
  18098. }
  18099. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18100. {
  18101. nextPlayPos = newPosition;
  18102. }
  18103. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18104. {
  18105. looping = shouldLoop;
  18106. }
  18107. int AudioFormatReaderSource::getNextReadPosition() const
  18108. {
  18109. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18110. : nextPlayPos;
  18111. }
  18112. int AudioFormatReaderSource::getTotalLength() const
  18113. {
  18114. return (int) reader->lengthInSamples;
  18115. }
  18116. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18117. double /*sampleRate*/)
  18118. {
  18119. }
  18120. void AudioFormatReaderSource::releaseResources()
  18121. {
  18122. }
  18123. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18124. {
  18125. if (info.numSamples > 0)
  18126. {
  18127. const int start = nextPlayPos;
  18128. if (looping)
  18129. {
  18130. const int newStart = start % (int) reader->lengthInSamples;
  18131. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18132. if (newEnd > newStart)
  18133. {
  18134. info.buffer->readFromAudioReader (reader,
  18135. info.startSample,
  18136. newEnd - newStart,
  18137. newStart,
  18138. true, true);
  18139. }
  18140. else
  18141. {
  18142. const int endSamps = (int) reader->lengthInSamples - newStart;
  18143. info.buffer->readFromAudioReader (reader,
  18144. info.startSample,
  18145. endSamps,
  18146. newStart,
  18147. true, true);
  18148. info.buffer->readFromAudioReader (reader,
  18149. info.startSample + endSamps,
  18150. newEnd,
  18151. 0,
  18152. true, true);
  18153. }
  18154. nextPlayPos = newEnd;
  18155. }
  18156. else
  18157. {
  18158. info.buffer->readFromAudioReader (reader,
  18159. info.startSample,
  18160. info.numSamples,
  18161. start,
  18162. true, true);
  18163. nextPlayPos += info.numSamples;
  18164. }
  18165. }
  18166. }
  18167. END_JUCE_NAMESPACE
  18168. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18169. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18170. BEGIN_JUCE_NAMESPACE
  18171. AudioSourcePlayer::AudioSourcePlayer()
  18172. : source (0),
  18173. sampleRate (0),
  18174. bufferSize (0),
  18175. tempBuffer (2, 8),
  18176. lastGain (1.0f),
  18177. gain (1.0f)
  18178. {
  18179. }
  18180. AudioSourcePlayer::~AudioSourcePlayer()
  18181. {
  18182. setSource (0);
  18183. }
  18184. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18185. {
  18186. if (source != newSource)
  18187. {
  18188. AudioSource* const oldSource = source;
  18189. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18190. newSource->prepareToPlay (bufferSize, sampleRate);
  18191. {
  18192. const ScopedLock sl (readLock);
  18193. source = newSource;
  18194. }
  18195. if (oldSource != 0)
  18196. oldSource->releaseResources();
  18197. }
  18198. }
  18199. void AudioSourcePlayer::setGain (const float newGain) throw()
  18200. {
  18201. gain = newGain;
  18202. }
  18203. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18204. int totalNumInputChannels,
  18205. float** outputChannelData,
  18206. int totalNumOutputChannels,
  18207. int numSamples)
  18208. {
  18209. // these should have been prepared by audioDeviceAboutToStart()...
  18210. jassert (sampleRate > 0 && bufferSize > 0);
  18211. const ScopedLock sl (readLock);
  18212. if (source != 0)
  18213. {
  18214. AudioSourceChannelInfo info;
  18215. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18216. // messy stuff needed to compact the channels down into an array
  18217. // of non-zero pointers..
  18218. for (i = 0; i < totalNumInputChannels; ++i)
  18219. {
  18220. if (inputChannelData[i] != 0)
  18221. {
  18222. inputChans [numInputs++] = inputChannelData[i];
  18223. if (numInputs >= numElementsInArray (inputChans))
  18224. break;
  18225. }
  18226. }
  18227. for (i = 0; i < totalNumOutputChannels; ++i)
  18228. {
  18229. if (outputChannelData[i] != 0)
  18230. {
  18231. outputChans [numOutputs++] = outputChannelData[i];
  18232. if (numOutputs >= numElementsInArray (outputChans))
  18233. break;
  18234. }
  18235. }
  18236. if (numInputs > numOutputs)
  18237. {
  18238. // if there aren't enough output channels for the number of
  18239. // inputs, we need to create some temporary extra ones (can't
  18240. // use the input data in case it gets written to)
  18241. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18242. false, false, true);
  18243. for (i = 0; i < numOutputs; ++i)
  18244. {
  18245. channels[numActiveChans] = outputChans[i];
  18246. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18247. ++numActiveChans;
  18248. }
  18249. for (i = numOutputs; i < numInputs; ++i)
  18250. {
  18251. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18252. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18253. ++numActiveChans;
  18254. }
  18255. }
  18256. else
  18257. {
  18258. for (i = 0; i < numInputs; ++i)
  18259. {
  18260. channels[numActiveChans] = outputChans[i];
  18261. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18262. ++numActiveChans;
  18263. }
  18264. for (i = numInputs; i < numOutputs; ++i)
  18265. {
  18266. channels[numActiveChans] = outputChans[i];
  18267. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18268. ++numActiveChans;
  18269. }
  18270. }
  18271. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18272. info.buffer = &buffer;
  18273. info.startSample = 0;
  18274. info.numSamples = numSamples;
  18275. source->getNextAudioBlock (info);
  18276. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18277. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18278. lastGain = gain;
  18279. }
  18280. else
  18281. {
  18282. for (int i = 0; i < totalNumOutputChannels; ++i)
  18283. if (outputChannelData[i] != 0)
  18284. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18285. }
  18286. }
  18287. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18288. {
  18289. sampleRate = device->getCurrentSampleRate();
  18290. bufferSize = device->getCurrentBufferSizeSamples();
  18291. zeromem (channels, sizeof (channels));
  18292. if (source != 0)
  18293. source->prepareToPlay (bufferSize, sampleRate);
  18294. }
  18295. void AudioSourcePlayer::audioDeviceStopped()
  18296. {
  18297. if (source != 0)
  18298. source->releaseResources();
  18299. sampleRate = 0.0;
  18300. bufferSize = 0;
  18301. tempBuffer.setSize (2, 8);
  18302. }
  18303. END_JUCE_NAMESPACE
  18304. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18305. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18306. BEGIN_JUCE_NAMESPACE
  18307. AudioTransportSource::AudioTransportSource()
  18308. : source (0),
  18309. resamplerSource (0),
  18310. bufferingSource (0),
  18311. positionableSource (0),
  18312. masterSource (0),
  18313. gain (1.0f),
  18314. lastGain (1.0f),
  18315. playing (false),
  18316. stopped (true),
  18317. sampleRate (44100.0),
  18318. sourceSampleRate (0.0),
  18319. blockSize (128),
  18320. readAheadBufferSize (0),
  18321. isPrepared (false),
  18322. inputStreamEOF (false)
  18323. {
  18324. }
  18325. AudioTransportSource::~AudioTransportSource()
  18326. {
  18327. setSource (0);
  18328. releaseResources();
  18329. }
  18330. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18331. int readAheadBufferSize_,
  18332. double sourceSampleRateToCorrectFor)
  18333. {
  18334. if (source == newSource)
  18335. {
  18336. if (source == 0)
  18337. return;
  18338. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18339. }
  18340. readAheadBufferSize = readAheadBufferSize_;
  18341. sourceSampleRate = sourceSampleRateToCorrectFor;
  18342. ResamplingAudioSource* newResamplerSource = 0;
  18343. BufferingAudioSource* newBufferingSource = 0;
  18344. PositionableAudioSource* newPositionableSource = 0;
  18345. AudioSource* newMasterSource = 0;
  18346. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18347. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18348. AudioSource* oldMasterSource = masterSource;
  18349. if (newSource != 0)
  18350. {
  18351. newPositionableSource = newSource;
  18352. if (readAheadBufferSize_ > 0)
  18353. newPositionableSource = newBufferingSource
  18354. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18355. newPositionableSource->setNextReadPosition (0);
  18356. if (sourceSampleRateToCorrectFor != 0)
  18357. newMasterSource = newResamplerSource
  18358. = new ResamplingAudioSource (newPositionableSource, false);
  18359. else
  18360. newMasterSource = newPositionableSource;
  18361. if (isPrepared)
  18362. {
  18363. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18364. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18365. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18366. }
  18367. }
  18368. {
  18369. const ScopedLock sl (callbackLock);
  18370. source = newSource;
  18371. resamplerSource = newResamplerSource;
  18372. bufferingSource = newBufferingSource;
  18373. masterSource = newMasterSource;
  18374. positionableSource = newPositionableSource;
  18375. playing = false;
  18376. }
  18377. if (oldMasterSource != 0)
  18378. oldMasterSource->releaseResources();
  18379. }
  18380. void AudioTransportSource::start()
  18381. {
  18382. if ((! playing) && masterSource != 0)
  18383. {
  18384. {
  18385. const ScopedLock sl (callbackLock);
  18386. playing = true;
  18387. stopped = false;
  18388. inputStreamEOF = false;
  18389. }
  18390. sendChangeMessage (this);
  18391. }
  18392. }
  18393. void AudioTransportSource::stop()
  18394. {
  18395. if (playing)
  18396. {
  18397. {
  18398. const ScopedLock sl (callbackLock);
  18399. playing = false;
  18400. }
  18401. int n = 500;
  18402. while (--n >= 0 && ! stopped)
  18403. Thread::sleep (2);
  18404. sendChangeMessage (this);
  18405. }
  18406. }
  18407. void AudioTransportSource::setPosition (double newPosition)
  18408. {
  18409. if (sampleRate > 0.0)
  18410. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18411. }
  18412. double AudioTransportSource::getCurrentPosition() const
  18413. {
  18414. if (sampleRate > 0.0)
  18415. return getNextReadPosition() / sampleRate;
  18416. else
  18417. return 0.0;
  18418. }
  18419. void AudioTransportSource::setNextReadPosition (int newPosition)
  18420. {
  18421. if (positionableSource != 0)
  18422. {
  18423. if (sampleRate > 0 && sourceSampleRate > 0)
  18424. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18425. positionableSource->setNextReadPosition (newPosition);
  18426. }
  18427. }
  18428. int AudioTransportSource::getNextReadPosition() const
  18429. {
  18430. if (positionableSource != 0)
  18431. {
  18432. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18433. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18434. }
  18435. return 0;
  18436. }
  18437. int AudioTransportSource::getTotalLength() const
  18438. {
  18439. const ScopedLock sl (callbackLock);
  18440. if (positionableSource != 0)
  18441. {
  18442. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18443. return roundToInt (positionableSource->getTotalLength() * ratio);
  18444. }
  18445. return 0;
  18446. }
  18447. bool AudioTransportSource::isLooping() const
  18448. {
  18449. const ScopedLock sl (callbackLock);
  18450. return positionableSource != 0
  18451. && positionableSource->isLooping();
  18452. }
  18453. void AudioTransportSource::setGain (const float newGain) throw()
  18454. {
  18455. gain = newGain;
  18456. }
  18457. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18458. double sampleRate_)
  18459. {
  18460. const ScopedLock sl (callbackLock);
  18461. sampleRate = sampleRate_;
  18462. blockSize = samplesPerBlockExpected;
  18463. if (masterSource != 0)
  18464. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18465. if (resamplerSource != 0 && sourceSampleRate != 0)
  18466. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18467. isPrepared = true;
  18468. }
  18469. void AudioTransportSource::releaseResources()
  18470. {
  18471. const ScopedLock sl (callbackLock);
  18472. if (masterSource != 0)
  18473. masterSource->releaseResources();
  18474. isPrepared = false;
  18475. }
  18476. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18477. {
  18478. const ScopedLock sl (callbackLock);
  18479. inputStreamEOF = false;
  18480. if (masterSource != 0 && ! stopped)
  18481. {
  18482. masterSource->getNextAudioBlock (info);
  18483. if (! playing)
  18484. {
  18485. // just stopped playing, so fade out the last block..
  18486. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18487. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18488. if (info.numSamples > 256)
  18489. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18490. }
  18491. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18492. && ! positionableSource->isLooping())
  18493. {
  18494. playing = false;
  18495. inputStreamEOF = true;
  18496. sendChangeMessage (this);
  18497. }
  18498. stopped = ! playing;
  18499. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18500. {
  18501. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18502. lastGain, gain);
  18503. }
  18504. }
  18505. else
  18506. {
  18507. info.clearActiveBufferRegion();
  18508. stopped = true;
  18509. }
  18510. lastGain = gain;
  18511. }
  18512. END_JUCE_NAMESPACE
  18513. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18514. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18515. BEGIN_JUCE_NAMESPACE
  18516. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18517. public Thread,
  18518. private Timer
  18519. {
  18520. public:
  18521. SharedBufferingAudioSourceThread()
  18522. : Thread ("Audio Buffer")
  18523. {
  18524. }
  18525. ~SharedBufferingAudioSourceThread()
  18526. {
  18527. stopThread (10000);
  18528. clearSingletonInstance();
  18529. }
  18530. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18531. void addSource (BufferingAudioSource* source)
  18532. {
  18533. const ScopedLock sl (lock);
  18534. if (! sources.contains (source))
  18535. {
  18536. sources.add (source);
  18537. startThread();
  18538. stopTimer();
  18539. }
  18540. notify();
  18541. }
  18542. void removeSource (BufferingAudioSource* source)
  18543. {
  18544. const ScopedLock sl (lock);
  18545. sources.removeValue (source);
  18546. if (sources.size() == 0)
  18547. startTimer (5000);
  18548. }
  18549. private:
  18550. Array <BufferingAudioSource*> sources;
  18551. CriticalSection lock;
  18552. void run()
  18553. {
  18554. while (! threadShouldExit())
  18555. {
  18556. bool busy = false;
  18557. for (int i = sources.size(); --i >= 0;)
  18558. {
  18559. if (threadShouldExit())
  18560. return;
  18561. const ScopedLock sl (lock);
  18562. BufferingAudioSource* const b = sources[i];
  18563. if (b != 0 && b->readNextBufferChunk())
  18564. busy = true;
  18565. }
  18566. if (! busy)
  18567. wait (500);
  18568. }
  18569. }
  18570. void timerCallback()
  18571. {
  18572. stopTimer();
  18573. if (sources.size() == 0)
  18574. deleteInstance();
  18575. }
  18576. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18577. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18578. };
  18579. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18580. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18581. const bool deleteSourceWhenDeleted_,
  18582. int numberOfSamplesToBuffer_)
  18583. : source (source_),
  18584. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18585. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18586. buffer (2, 0),
  18587. bufferValidStart (0),
  18588. bufferValidEnd (0),
  18589. nextPlayPos (0),
  18590. wasSourceLooping (false)
  18591. {
  18592. jassert (source_ != 0);
  18593. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18594. // not using a larger buffer..
  18595. }
  18596. BufferingAudioSource::~BufferingAudioSource()
  18597. {
  18598. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18599. if (thread != 0)
  18600. thread->removeSource (this);
  18601. if (deleteSourceWhenDeleted)
  18602. delete source;
  18603. }
  18604. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18605. {
  18606. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18607. sampleRate = sampleRate_;
  18608. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18609. buffer.clear();
  18610. bufferValidStart = 0;
  18611. bufferValidEnd = 0;
  18612. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18613. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18614. buffer.getNumSamples() / 2))
  18615. {
  18616. SharedBufferingAudioSourceThread::getInstance()->notify();
  18617. Thread::sleep (5);
  18618. }
  18619. }
  18620. void BufferingAudioSource::releaseResources()
  18621. {
  18622. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18623. if (thread != 0)
  18624. thread->removeSource (this);
  18625. buffer.setSize (2, 0);
  18626. source->releaseResources();
  18627. }
  18628. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18629. {
  18630. const ScopedLock sl (bufferStartPosLock);
  18631. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18632. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18633. if (validStart == validEnd)
  18634. {
  18635. // total cache miss
  18636. info.clearActiveBufferRegion();
  18637. }
  18638. else
  18639. {
  18640. if (validStart > 0)
  18641. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18642. if (validEnd < info.numSamples)
  18643. info.buffer->clear (info.startSample + validEnd,
  18644. info.numSamples - validEnd); // partial cache miss at end
  18645. if (validStart < validEnd)
  18646. {
  18647. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18648. {
  18649. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18650. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18651. if (startBufferIndex < endBufferIndex)
  18652. {
  18653. info.buffer->copyFrom (chan, info.startSample + validStart,
  18654. buffer,
  18655. chan, startBufferIndex,
  18656. validEnd - validStart);
  18657. }
  18658. else
  18659. {
  18660. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18661. info.buffer->copyFrom (chan, info.startSample + validStart,
  18662. buffer,
  18663. chan, startBufferIndex,
  18664. initialSize);
  18665. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18666. buffer,
  18667. chan, 0,
  18668. (validEnd - validStart) - initialSize);
  18669. }
  18670. }
  18671. }
  18672. nextPlayPos += info.numSamples;
  18673. if (source->isLooping() && nextPlayPos > 0)
  18674. nextPlayPos %= source->getTotalLength();
  18675. }
  18676. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18677. if (thread != 0)
  18678. thread->notify();
  18679. }
  18680. int BufferingAudioSource::getNextReadPosition() const
  18681. {
  18682. return (source->isLooping() && nextPlayPos > 0)
  18683. ? nextPlayPos % source->getTotalLength()
  18684. : nextPlayPos;
  18685. }
  18686. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18687. {
  18688. const ScopedLock sl (bufferStartPosLock);
  18689. nextPlayPos = newPosition;
  18690. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18691. if (thread != 0)
  18692. thread->notify();
  18693. }
  18694. bool BufferingAudioSource::readNextBufferChunk()
  18695. {
  18696. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18697. {
  18698. const ScopedLock sl (bufferStartPosLock);
  18699. if (wasSourceLooping != isLooping())
  18700. {
  18701. wasSourceLooping = isLooping();
  18702. bufferValidStart = 0;
  18703. bufferValidEnd = 0;
  18704. }
  18705. newBVS = jmax (0, nextPlayPos);
  18706. newBVE = newBVS + buffer.getNumSamples() - 4;
  18707. sectionToReadStart = 0;
  18708. sectionToReadEnd = 0;
  18709. const int maxChunkSize = 2048;
  18710. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18711. {
  18712. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18713. sectionToReadStart = newBVS;
  18714. sectionToReadEnd = newBVE;
  18715. bufferValidStart = 0;
  18716. bufferValidEnd = 0;
  18717. }
  18718. else if (abs (newBVS - bufferValidStart) > 512
  18719. || abs (newBVE - bufferValidEnd) > 512)
  18720. {
  18721. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18722. sectionToReadStart = bufferValidEnd;
  18723. sectionToReadEnd = newBVE;
  18724. bufferValidStart = newBVS;
  18725. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18726. }
  18727. }
  18728. if (sectionToReadStart != sectionToReadEnd)
  18729. {
  18730. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18731. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18732. if (bufferIndexStart < bufferIndexEnd)
  18733. {
  18734. readBufferSection (sectionToReadStart,
  18735. sectionToReadEnd - sectionToReadStart,
  18736. bufferIndexStart);
  18737. }
  18738. else
  18739. {
  18740. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18741. readBufferSection (sectionToReadStart,
  18742. initialSize,
  18743. bufferIndexStart);
  18744. readBufferSection (sectionToReadStart + initialSize,
  18745. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18746. 0);
  18747. }
  18748. const ScopedLock sl2 (bufferStartPosLock);
  18749. bufferValidStart = newBVS;
  18750. bufferValidEnd = newBVE;
  18751. return true;
  18752. }
  18753. else
  18754. {
  18755. return false;
  18756. }
  18757. }
  18758. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18759. {
  18760. if (source->getNextReadPosition() != start)
  18761. source->setNextReadPosition (start);
  18762. AudioSourceChannelInfo info;
  18763. info.buffer = &buffer;
  18764. info.startSample = bufferOffset;
  18765. info.numSamples = length;
  18766. source->getNextAudioBlock (info);
  18767. }
  18768. END_JUCE_NAMESPACE
  18769. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18770. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18771. BEGIN_JUCE_NAMESPACE
  18772. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18773. const bool deleteSourceWhenDeleted_)
  18774. : requiredNumberOfChannels (2),
  18775. source (source_),
  18776. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18777. buffer (2, 16)
  18778. {
  18779. remappedInfo.buffer = &buffer;
  18780. remappedInfo.startSample = 0;
  18781. }
  18782. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18783. {
  18784. if (deleteSourceWhenDeleted)
  18785. delete source;
  18786. }
  18787. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18788. {
  18789. const ScopedLock sl (lock);
  18790. requiredNumberOfChannels = requiredNumberOfChannels_;
  18791. }
  18792. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18793. {
  18794. const ScopedLock sl (lock);
  18795. remappedInputs.clear();
  18796. remappedOutputs.clear();
  18797. }
  18798. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18799. {
  18800. const ScopedLock sl (lock);
  18801. while (remappedInputs.size() < destIndex)
  18802. remappedInputs.add (-1);
  18803. remappedInputs.set (destIndex, sourceIndex);
  18804. }
  18805. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18806. {
  18807. const ScopedLock sl (lock);
  18808. while (remappedOutputs.size() < sourceIndex)
  18809. remappedOutputs.add (-1);
  18810. remappedOutputs.set (sourceIndex, destIndex);
  18811. }
  18812. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18813. {
  18814. const ScopedLock sl (lock);
  18815. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18816. return remappedInputs.getUnchecked (inputChannelIndex);
  18817. return -1;
  18818. }
  18819. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18820. {
  18821. const ScopedLock sl (lock);
  18822. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18823. return remappedOutputs .getUnchecked (outputChannelIndex);
  18824. return -1;
  18825. }
  18826. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18827. {
  18828. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18829. }
  18830. void ChannelRemappingAudioSource::releaseResources()
  18831. {
  18832. source->releaseResources();
  18833. }
  18834. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18835. {
  18836. const ScopedLock sl (lock);
  18837. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18838. const int numChans = bufferToFill.buffer->getNumChannels();
  18839. int i;
  18840. for (i = 0; i < buffer.getNumChannels(); ++i)
  18841. {
  18842. const int remappedChan = getRemappedInputChannel (i);
  18843. if (remappedChan >= 0 && remappedChan < numChans)
  18844. {
  18845. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18846. remappedChan,
  18847. bufferToFill.startSample,
  18848. bufferToFill.numSamples);
  18849. }
  18850. else
  18851. {
  18852. buffer.clear (i, 0, bufferToFill.numSamples);
  18853. }
  18854. }
  18855. remappedInfo.numSamples = bufferToFill.numSamples;
  18856. source->getNextAudioBlock (remappedInfo);
  18857. bufferToFill.clearActiveBufferRegion();
  18858. for (i = 0; i < requiredNumberOfChannels; ++i)
  18859. {
  18860. const int remappedChan = getRemappedOutputChannel (i);
  18861. if (remappedChan >= 0 && remappedChan < numChans)
  18862. {
  18863. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18864. buffer, i, 0, bufferToFill.numSamples);
  18865. }
  18866. }
  18867. }
  18868. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18869. {
  18870. XmlElement* e = new XmlElement ("MAPPINGS");
  18871. String ins, outs;
  18872. int i;
  18873. const ScopedLock sl (lock);
  18874. for (i = 0; i < remappedInputs.size(); ++i)
  18875. ins << remappedInputs.getUnchecked(i) << ' ';
  18876. for (i = 0; i < remappedOutputs.size(); ++i)
  18877. outs << remappedOutputs.getUnchecked(i) << ' ';
  18878. e->setAttribute ("inputs", ins.trimEnd());
  18879. e->setAttribute ("outputs", outs.trimEnd());
  18880. return e;
  18881. }
  18882. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18883. {
  18884. if (e.hasTagName ("MAPPINGS"))
  18885. {
  18886. const ScopedLock sl (lock);
  18887. clearAllMappings();
  18888. StringArray ins, outs;
  18889. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18890. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18891. int i;
  18892. for (i = 0; i < ins.size(); ++i)
  18893. remappedInputs.add (ins[i].getIntValue());
  18894. for (i = 0; i < outs.size(); ++i)
  18895. remappedOutputs.add (outs[i].getIntValue());
  18896. }
  18897. }
  18898. END_JUCE_NAMESPACE
  18899. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18900. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18901. BEGIN_JUCE_NAMESPACE
  18902. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18903. const bool deleteInputWhenDeleted_)
  18904. : input (inputSource),
  18905. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18906. {
  18907. jassert (inputSource != 0);
  18908. for (int i = 2; --i >= 0;)
  18909. iirFilters.add (new IIRFilter());
  18910. }
  18911. IIRFilterAudioSource::~IIRFilterAudioSource()
  18912. {
  18913. if (deleteInputWhenDeleted)
  18914. delete input;
  18915. }
  18916. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18917. {
  18918. for (int i = iirFilters.size(); --i >= 0;)
  18919. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18920. }
  18921. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18922. {
  18923. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18924. for (int i = iirFilters.size(); --i >= 0;)
  18925. iirFilters.getUnchecked(i)->reset();
  18926. }
  18927. void IIRFilterAudioSource::releaseResources()
  18928. {
  18929. input->releaseResources();
  18930. }
  18931. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18932. {
  18933. input->getNextAudioBlock (bufferToFill);
  18934. const int numChannels = bufferToFill.buffer->getNumChannels();
  18935. while (numChannels > iirFilters.size())
  18936. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18937. for (int i = 0; i < numChannels; ++i)
  18938. iirFilters.getUnchecked(i)
  18939. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18940. bufferToFill.numSamples);
  18941. }
  18942. END_JUCE_NAMESPACE
  18943. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18944. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18945. BEGIN_JUCE_NAMESPACE
  18946. MixerAudioSource::MixerAudioSource()
  18947. : tempBuffer (2, 0),
  18948. currentSampleRate (0.0),
  18949. bufferSizeExpected (0)
  18950. {
  18951. }
  18952. MixerAudioSource::~MixerAudioSource()
  18953. {
  18954. removeAllInputs();
  18955. }
  18956. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18957. {
  18958. if (input != 0 && ! inputs.contains (input))
  18959. {
  18960. double localRate;
  18961. int localBufferSize;
  18962. {
  18963. const ScopedLock sl (lock);
  18964. localRate = currentSampleRate;
  18965. localBufferSize = bufferSizeExpected;
  18966. }
  18967. if (localRate != 0.0)
  18968. input->prepareToPlay (localBufferSize, localRate);
  18969. const ScopedLock sl (lock);
  18970. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18971. inputs.add (input);
  18972. }
  18973. }
  18974. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18975. {
  18976. if (input != 0)
  18977. {
  18978. int index;
  18979. {
  18980. const ScopedLock sl (lock);
  18981. index = inputs.indexOf (input);
  18982. if (index >= 0)
  18983. {
  18984. inputsToDelete.shiftBits (index, 1);
  18985. inputs.remove (index);
  18986. }
  18987. }
  18988. if (index >= 0)
  18989. {
  18990. input->releaseResources();
  18991. if (deleteInput)
  18992. delete input;
  18993. }
  18994. }
  18995. }
  18996. void MixerAudioSource::removeAllInputs()
  18997. {
  18998. VoidArray inputsCopy;
  18999. BigInteger inputsToDeleteCopy;
  19000. {
  19001. const ScopedLock sl (lock);
  19002. inputsCopy = inputs;
  19003. inputsToDeleteCopy = inputsToDelete;
  19004. }
  19005. for (int i = inputsCopy.size(); --i >= 0;)
  19006. if (inputsToDeleteCopy[i])
  19007. delete (AudioSource*) inputsCopy[i];
  19008. }
  19009. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19010. {
  19011. tempBuffer.setSize (2, samplesPerBlockExpected);
  19012. const ScopedLock sl (lock);
  19013. currentSampleRate = sampleRate;
  19014. bufferSizeExpected = samplesPerBlockExpected;
  19015. for (int i = inputs.size(); --i >= 0;)
  19016. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  19017. sampleRate);
  19018. }
  19019. void MixerAudioSource::releaseResources()
  19020. {
  19021. const ScopedLock sl (lock);
  19022. for (int i = inputs.size(); --i >= 0;)
  19023. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  19024. tempBuffer.setSize (2, 0);
  19025. currentSampleRate = 0;
  19026. bufferSizeExpected = 0;
  19027. }
  19028. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19029. {
  19030. const ScopedLock sl (lock);
  19031. if (inputs.size() > 0)
  19032. {
  19033. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  19034. if (inputs.size() > 1)
  19035. {
  19036. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19037. info.buffer->getNumSamples());
  19038. AudioSourceChannelInfo info2;
  19039. info2.buffer = &tempBuffer;
  19040. info2.numSamples = info.numSamples;
  19041. info2.startSample = 0;
  19042. for (int i = 1; i < inputs.size(); ++i)
  19043. {
  19044. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  19045. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19046. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19047. }
  19048. }
  19049. }
  19050. else
  19051. {
  19052. info.clearActiveBufferRegion();
  19053. }
  19054. }
  19055. END_JUCE_NAMESPACE
  19056. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19057. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19058. BEGIN_JUCE_NAMESPACE
  19059. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19060. const bool deleteInputWhenDeleted_)
  19061. : input (inputSource),
  19062. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19063. ratio (1.0),
  19064. lastRatio (1.0),
  19065. buffer (2, 0),
  19066. sampsInBuffer (0)
  19067. {
  19068. jassert (input != 0);
  19069. }
  19070. ResamplingAudioSource::~ResamplingAudioSource()
  19071. {
  19072. if (deleteInputWhenDeleted)
  19073. delete input;
  19074. }
  19075. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19076. {
  19077. jassert (samplesInPerOutputSample > 0);
  19078. const ScopedLock sl (ratioLock);
  19079. ratio = jmax (0.0, samplesInPerOutputSample);
  19080. }
  19081. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19082. double sampleRate)
  19083. {
  19084. const ScopedLock sl (ratioLock);
  19085. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19086. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19087. buffer.clear();
  19088. sampsInBuffer = 0;
  19089. bufferPos = 0;
  19090. subSampleOffset = 0.0;
  19091. createLowPass (ratio);
  19092. resetFilters();
  19093. }
  19094. void ResamplingAudioSource::releaseResources()
  19095. {
  19096. input->releaseResources();
  19097. buffer.setSize (2, 0);
  19098. }
  19099. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19100. {
  19101. const ScopedLock sl (ratioLock);
  19102. if (lastRatio != ratio)
  19103. {
  19104. createLowPass (ratio);
  19105. lastRatio = ratio;
  19106. }
  19107. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19108. int bufferSize = buffer.getNumSamples();
  19109. if (bufferSize < sampsNeeded + 8)
  19110. {
  19111. bufferPos %= bufferSize;
  19112. bufferSize = sampsNeeded + 32;
  19113. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19114. }
  19115. bufferPos %= bufferSize;
  19116. int endOfBufferPos = bufferPos + sampsInBuffer;
  19117. while (sampsNeeded > sampsInBuffer)
  19118. {
  19119. endOfBufferPos %= bufferSize;
  19120. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19121. bufferSize - endOfBufferPos);
  19122. AudioSourceChannelInfo readInfo;
  19123. readInfo.buffer = &buffer;
  19124. readInfo.numSamples = numToDo;
  19125. readInfo.startSample = endOfBufferPos;
  19126. input->getNextAudioBlock (readInfo);
  19127. if (ratio > 1.0001)
  19128. {
  19129. // for down-sampling, pre-apply the filter..
  19130. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19131. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19132. }
  19133. sampsInBuffer += numToDo;
  19134. endOfBufferPos += numToDo;
  19135. }
  19136. float* dl = info.buffer->getSampleData (0, info.startSample);
  19137. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19138. const float* const bl = buffer.getSampleData (0, 0);
  19139. const float* const br = buffer.getSampleData (1, 0);
  19140. int nextPos = (bufferPos + 1) % bufferSize;
  19141. for (int m = info.numSamples; --m >= 0;)
  19142. {
  19143. const float alpha = (float) subSampleOffset;
  19144. const float invAlpha = 1.0f - alpha;
  19145. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19146. if (dr != 0)
  19147. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19148. subSampleOffset += ratio;
  19149. jassert (sampsInBuffer > 0);
  19150. while (subSampleOffset >= 1.0)
  19151. {
  19152. if (++bufferPos >= bufferSize)
  19153. bufferPos = 0;
  19154. --sampsInBuffer;
  19155. nextPos = (bufferPos + 1) % bufferSize;
  19156. subSampleOffset -= 1.0;
  19157. }
  19158. }
  19159. if (ratio < 0.9999)
  19160. {
  19161. // for up-sampling, apply the filter after transposing..
  19162. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19163. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19164. }
  19165. else if (ratio <= 1.0001)
  19166. {
  19167. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19168. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19169. {
  19170. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19171. FilterState& fs = filterStates[i];
  19172. if (info.numSamples > 1)
  19173. {
  19174. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19175. }
  19176. else
  19177. {
  19178. fs.y2 = fs.y1;
  19179. fs.x2 = fs.x1;
  19180. }
  19181. fs.y1 = fs.x1 = *endOfBuffer;
  19182. }
  19183. }
  19184. jassert (sampsInBuffer >= 0);
  19185. }
  19186. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19187. {
  19188. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19189. : 0.5 * frequencyRatio;
  19190. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19191. const double nSquared = n * n;
  19192. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  19193. setFilterCoefficients (c1,
  19194. c1 * 2.0f,
  19195. c1,
  19196. 1.0,
  19197. c1 * 2.0 * (1.0 - nSquared),
  19198. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  19199. }
  19200. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19201. {
  19202. const double a = 1.0 / c4;
  19203. c1 *= a;
  19204. c2 *= a;
  19205. c3 *= a;
  19206. c5 *= a;
  19207. c6 *= a;
  19208. coefficients[0] = c1;
  19209. coefficients[1] = c2;
  19210. coefficients[2] = c3;
  19211. coefficients[3] = c4;
  19212. coefficients[4] = c5;
  19213. coefficients[5] = c6;
  19214. }
  19215. void ResamplingAudioSource::resetFilters()
  19216. {
  19217. zeromem (filterStates, sizeof (filterStates));
  19218. }
  19219. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19220. {
  19221. while (--num >= 0)
  19222. {
  19223. const double in = *samples;
  19224. double out = coefficients[0] * in
  19225. + coefficients[1] * fs.x1
  19226. + coefficients[2] * fs.x2
  19227. - coefficients[4] * fs.y1
  19228. - coefficients[5] * fs.y2;
  19229. #if JUCE_INTEL
  19230. if (! (out < -1.0e-8 || out > 1.0e-8))
  19231. out = 0;
  19232. #endif
  19233. fs.x2 = fs.x1;
  19234. fs.x1 = in;
  19235. fs.y2 = fs.y1;
  19236. fs.y1 = out;
  19237. *samples++ = (float) out;
  19238. }
  19239. }
  19240. END_JUCE_NAMESPACE
  19241. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19242. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19243. BEGIN_JUCE_NAMESPACE
  19244. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19245. : frequency (1000.0),
  19246. sampleRate (44100.0),
  19247. currentPhase (0.0),
  19248. phasePerSample (0.0),
  19249. amplitude (0.5f)
  19250. {
  19251. }
  19252. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19253. {
  19254. }
  19255. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19256. {
  19257. amplitude = newAmplitude;
  19258. }
  19259. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19260. {
  19261. frequency = newFrequencyHz;
  19262. phasePerSample = 0.0;
  19263. }
  19264. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19265. double sampleRate_)
  19266. {
  19267. currentPhase = 0.0;
  19268. phasePerSample = 0.0;
  19269. sampleRate = sampleRate_;
  19270. }
  19271. void ToneGeneratorAudioSource::releaseResources()
  19272. {
  19273. }
  19274. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19275. {
  19276. if (phasePerSample == 0.0)
  19277. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19278. for (int i = 0; i < info.numSamples; ++i)
  19279. {
  19280. const float sample = amplitude * (float) sin (currentPhase);
  19281. currentPhase += phasePerSample;
  19282. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19283. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19284. }
  19285. }
  19286. END_JUCE_NAMESPACE
  19287. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19288. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19289. BEGIN_JUCE_NAMESPACE
  19290. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19291. : sampleRate (0),
  19292. bufferSize (0),
  19293. useDefaultInputChannels (true),
  19294. useDefaultOutputChannels (true)
  19295. {
  19296. }
  19297. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19298. {
  19299. return outputDeviceName == other.outputDeviceName
  19300. && inputDeviceName == other.inputDeviceName
  19301. && sampleRate == other.sampleRate
  19302. && bufferSize == other.bufferSize
  19303. && inputChannels == other.inputChannels
  19304. && useDefaultInputChannels == other.useDefaultInputChannels
  19305. && outputChannels == other.outputChannels
  19306. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19307. }
  19308. AudioDeviceManager::AudioDeviceManager()
  19309. : currentAudioDevice (0),
  19310. numInputChansNeeded (0),
  19311. numOutputChansNeeded (2),
  19312. listNeedsScanning (true),
  19313. useInputNames (false),
  19314. inputLevelMeasurementEnabledCount (0),
  19315. inputLevel (0),
  19316. tempBuffer (2, 2),
  19317. defaultMidiOutput (0),
  19318. cpuUsageMs (0),
  19319. timeToCpuScale (0)
  19320. {
  19321. callbackHandler.owner = this;
  19322. }
  19323. AudioDeviceManager::~AudioDeviceManager()
  19324. {
  19325. currentAudioDevice = 0;
  19326. defaultMidiOutput = 0;
  19327. }
  19328. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19329. {
  19330. if (availableDeviceTypes.size() == 0)
  19331. {
  19332. createAudioDeviceTypes (availableDeviceTypes);
  19333. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19334. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19335. if (availableDeviceTypes.size() > 0)
  19336. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19337. }
  19338. }
  19339. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19340. {
  19341. scanDevicesIfNeeded();
  19342. return availableDeviceTypes;
  19343. }
  19344. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19345. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19346. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19347. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19348. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19349. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19350. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19351. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19352. {
  19353. (void) list; // (to avoid 'unused param' warnings)
  19354. #if JUCE_WINDOWS
  19355. #if JUCE_WASAPI
  19356. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19357. list.add (juce_createAudioIODeviceType_WASAPI());
  19358. #endif
  19359. #if JUCE_DIRECTSOUND
  19360. list.add (juce_createAudioIODeviceType_DirectSound());
  19361. #endif
  19362. #if JUCE_ASIO
  19363. list.add (juce_createAudioIODeviceType_ASIO());
  19364. #endif
  19365. #endif
  19366. #if JUCE_MAC
  19367. list.add (juce_createAudioIODeviceType_CoreAudio());
  19368. #endif
  19369. #if JUCE_IPHONE
  19370. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19371. #endif
  19372. #if JUCE_LINUX && JUCE_ALSA
  19373. list.add (juce_createAudioIODeviceType_ALSA());
  19374. #endif
  19375. #if JUCE_LINUX && JUCE_JACK
  19376. list.add (juce_createAudioIODeviceType_JACK());
  19377. #endif
  19378. }
  19379. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19380. const int numOutputChannelsNeeded,
  19381. const XmlElement* const e,
  19382. const bool selectDefaultDeviceOnFailure,
  19383. const String& preferredDefaultDeviceName,
  19384. const AudioDeviceSetup* preferredSetupOptions)
  19385. {
  19386. scanDevicesIfNeeded();
  19387. numInputChansNeeded = numInputChannelsNeeded;
  19388. numOutputChansNeeded = numOutputChannelsNeeded;
  19389. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19390. {
  19391. lastExplicitSettings = new XmlElement (*e);
  19392. String error;
  19393. AudioDeviceSetup setup;
  19394. if (preferredSetupOptions != 0)
  19395. setup = *preferredSetupOptions;
  19396. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19397. {
  19398. setup.inputDeviceName = setup.outputDeviceName
  19399. = e->getStringAttribute ("audioDeviceName");
  19400. }
  19401. else
  19402. {
  19403. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19404. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19405. }
  19406. currentDeviceType = e->getStringAttribute ("deviceType");
  19407. if (currentDeviceType.isEmpty())
  19408. {
  19409. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19410. if (type != 0)
  19411. currentDeviceType = type->getTypeName();
  19412. else if (availableDeviceTypes.size() > 0)
  19413. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19414. }
  19415. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19416. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19417. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19418. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19419. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19420. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19421. error = setAudioDeviceSetup (setup, true);
  19422. midiInsFromXml.clear();
  19423. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19424. midiInsFromXml.add (c->getStringAttribute ("name"));
  19425. const StringArray allMidiIns (MidiInput::getDevices());
  19426. for (int i = allMidiIns.size(); --i >= 0;)
  19427. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19428. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19429. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19430. false, preferredDefaultDeviceName);
  19431. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19432. return error;
  19433. }
  19434. else
  19435. {
  19436. AudioDeviceSetup setup;
  19437. if (preferredSetupOptions != 0)
  19438. {
  19439. setup = *preferredSetupOptions;
  19440. }
  19441. else if (preferredDefaultDeviceName.isNotEmpty())
  19442. {
  19443. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19444. {
  19445. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19446. StringArray outs (type->getDeviceNames (false));
  19447. int i;
  19448. for (i = 0; i < outs.size(); ++i)
  19449. {
  19450. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19451. {
  19452. setup.outputDeviceName = outs[i];
  19453. break;
  19454. }
  19455. }
  19456. StringArray ins (type->getDeviceNames (true));
  19457. for (i = 0; i < ins.size(); ++i)
  19458. {
  19459. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19460. {
  19461. setup.inputDeviceName = ins[i];
  19462. break;
  19463. }
  19464. }
  19465. }
  19466. }
  19467. insertDefaultDeviceNames (setup);
  19468. return setAudioDeviceSetup (setup, false);
  19469. }
  19470. }
  19471. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19472. {
  19473. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19474. if (type != 0)
  19475. {
  19476. if (setup.outputDeviceName.isEmpty())
  19477. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19478. if (setup.inputDeviceName.isEmpty())
  19479. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19480. }
  19481. }
  19482. XmlElement* AudioDeviceManager::createStateXml() const
  19483. {
  19484. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19485. }
  19486. void AudioDeviceManager::scanDevicesIfNeeded()
  19487. {
  19488. if (listNeedsScanning)
  19489. {
  19490. listNeedsScanning = false;
  19491. createDeviceTypesIfNeeded();
  19492. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19493. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19494. }
  19495. }
  19496. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19497. {
  19498. scanDevicesIfNeeded();
  19499. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19500. {
  19501. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19502. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19503. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19504. {
  19505. return type;
  19506. }
  19507. }
  19508. return 0;
  19509. }
  19510. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19511. {
  19512. setup = currentSetup;
  19513. }
  19514. void AudioDeviceManager::deleteCurrentDevice()
  19515. {
  19516. currentAudioDevice = 0;
  19517. currentSetup.inputDeviceName = String::empty;
  19518. currentSetup.outputDeviceName = String::empty;
  19519. }
  19520. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19521. const bool treatAsChosenDevice)
  19522. {
  19523. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19524. {
  19525. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19526. && currentDeviceType != type)
  19527. {
  19528. currentDeviceType = type;
  19529. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19530. insertDefaultDeviceNames (s);
  19531. setAudioDeviceSetup (s, treatAsChosenDevice);
  19532. sendChangeMessage (this);
  19533. break;
  19534. }
  19535. }
  19536. }
  19537. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19538. {
  19539. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19540. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19541. return availableDeviceTypes[i];
  19542. return availableDeviceTypes[0];
  19543. }
  19544. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19545. const bool treatAsChosenDevice)
  19546. {
  19547. jassert (&newSetup != &currentSetup); // this will have no effect
  19548. if (newSetup == currentSetup && currentAudioDevice != 0)
  19549. return String::empty;
  19550. if (! (newSetup == currentSetup))
  19551. sendChangeMessage (this);
  19552. stopDevice();
  19553. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19554. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19555. String error;
  19556. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19557. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19558. {
  19559. deleteCurrentDevice();
  19560. if (treatAsChosenDevice)
  19561. updateXml();
  19562. return String::empty;
  19563. }
  19564. if (currentSetup.inputDeviceName != newInputDeviceName
  19565. || currentSetup.outputDeviceName != newOutputDeviceName
  19566. || currentAudioDevice == 0)
  19567. {
  19568. deleteCurrentDevice();
  19569. scanDevicesIfNeeded();
  19570. if (newOutputDeviceName.isNotEmpty()
  19571. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19572. {
  19573. return "No such device: " + newOutputDeviceName;
  19574. }
  19575. if (newInputDeviceName.isNotEmpty()
  19576. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19577. {
  19578. return "No such device: " + newInputDeviceName;
  19579. }
  19580. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19581. if (currentAudioDevice == 0)
  19582. 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!";
  19583. else
  19584. error = currentAudioDevice->getLastError();
  19585. if (error.isNotEmpty())
  19586. {
  19587. deleteCurrentDevice();
  19588. return error;
  19589. }
  19590. if (newSetup.useDefaultInputChannels)
  19591. {
  19592. inputChannels.clear();
  19593. inputChannels.setRange (0, numInputChansNeeded, true);
  19594. }
  19595. if (newSetup.useDefaultOutputChannels)
  19596. {
  19597. outputChannels.clear();
  19598. outputChannels.setRange (0, numOutputChansNeeded, true);
  19599. }
  19600. if (newInputDeviceName.isEmpty())
  19601. inputChannels.clear();
  19602. if (newOutputDeviceName.isEmpty())
  19603. outputChannels.clear();
  19604. }
  19605. if (! newSetup.useDefaultInputChannels)
  19606. inputChannels = newSetup.inputChannels;
  19607. if (! newSetup.useDefaultOutputChannels)
  19608. outputChannels = newSetup.outputChannels;
  19609. currentSetup = newSetup;
  19610. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19611. error = currentAudioDevice->open (inputChannels,
  19612. outputChannels,
  19613. currentSetup.sampleRate,
  19614. currentSetup.bufferSize);
  19615. if (error.isEmpty())
  19616. {
  19617. currentDeviceType = currentAudioDevice->getTypeName();
  19618. currentAudioDevice->start (&callbackHandler);
  19619. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19620. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19621. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19622. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19623. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19624. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19625. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19626. if (treatAsChosenDevice)
  19627. updateXml();
  19628. }
  19629. else
  19630. {
  19631. deleteCurrentDevice();
  19632. }
  19633. return error;
  19634. }
  19635. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19636. {
  19637. jassert (currentAudioDevice != 0);
  19638. if (rate > 0)
  19639. {
  19640. bool ok = false;
  19641. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19642. {
  19643. const double sr = currentAudioDevice->getSampleRate (i);
  19644. if (sr == rate)
  19645. ok = true;
  19646. }
  19647. if (! ok)
  19648. rate = 0;
  19649. }
  19650. if (rate == 0)
  19651. {
  19652. double lowestAbove44 = 0.0;
  19653. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19654. {
  19655. const double sr = currentAudioDevice->getSampleRate (i);
  19656. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19657. lowestAbove44 = sr;
  19658. }
  19659. if (lowestAbove44 == 0.0)
  19660. rate = currentAudioDevice->getSampleRate (0);
  19661. else
  19662. rate = lowestAbove44;
  19663. }
  19664. return rate;
  19665. }
  19666. void AudioDeviceManager::stopDevice()
  19667. {
  19668. if (currentAudioDevice != 0)
  19669. currentAudioDevice->stop();
  19670. testSound = 0;
  19671. }
  19672. void AudioDeviceManager::closeAudioDevice()
  19673. {
  19674. stopDevice();
  19675. currentAudioDevice = 0;
  19676. }
  19677. void AudioDeviceManager::restartLastAudioDevice()
  19678. {
  19679. if (currentAudioDevice == 0)
  19680. {
  19681. if (currentSetup.inputDeviceName.isEmpty()
  19682. && currentSetup.outputDeviceName.isEmpty())
  19683. {
  19684. // This method will only reload the last device that was running
  19685. // before closeAudioDevice() was called - you need to actually open
  19686. // one first, with setAudioDevice().
  19687. jassertfalse
  19688. return;
  19689. }
  19690. AudioDeviceSetup s (currentSetup);
  19691. setAudioDeviceSetup (s, false);
  19692. }
  19693. }
  19694. void AudioDeviceManager::updateXml()
  19695. {
  19696. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19697. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19698. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19699. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19700. if (currentAudioDevice != 0)
  19701. {
  19702. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19703. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19704. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19705. if (! currentSetup.useDefaultInputChannels)
  19706. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19707. if (! currentSetup.useDefaultOutputChannels)
  19708. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19709. }
  19710. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19711. {
  19712. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19713. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19714. }
  19715. if (midiInsFromXml.size() > 0)
  19716. {
  19717. // Add any midi devices that have been enabled before, but which aren't currently
  19718. // open because the device has been disconnected.
  19719. const StringArray availableMidiDevices (MidiInput::getDevices());
  19720. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19721. {
  19722. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19723. {
  19724. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19725. m->setAttribute ("name", midiInsFromXml[i]);
  19726. }
  19727. }
  19728. }
  19729. if (defaultMidiOutputName.isNotEmpty())
  19730. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19731. }
  19732. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19733. {
  19734. {
  19735. const ScopedLock sl (audioCallbackLock);
  19736. if (callbacks.contains (newCallback))
  19737. return;
  19738. }
  19739. if (currentAudioDevice != 0 && newCallback != 0)
  19740. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19741. const ScopedLock sl (audioCallbackLock);
  19742. callbacks.add (newCallback);
  19743. }
  19744. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19745. {
  19746. if (callback != 0)
  19747. {
  19748. bool needsDeinitialising = currentAudioDevice != 0;
  19749. {
  19750. const ScopedLock sl (audioCallbackLock);
  19751. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19752. callbacks.removeValue (callback);
  19753. }
  19754. if (needsDeinitialising)
  19755. callback->audioDeviceStopped();
  19756. }
  19757. }
  19758. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19759. int numInputChannels,
  19760. float** outputChannelData,
  19761. int numOutputChannels,
  19762. int numSamples)
  19763. {
  19764. const ScopedLock sl (audioCallbackLock);
  19765. if (inputLevelMeasurementEnabledCount > 0)
  19766. {
  19767. for (int j = 0; j < numSamples; ++j)
  19768. {
  19769. float s = 0;
  19770. for (int i = 0; i < numInputChannels; ++i)
  19771. s += fabsf (inputChannelData[i][j]);
  19772. s /= numInputChannels;
  19773. const double decayFactor = 0.99992;
  19774. if (s > inputLevel)
  19775. inputLevel = s;
  19776. else if (inputLevel > 0.001f)
  19777. inputLevel *= decayFactor;
  19778. else
  19779. inputLevel = 0;
  19780. }
  19781. }
  19782. if (callbacks.size() > 0)
  19783. {
  19784. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19785. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19786. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19787. outputChannelData, numOutputChannels, numSamples);
  19788. float** const tempChans = tempBuffer.getArrayOfChannels();
  19789. for (int i = callbacks.size(); --i > 0;)
  19790. {
  19791. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19792. tempChans, numOutputChannels, numSamples);
  19793. for (int chan = 0; chan < numOutputChannels; ++chan)
  19794. {
  19795. const float* const src = tempChans [chan];
  19796. float* const dst = outputChannelData [chan];
  19797. if (src != 0 && dst != 0)
  19798. for (int j = 0; j < numSamples; ++j)
  19799. dst[j] += src[j];
  19800. }
  19801. }
  19802. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19803. const double filterAmount = 0.2;
  19804. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19805. }
  19806. else
  19807. {
  19808. for (int i = 0; i < numOutputChannels; ++i)
  19809. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19810. }
  19811. if (testSound != 0)
  19812. {
  19813. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19814. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19815. for (int i = 0; i < numOutputChannels; ++i)
  19816. for (int j = 0; j < numSamps; ++j)
  19817. outputChannelData [i][j] += src[j];
  19818. testSoundPosition += numSamps;
  19819. if (testSoundPosition >= testSound->getNumSamples())
  19820. testSound = 0;
  19821. }
  19822. }
  19823. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19824. {
  19825. cpuUsageMs = 0;
  19826. const double sampleRate = device->getCurrentSampleRate();
  19827. const int blockSize = device->getCurrentBufferSizeSamples();
  19828. if (sampleRate > 0.0 && blockSize > 0)
  19829. {
  19830. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19831. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19832. }
  19833. {
  19834. const ScopedLock sl (audioCallbackLock);
  19835. for (int i = callbacks.size(); --i >= 0;)
  19836. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19837. }
  19838. sendChangeMessage (this);
  19839. }
  19840. void AudioDeviceManager::audioDeviceStoppedInt()
  19841. {
  19842. cpuUsageMs = 0;
  19843. timeToCpuScale = 0;
  19844. sendChangeMessage (this);
  19845. const ScopedLock sl (audioCallbackLock);
  19846. for (int i = callbacks.size(); --i >= 0;)
  19847. callbacks.getUnchecked(i)->audioDeviceStopped();
  19848. }
  19849. double AudioDeviceManager::getCpuUsage() const
  19850. {
  19851. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19852. }
  19853. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19854. const bool enabled)
  19855. {
  19856. if (enabled != isMidiInputEnabled (name))
  19857. {
  19858. if (enabled)
  19859. {
  19860. const int index = MidiInput::getDevices().indexOf (name);
  19861. if (index >= 0)
  19862. {
  19863. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19864. if (min != 0)
  19865. {
  19866. enabledMidiInputs.add (min);
  19867. min->start();
  19868. }
  19869. }
  19870. }
  19871. else
  19872. {
  19873. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19874. if (enabledMidiInputs[i]->getName() == name)
  19875. enabledMidiInputs.remove (i);
  19876. }
  19877. updateXml();
  19878. sendChangeMessage (this);
  19879. }
  19880. }
  19881. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19882. {
  19883. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19884. if (enabledMidiInputs[i]->getName() == name)
  19885. return true;
  19886. return false;
  19887. }
  19888. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19889. MidiInputCallback* callback)
  19890. {
  19891. removeMidiInputCallback (name, callback);
  19892. if (name.isEmpty())
  19893. {
  19894. midiCallbacks.add (callback);
  19895. midiCallbackDevices.add (0);
  19896. }
  19897. else
  19898. {
  19899. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19900. {
  19901. if (enabledMidiInputs[i]->getName() == name)
  19902. {
  19903. const ScopedLock sl (midiCallbackLock);
  19904. midiCallbacks.add (callback);
  19905. midiCallbackDevices.add (enabledMidiInputs[i]);
  19906. break;
  19907. }
  19908. }
  19909. }
  19910. }
  19911. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19912. MidiInputCallback* /*callback*/)
  19913. {
  19914. const ScopedLock sl (midiCallbackLock);
  19915. for (int i = midiCallbacks.size(); --i >= 0;)
  19916. {
  19917. String devName;
  19918. if (midiCallbackDevices.getUnchecked(i) != 0)
  19919. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19920. if (devName == name)
  19921. {
  19922. midiCallbacks.remove (i);
  19923. midiCallbackDevices.remove (i);
  19924. }
  19925. }
  19926. }
  19927. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19928. const MidiMessage& message)
  19929. {
  19930. if (! message.isActiveSense())
  19931. {
  19932. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19933. const ScopedLock sl (midiCallbackLock);
  19934. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19935. {
  19936. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19937. if (md == source || (md == 0 && isDefaultSource))
  19938. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19939. }
  19940. }
  19941. }
  19942. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19943. {
  19944. if (defaultMidiOutputName != deviceName)
  19945. {
  19946. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19947. {
  19948. const ScopedLock sl (audioCallbackLock);
  19949. oldCallbacks = callbacks;
  19950. callbacks.clear();
  19951. }
  19952. if (currentAudioDevice != 0)
  19953. for (int i = oldCallbacks.size(); --i >= 0;)
  19954. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19955. defaultMidiOutput = 0;
  19956. defaultMidiOutputName = deviceName;
  19957. if (deviceName.isNotEmpty())
  19958. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19959. if (currentAudioDevice != 0)
  19960. for (int i = oldCallbacks.size(); --i >= 0;)
  19961. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19962. {
  19963. const ScopedLock sl (audioCallbackLock);
  19964. callbacks = oldCallbacks;
  19965. }
  19966. updateXml();
  19967. sendChangeMessage (this);
  19968. }
  19969. }
  19970. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19971. int numInputChannels,
  19972. float** outputChannelData,
  19973. int numOutputChannels,
  19974. int numSamples)
  19975. {
  19976. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19977. }
  19978. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19979. {
  19980. owner->audioDeviceAboutToStartInt (device);
  19981. }
  19982. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19983. {
  19984. owner->audioDeviceStoppedInt();
  19985. }
  19986. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19987. {
  19988. owner->handleIncomingMidiMessageInt (source, message);
  19989. }
  19990. void AudioDeviceManager::playTestSound()
  19991. {
  19992. { // cunningly nested to swap, unlock and delete in that order.
  19993. ScopedPointer <AudioSampleBuffer> oldSound;
  19994. {
  19995. const ScopedLock sl (audioCallbackLock);
  19996. oldSound = testSound;
  19997. }
  19998. }
  19999. testSoundPosition = 0;
  20000. if (currentAudioDevice != 0)
  20001. {
  20002. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20003. const int soundLength = (int) sampleRate;
  20004. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20005. float* samples = newSound->getSampleData (0);
  20006. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20007. const float amplitude = 0.5f;
  20008. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20009. for (int i = 0; i < soundLength; ++i)
  20010. samples[i] = amplitude * (float) sin (i * phasePerSample);
  20011. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20012. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20013. const ScopedLock sl (audioCallbackLock);
  20014. testSound = newSound;
  20015. }
  20016. }
  20017. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20018. {
  20019. const ScopedLock sl (audioCallbackLock);
  20020. if (enableMeasurement)
  20021. ++inputLevelMeasurementEnabledCount;
  20022. else
  20023. --inputLevelMeasurementEnabledCount;
  20024. inputLevel = 0;
  20025. }
  20026. double AudioDeviceManager::getCurrentInputLevel() const
  20027. {
  20028. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20029. return inputLevel;
  20030. }
  20031. END_JUCE_NAMESPACE
  20032. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20033. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20034. BEGIN_JUCE_NAMESPACE
  20035. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20036. : name (deviceName),
  20037. typeName (typeName_)
  20038. {
  20039. }
  20040. AudioIODevice::~AudioIODevice()
  20041. {
  20042. }
  20043. bool AudioIODevice::hasControlPanel() const
  20044. {
  20045. return false;
  20046. }
  20047. bool AudioIODevice::showControlPanel()
  20048. {
  20049. jassertfalse // this should only be called for devices which return true from
  20050. // their hasControlPanel() method.
  20051. return false;
  20052. }
  20053. END_JUCE_NAMESPACE
  20054. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20055. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20056. BEGIN_JUCE_NAMESPACE
  20057. AudioIODeviceType::AudioIODeviceType (const String& name)
  20058. : typeName (name)
  20059. {
  20060. }
  20061. AudioIODeviceType::~AudioIODeviceType()
  20062. {
  20063. }
  20064. END_JUCE_NAMESPACE
  20065. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20066. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20067. BEGIN_JUCE_NAMESPACE
  20068. MidiOutput::MidiOutput()
  20069. : Thread ("midi out"),
  20070. internal (0),
  20071. firstMessage (0)
  20072. {
  20073. }
  20074. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20075. const double sampleNumber)
  20076. : message (data, len, sampleNumber)
  20077. {
  20078. }
  20079. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20080. const double millisecondCounterToStartAt,
  20081. double samplesPerSecondForBuffer)
  20082. {
  20083. // You've got to call startBackgroundThread() for this to actually work..
  20084. jassert (isThreadRunning());
  20085. // this needs to be a value in the future - RTFM for this method!
  20086. jassert (millisecondCounterToStartAt > 0);
  20087. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20088. MidiBuffer::Iterator i (buffer);
  20089. const uint8* data;
  20090. int len, time;
  20091. while (i.getNextEvent (data, len, time))
  20092. {
  20093. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20094. PendingMessage* const m
  20095. = new PendingMessage (data, len, eventTime);
  20096. const ScopedLock sl (lock);
  20097. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20098. {
  20099. m->next = firstMessage;
  20100. firstMessage = m;
  20101. }
  20102. else
  20103. {
  20104. PendingMessage* mm = firstMessage;
  20105. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20106. mm = mm->next;
  20107. m->next = mm->next;
  20108. mm->next = m;
  20109. }
  20110. }
  20111. notify();
  20112. }
  20113. void MidiOutput::clearAllPendingMessages()
  20114. {
  20115. const ScopedLock sl (lock);
  20116. while (firstMessage != 0)
  20117. {
  20118. PendingMessage* const m = firstMessage;
  20119. firstMessage = firstMessage->next;
  20120. delete m;
  20121. }
  20122. }
  20123. void MidiOutput::startBackgroundThread()
  20124. {
  20125. startThread (9);
  20126. }
  20127. void MidiOutput::stopBackgroundThread()
  20128. {
  20129. stopThread (5000);
  20130. }
  20131. void MidiOutput::run()
  20132. {
  20133. while (! threadShouldExit())
  20134. {
  20135. uint32 now = Time::getMillisecondCounter();
  20136. uint32 eventTime = 0;
  20137. uint32 timeToWait = 500;
  20138. PendingMessage* message;
  20139. {
  20140. const ScopedLock sl (lock);
  20141. message = firstMessage;
  20142. if (message != 0)
  20143. {
  20144. eventTime = roundToInt (message->message.getTimeStamp());
  20145. if (eventTime > now + 20)
  20146. {
  20147. timeToWait = eventTime - (now + 20);
  20148. message = 0;
  20149. }
  20150. else
  20151. {
  20152. firstMessage = message->next;
  20153. }
  20154. }
  20155. }
  20156. if (message != 0)
  20157. {
  20158. if (eventTime > now)
  20159. {
  20160. Time::waitForMillisecondCounter (eventTime);
  20161. if (threadShouldExit())
  20162. break;
  20163. }
  20164. if (eventTime > now - 200)
  20165. sendMessageNow (message->message);
  20166. delete message;
  20167. }
  20168. else
  20169. {
  20170. jassert (timeToWait < 1000 * 30);
  20171. wait (timeToWait);
  20172. }
  20173. }
  20174. clearAllPendingMessages();
  20175. }
  20176. END_JUCE_NAMESPACE
  20177. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20178. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20179. BEGIN_JUCE_NAMESPACE
  20180. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20181. {
  20182. const double maxVal = (double) 0x7fff;
  20183. char* intData = static_cast <char*> (dest);
  20184. if (dest != (void*) source || destBytesPerSample <= 4)
  20185. {
  20186. for (int i = 0; i < numSamples; ++i)
  20187. {
  20188. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20189. intData += destBytesPerSample;
  20190. }
  20191. }
  20192. else
  20193. {
  20194. intData += destBytesPerSample * numSamples;
  20195. for (int i = numSamples; --i >= 0;)
  20196. {
  20197. intData -= destBytesPerSample;
  20198. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20199. }
  20200. }
  20201. }
  20202. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20203. {
  20204. const double maxVal = (double) 0x7fff;
  20205. char* intData = static_cast <char*> (dest);
  20206. if (dest != (void*) source || destBytesPerSample <= 4)
  20207. {
  20208. for (int i = 0; i < numSamples; ++i)
  20209. {
  20210. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20211. intData += destBytesPerSample;
  20212. }
  20213. }
  20214. else
  20215. {
  20216. intData += destBytesPerSample * numSamples;
  20217. for (int i = numSamples; --i >= 0;)
  20218. {
  20219. intData -= destBytesPerSample;
  20220. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20221. }
  20222. }
  20223. }
  20224. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20225. {
  20226. const double maxVal = (double) 0x7fffff;
  20227. char* intData = static_cast <char*> (dest);
  20228. if (dest != (void*) source || destBytesPerSample <= 4)
  20229. {
  20230. for (int i = 0; i < numSamples; ++i)
  20231. {
  20232. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20233. intData += destBytesPerSample;
  20234. }
  20235. }
  20236. else
  20237. {
  20238. intData += destBytesPerSample * numSamples;
  20239. for (int i = numSamples; --i >= 0;)
  20240. {
  20241. intData -= destBytesPerSample;
  20242. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20243. }
  20244. }
  20245. }
  20246. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20247. {
  20248. const double maxVal = (double) 0x7fffff;
  20249. char* intData = static_cast <char*> (dest);
  20250. if (dest != (void*) source || destBytesPerSample <= 4)
  20251. {
  20252. for (int i = 0; i < numSamples; ++i)
  20253. {
  20254. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20255. intData += destBytesPerSample;
  20256. }
  20257. }
  20258. else
  20259. {
  20260. intData += destBytesPerSample * numSamples;
  20261. for (int i = numSamples; --i >= 0;)
  20262. {
  20263. intData -= destBytesPerSample;
  20264. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20265. }
  20266. }
  20267. }
  20268. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20269. {
  20270. const double maxVal = (double) 0x7fffffff;
  20271. char* intData = static_cast <char*> (dest);
  20272. if (dest != (void*) source || destBytesPerSample <= 4)
  20273. {
  20274. for (int i = 0; i < numSamples; ++i)
  20275. {
  20276. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20277. intData += destBytesPerSample;
  20278. }
  20279. }
  20280. else
  20281. {
  20282. intData += destBytesPerSample * numSamples;
  20283. for (int i = numSamples; --i >= 0;)
  20284. {
  20285. intData -= destBytesPerSample;
  20286. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20287. }
  20288. }
  20289. }
  20290. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20291. {
  20292. const double maxVal = (double) 0x7fffffff;
  20293. char* intData = static_cast <char*> (dest);
  20294. if (dest != (void*) source || destBytesPerSample <= 4)
  20295. {
  20296. for (int i = 0; i < numSamples; ++i)
  20297. {
  20298. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20299. intData += destBytesPerSample;
  20300. }
  20301. }
  20302. else
  20303. {
  20304. intData += destBytesPerSample * numSamples;
  20305. for (int i = numSamples; --i >= 0;)
  20306. {
  20307. intData -= destBytesPerSample;
  20308. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20309. }
  20310. }
  20311. }
  20312. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20313. {
  20314. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20315. char* d = static_cast <char*> (dest);
  20316. for (int i = 0; i < numSamples; ++i)
  20317. {
  20318. *(float*) d = source[i];
  20319. #if JUCE_BIG_ENDIAN
  20320. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20321. #endif
  20322. d += destBytesPerSample;
  20323. }
  20324. }
  20325. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20326. {
  20327. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20328. char* d = static_cast <char*> (dest);
  20329. for (int i = 0; i < numSamples; ++i)
  20330. {
  20331. *(float*) d = source[i];
  20332. #if JUCE_LITTLE_ENDIAN
  20333. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20334. #endif
  20335. d += destBytesPerSample;
  20336. }
  20337. }
  20338. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20339. {
  20340. const float scale = 1.0f / 0x7fff;
  20341. const char* intData = static_cast <const char*> (source);
  20342. if (source != (void*) dest || srcBytesPerSample >= 4)
  20343. {
  20344. for (int i = 0; i < numSamples; ++i)
  20345. {
  20346. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20347. intData += srcBytesPerSample;
  20348. }
  20349. }
  20350. else
  20351. {
  20352. intData += srcBytesPerSample * numSamples;
  20353. for (int i = numSamples; --i >= 0;)
  20354. {
  20355. intData -= srcBytesPerSample;
  20356. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20357. }
  20358. }
  20359. }
  20360. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20361. {
  20362. const float scale = 1.0f / 0x7fff;
  20363. const char* intData = static_cast <const char*> (source);
  20364. if (source != (void*) dest || srcBytesPerSample >= 4)
  20365. {
  20366. for (int i = 0; i < numSamples; ++i)
  20367. {
  20368. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20369. intData += srcBytesPerSample;
  20370. }
  20371. }
  20372. else
  20373. {
  20374. intData += srcBytesPerSample * numSamples;
  20375. for (int i = numSamples; --i >= 0;)
  20376. {
  20377. intData -= srcBytesPerSample;
  20378. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20379. }
  20380. }
  20381. }
  20382. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20383. {
  20384. const float scale = 1.0f / 0x7fffff;
  20385. const char* intData = static_cast <const char*> (source);
  20386. if (source != (void*) dest || srcBytesPerSample >= 4)
  20387. {
  20388. for (int i = 0; i < numSamples; ++i)
  20389. {
  20390. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20391. intData += srcBytesPerSample;
  20392. }
  20393. }
  20394. else
  20395. {
  20396. intData += srcBytesPerSample * numSamples;
  20397. for (int i = numSamples; --i >= 0;)
  20398. {
  20399. intData -= srcBytesPerSample;
  20400. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20401. }
  20402. }
  20403. }
  20404. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20405. {
  20406. const float scale = 1.0f / 0x7fffff;
  20407. const char* intData = static_cast <const char*> (source);
  20408. if (source != (void*) dest || srcBytesPerSample >= 4)
  20409. {
  20410. for (int i = 0; i < numSamples; ++i)
  20411. {
  20412. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20413. intData += srcBytesPerSample;
  20414. }
  20415. }
  20416. else
  20417. {
  20418. intData += srcBytesPerSample * numSamples;
  20419. for (int i = numSamples; --i >= 0;)
  20420. {
  20421. intData -= srcBytesPerSample;
  20422. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20423. }
  20424. }
  20425. }
  20426. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20427. {
  20428. const float scale = 1.0f / 0x7fffffff;
  20429. const char* intData = static_cast <const char*> (source);
  20430. if (source != (void*) dest || srcBytesPerSample >= 4)
  20431. {
  20432. for (int i = 0; i < numSamples; ++i)
  20433. {
  20434. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20435. intData += srcBytesPerSample;
  20436. }
  20437. }
  20438. else
  20439. {
  20440. intData += srcBytesPerSample * numSamples;
  20441. for (int i = numSamples; --i >= 0;)
  20442. {
  20443. intData -= srcBytesPerSample;
  20444. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20445. }
  20446. }
  20447. }
  20448. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20449. {
  20450. const float scale = 1.0f / 0x7fffffff;
  20451. const char* intData = static_cast <const char*> (source);
  20452. if (source != (void*) dest || srcBytesPerSample >= 4)
  20453. {
  20454. for (int i = 0; i < numSamples; ++i)
  20455. {
  20456. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20457. intData += srcBytesPerSample;
  20458. }
  20459. }
  20460. else
  20461. {
  20462. intData += srcBytesPerSample * numSamples;
  20463. for (int i = numSamples; --i >= 0;)
  20464. {
  20465. intData -= srcBytesPerSample;
  20466. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20467. }
  20468. }
  20469. }
  20470. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20471. {
  20472. const char* s = static_cast <const char*> (source);
  20473. for (int i = 0; i < numSamples; ++i)
  20474. {
  20475. dest[i] = *(float*)s;
  20476. #if JUCE_BIG_ENDIAN
  20477. uint32* const d = (uint32*) (dest + i);
  20478. *d = ByteOrder::swap (*d);
  20479. #endif
  20480. s += srcBytesPerSample;
  20481. }
  20482. }
  20483. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20484. {
  20485. const char* s = static_cast <const char*> (source);
  20486. for (int i = 0; i < numSamples; ++i)
  20487. {
  20488. dest[i] = *(float*)s;
  20489. #if JUCE_LITTLE_ENDIAN
  20490. uint32* const d = (uint32*) (dest + i);
  20491. *d = ByteOrder::swap (*d);
  20492. #endif
  20493. s += srcBytesPerSample;
  20494. }
  20495. }
  20496. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20497. const float* const source,
  20498. void* const dest,
  20499. const int numSamples)
  20500. {
  20501. switch (destFormat)
  20502. {
  20503. case int16LE:
  20504. convertFloatToInt16LE (source, dest, numSamples);
  20505. break;
  20506. case int16BE:
  20507. convertFloatToInt16BE (source, dest, numSamples);
  20508. break;
  20509. case int24LE:
  20510. convertFloatToInt24LE (source, dest, numSamples);
  20511. break;
  20512. case int24BE:
  20513. convertFloatToInt24BE (source, dest, numSamples);
  20514. break;
  20515. case int32LE:
  20516. convertFloatToInt32LE (source, dest, numSamples);
  20517. break;
  20518. case int32BE:
  20519. convertFloatToInt32BE (source, dest, numSamples);
  20520. break;
  20521. case float32LE:
  20522. convertFloatToFloat32LE (source, dest, numSamples);
  20523. break;
  20524. case float32BE:
  20525. convertFloatToFloat32BE (source, dest, numSamples);
  20526. break;
  20527. default:
  20528. jassertfalse
  20529. break;
  20530. }
  20531. }
  20532. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20533. const void* const source,
  20534. float* const dest,
  20535. const int numSamples)
  20536. {
  20537. switch (sourceFormat)
  20538. {
  20539. case int16LE:
  20540. convertInt16LEToFloat (source, dest, numSamples);
  20541. break;
  20542. case int16BE:
  20543. convertInt16BEToFloat (source, dest, numSamples);
  20544. break;
  20545. case int24LE:
  20546. convertInt24LEToFloat (source, dest, numSamples);
  20547. break;
  20548. case int24BE:
  20549. convertInt24BEToFloat (source, dest, numSamples);
  20550. break;
  20551. case int32LE:
  20552. convertInt32LEToFloat (source, dest, numSamples);
  20553. break;
  20554. case int32BE:
  20555. convertInt32BEToFloat (source, dest, numSamples);
  20556. break;
  20557. case float32LE:
  20558. convertFloat32LEToFloat (source, dest, numSamples);
  20559. break;
  20560. case float32BE:
  20561. convertFloat32BEToFloat (source, dest, numSamples);
  20562. break;
  20563. default:
  20564. jassertfalse
  20565. break;
  20566. }
  20567. }
  20568. void AudioDataConverters::interleaveSamples (const float** const source,
  20569. float* const dest,
  20570. const int numSamples,
  20571. const int numChannels)
  20572. {
  20573. for (int chan = 0; chan < numChannels; ++chan)
  20574. {
  20575. int i = chan;
  20576. const float* src = source [chan];
  20577. for (int j = 0; j < numSamples; ++j)
  20578. {
  20579. dest [i] = src [j];
  20580. i += numChannels;
  20581. }
  20582. }
  20583. }
  20584. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20585. float** const dest,
  20586. const int numSamples,
  20587. const int numChannels)
  20588. {
  20589. for (int chan = 0; chan < numChannels; ++chan)
  20590. {
  20591. int i = chan;
  20592. float* dst = dest [chan];
  20593. for (int j = 0; j < numSamples; ++j)
  20594. {
  20595. dst [j] = source [i];
  20596. i += numChannels;
  20597. }
  20598. }
  20599. }
  20600. END_JUCE_NAMESPACE
  20601. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20602. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20603. BEGIN_JUCE_NAMESPACE
  20604. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20605. const int numSamples) throw()
  20606. : numChannels (numChannels_),
  20607. size (numSamples)
  20608. {
  20609. jassert (numSamples >= 0);
  20610. jassert (numChannels_ > 0);
  20611. allocateData();
  20612. }
  20613. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20614. : numChannels (other.numChannels),
  20615. size (other.size)
  20616. {
  20617. allocateData();
  20618. const size_t numBytes = size * sizeof (float);
  20619. for (int i = 0; i < numChannels; ++i)
  20620. memcpy (channels[i], other.channels[i], numBytes);
  20621. }
  20622. void AudioSampleBuffer::allocateData()
  20623. {
  20624. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20625. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20626. allocatedData.malloc (allocatedBytes);
  20627. channels = reinterpret_cast <float**> (allocatedData.getData());
  20628. float* chan = (float*) (allocatedData + channelListSize);
  20629. for (int i = 0; i < numChannels; ++i)
  20630. {
  20631. channels[i] = chan;
  20632. chan += size;
  20633. }
  20634. channels [numChannels] = 0;
  20635. }
  20636. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20637. const int numChannels_,
  20638. const int numSamples) throw()
  20639. : numChannels (numChannels_),
  20640. size (numSamples),
  20641. allocatedBytes (0)
  20642. {
  20643. jassert (numChannels_ > 0);
  20644. allocateChannels (dataToReferTo);
  20645. }
  20646. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20647. const int newNumChannels,
  20648. const int newNumSamples) throw()
  20649. {
  20650. jassert (newNumChannels > 0);
  20651. allocatedBytes = 0;
  20652. allocatedData.free();
  20653. numChannels = newNumChannels;
  20654. size = newNumSamples;
  20655. allocateChannels (dataToReferTo);
  20656. }
  20657. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20658. {
  20659. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20660. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20661. {
  20662. channels = static_cast <float**> (preallocatedChannelSpace);
  20663. }
  20664. else
  20665. {
  20666. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20667. channels = reinterpret_cast <float**> (allocatedData.getData());
  20668. }
  20669. for (int i = 0; i < numChannels; ++i)
  20670. {
  20671. // you have to pass in the same number of valid pointers as numChannels
  20672. jassert (dataToReferTo[i] != 0);
  20673. channels[i] = dataToReferTo[i];
  20674. }
  20675. channels [numChannels] = 0;
  20676. }
  20677. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20678. {
  20679. if (this != &other)
  20680. {
  20681. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20682. const size_t numBytes = size * sizeof (float);
  20683. for (int i = 0; i < numChannels; ++i)
  20684. memcpy (channels[i], other.channels[i], numBytes);
  20685. }
  20686. return *this;
  20687. }
  20688. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20689. {
  20690. }
  20691. void AudioSampleBuffer::setSize (const int newNumChannels,
  20692. const int newNumSamples,
  20693. const bool keepExistingContent,
  20694. const bool clearExtraSpace,
  20695. const bool avoidReallocating) throw()
  20696. {
  20697. jassert (newNumChannels > 0);
  20698. if (newNumSamples != size || newNumChannels != numChannels)
  20699. {
  20700. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20701. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20702. if (keepExistingContent)
  20703. {
  20704. HeapBlock <char> newData;
  20705. newData.allocate (newTotalBytes, clearExtraSpace);
  20706. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20707. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20708. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20709. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20710. for (int i = 0; i < numChansToCopy; ++i)
  20711. {
  20712. memcpy (newChan, channels[i], numBytesToCopy);
  20713. newChannels[i] = newChan;
  20714. newChan += newNumSamples;
  20715. }
  20716. allocatedData.swapWith (newData);
  20717. allocatedBytes = (int) newTotalBytes;
  20718. channels = newChannels;
  20719. }
  20720. else
  20721. {
  20722. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20723. {
  20724. if (clearExtraSpace)
  20725. zeromem (allocatedData, newTotalBytes);
  20726. }
  20727. else
  20728. {
  20729. allocatedBytes = newTotalBytes;
  20730. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20731. channels = reinterpret_cast <float**> (allocatedData.getData());
  20732. }
  20733. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20734. for (int i = 0; i < newNumChannels; ++i)
  20735. {
  20736. channels[i] = chan;
  20737. chan += newNumSamples;
  20738. }
  20739. }
  20740. channels [newNumChannels] = 0;
  20741. size = newNumSamples;
  20742. numChannels = newNumChannels;
  20743. }
  20744. }
  20745. void AudioSampleBuffer::clear() throw()
  20746. {
  20747. for (int i = 0; i < numChannels; ++i)
  20748. zeromem (channels[i], size * sizeof (float));
  20749. }
  20750. void AudioSampleBuffer::clear (const int startSample,
  20751. const int numSamples) throw()
  20752. {
  20753. jassert (startSample >= 0 && startSample + numSamples <= size);
  20754. for (int i = 0; i < numChannels; ++i)
  20755. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20756. }
  20757. void AudioSampleBuffer::clear (const int channel,
  20758. const int startSample,
  20759. const int numSamples) throw()
  20760. {
  20761. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20762. jassert (startSample >= 0 && startSample + numSamples <= size);
  20763. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20764. }
  20765. void AudioSampleBuffer::applyGain (const int channel,
  20766. const int startSample,
  20767. int numSamples,
  20768. const float gain) throw()
  20769. {
  20770. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20771. jassert (startSample >= 0 && startSample + numSamples <= size);
  20772. if (gain != 1.0f)
  20773. {
  20774. float* d = channels [channel] + startSample;
  20775. if (gain == 0.0f)
  20776. {
  20777. zeromem (d, sizeof (float) * numSamples);
  20778. }
  20779. else
  20780. {
  20781. while (--numSamples >= 0)
  20782. *d++ *= gain;
  20783. }
  20784. }
  20785. }
  20786. void AudioSampleBuffer::applyGainRamp (const int channel,
  20787. const int startSample,
  20788. int numSamples,
  20789. float startGain,
  20790. float endGain) throw()
  20791. {
  20792. if (startGain == endGain)
  20793. {
  20794. applyGain (channel, startSample, numSamples, startGain);
  20795. }
  20796. else
  20797. {
  20798. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20799. jassert (startSample >= 0 && startSample + numSamples <= size);
  20800. const float increment = (endGain - startGain) / numSamples;
  20801. float* d = channels [channel] + startSample;
  20802. while (--numSamples >= 0)
  20803. {
  20804. *d++ *= startGain;
  20805. startGain += increment;
  20806. }
  20807. }
  20808. }
  20809. void AudioSampleBuffer::applyGain (const int startSample,
  20810. const int numSamples,
  20811. const float gain) throw()
  20812. {
  20813. for (int i = 0; i < numChannels; ++i)
  20814. applyGain (i, startSample, numSamples, gain);
  20815. }
  20816. void AudioSampleBuffer::addFrom (const int destChannel,
  20817. const int destStartSample,
  20818. const AudioSampleBuffer& source,
  20819. const int sourceChannel,
  20820. const int sourceStartSample,
  20821. int numSamples,
  20822. const float gain) throw()
  20823. {
  20824. jassert (&source != this || sourceChannel != destChannel);
  20825. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20826. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20827. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20828. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20829. if (gain != 0.0f && numSamples > 0)
  20830. {
  20831. float* d = channels [destChannel] + destStartSample;
  20832. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20833. if (gain != 1.0f)
  20834. {
  20835. while (--numSamples >= 0)
  20836. *d++ += gain * *s++;
  20837. }
  20838. else
  20839. {
  20840. while (--numSamples >= 0)
  20841. *d++ += *s++;
  20842. }
  20843. }
  20844. }
  20845. void AudioSampleBuffer::addFrom (const int destChannel,
  20846. const int destStartSample,
  20847. const float* source,
  20848. int numSamples,
  20849. const float gain) throw()
  20850. {
  20851. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20852. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20853. jassert (source != 0);
  20854. if (gain != 0.0f && numSamples > 0)
  20855. {
  20856. float* d = channels [destChannel] + destStartSample;
  20857. if (gain != 1.0f)
  20858. {
  20859. while (--numSamples >= 0)
  20860. *d++ += gain * *source++;
  20861. }
  20862. else
  20863. {
  20864. while (--numSamples >= 0)
  20865. *d++ += *source++;
  20866. }
  20867. }
  20868. }
  20869. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20870. const int destStartSample,
  20871. const float* source,
  20872. int numSamples,
  20873. float startGain,
  20874. const float endGain) throw()
  20875. {
  20876. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20877. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20878. jassert (source != 0);
  20879. if (startGain == endGain)
  20880. {
  20881. addFrom (destChannel,
  20882. destStartSample,
  20883. source,
  20884. numSamples,
  20885. startGain);
  20886. }
  20887. else
  20888. {
  20889. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20890. {
  20891. const float increment = (endGain - startGain) / numSamples;
  20892. float* d = channels [destChannel] + destStartSample;
  20893. while (--numSamples >= 0)
  20894. {
  20895. *d++ += startGain * *source++;
  20896. startGain += increment;
  20897. }
  20898. }
  20899. }
  20900. }
  20901. void AudioSampleBuffer::copyFrom (const int destChannel,
  20902. const int destStartSample,
  20903. const AudioSampleBuffer& source,
  20904. const int sourceChannel,
  20905. const int sourceStartSample,
  20906. int numSamples) throw()
  20907. {
  20908. jassert (&source != this || sourceChannel != destChannel);
  20909. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20910. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20911. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20912. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20913. if (numSamples > 0)
  20914. {
  20915. memcpy (channels [destChannel] + destStartSample,
  20916. source.channels [sourceChannel] + sourceStartSample,
  20917. sizeof (float) * numSamples);
  20918. }
  20919. }
  20920. void AudioSampleBuffer::copyFrom (const int destChannel,
  20921. const int destStartSample,
  20922. const float* source,
  20923. int numSamples) throw()
  20924. {
  20925. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20926. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20927. jassert (source != 0);
  20928. if (numSamples > 0)
  20929. {
  20930. memcpy (channels [destChannel] + destStartSample,
  20931. source,
  20932. sizeof (float) * numSamples);
  20933. }
  20934. }
  20935. void AudioSampleBuffer::copyFrom (const int destChannel,
  20936. const int destStartSample,
  20937. const float* source,
  20938. int numSamples,
  20939. const float gain) throw()
  20940. {
  20941. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20942. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20943. jassert (source != 0);
  20944. if (numSamples > 0)
  20945. {
  20946. float* d = channels [destChannel] + destStartSample;
  20947. if (gain != 1.0f)
  20948. {
  20949. if (gain == 0)
  20950. {
  20951. zeromem (d, sizeof (float) * numSamples);
  20952. }
  20953. else
  20954. {
  20955. while (--numSamples >= 0)
  20956. *d++ = gain * *source++;
  20957. }
  20958. }
  20959. else
  20960. {
  20961. memcpy (d, source, sizeof (float) * numSamples);
  20962. }
  20963. }
  20964. }
  20965. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20966. const int destStartSample,
  20967. const float* source,
  20968. int numSamples,
  20969. float startGain,
  20970. float endGain) throw()
  20971. {
  20972. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20973. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20974. jassert (source != 0);
  20975. if (startGain == endGain)
  20976. {
  20977. copyFrom (destChannel,
  20978. destStartSample,
  20979. source,
  20980. numSamples,
  20981. startGain);
  20982. }
  20983. else
  20984. {
  20985. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20986. {
  20987. const float increment = (endGain - startGain) / numSamples;
  20988. float* d = channels [destChannel] + destStartSample;
  20989. while (--numSamples >= 0)
  20990. {
  20991. *d++ = startGain * *source++;
  20992. startGain += increment;
  20993. }
  20994. }
  20995. }
  20996. }
  20997. void AudioSampleBuffer::findMinMax (const int channel,
  20998. const int startSample,
  20999. int numSamples,
  21000. float& minVal,
  21001. float& maxVal) const throw()
  21002. {
  21003. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21004. jassert (startSample >= 0 && startSample + numSamples <= size);
  21005. if (numSamples <= 0)
  21006. {
  21007. minVal = 0.0f;
  21008. maxVal = 0.0f;
  21009. }
  21010. else
  21011. {
  21012. const float* d = channels [channel] + startSample;
  21013. float mn = *d++;
  21014. float mx = mn;
  21015. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21016. {
  21017. const float samp = *d++;
  21018. if (samp > mx)
  21019. mx = samp;
  21020. if (samp < mn)
  21021. mn = samp;
  21022. }
  21023. maxVal = mx;
  21024. minVal = mn;
  21025. }
  21026. }
  21027. float AudioSampleBuffer::getMagnitude (const int channel,
  21028. const int startSample,
  21029. const int numSamples) const throw()
  21030. {
  21031. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21032. jassert (startSample >= 0 && startSample + numSamples <= size);
  21033. float mn, mx;
  21034. findMinMax (channel, startSample, numSamples, mn, mx);
  21035. return jmax (mn, -mn, mx, -mx);
  21036. }
  21037. float AudioSampleBuffer::getMagnitude (const int startSample,
  21038. const int numSamples) const throw()
  21039. {
  21040. float mag = 0.0f;
  21041. for (int i = 0; i < numChannels; ++i)
  21042. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21043. return mag;
  21044. }
  21045. float AudioSampleBuffer::getRMSLevel (const int channel,
  21046. const int startSample,
  21047. const int numSamples) const throw()
  21048. {
  21049. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21050. jassert (startSample >= 0 && startSample + numSamples <= size);
  21051. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21052. return 0.0f;
  21053. const float* const data = channels [channel] + startSample;
  21054. double sum = 0.0;
  21055. for (int i = 0; i < numSamples; ++i)
  21056. {
  21057. const float sample = data [i];
  21058. sum += sample * sample;
  21059. }
  21060. return (float) sqrt (sum / numSamples);
  21061. }
  21062. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21063. const int startSample,
  21064. const int numSamples,
  21065. const int readerStartSample,
  21066. const bool useLeftChan,
  21067. const bool useRightChan) throw()
  21068. {
  21069. jassert (reader != 0);
  21070. jassert (startSample >= 0 && startSample + numSamples <= size);
  21071. if (numSamples > 0)
  21072. {
  21073. int* chans[3];
  21074. if (useLeftChan == useRightChan)
  21075. {
  21076. chans[0] = (int*) getSampleData (0, startSample);
  21077. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21078. }
  21079. else if (useLeftChan || (reader->numChannels == 1))
  21080. {
  21081. chans[0] = (int*) getSampleData (0, startSample);
  21082. chans[1] = 0;
  21083. }
  21084. else if (useRightChan)
  21085. {
  21086. chans[0] = 0;
  21087. chans[1] = (int*) getSampleData (0, startSample);
  21088. }
  21089. chans[2] = 0;
  21090. reader->read (chans, 2, readerStartSample, numSamples, true);
  21091. if (! reader->usesFloatingPointData)
  21092. {
  21093. for (int j = 0; j < 2; ++j)
  21094. {
  21095. float* const d = reinterpret_cast <float*> (chans[j]);
  21096. if (d != 0)
  21097. {
  21098. const float multiplier = 1.0f / 0x7fffffff;
  21099. for (int i = 0; i < numSamples; ++i)
  21100. d[i] = *(int*)(d + i) * multiplier;
  21101. }
  21102. }
  21103. }
  21104. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21105. {
  21106. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21107. memcpy (getSampleData (1, startSample),
  21108. getSampleData (0, startSample),
  21109. sizeof (float) * numSamples);
  21110. }
  21111. }
  21112. }
  21113. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21114. const int startSample,
  21115. const int numSamples) const throw()
  21116. {
  21117. jassert (startSample >= 0 && startSample + numSamples <= size);
  21118. if (numSamples > 0)
  21119. {
  21120. int* chans [3];
  21121. if (writer->isFloatingPoint())
  21122. {
  21123. chans[0] = (int*) getSampleData (0, startSample);
  21124. if (numChannels > 1)
  21125. chans[1] = (int*) getSampleData (1, startSample);
  21126. else
  21127. chans[1] = 0;
  21128. chans[2] = 0;
  21129. writer->write ((const int**) chans, numSamples);
  21130. }
  21131. else
  21132. {
  21133. HeapBlock <int> tempBuffer (numSamples * 2);
  21134. chans[0] = tempBuffer;
  21135. if (numChannels > 1)
  21136. chans[1] = chans[0] + numSamples;
  21137. else
  21138. chans[1] = 0;
  21139. chans[2] = 0;
  21140. for (int j = 0; j < 2; ++j)
  21141. {
  21142. int* const dest = chans[j];
  21143. if (dest != 0)
  21144. {
  21145. const float* const src = channels [j] + startSample;
  21146. for (int i = 0; i < numSamples; ++i)
  21147. {
  21148. const double samp = src[i];
  21149. if (samp <= -1.0)
  21150. dest[i] = std::numeric_limits<int>::min();
  21151. else if (samp >= 1.0)
  21152. dest[i] = std::numeric_limits<int>::max();
  21153. else
  21154. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21155. }
  21156. }
  21157. }
  21158. writer->write ((const int**) chans, numSamples);
  21159. }
  21160. }
  21161. }
  21162. END_JUCE_NAMESPACE
  21163. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21164. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21165. BEGIN_JUCE_NAMESPACE
  21166. IIRFilter::IIRFilter()
  21167. : active (false)
  21168. {
  21169. reset();
  21170. }
  21171. IIRFilter::IIRFilter (const IIRFilter& other)
  21172. : active (other.active)
  21173. {
  21174. const ScopedLock sl (other.processLock);
  21175. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21176. reset();
  21177. }
  21178. IIRFilter::~IIRFilter()
  21179. {
  21180. }
  21181. void IIRFilter::reset() throw()
  21182. {
  21183. const ScopedLock sl (processLock);
  21184. x1 = 0;
  21185. x2 = 0;
  21186. y1 = 0;
  21187. y2 = 0;
  21188. }
  21189. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21190. {
  21191. float out = coefficients[0] * in
  21192. + coefficients[1] * x1
  21193. + coefficients[2] * x2
  21194. - coefficients[4] * y1
  21195. - coefficients[5] * y2;
  21196. #if JUCE_INTEL
  21197. if (! (out < -1.0e-8 || out > 1.0e-8))
  21198. out = 0;
  21199. #endif
  21200. x2 = x1;
  21201. x1 = in;
  21202. y2 = y1;
  21203. y1 = out;
  21204. return out;
  21205. }
  21206. void IIRFilter::processSamples (float* const samples,
  21207. const int numSamples) throw()
  21208. {
  21209. const ScopedLock sl (processLock);
  21210. if (active)
  21211. {
  21212. for (int i = 0; i < numSamples; ++i)
  21213. {
  21214. const float in = samples[i];
  21215. float out = coefficients[0] * in
  21216. + coefficients[1] * x1
  21217. + coefficients[2] * x2
  21218. - coefficients[4] * y1
  21219. - coefficients[5] * y2;
  21220. #if JUCE_INTEL
  21221. if (! (out < -1.0e-8 || out > 1.0e-8))
  21222. out = 0;
  21223. #endif
  21224. x2 = x1;
  21225. x1 = in;
  21226. y2 = y1;
  21227. y1 = out;
  21228. samples[i] = out;
  21229. }
  21230. }
  21231. }
  21232. void IIRFilter::makeLowPass (const double sampleRate,
  21233. const double frequency) throw()
  21234. {
  21235. jassert (sampleRate > 0);
  21236. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21237. const double nSquared = n * n;
  21238. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  21239. setCoefficients (c1,
  21240. c1 * 2.0f,
  21241. c1,
  21242. 1.0,
  21243. c1 * 2.0 * (1.0 - nSquared),
  21244. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  21245. }
  21246. void IIRFilter::makeHighPass (const double sampleRate,
  21247. const double frequency) throw()
  21248. {
  21249. const double n = tan (double_Pi * frequency / sampleRate);
  21250. const double nSquared = n * n;
  21251. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  21252. setCoefficients (c1,
  21253. c1 * -2.0f,
  21254. c1,
  21255. 1.0,
  21256. c1 * 2.0 * (nSquared - 1.0),
  21257. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  21258. }
  21259. void IIRFilter::makeLowShelf (const double sampleRate,
  21260. const double cutOffFrequency,
  21261. const double Q,
  21262. const float gainFactor) throw()
  21263. {
  21264. jassert (sampleRate > 0);
  21265. jassert (Q > 0);
  21266. const double A = jmax (0.0f, gainFactor);
  21267. const double aminus1 = A - 1.0;
  21268. const double aplus1 = A + 1.0;
  21269. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21270. const double coso = cos (omega);
  21271. const double beta = sin (omega) * sqrt (A) / Q;
  21272. const double aminus1TimesCoso = aminus1 * coso;
  21273. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21274. A * 2.0 * (aminus1 - aplus1 * coso),
  21275. A * (aplus1 - aminus1TimesCoso - beta),
  21276. aplus1 + aminus1TimesCoso + beta,
  21277. -2.0 * (aminus1 + aplus1 * coso),
  21278. aplus1 + aminus1TimesCoso - beta);
  21279. }
  21280. void IIRFilter::makeHighShelf (const double sampleRate,
  21281. const double cutOffFrequency,
  21282. const double Q,
  21283. const float gainFactor) throw()
  21284. {
  21285. jassert (sampleRate > 0);
  21286. jassert (Q > 0);
  21287. const double A = jmax (0.0f, gainFactor);
  21288. const double aminus1 = A - 1.0;
  21289. const double aplus1 = A + 1.0;
  21290. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21291. const double coso = cos (omega);
  21292. const double beta = sin (omega) * sqrt (A) / Q;
  21293. const double aminus1TimesCoso = aminus1 * coso;
  21294. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21295. A * -2.0 * (aminus1 + aplus1 * coso),
  21296. A * (aplus1 + aminus1TimesCoso - beta),
  21297. aplus1 - aminus1TimesCoso + beta,
  21298. 2.0 * (aminus1 - aplus1 * coso),
  21299. aplus1 - aminus1TimesCoso - beta);
  21300. }
  21301. void IIRFilter::makeBandPass (const double sampleRate,
  21302. const double centreFrequency,
  21303. const double Q,
  21304. const float gainFactor) throw()
  21305. {
  21306. jassert (sampleRate > 0);
  21307. jassert (Q > 0);
  21308. const double A = jmax (0.0f, gainFactor);
  21309. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21310. const double alpha = 0.5 * sin (omega) / Q;
  21311. const double c2 = -2.0 * cos (omega);
  21312. const double alphaTimesA = alpha * A;
  21313. const double alphaOverA = alpha / A;
  21314. setCoefficients (1.0 + alphaTimesA,
  21315. c2,
  21316. 1.0 - alphaTimesA,
  21317. 1.0 + alphaOverA,
  21318. c2,
  21319. 1.0 - alphaOverA);
  21320. }
  21321. void IIRFilter::makeInactive() throw()
  21322. {
  21323. const ScopedLock sl (processLock);
  21324. active = false;
  21325. }
  21326. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21327. {
  21328. const ScopedLock sl (processLock);
  21329. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21330. active = other.active;
  21331. }
  21332. void IIRFilter::setCoefficients (double c1,
  21333. double c2,
  21334. double c3,
  21335. double c4,
  21336. double c5,
  21337. double c6) throw()
  21338. {
  21339. const double a = 1.0 / c4;
  21340. c1 *= a;
  21341. c2 *= a;
  21342. c3 *= a;
  21343. c5 *= a;
  21344. c6 *= a;
  21345. const ScopedLock sl (processLock);
  21346. coefficients[0] = (float) c1;
  21347. coefficients[1] = (float) c2;
  21348. coefficients[2] = (float) c3;
  21349. coefficients[3] = (float) c4;
  21350. coefficients[4] = (float) c5;
  21351. coefficients[5] = (float) c6;
  21352. active = true;
  21353. }
  21354. END_JUCE_NAMESPACE
  21355. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21356. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21357. BEGIN_JUCE_NAMESPACE
  21358. MidiBuffer::MidiBuffer() throw()
  21359. : bytesUsed (0)
  21360. {
  21361. }
  21362. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21363. : bytesUsed (0)
  21364. {
  21365. addEvent (message, 0);
  21366. }
  21367. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21368. : data (other.data),
  21369. bytesUsed (other.bytesUsed)
  21370. {
  21371. }
  21372. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21373. {
  21374. bytesUsed = other.bytesUsed;
  21375. data = other.data;
  21376. return *this;
  21377. }
  21378. void MidiBuffer::swapWith (MidiBuffer& other)
  21379. {
  21380. data.swapWith (other.data);
  21381. swapVariables <int> (bytesUsed, other.bytesUsed);
  21382. }
  21383. MidiBuffer::~MidiBuffer() throw()
  21384. {
  21385. }
  21386. inline uint8* MidiBuffer::getData() const throw()
  21387. {
  21388. return static_cast <uint8*> (data.getData());
  21389. }
  21390. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21391. {
  21392. return *static_cast <const int*> (d);
  21393. }
  21394. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21395. {
  21396. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21397. }
  21398. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21399. {
  21400. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21401. }
  21402. void MidiBuffer::clear() throw()
  21403. {
  21404. bytesUsed = 0;
  21405. }
  21406. void MidiBuffer::clear (const int startSample,
  21407. const int numSamples) throw()
  21408. {
  21409. uint8* const start = findEventAfter (getData(), startSample - 1);
  21410. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21411. if (end > start)
  21412. {
  21413. const int bytesToMove = bytesUsed - (int) (end - getData());
  21414. if (bytesToMove > 0)
  21415. memmove (start, end, bytesToMove);
  21416. bytesUsed -= (int) (end - start);
  21417. }
  21418. }
  21419. void MidiBuffer::addEvent (const MidiMessage& m,
  21420. const int sampleNumber) throw()
  21421. {
  21422. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21423. }
  21424. static int findActualEventLength (const uint8* const data,
  21425. const int maxBytes) throw()
  21426. {
  21427. unsigned int byte = (unsigned int) *data;
  21428. int size = 0;
  21429. if (byte == 0xf0 || byte == 0xf7)
  21430. {
  21431. const uint8* d = data + 1;
  21432. while (d < data + maxBytes)
  21433. if (*d++ == 0xf7)
  21434. break;
  21435. size = (int) (d - data);
  21436. }
  21437. else if (byte == 0xff)
  21438. {
  21439. int n;
  21440. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21441. size = jmin (maxBytes, n + 2 + bytesLeft);
  21442. }
  21443. else if (byte >= 0x80)
  21444. {
  21445. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21446. }
  21447. return size;
  21448. }
  21449. void MidiBuffer::addEvent (const uint8* const newData,
  21450. const int maxBytes,
  21451. const int sampleNumber) throw()
  21452. {
  21453. const int numBytes = findActualEventLength (newData, maxBytes);
  21454. if (numBytes > 0)
  21455. {
  21456. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21457. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21458. uint8* d = findEventAfter (getData(), sampleNumber);
  21459. const int bytesToMove = bytesUsed - (int) (d - getData());
  21460. if (bytesToMove > 0)
  21461. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21462. *reinterpret_cast <int*> (d) = sampleNumber;
  21463. d += sizeof (int);
  21464. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21465. d += sizeof (uint16);
  21466. memcpy (d, newData, numBytes);
  21467. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21468. }
  21469. }
  21470. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21471. const int startSample,
  21472. const int numSamples,
  21473. const int sampleDeltaToAdd) throw()
  21474. {
  21475. Iterator i (otherBuffer);
  21476. i.setNextSamplePosition (startSample);
  21477. const uint8* eventData;
  21478. int eventSize, position;
  21479. while (i.getNextEvent (eventData, eventSize, position)
  21480. && (position < startSample + numSamples || numSamples < 0))
  21481. {
  21482. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21483. }
  21484. }
  21485. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21486. {
  21487. data.ensureSize (minimumNumBytes);
  21488. }
  21489. bool MidiBuffer::isEmpty() const throw()
  21490. {
  21491. return bytesUsed == 0;
  21492. }
  21493. int MidiBuffer::getNumEvents() const throw()
  21494. {
  21495. int n = 0;
  21496. const uint8* d = getData();
  21497. const uint8* const end = d + bytesUsed;
  21498. while (d < end)
  21499. {
  21500. d += getEventTotalSize (d);
  21501. ++n;
  21502. }
  21503. return n;
  21504. }
  21505. int MidiBuffer::getFirstEventTime() const throw()
  21506. {
  21507. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21508. }
  21509. int MidiBuffer::getLastEventTime() const throw()
  21510. {
  21511. if (bytesUsed == 0)
  21512. return 0;
  21513. const uint8* d = getData();
  21514. const uint8* const endData = d + bytesUsed;
  21515. for (;;)
  21516. {
  21517. const uint8* const nextOne = d + getEventTotalSize (d);
  21518. if (nextOne >= endData)
  21519. return getEventTime (d);
  21520. d = nextOne;
  21521. }
  21522. }
  21523. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21524. {
  21525. const uint8* const endData = getData() + bytesUsed;
  21526. while (d < endData && getEventTime (d) <= samplePosition)
  21527. d += getEventTotalSize (d);
  21528. return d;
  21529. }
  21530. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21531. : buffer (buffer_),
  21532. data (buffer_.getData())
  21533. {
  21534. }
  21535. MidiBuffer::Iterator::~Iterator() throw()
  21536. {
  21537. }
  21538. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21539. {
  21540. data = buffer.getData();
  21541. const uint8* dataEnd = data + buffer.bytesUsed;
  21542. while (data < dataEnd && getEventTime (data) < samplePosition)
  21543. data += getEventTotalSize (data);
  21544. }
  21545. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21546. {
  21547. if (data >= buffer.getData() + buffer.bytesUsed)
  21548. return false;
  21549. samplePosition = getEventTime (data);
  21550. numBytes = getEventDataSize (data);
  21551. data += sizeof (int) + sizeof (uint16);
  21552. midiData = data;
  21553. data += numBytes;
  21554. return true;
  21555. }
  21556. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21557. {
  21558. if (data >= buffer.getData() + buffer.bytesUsed)
  21559. return false;
  21560. samplePosition = getEventTime (data);
  21561. const int numBytes = getEventDataSize (data);
  21562. data += sizeof (int) + sizeof (uint16);
  21563. result = MidiMessage (data, numBytes, samplePosition);
  21564. data += numBytes;
  21565. return true;
  21566. }
  21567. END_JUCE_NAMESPACE
  21568. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21569. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21570. BEGIN_JUCE_NAMESPACE
  21571. namespace MidiFileHelpers
  21572. {
  21573. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21574. {
  21575. unsigned int buffer = v & 0x7F;
  21576. while ((v >>= 7) != 0)
  21577. {
  21578. buffer <<= 8;
  21579. buffer |= ((v & 0x7F) | 0x80);
  21580. }
  21581. for (;;)
  21582. {
  21583. out.writeByte ((char) buffer);
  21584. if (buffer & 0x80)
  21585. buffer >>= 8;
  21586. else
  21587. break;
  21588. }
  21589. }
  21590. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21591. {
  21592. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21593. data += 4;
  21594. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21595. {
  21596. bool ok = false;
  21597. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21598. {
  21599. for (int i = 0; i < 8; ++i)
  21600. {
  21601. ch = ByteOrder::bigEndianInt (data);
  21602. data += 4;
  21603. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21604. {
  21605. ok = true;
  21606. break;
  21607. }
  21608. }
  21609. }
  21610. if (! ok)
  21611. return false;
  21612. }
  21613. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21614. data += 4;
  21615. fileType = (short) ByteOrder::bigEndianShort (data);
  21616. data += 2;
  21617. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21618. data += 2;
  21619. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21620. data += 2;
  21621. bytesRemaining -= 6;
  21622. data += bytesRemaining;
  21623. return true;
  21624. }
  21625. static double convertTicksToSeconds (const double time,
  21626. const MidiMessageSequence& tempoEvents,
  21627. const int timeFormat)
  21628. {
  21629. if (timeFormat > 0)
  21630. {
  21631. int numer = 4, denom = 4;
  21632. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21633. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21634. double secsPerTick = 0.5 * tickLen;
  21635. const int numEvents = tempoEvents.getNumEvents();
  21636. for (int i = 0; i < numEvents; ++i)
  21637. {
  21638. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21639. if (time <= m.getTimeStamp())
  21640. break;
  21641. if (timeFormat > 0)
  21642. {
  21643. correctedTempoTime = correctedTempoTime
  21644. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21645. }
  21646. else
  21647. {
  21648. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21649. }
  21650. tempoTime = m.getTimeStamp();
  21651. if (m.isTempoMetaEvent())
  21652. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21653. else if (m.isTimeSignatureMetaEvent())
  21654. m.getTimeSignatureInfo (numer, denom);
  21655. while (i + 1 < numEvents)
  21656. {
  21657. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21658. if (m2.getTimeStamp() == tempoTime)
  21659. {
  21660. ++i;
  21661. if (m2.isTempoMetaEvent())
  21662. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21663. else if (m2.isTimeSignatureMetaEvent())
  21664. m2.getTimeSignatureInfo (numer, denom);
  21665. }
  21666. else
  21667. {
  21668. break;
  21669. }
  21670. }
  21671. }
  21672. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21673. }
  21674. else
  21675. {
  21676. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21677. }
  21678. }
  21679. }
  21680. MidiFile::MidiFile()
  21681. : timeFormat ((short) (unsigned short) 0xe728)
  21682. {
  21683. }
  21684. MidiFile::~MidiFile()
  21685. {
  21686. clear();
  21687. }
  21688. void MidiFile::clear()
  21689. {
  21690. tracks.clear();
  21691. }
  21692. int MidiFile::getNumTracks() const throw()
  21693. {
  21694. return tracks.size();
  21695. }
  21696. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21697. {
  21698. return tracks [index];
  21699. }
  21700. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21701. {
  21702. tracks.add (new MidiMessageSequence (trackSequence));
  21703. }
  21704. short MidiFile::getTimeFormat() const throw()
  21705. {
  21706. return timeFormat;
  21707. }
  21708. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21709. {
  21710. timeFormat = (short) ticks;
  21711. }
  21712. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21713. const int subframeResolution) throw()
  21714. {
  21715. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21716. }
  21717. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21718. {
  21719. for (int i = tracks.size(); --i >= 0;)
  21720. {
  21721. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21722. for (int j = 0; j < numEvents; ++j)
  21723. {
  21724. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21725. if (m.isTempoMetaEvent())
  21726. tempoChangeEvents.addEvent (m);
  21727. }
  21728. }
  21729. }
  21730. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21731. {
  21732. for (int i = tracks.size(); --i >= 0;)
  21733. {
  21734. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21735. for (int j = 0; j < numEvents; ++j)
  21736. {
  21737. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21738. if (m.isTimeSignatureMetaEvent())
  21739. timeSigEvents.addEvent (m);
  21740. }
  21741. }
  21742. }
  21743. double MidiFile::getLastTimestamp() const
  21744. {
  21745. double t = 0.0;
  21746. for (int i = tracks.size(); --i >= 0;)
  21747. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21748. return t;
  21749. }
  21750. bool MidiFile::readFrom (InputStream& sourceStream)
  21751. {
  21752. clear();
  21753. MemoryBlock data;
  21754. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21755. // (put a sanity-check on the file size, as midi files are generally small)
  21756. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21757. {
  21758. size_t size = data.getSize();
  21759. const uint8* d = static_cast <const uint8*> (data.getData());
  21760. short fileType, expectedTracks;
  21761. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21762. {
  21763. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21764. int track = 0;
  21765. while (size > 0 && track < expectedTracks)
  21766. {
  21767. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21768. d += 4;
  21769. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21770. d += 4;
  21771. if (chunkSize <= 0)
  21772. break;
  21773. if (size < 0)
  21774. return false;
  21775. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21776. {
  21777. readNextTrack (d, chunkSize);
  21778. }
  21779. size -= chunkSize + 8;
  21780. d += chunkSize;
  21781. ++track;
  21782. }
  21783. return true;
  21784. }
  21785. }
  21786. return false;
  21787. }
  21788. // a comparator that puts all the note-offs before note-ons that have the same time
  21789. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21790. const MidiMessageSequence::MidiEventHolder* const second)
  21791. {
  21792. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21793. if (diff == 0)
  21794. {
  21795. if (first->message.isNoteOff() && second->message.isNoteOn())
  21796. return -1;
  21797. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21798. return 1;
  21799. else
  21800. return 0;
  21801. }
  21802. else
  21803. {
  21804. return (diff > 0) ? 1 : -1;
  21805. }
  21806. }
  21807. void MidiFile::readNextTrack (const uint8* data, int size)
  21808. {
  21809. double time = 0;
  21810. char lastStatusByte = 0;
  21811. MidiMessageSequence result;
  21812. while (size > 0)
  21813. {
  21814. int bytesUsed;
  21815. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21816. data += bytesUsed;
  21817. size -= bytesUsed;
  21818. time += delay;
  21819. int messSize = 0;
  21820. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21821. if (messSize <= 0)
  21822. break;
  21823. size -= messSize;
  21824. data += messSize;
  21825. result.addEvent (mm);
  21826. const char firstByte = *(mm.getRawData());
  21827. if ((firstByte & 0xf0) != 0xf0)
  21828. lastStatusByte = firstByte;
  21829. }
  21830. // use a sort that puts all the note-offs before note-ons that have the same time
  21831. result.list.sort (*this, true);
  21832. result.updateMatchedPairs();
  21833. addTrack (result);
  21834. }
  21835. void MidiFile::convertTimestampTicksToSeconds()
  21836. {
  21837. MidiMessageSequence tempoEvents;
  21838. findAllTempoEvents (tempoEvents);
  21839. findAllTimeSigEvents (tempoEvents);
  21840. for (int i = 0; i < tracks.size(); ++i)
  21841. {
  21842. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21843. for (int j = ms.getNumEvents(); --j >= 0;)
  21844. {
  21845. MidiMessage& m = ms.getEventPointer(j)->message;
  21846. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21847. tempoEvents,
  21848. timeFormat));
  21849. }
  21850. }
  21851. }
  21852. bool MidiFile::writeTo (OutputStream& out)
  21853. {
  21854. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21855. out.writeIntBigEndian (6);
  21856. out.writeShortBigEndian (1); // type
  21857. out.writeShortBigEndian ((short) tracks.size());
  21858. out.writeShortBigEndian (timeFormat);
  21859. for (int i = 0; i < tracks.size(); ++i)
  21860. writeTrack (out, i);
  21861. out.flush();
  21862. return true;
  21863. }
  21864. void MidiFile::writeTrack (OutputStream& mainOut,
  21865. const int trackNum)
  21866. {
  21867. MemoryOutputStream out;
  21868. const MidiMessageSequence& ms = *tracks[trackNum];
  21869. int lastTick = 0;
  21870. char lastStatusByte = 0;
  21871. for (int i = 0; i < ms.getNumEvents(); ++i)
  21872. {
  21873. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21874. const int tick = roundToInt (mm.getTimeStamp());
  21875. const int delta = jmax (0, tick - lastTick);
  21876. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21877. lastTick = tick;
  21878. const char statusByte = *(mm.getRawData());
  21879. if ((statusByte == lastStatusByte)
  21880. && ((statusByte & 0xf0) != 0xf0)
  21881. && i > 0
  21882. && mm.getRawDataSize() > 1)
  21883. {
  21884. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21885. }
  21886. else
  21887. {
  21888. out.write (mm.getRawData(), mm.getRawDataSize());
  21889. }
  21890. lastStatusByte = statusByte;
  21891. }
  21892. out.writeByte (0);
  21893. const MidiMessage m (MidiMessage::endOfTrack());
  21894. out.write (m.getRawData(),
  21895. m.getRawDataSize());
  21896. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21897. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21898. mainOut.write (out.getData(), (int) out.getDataSize());
  21899. }
  21900. END_JUCE_NAMESPACE
  21901. /*** End of inlined file: juce_MidiFile.cpp ***/
  21902. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21903. BEGIN_JUCE_NAMESPACE
  21904. MidiKeyboardState::MidiKeyboardState()
  21905. {
  21906. zerostruct (noteStates);
  21907. }
  21908. MidiKeyboardState::~MidiKeyboardState()
  21909. {
  21910. }
  21911. void MidiKeyboardState::reset()
  21912. {
  21913. const ScopedLock sl (lock);
  21914. zerostruct (noteStates);
  21915. eventsToAdd.clear();
  21916. }
  21917. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21918. {
  21919. jassert (midiChannel >= 0 && midiChannel <= 16);
  21920. return ((unsigned int) n) < 128
  21921. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21922. }
  21923. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21924. {
  21925. return ((unsigned int) n) < 128
  21926. && (noteStates[n] & midiChannelMask) != 0;
  21927. }
  21928. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21929. {
  21930. jassert (midiChannel >= 0 && midiChannel <= 16);
  21931. jassert (((unsigned int) midiNoteNumber) < 128);
  21932. const ScopedLock sl (lock);
  21933. if (((unsigned int) midiNoteNumber) < 128)
  21934. {
  21935. const int timeNow = (int) Time::getMillisecondCounter();
  21936. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21937. eventsToAdd.clear (0, timeNow - 500);
  21938. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21939. }
  21940. }
  21941. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21942. {
  21943. if (((unsigned int) midiNoteNumber) < 128)
  21944. {
  21945. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21946. for (int i = listeners.size(); --i >= 0;)
  21947. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21948. }
  21949. }
  21950. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21951. {
  21952. const ScopedLock sl (lock);
  21953. if (isNoteOn (midiChannel, midiNoteNumber))
  21954. {
  21955. const int timeNow = (int) Time::getMillisecondCounter();
  21956. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21957. eventsToAdd.clear (0, timeNow - 500);
  21958. noteOffInternal (midiChannel, midiNoteNumber);
  21959. }
  21960. }
  21961. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21962. {
  21963. if (isNoteOn (midiChannel, midiNoteNumber))
  21964. {
  21965. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21966. for (int i = listeners.size(); --i >= 0;)
  21967. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  21968. }
  21969. }
  21970. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21971. {
  21972. const ScopedLock sl (lock);
  21973. if (midiChannel <= 0)
  21974. {
  21975. for (int i = 1; i <= 16; ++i)
  21976. allNotesOff (i);
  21977. }
  21978. else
  21979. {
  21980. for (int i = 0; i < 128; ++i)
  21981. noteOff (midiChannel, i);
  21982. }
  21983. }
  21984. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21985. {
  21986. if (message.isNoteOn())
  21987. {
  21988. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21989. }
  21990. else if (message.isNoteOff())
  21991. {
  21992. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21993. }
  21994. else if (message.isAllNotesOff())
  21995. {
  21996. for (int i = 0; i < 128; ++i)
  21997. noteOffInternal (message.getChannel(), i);
  21998. }
  21999. }
  22000. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22001. const int startSample,
  22002. const int numSamples,
  22003. const bool injectIndirectEvents)
  22004. {
  22005. MidiBuffer::Iterator i (buffer);
  22006. MidiMessage message (0xf4, 0.0);
  22007. int time;
  22008. const ScopedLock sl (lock);
  22009. while (i.getNextEvent (message, time))
  22010. processNextMidiEvent (message);
  22011. if (injectIndirectEvents)
  22012. {
  22013. MidiBuffer::Iterator i2 (eventsToAdd);
  22014. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22015. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22016. while (i2.getNextEvent (message, time))
  22017. {
  22018. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22019. buffer.addEvent (message, startSample + pos);
  22020. }
  22021. }
  22022. eventsToAdd.clear();
  22023. }
  22024. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22025. {
  22026. const ScopedLock sl (lock);
  22027. listeners.addIfNotAlreadyThere (listener);
  22028. }
  22029. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22030. {
  22031. const ScopedLock sl (lock);
  22032. listeners.removeValue (listener);
  22033. }
  22034. END_JUCE_NAMESPACE
  22035. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22036. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22037. BEGIN_JUCE_NAMESPACE
  22038. int MidiMessage::readVariableLengthVal (const uint8* data,
  22039. int& numBytesUsed) throw()
  22040. {
  22041. numBytesUsed = 0;
  22042. int v = 0;
  22043. int i;
  22044. do
  22045. {
  22046. i = (int) *data++;
  22047. if (++numBytesUsed > 6)
  22048. break;
  22049. v = (v << 7) + (i & 0x7f);
  22050. } while (i & 0x80);
  22051. return v;
  22052. }
  22053. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22054. {
  22055. // this method only works for valid starting bytes of a short midi message
  22056. jassert (firstByte >= 0x80
  22057. && firstByte != 0xf0
  22058. && firstByte != 0xf7);
  22059. static const char messageLengths[] =
  22060. {
  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. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22064. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22065. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22066. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22067. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22068. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22069. };
  22070. return messageLengths [firstByte & 0x7f];
  22071. }
  22072. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22073. : timeStamp (t),
  22074. size (dataSize)
  22075. {
  22076. jassert (dataSize > 0);
  22077. if (dataSize <= 4)
  22078. data = static_cast<uint8*> (preallocatedData.asBytes);
  22079. else
  22080. data = new uint8 [dataSize];
  22081. memcpy (data, d, dataSize);
  22082. // check that the length matches the data..
  22083. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22084. }
  22085. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22086. : timeStamp (t),
  22087. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22088. size (1)
  22089. {
  22090. data[0] = (uint8) byte1;
  22091. // check that the length matches the data..
  22092. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22093. }
  22094. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22095. : timeStamp (t),
  22096. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22097. size (2)
  22098. {
  22099. data[0] = (uint8) byte1;
  22100. data[1] = (uint8) byte2;
  22101. // check that the length matches the data..
  22102. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22103. }
  22104. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22105. : timeStamp (t),
  22106. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22107. size (3)
  22108. {
  22109. data[0] = (uint8) byte1;
  22110. data[1] = (uint8) byte2;
  22111. data[2] = (uint8) byte3;
  22112. // check that the length matches the data..
  22113. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22114. }
  22115. MidiMessage::MidiMessage (const MidiMessage& other)
  22116. : timeStamp (other.timeStamp),
  22117. size (other.size)
  22118. {
  22119. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22120. {
  22121. data = new uint8 [size];
  22122. memcpy (data, other.data, size);
  22123. }
  22124. else
  22125. {
  22126. data = static_cast<uint8*> (preallocatedData.asBytes);
  22127. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22128. }
  22129. }
  22130. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22131. : timeStamp (newTimeStamp),
  22132. size (other.size)
  22133. {
  22134. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22135. {
  22136. data = new uint8 [size];
  22137. memcpy (data, other.data, size);
  22138. }
  22139. else
  22140. {
  22141. data = static_cast<uint8*> (preallocatedData.asBytes);
  22142. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22143. }
  22144. }
  22145. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22146. : timeStamp (t),
  22147. data (static_cast<uint8*> (preallocatedData.asBytes))
  22148. {
  22149. const uint8* src = static_cast <const uint8*> (src_);
  22150. unsigned int byte = (unsigned int) *src;
  22151. if (byte < 0x80)
  22152. {
  22153. byte = (unsigned int) (uint8) lastStatusByte;
  22154. numBytesUsed = -1;
  22155. }
  22156. else
  22157. {
  22158. numBytesUsed = 0;
  22159. --sz;
  22160. ++src;
  22161. }
  22162. if (byte >= 0x80)
  22163. {
  22164. if (byte == 0xf0)
  22165. {
  22166. const uint8* d = src;
  22167. while (d < src + sz)
  22168. {
  22169. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22170. {
  22171. if (*d == 0xf7) // include an 0xf7 if we hit one
  22172. ++d;
  22173. break;
  22174. }
  22175. ++d;
  22176. }
  22177. size = 1 + (int) (d - src);
  22178. data = new uint8 [size];
  22179. *data = (uint8) byte;
  22180. memcpy (data + 1, src, size - 1);
  22181. }
  22182. else if (byte == 0xff)
  22183. {
  22184. int n;
  22185. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22186. size = jmin (sz + 1, n + 2 + bytesLeft);
  22187. data = new uint8 [size];
  22188. *data = (uint8) byte;
  22189. memcpy (data + 1, src, size - 1);
  22190. }
  22191. else
  22192. {
  22193. preallocatedData.asInt32 = 0;
  22194. size = getMessageLengthFromFirstByte ((uint8) byte);
  22195. data[0] = (uint8) byte;
  22196. if (size > 1)
  22197. {
  22198. data[1] = src[0];
  22199. if (size > 2)
  22200. data[2] = src[1];
  22201. }
  22202. }
  22203. numBytesUsed += size;
  22204. }
  22205. else
  22206. {
  22207. preallocatedData.asInt32 = 0;
  22208. size = 0;
  22209. }
  22210. }
  22211. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22212. {
  22213. if (this != &other)
  22214. {
  22215. timeStamp = other.timeStamp;
  22216. size = other.size;
  22217. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22218. delete[] data;
  22219. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22220. {
  22221. data = new uint8 [size];
  22222. memcpy (data, other.data, size);
  22223. }
  22224. else
  22225. {
  22226. data = static_cast<uint8*> (preallocatedData.asBytes);
  22227. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22228. }
  22229. }
  22230. return *this;
  22231. }
  22232. MidiMessage::~MidiMessage()
  22233. {
  22234. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22235. delete[] data;
  22236. }
  22237. int MidiMessage::getChannel() const throw()
  22238. {
  22239. if ((data[0] & 0xf0) != 0xf0)
  22240. return (data[0] & 0xf) + 1;
  22241. else
  22242. return 0;
  22243. }
  22244. bool MidiMessage::isForChannel (const int channel) const throw()
  22245. {
  22246. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22247. return ((data[0] & 0xf) == channel - 1)
  22248. && ((data[0] & 0xf0) != 0xf0);
  22249. }
  22250. void MidiMessage::setChannel (const int channel) throw()
  22251. {
  22252. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22253. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22254. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22255. | (uint8)(channel - 1));
  22256. }
  22257. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22258. {
  22259. return ((data[0] & 0xf0) == 0x90)
  22260. && (returnTrueForVelocity0 || data[2] != 0);
  22261. }
  22262. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22263. {
  22264. return ((data[0] & 0xf0) == 0x80)
  22265. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22266. }
  22267. bool MidiMessage::isNoteOnOrOff() const throw()
  22268. {
  22269. const int d = data[0] & 0xf0;
  22270. return (d == 0x90) || (d == 0x80);
  22271. }
  22272. int MidiMessage::getNoteNumber() const throw()
  22273. {
  22274. return data[1];
  22275. }
  22276. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22277. {
  22278. if (isNoteOnOrOff())
  22279. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22280. }
  22281. uint8 MidiMessage::getVelocity() const throw()
  22282. {
  22283. if (isNoteOnOrOff())
  22284. return data[2];
  22285. else
  22286. return 0;
  22287. }
  22288. float MidiMessage::getFloatVelocity() const throw()
  22289. {
  22290. return getVelocity() * (1.0f / 127.0f);
  22291. }
  22292. void MidiMessage::setVelocity (const float newVelocity) throw()
  22293. {
  22294. if (isNoteOnOrOff())
  22295. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22296. }
  22297. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22298. {
  22299. if (isNoteOnOrOff())
  22300. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22301. }
  22302. bool MidiMessage::isAftertouch() const throw()
  22303. {
  22304. return (data[0] & 0xf0) == 0xa0;
  22305. }
  22306. int MidiMessage::getAfterTouchValue() const throw()
  22307. {
  22308. return data[2];
  22309. }
  22310. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22311. const int noteNum,
  22312. const int aftertouchValue) throw()
  22313. {
  22314. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22315. jassert (((unsigned int) noteNum) <= 127);
  22316. jassert (((unsigned int) aftertouchValue) <= 127);
  22317. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22318. noteNum & 0x7f,
  22319. aftertouchValue & 0x7f);
  22320. }
  22321. bool MidiMessage::isChannelPressure() const throw()
  22322. {
  22323. return (data[0] & 0xf0) == 0xd0;
  22324. }
  22325. int MidiMessage::getChannelPressureValue() const throw()
  22326. {
  22327. jassert (isChannelPressure());
  22328. return data[1];
  22329. }
  22330. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22331. const int pressure) throw()
  22332. {
  22333. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22334. jassert (((unsigned int) pressure) <= 127);
  22335. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22336. pressure & 0x7f);
  22337. }
  22338. bool MidiMessage::isProgramChange() const throw()
  22339. {
  22340. return (data[0] & 0xf0) == 0xc0;
  22341. }
  22342. int MidiMessage::getProgramChangeNumber() const throw()
  22343. {
  22344. return data[1];
  22345. }
  22346. const MidiMessage MidiMessage::programChange (const int channel,
  22347. const int programNumber) throw()
  22348. {
  22349. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22350. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22351. programNumber & 0x7f);
  22352. }
  22353. bool MidiMessage::isPitchWheel() const throw()
  22354. {
  22355. return (data[0] & 0xf0) == 0xe0;
  22356. }
  22357. int MidiMessage::getPitchWheelValue() const throw()
  22358. {
  22359. return data[1] | (data[2] << 7);
  22360. }
  22361. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22362. const int position) throw()
  22363. {
  22364. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22365. jassert (((unsigned int) position) <= 0x3fff);
  22366. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22367. position & 127,
  22368. (position >> 7) & 127);
  22369. }
  22370. bool MidiMessage::isController() const throw()
  22371. {
  22372. return (data[0] & 0xf0) == 0xb0;
  22373. }
  22374. int MidiMessage::getControllerNumber() const throw()
  22375. {
  22376. jassert (isController());
  22377. return data[1];
  22378. }
  22379. int MidiMessage::getControllerValue() const throw()
  22380. {
  22381. jassert (isController());
  22382. return data[2];
  22383. }
  22384. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22385. const int controllerType,
  22386. const int value) throw()
  22387. {
  22388. // the channel must be between 1 and 16 inclusive
  22389. jassert (channel > 0 && channel <= 16);
  22390. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22391. controllerType & 127,
  22392. value & 127);
  22393. }
  22394. const MidiMessage MidiMessage::noteOn (const int channel,
  22395. const int noteNumber,
  22396. const float velocity) throw()
  22397. {
  22398. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22399. }
  22400. const MidiMessage MidiMessage::noteOn (const int channel,
  22401. const int noteNumber,
  22402. const uint8 velocity) throw()
  22403. {
  22404. jassert (channel > 0 && channel <= 16);
  22405. jassert (((unsigned int) noteNumber) <= 127);
  22406. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22407. noteNumber & 127,
  22408. jlimit (0, 127, roundToInt (velocity)));
  22409. }
  22410. const MidiMessage MidiMessage::noteOff (const int channel,
  22411. const int noteNumber) throw()
  22412. {
  22413. jassert (channel > 0 && channel <= 16);
  22414. jassert (((unsigned int) noteNumber) <= 127);
  22415. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22416. }
  22417. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22418. {
  22419. jassert (channel > 0 && channel <= 16);
  22420. return controllerEvent (channel, 123, 0);
  22421. }
  22422. bool MidiMessage::isAllNotesOff() const throw()
  22423. {
  22424. return (data[0] & 0xf0) == 0xb0
  22425. && data[1] == 123;
  22426. }
  22427. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22428. {
  22429. return controllerEvent (channel, 120, 0);
  22430. }
  22431. bool MidiMessage::isAllSoundOff() const throw()
  22432. {
  22433. return (data[0] & 0xf0) == 0xb0
  22434. && data[1] == 120;
  22435. }
  22436. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22437. {
  22438. return controllerEvent (channel, 121, 0);
  22439. }
  22440. const MidiMessage MidiMessage::masterVolume (const float volume)
  22441. {
  22442. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22443. uint8 buf[8];
  22444. buf[0] = 0xf0;
  22445. buf[1] = 0x7f;
  22446. buf[2] = 0x7f;
  22447. buf[3] = 0x04;
  22448. buf[4] = 0x01;
  22449. buf[5] = (uint8) (vol & 0x7f);
  22450. buf[6] = (uint8) (vol >> 7);
  22451. buf[7] = 0xf7;
  22452. return MidiMessage (buf, 8);
  22453. }
  22454. bool MidiMessage::isSysEx() const throw()
  22455. {
  22456. return *data == 0xf0;
  22457. }
  22458. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22459. {
  22460. MemoryBlock mm (dataSize + 2);
  22461. uint8* const m = static_cast <uint8*> (mm.getData());
  22462. m[0] = 0xf0;
  22463. memcpy (m + 1, sysexData, dataSize);
  22464. m[dataSize + 1] = 0xf7;
  22465. return MidiMessage (m, dataSize + 2);
  22466. }
  22467. const uint8* MidiMessage::getSysExData() const throw()
  22468. {
  22469. return (isSysEx()) ? getRawData() + 1 : 0;
  22470. }
  22471. int MidiMessage::getSysExDataSize() const throw()
  22472. {
  22473. return (isSysEx()) ? size - 2 : 0;
  22474. }
  22475. bool MidiMessage::isMetaEvent() const throw()
  22476. {
  22477. return *data == 0xff;
  22478. }
  22479. bool MidiMessage::isActiveSense() const throw()
  22480. {
  22481. return *data == 0xfe;
  22482. }
  22483. int MidiMessage::getMetaEventType() const throw()
  22484. {
  22485. if (*data != 0xff)
  22486. return -1;
  22487. else
  22488. return data[1];
  22489. }
  22490. int MidiMessage::getMetaEventLength() const throw()
  22491. {
  22492. if (*data == 0xff)
  22493. {
  22494. int n;
  22495. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22496. }
  22497. return 0;
  22498. }
  22499. const uint8* MidiMessage::getMetaEventData() const throw()
  22500. {
  22501. int n;
  22502. const uint8* d = data + 2;
  22503. readVariableLengthVal (d, n);
  22504. return d + n;
  22505. }
  22506. bool MidiMessage::isTrackMetaEvent() const throw()
  22507. {
  22508. return getMetaEventType() == 0;
  22509. }
  22510. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22511. {
  22512. return getMetaEventType() == 47;
  22513. }
  22514. bool MidiMessage::isTextMetaEvent() const throw()
  22515. {
  22516. const int t = getMetaEventType();
  22517. return t > 0 && t < 16;
  22518. }
  22519. const String MidiMessage::getTextFromTextMetaEvent() const
  22520. {
  22521. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22522. }
  22523. bool MidiMessage::isTrackNameEvent() const throw()
  22524. {
  22525. return (data[1] == 3)
  22526. && (*data == 0xff);
  22527. }
  22528. bool MidiMessage::isTempoMetaEvent() const throw()
  22529. {
  22530. return (data[1] == 81)
  22531. && (*data == 0xff);
  22532. }
  22533. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22534. {
  22535. return (data[1] == 0x20)
  22536. && (*data == 0xff)
  22537. && (data[2] == 1);
  22538. }
  22539. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22540. {
  22541. return data[3] + 1;
  22542. }
  22543. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22544. {
  22545. if (! isTempoMetaEvent())
  22546. return 0.0;
  22547. const uint8* const d = getMetaEventData();
  22548. return (((unsigned int) d[0] << 16)
  22549. | ((unsigned int) d[1] << 8)
  22550. | d[2])
  22551. / 1000000.0;
  22552. }
  22553. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22554. {
  22555. if (timeFormat > 0)
  22556. {
  22557. if (! isTempoMetaEvent())
  22558. return 0.5 / timeFormat;
  22559. return getTempoSecondsPerQuarterNote() / timeFormat;
  22560. }
  22561. else
  22562. {
  22563. const int frameCode = (-timeFormat) >> 8;
  22564. double framesPerSecond;
  22565. switch (frameCode)
  22566. {
  22567. case 24: framesPerSecond = 24.0; break;
  22568. case 25: framesPerSecond = 25.0; break;
  22569. case 29: framesPerSecond = 29.97; break;
  22570. case 30: framesPerSecond = 30.0; break;
  22571. default: framesPerSecond = 30.0; break;
  22572. }
  22573. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22574. }
  22575. }
  22576. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22577. {
  22578. uint8 d[8];
  22579. d[0] = 0xff;
  22580. d[1] = 81;
  22581. d[2] = 3;
  22582. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22583. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22584. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22585. return MidiMessage (d, 6, 0.0);
  22586. }
  22587. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22588. {
  22589. return (data[1] == 0x58)
  22590. && (*data == (uint8) 0xff);
  22591. }
  22592. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22593. {
  22594. if (isTimeSignatureMetaEvent())
  22595. {
  22596. const uint8* const d = getMetaEventData();
  22597. numerator = d[0];
  22598. denominator = 1 << d[1];
  22599. }
  22600. else
  22601. {
  22602. numerator = 4;
  22603. denominator = 4;
  22604. }
  22605. }
  22606. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22607. {
  22608. uint8 d[8];
  22609. d[0] = 0xff;
  22610. d[1] = 0x58;
  22611. d[2] = 0x04;
  22612. d[3] = (uint8) numerator;
  22613. int n = 1;
  22614. int powerOfTwo = 0;
  22615. while (n < denominator)
  22616. {
  22617. n <<= 1;
  22618. ++powerOfTwo;
  22619. }
  22620. d[4] = (uint8) powerOfTwo;
  22621. d[5] = 0x01;
  22622. d[6] = 96;
  22623. return MidiMessage (d, 7, 0.0);
  22624. }
  22625. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22626. {
  22627. uint8 d[8];
  22628. d[0] = 0xff;
  22629. d[1] = 0x20;
  22630. d[2] = 0x01;
  22631. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22632. return MidiMessage (d, 4, 0.0);
  22633. }
  22634. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22635. {
  22636. return getMetaEventType() == 89;
  22637. }
  22638. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22639. {
  22640. return (int) *getMetaEventData();
  22641. }
  22642. const MidiMessage MidiMessage::endOfTrack() throw()
  22643. {
  22644. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22645. }
  22646. bool MidiMessage::isSongPositionPointer() const throw()
  22647. {
  22648. return *data == 0xf2;
  22649. }
  22650. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22651. {
  22652. return data[1] | (data[2] << 7);
  22653. }
  22654. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22655. {
  22656. return MidiMessage (0xf2,
  22657. positionInMidiBeats & 127,
  22658. (positionInMidiBeats >> 7) & 127);
  22659. }
  22660. bool MidiMessage::isMidiStart() const throw()
  22661. {
  22662. return *data == 0xfa;
  22663. }
  22664. const MidiMessage MidiMessage::midiStart() throw()
  22665. {
  22666. return MidiMessage (0xfa);
  22667. }
  22668. bool MidiMessage::isMidiContinue() const throw()
  22669. {
  22670. return *data == 0xfb;
  22671. }
  22672. const MidiMessage MidiMessage::midiContinue() throw()
  22673. {
  22674. return MidiMessage (0xfb);
  22675. }
  22676. bool MidiMessage::isMidiStop() const throw()
  22677. {
  22678. return *data == 0xfc;
  22679. }
  22680. const MidiMessage MidiMessage::midiStop() throw()
  22681. {
  22682. return MidiMessage (0xfc);
  22683. }
  22684. bool MidiMessage::isMidiClock() const throw()
  22685. {
  22686. return *data == 0xf8;
  22687. }
  22688. const MidiMessage MidiMessage::midiClock() throw()
  22689. {
  22690. return MidiMessage (0xf8);
  22691. }
  22692. bool MidiMessage::isQuarterFrame() const throw()
  22693. {
  22694. return *data == 0xf1;
  22695. }
  22696. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22697. {
  22698. return ((int) data[1]) >> 4;
  22699. }
  22700. int MidiMessage::getQuarterFrameValue() const throw()
  22701. {
  22702. return ((int) data[1]) & 0x0f;
  22703. }
  22704. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22705. const int value) throw()
  22706. {
  22707. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22708. }
  22709. bool MidiMessage::isFullFrame() const throw()
  22710. {
  22711. return data[0] == 0xf0
  22712. && data[1] == 0x7f
  22713. && size >= 10
  22714. && data[3] == 0x01
  22715. && data[4] == 0x01;
  22716. }
  22717. void MidiMessage::getFullFrameParameters (int& hours,
  22718. int& minutes,
  22719. int& seconds,
  22720. int& frames,
  22721. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22722. {
  22723. jassert (isFullFrame());
  22724. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22725. hours = data[5] & 0x1f;
  22726. minutes = data[6];
  22727. seconds = data[7];
  22728. frames = data[8];
  22729. }
  22730. const MidiMessage MidiMessage::fullFrame (const int hours,
  22731. const int minutes,
  22732. const int seconds,
  22733. const int frames,
  22734. MidiMessage::SmpteTimecodeType timecodeType)
  22735. {
  22736. uint8 d[10];
  22737. d[0] = 0xf0;
  22738. d[1] = 0x7f;
  22739. d[2] = 0x7f;
  22740. d[3] = 0x01;
  22741. d[4] = 0x01;
  22742. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22743. d[6] = (uint8) minutes;
  22744. d[7] = (uint8) seconds;
  22745. d[8] = (uint8) frames;
  22746. d[9] = 0xf7;
  22747. return MidiMessage (d, 10, 0.0);
  22748. }
  22749. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22750. {
  22751. return data[0] == 0xf0
  22752. && data[1] == 0x7f
  22753. && data[3] == 0x06
  22754. && size > 5;
  22755. }
  22756. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22757. {
  22758. jassert (isMidiMachineControlMessage());
  22759. return (MidiMachineControlCommand) data[4];
  22760. }
  22761. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22762. {
  22763. uint8 d[6];
  22764. d[0] = 0xf0;
  22765. d[1] = 0x7f;
  22766. d[2] = 0x00;
  22767. d[3] = 0x06;
  22768. d[4] = (uint8) command;
  22769. d[5] = 0xf7;
  22770. return MidiMessage (d, 6, 0.0);
  22771. }
  22772. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22773. int& minutes,
  22774. int& seconds,
  22775. int& frames) const throw()
  22776. {
  22777. if (size >= 12
  22778. && data[0] == 0xf0
  22779. && data[1] == 0x7f
  22780. && data[3] == 0x06
  22781. && data[4] == 0x44
  22782. && data[5] == 0x06
  22783. && data[6] == 0x01)
  22784. {
  22785. hours = data[7] % 24; // (that some machines send out hours > 24)
  22786. minutes = data[8];
  22787. seconds = data[9];
  22788. frames = data[10];
  22789. return true;
  22790. }
  22791. return false;
  22792. }
  22793. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22794. int minutes,
  22795. int seconds,
  22796. int frames)
  22797. {
  22798. uint8 d[12];
  22799. d[0] = 0xf0;
  22800. d[1] = 0x7f;
  22801. d[2] = 0x00;
  22802. d[3] = 0x06;
  22803. d[4] = 0x44;
  22804. d[5] = 0x06;
  22805. d[6] = 0x01;
  22806. d[7] = (uint8) hours;
  22807. d[8] = (uint8) minutes;
  22808. d[9] = (uint8) seconds;
  22809. d[10] = (uint8) frames;
  22810. d[11] = 0xf7;
  22811. return MidiMessage (d, 12, 0.0);
  22812. }
  22813. const String MidiMessage::getMidiNoteName (int note,
  22814. bool useSharps,
  22815. bool includeOctaveNumber,
  22816. int octaveNumForMiddleC) throw()
  22817. {
  22818. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22819. "F", "F#", "G", "G#", "A",
  22820. "A#", "B" };
  22821. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22822. "F", "Gb", "G", "Ab", "A",
  22823. "Bb", "B" };
  22824. if (((unsigned int) note) < 128)
  22825. {
  22826. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22827. : flatNoteNames [note % 12]);
  22828. if (includeOctaveNumber)
  22829. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22830. else
  22831. return s;
  22832. }
  22833. return String::empty;
  22834. }
  22835. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22836. {
  22837. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22838. return 440.0 * pow (2.0, noteNumber / 12.0);
  22839. }
  22840. const String MidiMessage::getGMInstrumentName (int n) throw()
  22841. {
  22842. const char *names[] =
  22843. {
  22844. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22845. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22846. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22847. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22848. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22849. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22850. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22851. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22852. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22853. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22854. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22855. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22856. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22857. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22858. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22859. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22860. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22861. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22862. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22863. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22864. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22865. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22866. "Applause", "Gunshot"
  22867. };
  22868. return (((unsigned int) n) < 128) ? names[n]
  22869. : (const char*)0;
  22870. }
  22871. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22872. {
  22873. const char* names[] =
  22874. {
  22875. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22876. "Bass", "Strings", "Ensemble", "Brass",
  22877. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22878. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22879. };
  22880. return (((unsigned int) n) <= 15) ? names[n]
  22881. : (const char*)0;
  22882. }
  22883. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22884. {
  22885. const char* names[] =
  22886. {
  22887. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22888. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22889. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22890. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22891. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22892. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22893. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22894. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22895. "Mute Triangle", "Open Triangle"
  22896. };
  22897. return (n >= 35 && n <= 81) ? names [n - 35]
  22898. : (const char*)0;
  22899. }
  22900. const String MidiMessage::getControllerName (int n) throw()
  22901. {
  22902. const char* names[] =
  22903. {
  22904. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22905. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22906. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22907. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22908. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22909. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22910. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22911. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22912. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22913. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22914. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22915. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22916. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22917. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22918. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22919. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22920. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22921. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22922. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22924. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22925. "Poly Operation"
  22926. };
  22927. return (((unsigned int) n) < 128) ? names[n]
  22928. : (const char*)0;
  22929. }
  22930. END_JUCE_NAMESPACE
  22931. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22932. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22933. BEGIN_JUCE_NAMESPACE
  22934. MidiMessageCollector::MidiMessageCollector()
  22935. : lastCallbackTime (0),
  22936. sampleRate (44100.0001)
  22937. {
  22938. }
  22939. MidiMessageCollector::~MidiMessageCollector()
  22940. {
  22941. }
  22942. void MidiMessageCollector::reset (const double sampleRate_)
  22943. {
  22944. jassert (sampleRate_ > 0);
  22945. const ScopedLock sl (midiCallbackLock);
  22946. sampleRate = sampleRate_;
  22947. incomingMessages.clear();
  22948. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22949. }
  22950. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22951. {
  22952. // you need to call reset() to set the correct sample rate before using this object
  22953. jassert (sampleRate != 44100.0001);
  22954. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22955. // for details of what the number should be.
  22956. jassert (message.getTimeStamp() != 0);
  22957. const ScopedLock sl (midiCallbackLock);
  22958. const int sampleNumber
  22959. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22960. incomingMessages.addEvent (message, sampleNumber);
  22961. // if the messages don't get used for over a second, we'd better
  22962. // get rid of any old ones to avoid the queue getting too big
  22963. if (sampleNumber > sampleRate)
  22964. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22965. }
  22966. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22967. const int numSamples)
  22968. {
  22969. // you need to call reset() to set the correct sample rate before using this object
  22970. jassert (sampleRate != 44100.0001);
  22971. const double timeNow = Time::getMillisecondCounterHiRes();
  22972. const double msElapsed = timeNow - lastCallbackTime;
  22973. const ScopedLock sl (midiCallbackLock);
  22974. lastCallbackTime = timeNow;
  22975. if (! incomingMessages.isEmpty())
  22976. {
  22977. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  22978. int startSample = 0;
  22979. int scale = 1 << 16;
  22980. const uint8* midiData;
  22981. int numBytes, samplePosition;
  22982. MidiBuffer::Iterator iter (incomingMessages);
  22983. if (numSourceSamples > numSamples)
  22984. {
  22985. // if our list of events is longer than the buffer we're being
  22986. // asked for, scale them down to squeeze them all in..
  22987. const int maxBlockLengthToUse = numSamples << 5;
  22988. if (numSourceSamples > maxBlockLengthToUse)
  22989. {
  22990. startSample = numSourceSamples - maxBlockLengthToUse;
  22991. numSourceSamples = maxBlockLengthToUse;
  22992. iter.setNextSamplePosition (startSample);
  22993. }
  22994. scale = (numSamples << 10) / numSourceSamples;
  22995. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22996. {
  22997. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22998. destBuffer.addEvent (midiData, numBytes,
  22999. jlimit (0, numSamples - 1, samplePosition));
  23000. }
  23001. }
  23002. else
  23003. {
  23004. // if our event list is shorter than the number we need, put them
  23005. // towards the end of the buffer
  23006. startSample = numSamples - numSourceSamples;
  23007. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23008. {
  23009. destBuffer.addEvent (midiData, numBytes,
  23010. jlimit (0, numSamples - 1, samplePosition + startSample));
  23011. }
  23012. }
  23013. incomingMessages.clear();
  23014. }
  23015. }
  23016. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23017. {
  23018. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23019. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23020. addMessageToQueue (m);
  23021. }
  23022. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23023. {
  23024. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23025. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23026. addMessageToQueue (m);
  23027. }
  23028. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23029. {
  23030. addMessageToQueue (message);
  23031. }
  23032. END_JUCE_NAMESPACE
  23033. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23034. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23035. BEGIN_JUCE_NAMESPACE
  23036. MidiMessageSequence::MidiMessageSequence()
  23037. {
  23038. }
  23039. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23040. {
  23041. list.ensureStorageAllocated (other.list.size());
  23042. for (int i = 0; i < other.list.size(); ++i)
  23043. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23044. }
  23045. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23046. {
  23047. MidiMessageSequence otherCopy (other);
  23048. swapWith (otherCopy);
  23049. return *this;
  23050. }
  23051. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23052. {
  23053. list.swapWithArray (other.list);
  23054. }
  23055. MidiMessageSequence::~MidiMessageSequence()
  23056. {
  23057. }
  23058. void MidiMessageSequence::clear()
  23059. {
  23060. list.clear();
  23061. }
  23062. int MidiMessageSequence::getNumEvents() const
  23063. {
  23064. return list.size();
  23065. }
  23066. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23067. {
  23068. return list [index];
  23069. }
  23070. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23071. {
  23072. const MidiEventHolder* const meh = list [index];
  23073. if (meh != 0 && meh->noteOffObject != 0)
  23074. return meh->noteOffObject->message.getTimeStamp();
  23075. else
  23076. return 0.0;
  23077. }
  23078. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23079. {
  23080. const MidiEventHolder* const meh = list [index];
  23081. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23082. }
  23083. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23084. {
  23085. return list.indexOf (event);
  23086. }
  23087. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23088. {
  23089. const int numEvents = list.size();
  23090. int i;
  23091. for (i = 0; i < numEvents; ++i)
  23092. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23093. break;
  23094. return i;
  23095. }
  23096. double MidiMessageSequence::getStartTime() const
  23097. {
  23098. if (list.size() > 0)
  23099. return list.getUnchecked(0)->message.getTimeStamp();
  23100. else
  23101. return 0;
  23102. }
  23103. double MidiMessageSequence::getEndTime() const
  23104. {
  23105. if (list.size() > 0)
  23106. return list.getLast()->message.getTimeStamp();
  23107. else
  23108. return 0;
  23109. }
  23110. double MidiMessageSequence::getEventTime (const int index) const
  23111. {
  23112. if (((unsigned int) index) < (unsigned int) list.size())
  23113. return list.getUnchecked (index)->message.getTimeStamp();
  23114. return 0.0;
  23115. }
  23116. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23117. double timeAdjustment)
  23118. {
  23119. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23120. timeAdjustment += newMessage.getTimeStamp();
  23121. newOne->message.setTimeStamp (timeAdjustment);
  23122. int i;
  23123. for (i = list.size(); --i >= 0;)
  23124. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23125. break;
  23126. list.insert (i + 1, newOne);
  23127. }
  23128. void MidiMessageSequence::deleteEvent (const int index,
  23129. const bool deleteMatchingNoteUp)
  23130. {
  23131. if (((unsigned int) index) < (unsigned int) list.size())
  23132. {
  23133. if (deleteMatchingNoteUp)
  23134. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23135. list.remove (index);
  23136. }
  23137. }
  23138. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23139. double timeAdjustment,
  23140. double firstAllowableTime,
  23141. double endOfAllowableDestTimes)
  23142. {
  23143. firstAllowableTime -= timeAdjustment;
  23144. endOfAllowableDestTimes -= timeAdjustment;
  23145. for (int i = 0; i < other.list.size(); ++i)
  23146. {
  23147. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23148. const double t = m.getTimeStamp();
  23149. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23150. {
  23151. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23152. newOne->message.setTimeStamp (timeAdjustment + t);
  23153. list.add (newOne);
  23154. }
  23155. }
  23156. sort();
  23157. }
  23158. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23159. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23160. {
  23161. const double diff = first->message.getTimeStamp()
  23162. - second->message.getTimeStamp();
  23163. return (diff > 0) - (diff < 0);
  23164. }
  23165. void MidiMessageSequence::sort()
  23166. {
  23167. list.sort (*this, true);
  23168. }
  23169. void MidiMessageSequence::updateMatchedPairs()
  23170. {
  23171. for (int i = 0; i < list.size(); ++i)
  23172. {
  23173. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23174. if (m1.isNoteOn())
  23175. {
  23176. list.getUnchecked(i)->noteOffObject = 0;
  23177. const int note = m1.getNoteNumber();
  23178. const int chan = m1.getChannel();
  23179. const int len = list.size();
  23180. for (int j = i + 1; j < len; ++j)
  23181. {
  23182. const MidiMessage& m = list.getUnchecked(j)->message;
  23183. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23184. {
  23185. if (m.isNoteOff())
  23186. {
  23187. list.getUnchecked(i)->noteOffObject = list[j];
  23188. break;
  23189. }
  23190. else if (m.isNoteOn())
  23191. {
  23192. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23193. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23194. list.getUnchecked(i)->noteOffObject = list[j];
  23195. break;
  23196. }
  23197. }
  23198. }
  23199. }
  23200. }
  23201. }
  23202. void MidiMessageSequence::addTimeToMessages (const double delta)
  23203. {
  23204. for (int i = list.size(); --i >= 0;)
  23205. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23206. + delta);
  23207. }
  23208. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23209. MidiMessageSequence& destSequence,
  23210. const bool alsoIncludeMetaEvents) const
  23211. {
  23212. for (int i = 0; i < list.size(); ++i)
  23213. {
  23214. const MidiMessage& mm = list.getUnchecked(i)->message;
  23215. if (mm.isForChannel (channelNumberToExtract)
  23216. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23217. {
  23218. destSequence.addEvent (mm);
  23219. }
  23220. }
  23221. }
  23222. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23223. {
  23224. for (int i = 0; i < list.size(); ++i)
  23225. {
  23226. const MidiMessage& mm = list.getUnchecked(i)->message;
  23227. if (mm.isSysEx())
  23228. destSequence.addEvent (mm);
  23229. }
  23230. }
  23231. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23232. {
  23233. for (int i = list.size(); --i >= 0;)
  23234. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23235. list.remove(i);
  23236. }
  23237. void MidiMessageSequence::deleteSysExMessages()
  23238. {
  23239. for (int i = list.size(); --i >= 0;)
  23240. if (list.getUnchecked(i)->message.isSysEx())
  23241. list.remove(i);
  23242. }
  23243. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23244. const double time,
  23245. OwnedArray<MidiMessage>& dest)
  23246. {
  23247. bool doneProg = false;
  23248. bool donePitchWheel = false;
  23249. Array <int> doneControllers;
  23250. doneControllers.ensureStorageAllocated (32);
  23251. for (int i = list.size(); --i >= 0;)
  23252. {
  23253. const MidiMessage& mm = list.getUnchecked(i)->message;
  23254. if (mm.isForChannel (channelNumber)
  23255. && mm.getTimeStamp() <= time)
  23256. {
  23257. if (mm.isProgramChange())
  23258. {
  23259. if (! doneProg)
  23260. {
  23261. dest.add (new MidiMessage (mm, 0.0));
  23262. doneProg = true;
  23263. }
  23264. }
  23265. else if (mm.isController())
  23266. {
  23267. if (! doneControllers.contains (mm.getControllerNumber()))
  23268. {
  23269. dest.add (new MidiMessage (mm, 0.0));
  23270. doneControllers.add (mm.getControllerNumber());
  23271. }
  23272. }
  23273. else if (mm.isPitchWheel())
  23274. {
  23275. if (! donePitchWheel)
  23276. {
  23277. dest.add (new MidiMessage (mm, 0.0));
  23278. donePitchWheel = true;
  23279. }
  23280. }
  23281. }
  23282. }
  23283. }
  23284. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23285. : message (message_),
  23286. noteOffObject (0)
  23287. {
  23288. }
  23289. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23290. {
  23291. }
  23292. END_JUCE_NAMESPACE
  23293. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23294. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23295. BEGIN_JUCE_NAMESPACE
  23296. AudioPluginFormat::AudioPluginFormat() throw()
  23297. {
  23298. }
  23299. AudioPluginFormat::~AudioPluginFormat()
  23300. {
  23301. }
  23302. END_JUCE_NAMESPACE
  23303. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23304. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23305. BEGIN_JUCE_NAMESPACE
  23306. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23307. {
  23308. }
  23309. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23310. {
  23311. clearSingletonInstance();
  23312. }
  23313. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23314. void AudioPluginFormatManager::addDefaultFormats()
  23315. {
  23316. #if JUCE_DEBUG
  23317. // you should only call this method once!
  23318. for (int i = formats.size(); --i >= 0;)
  23319. {
  23320. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23321. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23322. #endif
  23323. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23324. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23325. #endif
  23326. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23327. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23328. #endif
  23329. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23330. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23331. #endif
  23332. }
  23333. #endif
  23334. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23335. formats.add (new AudioUnitPluginFormat());
  23336. #endif
  23337. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23338. formats.add (new VSTPluginFormat());
  23339. #endif
  23340. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23341. formats.add (new DirectXPluginFormat());
  23342. #endif
  23343. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23344. formats.add (new LADSPAPluginFormat());
  23345. #endif
  23346. }
  23347. int AudioPluginFormatManager::getNumFormats() throw()
  23348. {
  23349. return formats.size();
  23350. }
  23351. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23352. {
  23353. return formats [index];
  23354. }
  23355. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23356. {
  23357. formats.add (format);
  23358. }
  23359. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23360. String& errorMessage) const
  23361. {
  23362. AudioPluginInstance* result = 0;
  23363. for (int i = 0; i < formats.size(); ++i)
  23364. {
  23365. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23366. if (result != 0)
  23367. break;
  23368. }
  23369. if (result == 0)
  23370. {
  23371. if (! doesPluginStillExist (description))
  23372. errorMessage = TRANS ("This plug-in file no longer exists");
  23373. else
  23374. errorMessage = TRANS ("This plug-in failed to load correctly");
  23375. }
  23376. return result;
  23377. }
  23378. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23379. {
  23380. for (int i = 0; i < formats.size(); ++i)
  23381. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23382. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23383. return false;
  23384. }
  23385. END_JUCE_NAMESPACE
  23386. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23387. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23388. #define JUCE_PLUGIN_HOST 1
  23389. BEGIN_JUCE_NAMESPACE
  23390. AudioPluginInstance::AudioPluginInstance()
  23391. {
  23392. }
  23393. AudioPluginInstance::~AudioPluginInstance()
  23394. {
  23395. }
  23396. END_JUCE_NAMESPACE
  23397. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23398. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23399. BEGIN_JUCE_NAMESPACE
  23400. KnownPluginList::KnownPluginList()
  23401. {
  23402. }
  23403. KnownPluginList::~KnownPluginList()
  23404. {
  23405. }
  23406. void KnownPluginList::clear()
  23407. {
  23408. if (types.size() > 0)
  23409. {
  23410. types.clear();
  23411. sendChangeMessage (this);
  23412. }
  23413. }
  23414. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23415. {
  23416. for (int i = 0; i < types.size(); ++i)
  23417. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23418. return types.getUnchecked(i);
  23419. return 0;
  23420. }
  23421. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23422. {
  23423. for (int i = 0; i < types.size(); ++i)
  23424. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23425. return types.getUnchecked(i);
  23426. return 0;
  23427. }
  23428. bool KnownPluginList::addType (const PluginDescription& type)
  23429. {
  23430. for (int i = types.size(); --i >= 0;)
  23431. {
  23432. if (types.getUnchecked(i)->isDuplicateOf (type))
  23433. {
  23434. // strange - found a duplicate plugin with different info..
  23435. jassert (types.getUnchecked(i)->name == type.name);
  23436. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23437. *types.getUnchecked(i) = type;
  23438. return false;
  23439. }
  23440. }
  23441. types.add (new PluginDescription (type));
  23442. sendChangeMessage (this);
  23443. return true;
  23444. }
  23445. void KnownPluginList::removeType (const int index) throw()
  23446. {
  23447. types.remove (index);
  23448. sendChangeMessage (this);
  23449. }
  23450. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23451. {
  23452. if (fileOrIdentifier.startsWithChar ('/')
  23453. || fileOrIdentifier[1] == ':')
  23454. {
  23455. return File (fileOrIdentifier).getLastModificationTime();
  23456. }
  23457. return Time (0);
  23458. }
  23459. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23460. {
  23461. return t1 != t2 || t1 == Time (0);
  23462. }
  23463. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23464. {
  23465. if (getTypeForFile (fileOrIdentifier) == 0)
  23466. return false;
  23467. for (int i = types.size(); --i >= 0;)
  23468. {
  23469. const PluginDescription* const d = types.getUnchecked(i);
  23470. if (d->fileOrIdentifier == fileOrIdentifier
  23471. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23472. {
  23473. return false;
  23474. }
  23475. }
  23476. return true;
  23477. }
  23478. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23479. const bool dontRescanIfAlreadyInList,
  23480. OwnedArray <PluginDescription>& typesFound,
  23481. AudioPluginFormat& format)
  23482. {
  23483. bool addedOne = false;
  23484. if (dontRescanIfAlreadyInList
  23485. && getTypeForFile (fileOrIdentifier) != 0)
  23486. {
  23487. bool needsRescanning = false;
  23488. for (int i = types.size(); --i >= 0;)
  23489. {
  23490. const PluginDescription* const d = types.getUnchecked(i);
  23491. if (d->fileOrIdentifier == fileOrIdentifier)
  23492. {
  23493. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23494. needsRescanning = true;
  23495. else
  23496. typesFound.add (new PluginDescription (*d));
  23497. }
  23498. }
  23499. if (! needsRescanning)
  23500. return false;
  23501. }
  23502. OwnedArray <PluginDescription> found;
  23503. format.findAllTypesForFile (found, fileOrIdentifier);
  23504. for (int i = 0; i < found.size(); ++i)
  23505. {
  23506. PluginDescription* const desc = found.getUnchecked(i);
  23507. jassert (desc != 0);
  23508. if (addType (*desc))
  23509. addedOne = true;
  23510. typesFound.add (new PluginDescription (*desc));
  23511. }
  23512. return addedOne;
  23513. }
  23514. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23515. OwnedArray <PluginDescription>& typesFound)
  23516. {
  23517. for (int i = 0; i < files.size(); ++i)
  23518. {
  23519. bool loaded = false;
  23520. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23521. {
  23522. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23523. if (scanAndAddFile (files[i], true, typesFound, *format))
  23524. loaded = true;
  23525. }
  23526. if (! loaded)
  23527. {
  23528. const File f (files[i]);
  23529. if (f.isDirectory())
  23530. {
  23531. StringArray s;
  23532. {
  23533. Array<File> subFiles;
  23534. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23535. for (int j = 0; j < subFiles.size(); ++j)
  23536. s.add (subFiles.getReference(j).getFullPathName());
  23537. }
  23538. scanAndAddDragAndDroppedFiles (s, typesFound);
  23539. }
  23540. }
  23541. }
  23542. }
  23543. class PluginSorter
  23544. {
  23545. public:
  23546. KnownPluginList::SortMethod method;
  23547. PluginSorter() throw() {}
  23548. int compareElements (const PluginDescription* const first,
  23549. const PluginDescription* const second) const throw()
  23550. {
  23551. int diff = 0;
  23552. if (method == KnownPluginList::sortByCategory)
  23553. diff = first->category.compareLexicographically (second->category);
  23554. else if (method == KnownPluginList::sortByManufacturer)
  23555. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23556. else if (method == KnownPluginList::sortByFileSystemLocation)
  23557. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23558. .upToLastOccurrenceOf ("/", false, false)
  23559. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23560. .upToLastOccurrenceOf ("/", false, false));
  23561. if (diff == 0)
  23562. diff = first->name.compareLexicographically (second->name);
  23563. return diff;
  23564. }
  23565. };
  23566. void KnownPluginList::sort (const SortMethod method)
  23567. {
  23568. if (method != defaultOrder)
  23569. {
  23570. PluginSorter sorter;
  23571. sorter.method = method;
  23572. types.sort (sorter, true);
  23573. sendChangeMessage (this);
  23574. }
  23575. }
  23576. XmlElement* KnownPluginList::createXml() const
  23577. {
  23578. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23579. for (int i = 0; i < types.size(); ++i)
  23580. e->addChildElement (types.getUnchecked(i)->createXml());
  23581. return e;
  23582. }
  23583. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23584. {
  23585. clear();
  23586. if (xml.hasTagName ("KNOWNPLUGINS"))
  23587. {
  23588. forEachXmlChildElement (xml, e)
  23589. {
  23590. PluginDescription info;
  23591. if (info.loadFromXml (*e))
  23592. addType (info);
  23593. }
  23594. }
  23595. }
  23596. const int menuIdBase = 0x324503f4;
  23597. // This is used to turn a bunch of paths into a nested menu structure.
  23598. struct PluginFilesystemTree
  23599. {
  23600. private:
  23601. String folder;
  23602. OwnedArray <PluginFilesystemTree> subFolders;
  23603. Array <PluginDescription*> plugins;
  23604. void addPlugin (PluginDescription* const pd, const String& path)
  23605. {
  23606. if (path.isEmpty())
  23607. {
  23608. plugins.add (pd);
  23609. }
  23610. else
  23611. {
  23612. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23613. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23614. for (int i = subFolders.size(); --i >= 0;)
  23615. {
  23616. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23617. {
  23618. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23619. return;
  23620. }
  23621. }
  23622. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23623. newFolder->folder = firstSubFolder;
  23624. subFolders.add (newFolder);
  23625. newFolder->addPlugin (pd, remainingPath);
  23626. }
  23627. }
  23628. // removes any deeply nested folders that don't contain any actual plugins
  23629. void optimise()
  23630. {
  23631. for (int i = subFolders.size(); --i >= 0;)
  23632. {
  23633. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23634. sub->optimise();
  23635. if (sub->plugins.size() == 0)
  23636. {
  23637. for (int j = 0; j < sub->subFolders.size(); ++j)
  23638. subFolders.add (sub->subFolders.getUnchecked(j));
  23639. sub->subFolders.clear (false);
  23640. subFolders.remove (i);
  23641. }
  23642. }
  23643. }
  23644. public:
  23645. void buildTree (const Array <PluginDescription*>& allPlugins)
  23646. {
  23647. for (int i = 0; i < allPlugins.size(); ++i)
  23648. {
  23649. String path (allPlugins.getUnchecked(i)
  23650. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23651. .upToLastOccurrenceOf ("/", false, false));
  23652. if (path.substring (1, 2) == ":")
  23653. path = path.substring (2);
  23654. addPlugin (allPlugins.getUnchecked(i), path);
  23655. }
  23656. optimise();
  23657. }
  23658. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23659. {
  23660. int i;
  23661. for (i = 0; i < subFolders.size(); ++i)
  23662. {
  23663. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23664. PopupMenu subMenu;
  23665. sub->addToMenu (subMenu, allPlugins);
  23666. #if JUCE_MAC
  23667. // avoid the special AU formatting nonsense on Mac..
  23668. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23669. #else
  23670. m.addSubMenu (sub->folder, subMenu);
  23671. #endif
  23672. }
  23673. for (i = 0; i < plugins.size(); ++i)
  23674. {
  23675. PluginDescription* const plugin = plugins.getUnchecked(i);
  23676. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23677. plugin->name, true, false);
  23678. }
  23679. }
  23680. };
  23681. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23682. {
  23683. Array <PluginDescription*> sorted;
  23684. {
  23685. PluginSorter sorter;
  23686. sorter.method = sortMethod;
  23687. for (int i = 0; i < types.size(); ++i)
  23688. sorted.addSorted (sorter, types.getUnchecked(i));
  23689. }
  23690. if (sortMethod == sortByCategory
  23691. || sortMethod == sortByManufacturer)
  23692. {
  23693. String lastSubMenuName;
  23694. PopupMenu sub;
  23695. for (int i = 0; i < sorted.size(); ++i)
  23696. {
  23697. const PluginDescription* const pd = sorted.getUnchecked(i);
  23698. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23699. : pd->manufacturerName);
  23700. if (! thisSubMenuName.containsNonWhitespaceChars())
  23701. thisSubMenuName = "Other";
  23702. if (thisSubMenuName != lastSubMenuName)
  23703. {
  23704. if (sub.getNumItems() > 0)
  23705. {
  23706. menu.addSubMenu (lastSubMenuName, sub);
  23707. sub.clear();
  23708. }
  23709. lastSubMenuName = thisSubMenuName;
  23710. }
  23711. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23712. }
  23713. if (sub.getNumItems() > 0)
  23714. menu.addSubMenu (lastSubMenuName, sub);
  23715. }
  23716. else if (sortMethod == sortByFileSystemLocation)
  23717. {
  23718. PluginFilesystemTree root;
  23719. root.buildTree (sorted);
  23720. root.addToMenu (menu, types);
  23721. }
  23722. else
  23723. {
  23724. for (int i = 0; i < sorted.size(); ++i)
  23725. {
  23726. const PluginDescription* const pd = sorted.getUnchecked(i);
  23727. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23728. }
  23729. }
  23730. }
  23731. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23732. {
  23733. const int i = menuResultCode - menuIdBase;
  23734. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23735. }
  23736. END_JUCE_NAMESPACE
  23737. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23738. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23739. BEGIN_JUCE_NAMESPACE
  23740. PluginDescription::PluginDescription() throw()
  23741. : uid (0),
  23742. isInstrument (false),
  23743. numInputChannels (0),
  23744. numOutputChannels (0)
  23745. {
  23746. }
  23747. PluginDescription::~PluginDescription() throw()
  23748. {
  23749. }
  23750. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23751. : name (other.name),
  23752. pluginFormatName (other.pluginFormatName),
  23753. category (other.category),
  23754. manufacturerName (other.manufacturerName),
  23755. version (other.version),
  23756. fileOrIdentifier (other.fileOrIdentifier),
  23757. lastFileModTime (other.lastFileModTime),
  23758. uid (other.uid),
  23759. isInstrument (other.isInstrument),
  23760. numInputChannels (other.numInputChannels),
  23761. numOutputChannels (other.numOutputChannels)
  23762. {
  23763. }
  23764. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23765. {
  23766. name = other.name;
  23767. pluginFormatName = other.pluginFormatName;
  23768. category = other.category;
  23769. manufacturerName = other.manufacturerName;
  23770. version = other.version;
  23771. fileOrIdentifier = other.fileOrIdentifier;
  23772. uid = other.uid;
  23773. isInstrument = other.isInstrument;
  23774. lastFileModTime = other.lastFileModTime;
  23775. numInputChannels = other.numInputChannels;
  23776. numOutputChannels = other.numOutputChannels;
  23777. return *this;
  23778. }
  23779. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23780. {
  23781. return fileOrIdentifier == other.fileOrIdentifier
  23782. && uid == other.uid;
  23783. }
  23784. const String PluginDescription::createIdentifierString() const throw()
  23785. {
  23786. return pluginFormatName
  23787. + "-" + name
  23788. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23789. + "-" + String::toHexString (uid);
  23790. }
  23791. XmlElement* PluginDescription::createXml() const
  23792. {
  23793. XmlElement* const e = new XmlElement ("PLUGIN");
  23794. e->setAttribute ("name", name);
  23795. e->setAttribute ("format", pluginFormatName);
  23796. e->setAttribute ("category", category);
  23797. e->setAttribute ("manufacturer", manufacturerName);
  23798. e->setAttribute ("version", version);
  23799. e->setAttribute ("file", fileOrIdentifier);
  23800. e->setAttribute ("uid", String::toHexString (uid));
  23801. e->setAttribute ("isInstrument", isInstrument);
  23802. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23803. e->setAttribute ("numInputs", numInputChannels);
  23804. e->setAttribute ("numOutputs", numOutputChannels);
  23805. return e;
  23806. }
  23807. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23808. {
  23809. if (xml.hasTagName ("PLUGIN"))
  23810. {
  23811. name = xml.getStringAttribute ("name");
  23812. pluginFormatName = xml.getStringAttribute ("format");
  23813. category = xml.getStringAttribute ("category");
  23814. manufacturerName = xml.getStringAttribute ("manufacturer");
  23815. version = xml.getStringAttribute ("version");
  23816. fileOrIdentifier = xml.getStringAttribute ("file");
  23817. uid = xml.getStringAttribute ("uid").getHexValue32();
  23818. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23819. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23820. numInputChannels = xml.getIntAttribute ("numInputs");
  23821. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23822. return true;
  23823. }
  23824. return false;
  23825. }
  23826. END_JUCE_NAMESPACE
  23827. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23828. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23829. BEGIN_JUCE_NAMESPACE
  23830. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23831. AudioPluginFormat& formatToLookFor,
  23832. FileSearchPath directoriesToSearch,
  23833. const bool recursive,
  23834. const File& deadMansPedalFile_)
  23835. : list (listToAddTo),
  23836. format (formatToLookFor),
  23837. deadMansPedalFile (deadMansPedalFile_),
  23838. nextIndex (0),
  23839. progress (0)
  23840. {
  23841. directoriesToSearch.removeRedundantPaths();
  23842. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23843. // If any plugins have crashed recently when being loaded, move them to the
  23844. // end of the list to give the others a chance to load correctly..
  23845. const StringArray crashedPlugins (getDeadMansPedalFile());
  23846. for (int i = 0; i < crashedPlugins.size(); ++i)
  23847. {
  23848. const String f = crashedPlugins[i];
  23849. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23850. if (f == filesOrIdentifiersToScan[j])
  23851. filesOrIdentifiersToScan.move (j, -1);
  23852. }
  23853. }
  23854. PluginDirectoryScanner::~PluginDirectoryScanner()
  23855. {
  23856. }
  23857. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23858. {
  23859. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23860. }
  23861. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23862. {
  23863. String file (filesOrIdentifiersToScan [nextIndex]);
  23864. if (file.isNotEmpty())
  23865. {
  23866. if (! list.isListingUpToDate (file))
  23867. {
  23868. OwnedArray <PluginDescription> typesFound;
  23869. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23870. StringArray crashedPlugins (getDeadMansPedalFile());
  23871. crashedPlugins.removeString (file);
  23872. crashedPlugins.add (file);
  23873. setDeadMansPedalFile (crashedPlugins);
  23874. list.scanAndAddFile (file,
  23875. dontRescanIfAlreadyInList,
  23876. typesFound,
  23877. format);
  23878. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23879. crashedPlugins.removeString (file);
  23880. setDeadMansPedalFile (crashedPlugins);
  23881. if (typesFound.size() == 0)
  23882. failedFiles.add (file);
  23883. }
  23884. ++nextIndex;
  23885. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23886. }
  23887. return nextIndex < filesOrIdentifiersToScan.size();
  23888. }
  23889. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23890. {
  23891. StringArray lines;
  23892. if (deadMansPedalFile != File::nonexistent)
  23893. {
  23894. lines.addLines (deadMansPedalFile.loadFileAsString());
  23895. lines.removeEmptyStrings();
  23896. }
  23897. return lines;
  23898. }
  23899. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23900. {
  23901. if (deadMansPedalFile != File::nonexistent)
  23902. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23903. }
  23904. END_JUCE_NAMESPACE
  23905. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23906. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23907. BEGIN_JUCE_NAMESPACE
  23908. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23909. const File& deadMansPedalFile_,
  23910. PropertiesFile* const propertiesToUse_)
  23911. : list (listToEdit),
  23912. deadMansPedalFile (deadMansPedalFile_),
  23913. propertiesToUse (propertiesToUse_)
  23914. {
  23915. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23916. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23917. optionsButton->addButtonListener (this);
  23918. optionsButton->setTriggeredOnMouseDown (true);
  23919. setSize (400, 600);
  23920. list.addChangeListener (this);
  23921. }
  23922. PluginListComponent::~PluginListComponent()
  23923. {
  23924. list.removeChangeListener (this);
  23925. deleteAllChildren();
  23926. }
  23927. void PluginListComponent::resized()
  23928. {
  23929. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23930. optionsButton->changeWidthToFitText (24);
  23931. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23932. }
  23933. void PluginListComponent::changeListenerCallback (void*)
  23934. {
  23935. listBox->updateContent();
  23936. listBox->repaint();
  23937. }
  23938. int PluginListComponent::getNumRows()
  23939. {
  23940. return list.getNumTypes();
  23941. }
  23942. void PluginListComponent::paintListBoxItem (int row,
  23943. Graphics& g,
  23944. int width, int height,
  23945. bool rowIsSelected)
  23946. {
  23947. if (rowIsSelected)
  23948. g.fillAll (findColour (TextEditor::highlightColourId));
  23949. const PluginDescription* const pd = list.getType (row);
  23950. if (pd != 0)
  23951. {
  23952. GlyphArrangement ga;
  23953. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23954. g.setColour (Colours::black);
  23955. ga.draw (g);
  23956. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23957. String desc;
  23958. desc << pd->pluginFormatName
  23959. << (pd->isInstrument ? " instrument" : " effect")
  23960. << " - "
  23961. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23962. << " / "
  23963. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23964. if (pd->manufacturerName.isNotEmpty())
  23965. desc << " - " << pd->manufacturerName;
  23966. if (pd->version.isNotEmpty())
  23967. desc << " - " << pd->version;
  23968. if (pd->category.isNotEmpty())
  23969. desc << " - category: '" << pd->category << '\'';
  23970. g.setColour (Colours::grey);
  23971. ga.clear();
  23972. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  23973. ga.draw (g);
  23974. }
  23975. }
  23976. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23977. {
  23978. list.removeType (lastRowSelected);
  23979. }
  23980. void PluginListComponent::buttonClicked (Button* b)
  23981. {
  23982. if (optionsButton == b)
  23983. {
  23984. PopupMenu menu;
  23985. menu.addItem (1, TRANS("Clear list"));
  23986. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23987. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23988. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23989. menu.addSeparator();
  23990. menu.addItem (2, TRANS("Sort alphabetically"));
  23991. menu.addItem (3, TRANS("Sort by category"));
  23992. menu.addItem (4, TRANS("Sort by manufacturer"));
  23993. menu.addSeparator();
  23994. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23995. {
  23996. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23997. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23998. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23999. }
  24000. const int r = menu.showAt (optionsButton);
  24001. if (r == 1)
  24002. {
  24003. list.clear();
  24004. }
  24005. else if (r == 2)
  24006. {
  24007. list.sort (KnownPluginList::sortAlphabetically);
  24008. }
  24009. else if (r == 3)
  24010. {
  24011. list.sort (KnownPluginList::sortByCategory);
  24012. }
  24013. else if (r == 4)
  24014. {
  24015. list.sort (KnownPluginList::sortByManufacturer);
  24016. }
  24017. else if (r == 5)
  24018. {
  24019. const SparseSet <int> selected (listBox->getSelectedRows());
  24020. for (int i = list.getNumTypes(); --i >= 0;)
  24021. if (selected.contains (i))
  24022. list.removeType (i);
  24023. }
  24024. else if (r == 6)
  24025. {
  24026. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24027. if (desc != 0)
  24028. {
  24029. if (File (desc->fileOrIdentifier).existsAsFile())
  24030. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24031. }
  24032. }
  24033. else if (r == 7)
  24034. {
  24035. for (int i = list.getNumTypes(); --i >= 0;)
  24036. {
  24037. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24038. {
  24039. list.removeType (i);
  24040. }
  24041. }
  24042. }
  24043. else if (r != 0)
  24044. {
  24045. typeToScan = r - 10;
  24046. startTimer (1);
  24047. }
  24048. }
  24049. }
  24050. void PluginListComponent::timerCallback()
  24051. {
  24052. stopTimer();
  24053. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24054. }
  24055. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24056. {
  24057. return true;
  24058. }
  24059. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24060. {
  24061. OwnedArray <PluginDescription> typesFound;
  24062. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24063. }
  24064. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24065. {
  24066. if (format == 0)
  24067. return;
  24068. FileSearchPath path (format->getDefaultLocationsToSearch());
  24069. if (propertiesToUse != 0)
  24070. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24071. {
  24072. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24073. FileSearchPathListComponent pathList;
  24074. pathList.setSize (500, 300);
  24075. pathList.setPath (path);
  24076. aw.addCustomComponent (&pathList);
  24077. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24078. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24079. if (aw.runModalLoop() == 0)
  24080. return;
  24081. path = pathList.getPath();
  24082. }
  24083. if (propertiesToUse != 0)
  24084. {
  24085. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24086. propertiesToUse->saveIfNeeded();
  24087. }
  24088. double progress = 0.0;
  24089. AlertWindow aw (TRANS("Scanning for plugins..."),
  24090. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24091. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24092. aw.addProgressBarComponent (progress);
  24093. aw.enterModalState();
  24094. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24095. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24096. for (;;)
  24097. {
  24098. aw.setMessage (TRANS("Testing:\n\n")
  24099. + scanner.getNextPluginFileThatWillBeScanned());
  24100. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24101. if (! scanner.scanNextFile (true))
  24102. break;
  24103. if (! aw.isCurrentlyModal())
  24104. break;
  24105. progress = scanner.getProgress();
  24106. }
  24107. if (scanner.getFailedFiles().size() > 0)
  24108. {
  24109. StringArray shortNames;
  24110. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24111. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24112. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24113. TRANS("Scan complete"),
  24114. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24115. + shortNames.joinIntoString (", "));
  24116. }
  24117. }
  24118. END_JUCE_NAMESPACE
  24119. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24120. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24121. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24122. #include <AudioUnit/AudioUnit.h>
  24123. #include <AudioUnit/AUCocoaUIView.h>
  24124. #include <CoreAudioKit/AUGenericView.h>
  24125. #if JUCE_SUPPORT_CARBON
  24126. #include <AudioToolbox/AudioUnitUtilities.h>
  24127. #include <AudioUnit/AudioUnitCarbonView.h>
  24128. #endif
  24129. BEGIN_JUCE_NAMESPACE
  24130. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24131. #endif
  24132. #if JUCE_MAC
  24133. // Change this to disable logging of various activities
  24134. #ifndef AU_LOGGING
  24135. #define AU_LOGGING 1
  24136. #endif
  24137. #if AU_LOGGING
  24138. #define log(a) Logger::writeToLog(a);
  24139. #else
  24140. #define log(a)
  24141. #endif
  24142. static int insideCallback = 0;
  24143. static const String osTypeToString (OSType type)
  24144. {
  24145. char s[4];
  24146. s[0] = (char) (((uint32) type) >> 24);
  24147. s[1] = (char) (((uint32) type) >> 16);
  24148. s[2] = (char) (((uint32) type) >> 8);
  24149. s[3] = (char) ((uint32) type);
  24150. return String (s, 4);
  24151. }
  24152. static OSType stringToOSType (const String& s1)
  24153. {
  24154. const String s (s1 + " ");
  24155. return (((OSType) (unsigned char) s[0]) << 24)
  24156. | (((OSType) (unsigned char) s[1]) << 16)
  24157. | (((OSType) (unsigned char) s[2]) << 8)
  24158. | ((OSType) (unsigned char) s[3]);
  24159. }
  24160. static const char* auIdentifierPrefix = "AudioUnit:";
  24161. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24162. {
  24163. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24164. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24165. String s (auIdentifierPrefix);
  24166. if (desc.componentType == kAudioUnitType_MusicDevice)
  24167. s << "Synths/";
  24168. else if (desc.componentType == kAudioUnitType_MusicEffect
  24169. || desc.componentType == kAudioUnitType_Effect)
  24170. s << "Effects/";
  24171. else if (desc.componentType == kAudioUnitType_Generator)
  24172. s << "Generators/";
  24173. else if (desc.componentType == kAudioUnitType_Panner)
  24174. s << "Panners/";
  24175. s << osTypeToString (desc.componentType) << ","
  24176. << osTypeToString (desc.componentSubType) << ","
  24177. << osTypeToString (desc.componentManufacturer);
  24178. return s;
  24179. }
  24180. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24181. {
  24182. Handle componentNameHandle = NewHandle (sizeof (void*));
  24183. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24184. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24185. {
  24186. ComponentDescription desc;
  24187. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24188. {
  24189. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24190. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24191. if (nameString != 0 && nameString[0] != 0)
  24192. {
  24193. const String all ((const char*) nameString + 1, nameString[0]);
  24194. DBG ("name: "+ all);
  24195. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24196. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24197. }
  24198. if (infoString != 0 && infoString[0] != 0)
  24199. {
  24200. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24201. }
  24202. if (name.isEmpty())
  24203. name = "<Unknown>";
  24204. }
  24205. DisposeHandle (componentNameHandle);
  24206. DisposeHandle (componentInfoHandle);
  24207. }
  24208. }
  24209. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24210. String& name, String& version, String& manufacturer)
  24211. {
  24212. zerostruct (desc);
  24213. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24214. {
  24215. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24216. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24217. StringArray tokens;
  24218. tokens.addTokens (s, ",", String::empty);
  24219. tokens.trim();
  24220. tokens.removeEmptyStrings();
  24221. if (tokens.size() == 3)
  24222. {
  24223. desc.componentType = stringToOSType (tokens[0]);
  24224. desc.componentSubType = stringToOSType (tokens[1]);
  24225. desc.componentManufacturer = stringToOSType (tokens[2]);
  24226. ComponentRecord* comp = FindNextComponent (0, &desc);
  24227. if (comp != 0)
  24228. {
  24229. getAUDetails (comp, name, manufacturer);
  24230. return true;
  24231. }
  24232. }
  24233. }
  24234. return false;
  24235. }
  24236. class AudioUnitPluginWindowCarbon;
  24237. class AudioUnitPluginWindowCocoa;
  24238. class AudioUnitPluginInstance : public AudioPluginInstance
  24239. {
  24240. public:
  24241. ~AudioUnitPluginInstance();
  24242. // AudioPluginInstance methods:
  24243. void fillInPluginDescription (PluginDescription& desc) const
  24244. {
  24245. desc.name = pluginName;
  24246. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  24247. desc.uid = ((int) componentDesc.componentType)
  24248. ^ ((int) componentDesc.componentSubType)
  24249. ^ ((int) componentDesc.componentManufacturer);
  24250. desc.lastFileModTime = 0;
  24251. desc.pluginFormatName = "AudioUnit";
  24252. desc.category = getCategory();
  24253. desc.manufacturerName = manufacturer;
  24254. desc.version = version;
  24255. desc.numInputChannels = getNumInputChannels();
  24256. desc.numOutputChannels = getNumOutputChannels();
  24257. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24258. }
  24259. const String getName() const { return pluginName; }
  24260. bool acceptsMidi() const { return wantsMidiMessages; }
  24261. bool producesMidi() const { return false; }
  24262. // AudioProcessor methods:
  24263. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24264. void releaseResources();
  24265. void processBlock (AudioSampleBuffer& buffer,
  24266. MidiBuffer& midiMessages);
  24267. AudioProcessorEditor* createEditor();
  24268. const String getInputChannelName (const int index) const;
  24269. bool isInputChannelStereoPair (int index) const;
  24270. const String getOutputChannelName (const int index) const;
  24271. bool isOutputChannelStereoPair (int index) const;
  24272. int getNumParameters();
  24273. float getParameter (int index);
  24274. void setParameter (int index, float newValue);
  24275. const String getParameterName (int index);
  24276. const String getParameterText (int index);
  24277. bool isParameterAutomatable (int index) const;
  24278. int getNumPrograms();
  24279. int getCurrentProgram();
  24280. void setCurrentProgram (int index);
  24281. const String getProgramName (int index);
  24282. void changeProgramName (int index, const String& newName);
  24283. void getStateInformation (MemoryBlock& destData);
  24284. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24285. void setStateInformation (const void* data, int sizeInBytes);
  24286. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24287. juce_UseDebuggingNewOperator
  24288. private:
  24289. friend class AudioUnitPluginWindowCarbon;
  24290. friend class AudioUnitPluginWindowCocoa;
  24291. friend class AudioUnitPluginFormat;
  24292. ComponentDescription componentDesc;
  24293. String pluginName, manufacturer, version;
  24294. String fileOrIdentifier;
  24295. CriticalSection lock;
  24296. bool initialised, wantsMidiMessages, wasPlaying;
  24297. HeapBlock <AudioBufferList> outputBufferList;
  24298. AudioTimeStamp timeStamp;
  24299. AudioSampleBuffer* currentBuffer;
  24300. AudioUnit audioUnit;
  24301. Array <int> parameterIds;
  24302. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24303. void initialise();
  24304. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24305. const AudioTimeStamp* inTimeStamp,
  24306. UInt32 inBusNumber,
  24307. UInt32 inNumberFrames,
  24308. AudioBufferList* ioData) const;
  24309. static OSStatus renderGetInputCallback (void* inRefCon,
  24310. AudioUnitRenderActionFlags* ioActionFlags,
  24311. const AudioTimeStamp* inTimeStamp,
  24312. UInt32 inBusNumber,
  24313. UInt32 inNumberFrames,
  24314. AudioBufferList* ioData)
  24315. {
  24316. return ((AudioUnitPluginInstance*) inRefCon)
  24317. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24318. }
  24319. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24320. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24321. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24322. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24323. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24324. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24325. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24326. {
  24327. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24328. }
  24329. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24330. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24331. Float64* outCurrentMeasureDownBeat)
  24332. {
  24333. return ((AudioUnitPluginInstance*) inHostUserData)
  24334. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24335. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24336. }
  24337. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24338. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24339. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24340. {
  24341. return ((AudioUnitPluginInstance*) inHostUserData)
  24342. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24343. outCurrentSampleInTimeLine, outIsCycling,
  24344. outCycleStartBeat, outCycleEndBeat);
  24345. }
  24346. void getNumChannels (int& numIns, int& numOuts)
  24347. {
  24348. numIns = 0;
  24349. numOuts = 0;
  24350. AUChannelInfo supportedChannels [128];
  24351. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24352. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24353. 0, supportedChannels, &supportedChannelsSize) == noErr
  24354. && supportedChannelsSize > 0)
  24355. {
  24356. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24357. {
  24358. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24359. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24360. }
  24361. }
  24362. else
  24363. {
  24364. // (this really means the plugin will take any number of ins/outs as long
  24365. // as they are the same)
  24366. numIns = numOuts = 2;
  24367. }
  24368. }
  24369. const String getCategory() const;
  24370. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24371. };
  24372. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24373. : fileOrIdentifier (fileOrIdentifier),
  24374. initialised (false),
  24375. wantsMidiMessages (false),
  24376. audioUnit (0),
  24377. currentBuffer (0)
  24378. {
  24379. try
  24380. {
  24381. ++insideCallback;
  24382. log ("Opening AU: " + fileOrIdentifier);
  24383. if (getComponentDescFromFile (fileOrIdentifier))
  24384. {
  24385. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24386. if (comp != 0)
  24387. {
  24388. audioUnit = (AudioUnit) OpenComponent (comp);
  24389. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24390. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24391. }
  24392. }
  24393. --insideCallback;
  24394. }
  24395. catch (...)
  24396. {
  24397. --insideCallback;
  24398. }
  24399. }
  24400. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24401. {
  24402. const ScopedLock sl (lock);
  24403. jassert (insideCallback == 0);
  24404. if (audioUnit != 0)
  24405. {
  24406. AudioUnitUninitialize (audioUnit);
  24407. CloseComponent (audioUnit);
  24408. audioUnit = 0;
  24409. }
  24410. }
  24411. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24412. {
  24413. zerostruct (componentDesc);
  24414. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24415. return true;
  24416. const File file (fileOrIdentifier);
  24417. if (! file.hasFileExtension (".component"))
  24418. return false;
  24419. const char* const utf8 = fileOrIdentifier.toUTF8();
  24420. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24421. strlen (utf8), file.isDirectory());
  24422. if (url != 0)
  24423. {
  24424. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24425. CFRelease (url);
  24426. if (bundleRef != 0)
  24427. {
  24428. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24429. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24430. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24431. if (pluginName.isEmpty())
  24432. pluginName = file.getFileNameWithoutExtension();
  24433. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24434. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24435. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24436. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24437. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24438. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24439. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24440. UseResFile (resFileId);
  24441. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24442. {
  24443. Handle h = Get1IndResource ('thng', i);
  24444. if (h != 0)
  24445. {
  24446. HLock (h);
  24447. const uint32* const types = (const uint32*) *h;
  24448. if (types[0] == kAudioUnitType_MusicDevice
  24449. || types[0] == kAudioUnitType_MusicEffect
  24450. || types[0] == kAudioUnitType_Effect
  24451. || types[0] == kAudioUnitType_Generator
  24452. || types[0] == kAudioUnitType_Panner)
  24453. {
  24454. componentDesc.componentType = types[0];
  24455. componentDesc.componentSubType = types[1];
  24456. componentDesc.componentManufacturer = types[2];
  24457. break;
  24458. }
  24459. HUnlock (h);
  24460. ReleaseResource (h);
  24461. }
  24462. }
  24463. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24464. CFRelease (bundleRef);
  24465. }
  24466. }
  24467. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24468. }
  24469. void AudioUnitPluginInstance::initialise()
  24470. {
  24471. if (initialised || audioUnit == 0)
  24472. return;
  24473. log ("Initialising AU: " + pluginName);
  24474. parameterIds.clear();
  24475. {
  24476. UInt32 paramListSize = 0;
  24477. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24478. 0, 0, &paramListSize);
  24479. if (paramListSize > 0)
  24480. {
  24481. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24482. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24483. 0, &parameterIds.getReference(0), &paramListSize);
  24484. }
  24485. }
  24486. {
  24487. AURenderCallbackStruct info;
  24488. zerostruct (info);
  24489. info.inputProcRefCon = this;
  24490. info.inputProc = renderGetInputCallback;
  24491. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24492. 0, &info, sizeof (info));
  24493. }
  24494. {
  24495. HostCallbackInfo info;
  24496. zerostruct (info);
  24497. info.hostUserData = this;
  24498. info.beatAndTempoProc = getBeatAndTempoCallback;
  24499. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24500. info.transportStateProc = getTransportStateCallback;
  24501. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24502. 0, &info, sizeof (info));
  24503. }
  24504. int numIns, numOuts;
  24505. getNumChannels (numIns, numOuts);
  24506. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24507. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24508. setLatencySamples (0);
  24509. }
  24510. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24511. int samplesPerBlockExpected)
  24512. {
  24513. initialise();
  24514. if (initialised)
  24515. {
  24516. int numIns, numOuts;
  24517. getNumChannels (numIns, numOuts);
  24518. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24519. Float64 latencySecs = 0.0;
  24520. UInt32 latencySize = sizeof (latencySecs);
  24521. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24522. 0, &latencySecs, &latencySize);
  24523. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24524. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24525. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24526. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24527. AudioStreamBasicDescription stream;
  24528. zerostruct (stream);
  24529. stream.mSampleRate = sampleRate_;
  24530. stream.mFormatID = kAudioFormatLinearPCM;
  24531. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24532. stream.mFramesPerPacket = 1;
  24533. stream.mBytesPerPacket = 4;
  24534. stream.mBytesPerFrame = 4;
  24535. stream.mBitsPerChannel = 32;
  24536. stream.mChannelsPerFrame = numIns;
  24537. OSStatus err = AudioUnitSetProperty (audioUnit,
  24538. kAudioUnitProperty_StreamFormat,
  24539. kAudioUnitScope_Input,
  24540. 0, &stream, sizeof (stream));
  24541. stream.mChannelsPerFrame = numOuts;
  24542. err = AudioUnitSetProperty (audioUnit,
  24543. kAudioUnitProperty_StreamFormat,
  24544. kAudioUnitScope_Output,
  24545. 0, &stream, sizeof (stream));
  24546. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24547. outputBufferList->mNumberBuffers = numOuts;
  24548. for (int i = numOuts; --i >= 0;)
  24549. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24550. zerostruct (timeStamp);
  24551. timeStamp.mSampleTime = 0;
  24552. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24553. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24554. currentBuffer = 0;
  24555. wasPlaying = false;
  24556. }
  24557. }
  24558. void AudioUnitPluginInstance::releaseResources()
  24559. {
  24560. if (initialised)
  24561. {
  24562. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24563. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24564. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24565. outputBufferList.free();
  24566. currentBuffer = 0;
  24567. }
  24568. }
  24569. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24570. const AudioTimeStamp* inTimeStamp,
  24571. UInt32 inBusNumber,
  24572. UInt32 inNumberFrames,
  24573. AudioBufferList* ioData) const
  24574. {
  24575. if (inBusNumber == 0
  24576. && currentBuffer != 0)
  24577. {
  24578. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24579. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24580. {
  24581. if (i < currentBuffer->getNumChannels())
  24582. {
  24583. memcpy (ioData->mBuffers[i].mData,
  24584. currentBuffer->getSampleData (i, 0),
  24585. sizeof (float) * inNumberFrames);
  24586. }
  24587. else
  24588. {
  24589. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24590. }
  24591. }
  24592. }
  24593. return noErr;
  24594. }
  24595. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24596. MidiBuffer& midiMessages)
  24597. {
  24598. const int numSamples = buffer.getNumSamples();
  24599. if (initialised)
  24600. {
  24601. AudioUnitRenderActionFlags flags = 0;
  24602. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24603. for (int i = getNumOutputChannels(); --i >= 0;)
  24604. {
  24605. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24606. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24607. }
  24608. currentBuffer = &buffer;
  24609. if (wantsMidiMessages)
  24610. {
  24611. const uint8* midiEventData;
  24612. int midiEventSize, midiEventPosition;
  24613. MidiBuffer::Iterator i (midiMessages);
  24614. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24615. {
  24616. if (midiEventSize <= 3)
  24617. MusicDeviceMIDIEvent (audioUnit,
  24618. midiEventData[0], midiEventData[1], midiEventData[2],
  24619. midiEventPosition);
  24620. else
  24621. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24622. }
  24623. midiMessages.clear();
  24624. }
  24625. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24626. 0, numSamples, outputBufferList);
  24627. timeStamp.mSampleTime += numSamples;
  24628. }
  24629. else
  24630. {
  24631. // Not initialised, so just bypass..
  24632. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24633. buffer.clear (i, 0, buffer.getNumSamples());
  24634. }
  24635. }
  24636. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24637. {
  24638. AudioPlayHead* const ph = getPlayHead();
  24639. AudioPlayHead::CurrentPositionInfo result;
  24640. if (ph != 0 && ph->getCurrentPosition (result))
  24641. {
  24642. if (outCurrentBeat != 0)
  24643. *outCurrentBeat = result.ppqPosition;
  24644. if (outCurrentTempo != 0)
  24645. *outCurrentTempo = result.bpm;
  24646. }
  24647. else
  24648. {
  24649. if (outCurrentBeat != 0)
  24650. *outCurrentBeat = 0;
  24651. if (outCurrentTempo != 0)
  24652. *outCurrentTempo = 120.0;
  24653. }
  24654. return noErr;
  24655. }
  24656. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24657. Float32* outTimeSig_Numerator,
  24658. UInt32* outTimeSig_Denominator,
  24659. Float64* outCurrentMeasureDownBeat) const
  24660. {
  24661. AudioPlayHead* const ph = getPlayHead();
  24662. AudioPlayHead::CurrentPositionInfo result;
  24663. if (ph != 0 && ph->getCurrentPosition (result))
  24664. {
  24665. if (outTimeSig_Numerator != 0)
  24666. *outTimeSig_Numerator = result.timeSigNumerator;
  24667. if (outTimeSig_Denominator != 0)
  24668. *outTimeSig_Denominator = result.timeSigDenominator;
  24669. if (outDeltaSampleOffsetToNextBeat != 0)
  24670. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24671. if (outCurrentMeasureDownBeat != 0)
  24672. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24673. }
  24674. else
  24675. {
  24676. if (outDeltaSampleOffsetToNextBeat != 0)
  24677. *outDeltaSampleOffsetToNextBeat = 0;
  24678. if (outTimeSig_Numerator != 0)
  24679. *outTimeSig_Numerator = 4;
  24680. if (outTimeSig_Denominator != 0)
  24681. *outTimeSig_Denominator = 4;
  24682. if (outCurrentMeasureDownBeat != 0)
  24683. *outCurrentMeasureDownBeat = 0;
  24684. }
  24685. return noErr;
  24686. }
  24687. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24688. Boolean* outTransportStateChanged,
  24689. Float64* outCurrentSampleInTimeLine,
  24690. Boolean* outIsCycling,
  24691. Float64* outCycleStartBeat,
  24692. Float64* outCycleEndBeat)
  24693. {
  24694. AudioPlayHead* const ph = getPlayHead();
  24695. AudioPlayHead::CurrentPositionInfo result;
  24696. if (ph != 0 && ph->getCurrentPosition (result))
  24697. {
  24698. if (outIsPlaying != 0)
  24699. *outIsPlaying = result.isPlaying;
  24700. if (outTransportStateChanged != 0)
  24701. {
  24702. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24703. wasPlaying = result.isPlaying;
  24704. }
  24705. if (outCurrentSampleInTimeLine != 0)
  24706. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24707. if (outIsCycling != 0)
  24708. *outIsCycling = false;
  24709. if (outCycleStartBeat != 0)
  24710. *outCycleStartBeat = 0;
  24711. if (outCycleEndBeat != 0)
  24712. *outCycleEndBeat = 0;
  24713. }
  24714. else
  24715. {
  24716. if (outIsPlaying != 0)
  24717. *outIsPlaying = false;
  24718. if (outTransportStateChanged != 0)
  24719. *outTransportStateChanged = false;
  24720. if (outCurrentSampleInTimeLine != 0)
  24721. *outCurrentSampleInTimeLine = 0;
  24722. if (outIsCycling != 0)
  24723. *outIsCycling = false;
  24724. if (outCycleStartBeat != 0)
  24725. *outCycleStartBeat = 0;
  24726. if (outCycleEndBeat != 0)
  24727. *outCycleEndBeat = 0;
  24728. }
  24729. return noErr;
  24730. }
  24731. static VoidArray activeWindows;
  24732. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24733. {
  24734. public:
  24735. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24736. : AudioProcessorEditor (&plugin_),
  24737. plugin (plugin_),
  24738. wrapper (0)
  24739. {
  24740. addAndMakeVisible (wrapper = new NSViewComponent());
  24741. activeWindows.add (this);
  24742. setOpaque (true);
  24743. setVisible (true);
  24744. setSize (100, 100);
  24745. createView (createGenericViewIfNeeded);
  24746. }
  24747. ~AudioUnitPluginWindowCocoa()
  24748. {
  24749. const bool wasValid = isValid();
  24750. wrapper->setView (0);
  24751. activeWindows.removeValue (this);
  24752. if (wasValid)
  24753. plugin.editorBeingDeleted (this);
  24754. delete wrapper;
  24755. }
  24756. bool isValid() const { return wrapper->getView() != 0; }
  24757. void paint (Graphics& g)
  24758. {
  24759. g.fillAll (Colours::white);
  24760. }
  24761. void resized()
  24762. {
  24763. wrapper->setSize (getWidth(), getHeight());
  24764. }
  24765. private:
  24766. AudioUnitPluginInstance& plugin;
  24767. NSViewComponent* wrapper;
  24768. bool createView (const bool createGenericViewIfNeeded)
  24769. {
  24770. NSView* pluginView = 0;
  24771. UInt32 dataSize = 0;
  24772. Boolean isWritable = false;
  24773. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24774. 0, &dataSize, &isWritable) == noErr
  24775. && dataSize != 0
  24776. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24777. 0, &dataSize, &isWritable) == noErr)
  24778. {
  24779. HeapBlock <AudioUnitCocoaViewInfo> info;
  24780. info.calloc (dataSize, 1);
  24781. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24782. 0, info, &dataSize) == noErr)
  24783. {
  24784. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24785. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24786. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24787. Class viewClass = [viewBundle classNamed: viewClassName];
  24788. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24789. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24790. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24791. {
  24792. id factory = [[[viewClass alloc] init] autorelease];
  24793. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24794. withSize: NSMakeSize (getWidth(), getHeight())];
  24795. }
  24796. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24797. {
  24798. CFRelease (info->mCocoaAUViewClass[i]);
  24799. CFRelease (info->mCocoaAUViewBundleLocation);
  24800. }
  24801. }
  24802. }
  24803. if (createGenericViewIfNeeded && (pluginView == 0))
  24804. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24805. wrapper->setView (pluginView);
  24806. if (pluginView != 0)
  24807. setSize ([pluginView frame].size.width,
  24808. [pluginView frame].size.height);
  24809. return pluginView != 0;
  24810. }
  24811. };
  24812. #if JUCE_SUPPORT_CARBON
  24813. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24814. {
  24815. public:
  24816. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24817. : AudioProcessorEditor (&plugin_),
  24818. plugin (plugin_),
  24819. viewComponent (0)
  24820. {
  24821. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24822. activeWindows.add (this);
  24823. setOpaque (true);
  24824. setVisible (true);
  24825. setSize (400, 300);
  24826. ComponentDescription viewList [16];
  24827. UInt32 viewListSize = sizeof (viewList);
  24828. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24829. 0, &viewList, &viewListSize);
  24830. componentRecord = FindNextComponent (0, &viewList[0]);
  24831. }
  24832. ~AudioUnitPluginWindowCarbon()
  24833. {
  24834. innerWrapper = 0;
  24835. activeWindows.removeValue (this);
  24836. if (isValid())
  24837. plugin.editorBeingDeleted (this);
  24838. }
  24839. bool isValid() const throw() { return componentRecord != 0; }
  24840. void paint (Graphics& g)
  24841. {
  24842. g.fillAll (Colours::black);
  24843. }
  24844. void resized()
  24845. {
  24846. innerWrapper->setSize (getWidth(), getHeight());
  24847. }
  24848. bool keyStateChanged (bool)
  24849. {
  24850. return false;
  24851. }
  24852. bool keyPressed (const KeyPress&)
  24853. {
  24854. return false;
  24855. }
  24856. void broughtToFront()
  24857. {
  24858. activeWindows.removeValue (this);
  24859. activeWindows.add (this);
  24860. }
  24861. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24862. AudioUnitCarbonView getViewComponent()
  24863. {
  24864. if (viewComponent == 0 && componentRecord != 0)
  24865. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24866. return viewComponent;
  24867. }
  24868. void closeViewComponent()
  24869. {
  24870. if (viewComponent != 0)
  24871. {
  24872. CloseComponent (viewComponent);
  24873. viewComponent = 0;
  24874. }
  24875. }
  24876. juce_UseDebuggingNewOperator
  24877. private:
  24878. AudioUnitPluginInstance& plugin;
  24879. ComponentRecord* componentRecord;
  24880. AudioUnitCarbonView viewComponent;
  24881. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24882. {
  24883. public:
  24884. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24885. : owner (owner_)
  24886. {
  24887. }
  24888. ~InnerWrapperComponent()
  24889. {
  24890. deleteWindow();
  24891. }
  24892. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24893. {
  24894. log ("Opening AU GUI: " + owner->plugin.getName());
  24895. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24896. if (viewComponent == 0)
  24897. return 0;
  24898. Float32Point pos = { 0, 0 };
  24899. Float32Point size = { 250, 200 };
  24900. HIViewRef pluginView = 0;
  24901. AudioUnitCarbonViewCreate (viewComponent,
  24902. owner->getAudioUnit(),
  24903. windowRef,
  24904. rootView,
  24905. &pos,
  24906. &size,
  24907. (ControlRef*) &pluginView);
  24908. return pluginView;
  24909. }
  24910. void removeView (HIViewRef)
  24911. {
  24912. log ("Closing AU GUI: " + owner->plugin.getName());
  24913. owner->closeViewComponent();
  24914. }
  24915. private:
  24916. AudioUnitPluginWindowCarbon* const owner;
  24917. };
  24918. friend class InnerWrapperComponent;
  24919. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24920. };
  24921. #endif
  24922. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24923. {
  24924. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24925. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24926. w = 0;
  24927. #if JUCE_SUPPORT_CARBON
  24928. if (w == 0)
  24929. {
  24930. w = new AudioUnitPluginWindowCarbon (*this);
  24931. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24932. w = 0;
  24933. }
  24934. #endif
  24935. if (w == 0)
  24936. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24937. return w.release();
  24938. }
  24939. const String AudioUnitPluginInstance::getCategory() const
  24940. {
  24941. const char* result = 0;
  24942. switch (componentDesc.componentType)
  24943. {
  24944. case kAudioUnitType_Effect:
  24945. case kAudioUnitType_MusicEffect:
  24946. result = "Effect";
  24947. break;
  24948. case kAudioUnitType_MusicDevice:
  24949. result = "Synth";
  24950. break;
  24951. case kAudioUnitType_Generator:
  24952. result = "Generator";
  24953. break;
  24954. case kAudioUnitType_Panner:
  24955. result = "Panner";
  24956. break;
  24957. default:
  24958. break;
  24959. }
  24960. return result;
  24961. }
  24962. int AudioUnitPluginInstance::getNumParameters()
  24963. {
  24964. return parameterIds.size();
  24965. }
  24966. float AudioUnitPluginInstance::getParameter (int index)
  24967. {
  24968. const ScopedLock sl (lock);
  24969. Float32 value = 0.0f;
  24970. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24971. {
  24972. AudioUnitGetParameter (audioUnit,
  24973. (UInt32) parameterIds.getUnchecked (index),
  24974. kAudioUnitScope_Global, 0,
  24975. &value);
  24976. }
  24977. return value;
  24978. }
  24979. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24980. {
  24981. const ScopedLock sl (lock);
  24982. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24983. {
  24984. AudioUnitSetParameter (audioUnit,
  24985. (UInt32) parameterIds.getUnchecked (index),
  24986. kAudioUnitScope_Global, 0,
  24987. newValue, 0);
  24988. }
  24989. }
  24990. const String AudioUnitPluginInstance::getParameterName (int index)
  24991. {
  24992. AudioUnitParameterInfo info;
  24993. zerostruct (info);
  24994. UInt32 sz = sizeof (info);
  24995. String name;
  24996. if (AudioUnitGetProperty (audioUnit,
  24997. kAudioUnitProperty_ParameterInfo,
  24998. kAudioUnitScope_Global,
  24999. parameterIds [index], &info, &sz) == noErr)
  25000. {
  25001. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25002. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25003. else
  25004. name = String (info.name, sizeof (info.name));
  25005. }
  25006. return name;
  25007. }
  25008. const String AudioUnitPluginInstance::getParameterText (int index)
  25009. {
  25010. return String (getParameter (index));
  25011. }
  25012. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25013. {
  25014. AudioUnitParameterInfo info;
  25015. UInt32 sz = sizeof (info);
  25016. if (AudioUnitGetProperty (audioUnit,
  25017. kAudioUnitProperty_ParameterInfo,
  25018. kAudioUnitScope_Global,
  25019. parameterIds [index], &info, &sz) == noErr)
  25020. {
  25021. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25022. }
  25023. return true;
  25024. }
  25025. int AudioUnitPluginInstance::getNumPrograms()
  25026. {
  25027. CFArrayRef presets;
  25028. UInt32 sz = sizeof (CFArrayRef);
  25029. int num = 0;
  25030. if (AudioUnitGetProperty (audioUnit,
  25031. kAudioUnitProperty_FactoryPresets,
  25032. kAudioUnitScope_Global,
  25033. 0, &presets, &sz) == noErr)
  25034. {
  25035. num = (int) CFArrayGetCount (presets);
  25036. CFRelease (presets);
  25037. }
  25038. return num;
  25039. }
  25040. int AudioUnitPluginInstance::getCurrentProgram()
  25041. {
  25042. AUPreset current;
  25043. current.presetNumber = 0;
  25044. UInt32 sz = sizeof (AUPreset);
  25045. AudioUnitGetProperty (audioUnit,
  25046. kAudioUnitProperty_FactoryPresets,
  25047. kAudioUnitScope_Global,
  25048. 0, &current, &sz);
  25049. return current.presetNumber;
  25050. }
  25051. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25052. {
  25053. AUPreset current;
  25054. current.presetNumber = newIndex;
  25055. current.presetName = 0;
  25056. AudioUnitSetProperty (audioUnit,
  25057. kAudioUnitProperty_FactoryPresets,
  25058. kAudioUnitScope_Global,
  25059. 0, &current, sizeof (AUPreset));
  25060. }
  25061. const String AudioUnitPluginInstance::getProgramName (int index)
  25062. {
  25063. String s;
  25064. CFArrayRef presets;
  25065. UInt32 sz = sizeof (CFArrayRef);
  25066. if (AudioUnitGetProperty (audioUnit,
  25067. kAudioUnitProperty_FactoryPresets,
  25068. kAudioUnitScope_Global,
  25069. 0, &presets, &sz) == noErr)
  25070. {
  25071. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25072. {
  25073. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25074. if (p != 0 && p->presetNumber == index)
  25075. {
  25076. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25077. break;
  25078. }
  25079. }
  25080. CFRelease (presets);
  25081. }
  25082. return s;
  25083. }
  25084. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25085. {
  25086. jassertfalse // xxx not implemented!
  25087. }
  25088. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25089. {
  25090. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25091. return "Input " + String (index + 1);
  25092. return String::empty;
  25093. }
  25094. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25095. {
  25096. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25097. return false;
  25098. return true;
  25099. }
  25100. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25101. {
  25102. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25103. return "Output " + String (index + 1);
  25104. return String::empty;
  25105. }
  25106. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25107. {
  25108. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25109. return false;
  25110. return true;
  25111. }
  25112. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25113. {
  25114. getCurrentProgramStateInformation (destData);
  25115. }
  25116. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25117. {
  25118. CFPropertyListRef propertyList = 0;
  25119. UInt32 sz = sizeof (CFPropertyListRef);
  25120. if (AudioUnitGetProperty (audioUnit,
  25121. kAudioUnitProperty_ClassInfo,
  25122. kAudioUnitScope_Global,
  25123. 0, &propertyList, &sz) == noErr)
  25124. {
  25125. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25126. CFWriteStreamOpen (stream);
  25127. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25128. CFWriteStreamClose (stream);
  25129. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25130. destData.setSize (bytesWritten);
  25131. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25132. CFRelease (data);
  25133. CFRelease (stream);
  25134. CFRelease (propertyList);
  25135. }
  25136. }
  25137. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25138. {
  25139. setCurrentProgramStateInformation (data, sizeInBytes);
  25140. }
  25141. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25142. {
  25143. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25144. (const UInt8*) data,
  25145. sizeInBytes,
  25146. kCFAllocatorNull);
  25147. CFReadStreamOpen (stream);
  25148. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25149. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25150. stream,
  25151. 0,
  25152. kCFPropertyListImmutable,
  25153. &format,
  25154. 0);
  25155. CFRelease (stream);
  25156. if (propertyList != 0)
  25157. AudioUnitSetProperty (audioUnit,
  25158. kAudioUnitProperty_ClassInfo,
  25159. kAudioUnitScope_Global,
  25160. 0, &propertyList, sizeof (propertyList));
  25161. }
  25162. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25163. {
  25164. }
  25165. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25166. {
  25167. }
  25168. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25169. const String& fileOrIdentifier)
  25170. {
  25171. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25172. return;
  25173. PluginDescription desc;
  25174. desc.fileOrIdentifier = fileOrIdentifier;
  25175. desc.uid = 0;
  25176. try
  25177. {
  25178. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25179. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25180. if (auInstance != 0)
  25181. {
  25182. auInstance->fillInPluginDescription (desc);
  25183. results.add (new PluginDescription (desc));
  25184. }
  25185. }
  25186. catch (...)
  25187. {
  25188. // crashed while loading...
  25189. }
  25190. }
  25191. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25192. {
  25193. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25194. {
  25195. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25196. if (result->audioUnit != 0)
  25197. {
  25198. result->initialise();
  25199. return result.release();
  25200. }
  25201. }
  25202. return 0;
  25203. }
  25204. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25205. const bool /*recursive*/)
  25206. {
  25207. StringArray result;
  25208. ComponentRecord* comp = 0;
  25209. ComponentDescription desc;
  25210. zerostruct (desc);
  25211. for (;;)
  25212. {
  25213. zerostruct (desc);
  25214. comp = FindNextComponent (comp, &desc);
  25215. if (comp == 0)
  25216. break;
  25217. GetComponentInfo (comp, &desc, 0, 0, 0);
  25218. if (desc.componentType == kAudioUnitType_MusicDevice
  25219. || desc.componentType == kAudioUnitType_MusicEffect
  25220. || desc.componentType == kAudioUnitType_Effect
  25221. || desc.componentType == kAudioUnitType_Generator
  25222. || desc.componentType == kAudioUnitType_Panner)
  25223. {
  25224. const String s (createAUPluginIdentifier (desc));
  25225. DBG (s);
  25226. result.add (s);
  25227. }
  25228. }
  25229. return result;
  25230. }
  25231. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25232. {
  25233. ComponentDescription desc;
  25234. String name, version, manufacturer;
  25235. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25236. return FindNextComponent (0, &desc) != 0;
  25237. const File f (fileOrIdentifier);
  25238. return f.hasFileExtension (".component")
  25239. && f.isDirectory();
  25240. }
  25241. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25242. {
  25243. ComponentDescription desc;
  25244. String name, version, manufacturer;
  25245. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25246. if (name.isEmpty())
  25247. name = fileOrIdentifier;
  25248. return name;
  25249. }
  25250. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25251. {
  25252. if (desc.fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25253. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25254. else
  25255. return File (desc.fileOrIdentifier).exists();
  25256. }
  25257. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25258. {
  25259. return FileSearchPath ("/(Default AudioUnit locations)");
  25260. }
  25261. #endif
  25262. END_JUCE_NAMESPACE
  25263. #undef log
  25264. #endif
  25265. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25266. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25267. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25268. #define JUCE_MAC_VST_INCLUDED 1
  25269. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25270. #if JUCE_PLUGINHOST_VST
  25271. #if JUCE_WINDOWS
  25272. #undef _WIN32_WINNT
  25273. #define _WIN32_WINNT 0x500
  25274. #undef STRICT
  25275. #define STRICT
  25276. #include <windows.h>
  25277. #include <float.h>
  25278. #pragma warning (disable : 4312 4355)
  25279. #elif JUCE_LINUX
  25280. #include <float.h>
  25281. #include <sys/time.h>
  25282. #include <X11/Xlib.h>
  25283. #include <X11/Xutil.h>
  25284. #include <X11/Xatom.h>
  25285. #undef Font
  25286. #undef KeyPress
  25287. #undef Drawable
  25288. #undef Time
  25289. #else
  25290. #ifndef JUCE_MAC_VST_INCLUDED
  25291. // On the mac, this file needs to be compiled indirectly, by using
  25292. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  25293. #error
  25294. #endif
  25295. #include <Cocoa/Cocoa.h>
  25296. #include <Carbon/Carbon.h>
  25297. #endif
  25298. #if ! (JUCE_MAC && JUCE_64BIT)
  25299. BEGIN_JUCE_NAMESPACE
  25300. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25301. #endif
  25302. #undef PRAGMA_ALIGN_SUPPORTED
  25303. #define VST_FORCE_DEPRECATED 0
  25304. #ifdef _MSC_VER
  25305. #pragma warning (push)
  25306. #pragma warning (disable: 4996)
  25307. #endif
  25308. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25309. your include path if you want to add VST support.
  25310. If you're not interested in VSTs, you can disable them by changing the
  25311. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25312. */
  25313. #include "pluginterfaces/vst2.x/aeffectx.h"
  25314. #ifdef _MSC_VER
  25315. #pragma warning (pop)
  25316. #endif
  25317. #if JUCE_LINUX
  25318. #define Font JUCE_NAMESPACE::Font
  25319. #define KeyPress JUCE_NAMESPACE::KeyPress
  25320. #define Drawable JUCE_NAMESPACE::Drawable
  25321. #define Time JUCE_NAMESPACE::Time
  25322. #endif
  25323. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25324. #ifdef __aeffect__
  25325. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25326. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25327. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25328. events to the list.
  25329. This is used by both the VST hosting code and the plugin wrapper.
  25330. */
  25331. class VSTMidiEventList
  25332. {
  25333. public:
  25334. VSTMidiEventList()
  25335. : numEventsUsed (0), numEventsAllocated (0)
  25336. {
  25337. }
  25338. ~VSTMidiEventList()
  25339. {
  25340. freeEvents();
  25341. }
  25342. void clear()
  25343. {
  25344. numEventsUsed = 0;
  25345. if (events != 0)
  25346. events->numEvents = 0;
  25347. }
  25348. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25349. {
  25350. ensureSize (numEventsUsed + 1);
  25351. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25352. events->numEvents = ++numEventsUsed;
  25353. if (numBytes <= 4)
  25354. {
  25355. if (e->type == kVstSysExType)
  25356. {
  25357. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25358. e->type = kVstMidiType;
  25359. e->byteSize = sizeof (VstMidiEvent);
  25360. e->noteLength = 0;
  25361. e->noteOffset = 0;
  25362. e->detune = 0;
  25363. e->noteOffVelocity = 0;
  25364. }
  25365. e->deltaFrames = frameOffset;
  25366. memcpy (e->midiData, midiData, numBytes);
  25367. }
  25368. else
  25369. {
  25370. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25371. if (se->type == kVstSysExType)
  25372. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25373. else
  25374. se->sysexDump = (char*) juce_malloc (numBytes);
  25375. memcpy (se->sysexDump, midiData, numBytes);
  25376. se->type = kVstSysExType;
  25377. se->byteSize = sizeof (VstMidiSysexEvent);
  25378. se->deltaFrames = frameOffset;
  25379. se->flags = 0;
  25380. se->dumpBytes = numBytes;
  25381. se->resvd1 = 0;
  25382. se->resvd2 = 0;
  25383. }
  25384. }
  25385. // Handy method to pull the events out of an event buffer supplied by the host
  25386. // or plugin.
  25387. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25388. {
  25389. for (int i = 0; i < events->numEvents; ++i)
  25390. {
  25391. const VstEvent* const e = events->events[i];
  25392. if (e != 0)
  25393. {
  25394. if (e->type == kVstMidiType)
  25395. {
  25396. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25397. 4, e->deltaFrames);
  25398. }
  25399. else if (e->type == kVstSysExType)
  25400. {
  25401. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25402. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25403. e->deltaFrames);
  25404. }
  25405. }
  25406. }
  25407. }
  25408. void ensureSize (int numEventsNeeded)
  25409. {
  25410. if (numEventsNeeded > numEventsAllocated)
  25411. {
  25412. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25413. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25414. if (events == 0)
  25415. events.calloc (size, 1);
  25416. else
  25417. events.realloc (size, 1);
  25418. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25419. {
  25420. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25421. (int) sizeof (VstMidiSysexEvent)));
  25422. e->type = kVstMidiType;
  25423. e->byteSize = sizeof (VstMidiEvent);
  25424. events->events[i] = (VstEvent*) e;
  25425. }
  25426. numEventsAllocated = numEventsNeeded;
  25427. }
  25428. }
  25429. void freeEvents()
  25430. {
  25431. if (events != 0)
  25432. {
  25433. for (int i = numEventsAllocated; --i >= 0;)
  25434. {
  25435. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25436. if (e->type == kVstSysExType)
  25437. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25438. juce_free (e);
  25439. }
  25440. events.free();
  25441. numEventsUsed = 0;
  25442. numEventsAllocated = 0;
  25443. }
  25444. }
  25445. HeapBlock <VstEvents> events;
  25446. private:
  25447. int numEventsUsed, numEventsAllocated;
  25448. };
  25449. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25450. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25451. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25452. #if ! JUCE_WIN32
  25453. static void _fpreset() {}
  25454. static void _clearfp() {}
  25455. #endif
  25456. extern void juce_callAnyTimersSynchronously();
  25457. const int fxbVersionNum = 1;
  25458. struct fxProgram
  25459. {
  25460. long chunkMagic; // 'CcnK'
  25461. long byteSize; // of this chunk, excl. magic + byteSize
  25462. long fxMagic; // 'FxCk'
  25463. long version;
  25464. long fxID; // fx unique id
  25465. long fxVersion;
  25466. long numParams;
  25467. char prgName[28];
  25468. float params[1]; // variable no. of parameters
  25469. };
  25470. struct fxSet
  25471. {
  25472. long chunkMagic; // 'CcnK'
  25473. long byteSize; // of this chunk, excl. magic + byteSize
  25474. long fxMagic; // 'FxBk'
  25475. long version;
  25476. long fxID; // fx unique id
  25477. long fxVersion;
  25478. long numPrograms;
  25479. char future[128];
  25480. fxProgram programs[1]; // variable no. of programs
  25481. };
  25482. struct fxChunkSet
  25483. {
  25484. long chunkMagic; // 'CcnK'
  25485. long byteSize; // of this chunk, excl. magic + byteSize
  25486. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25487. long version;
  25488. long fxID; // fx unique id
  25489. long fxVersion;
  25490. long numPrograms;
  25491. char future[128];
  25492. long chunkSize;
  25493. char chunk[8]; // variable
  25494. };
  25495. struct fxProgramSet
  25496. {
  25497. long chunkMagic; // 'CcnK'
  25498. long byteSize; // of this chunk, excl. magic + byteSize
  25499. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25500. long version;
  25501. long fxID; // fx unique id
  25502. long fxVersion;
  25503. long numPrograms;
  25504. char name[28];
  25505. long chunkSize;
  25506. char chunk[8]; // variable
  25507. };
  25508. static long vst_swap (const long x) throw()
  25509. {
  25510. #ifdef JUCE_LITTLE_ENDIAN
  25511. return (long) ByteOrder::swap ((uint32) x);
  25512. #else
  25513. return x;
  25514. #endif
  25515. }
  25516. static float vst_swapFloat (const float x) throw()
  25517. {
  25518. #ifdef JUCE_LITTLE_ENDIAN
  25519. union { uint32 asInt; float asFloat; } n;
  25520. n.asFloat = x;
  25521. n.asInt = ByteOrder::swap (n.asInt);
  25522. return n.asFloat;
  25523. #else
  25524. return x;
  25525. #endif
  25526. }
  25527. typedef AEffect* (*MainCall) (audioMasterCallback);
  25528. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25529. static int shellUIDToCreate = 0;
  25530. static int insideVSTCallback = 0;
  25531. class VSTPluginWindow;
  25532. // Change this to disable logging of various VST activities
  25533. #ifndef VST_LOGGING
  25534. #define VST_LOGGING 1
  25535. #endif
  25536. #if VST_LOGGING
  25537. #define log(a) Logger::writeToLog(a);
  25538. #else
  25539. #define log(a)
  25540. #endif
  25541. #if JUCE_MAC && JUCE_PPC
  25542. static void* NewCFMFromMachO (void* const machofp) throw()
  25543. {
  25544. void* result = juce_malloc (8);
  25545. ((void**) result)[0] = machofp;
  25546. ((void**) result)[1] = result;
  25547. return result;
  25548. }
  25549. #endif
  25550. #if JUCE_LINUX
  25551. extern Display* display;
  25552. extern XContext windowHandleXContext;
  25553. typedef void (*EventProcPtr) (XEvent* ev);
  25554. static bool xErrorTriggered;
  25555. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25556. {
  25557. xErrorTriggered = true;
  25558. return 0;
  25559. }
  25560. static int getPropertyFromXWindow (Window handle, Atom atom)
  25561. {
  25562. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25563. xErrorTriggered = false;
  25564. int userSize;
  25565. unsigned long bytes, userCount;
  25566. unsigned char* data;
  25567. Atom userType;
  25568. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25569. &userType, &userSize, &userCount, &bytes, &data);
  25570. XSetErrorHandler (oldErrorHandler);
  25571. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25572. : 0;
  25573. }
  25574. static Window getChildWindow (Window windowToCheck)
  25575. {
  25576. Window rootWindow, parentWindow;
  25577. Window* childWindows;
  25578. unsigned int numChildren;
  25579. XQueryTree (display,
  25580. windowToCheck,
  25581. &rootWindow,
  25582. &parentWindow,
  25583. &childWindows,
  25584. &numChildren);
  25585. if (numChildren > 0)
  25586. return childWindows [0];
  25587. return 0;
  25588. }
  25589. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25590. {
  25591. if (e.mods.isLeftButtonDown())
  25592. {
  25593. ev.xbutton.button = Button1;
  25594. ev.xbutton.state |= Button1Mask;
  25595. }
  25596. else if (e.mods.isRightButtonDown())
  25597. {
  25598. ev.xbutton.button = Button3;
  25599. ev.xbutton.state |= Button3Mask;
  25600. }
  25601. else if (e.mods.isMiddleButtonDown())
  25602. {
  25603. ev.xbutton.button = Button2;
  25604. ev.xbutton.state |= Button2Mask;
  25605. }
  25606. }
  25607. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25608. {
  25609. if (e.mods.isLeftButtonDown())
  25610. ev.xmotion.state |= Button1Mask;
  25611. else if (e.mods.isRightButtonDown())
  25612. ev.xmotion.state |= Button3Mask;
  25613. else if (e.mods.isMiddleButtonDown())
  25614. ev.xmotion.state |= Button2Mask;
  25615. }
  25616. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25617. {
  25618. if (e.mods.isLeftButtonDown())
  25619. ev.xcrossing.state |= Button1Mask;
  25620. else if (e.mods.isRightButtonDown())
  25621. ev.xcrossing.state |= Button3Mask;
  25622. else if (e.mods.isMiddleButtonDown())
  25623. ev.xcrossing.state |= Button2Mask;
  25624. }
  25625. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25626. {
  25627. if (increment < 0)
  25628. {
  25629. ev.xbutton.button = Button5;
  25630. ev.xbutton.state |= Button5Mask;
  25631. }
  25632. else if (increment > 0)
  25633. {
  25634. ev.xbutton.button = Button4;
  25635. ev.xbutton.state |= Button4Mask;
  25636. }
  25637. }
  25638. #endif
  25639. static VoidArray activeModules;
  25640. class ModuleHandle : public ReferenceCountedObject
  25641. {
  25642. public:
  25643. File file;
  25644. MainCall moduleMain;
  25645. String pluginName;
  25646. static ModuleHandle* findOrCreateModule (const File& file)
  25647. {
  25648. for (int i = activeModules.size(); --i >= 0;)
  25649. {
  25650. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  25651. if (module->file == file)
  25652. return module;
  25653. }
  25654. _fpreset(); // (doesn't do any harm)
  25655. ++insideVSTCallback;
  25656. shellUIDToCreate = 0;
  25657. log ("Attempting to load VST: " + file.getFullPathName());
  25658. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25659. if (! m->open())
  25660. m = 0;
  25661. --insideVSTCallback;
  25662. _fpreset(); // (doesn't do any harm)
  25663. return m.release();
  25664. }
  25665. ModuleHandle (const File& file_)
  25666. : file (file_),
  25667. moduleMain (0),
  25668. #if JUCE_WIN32 || JUCE_LINUX
  25669. hModule (0)
  25670. #elif JUCE_MAC
  25671. fragId (0),
  25672. resHandle (0),
  25673. bundleRef (0),
  25674. resFileId (0)
  25675. #endif
  25676. {
  25677. activeModules.add (this);
  25678. #if JUCE_WIN32 || JUCE_LINUX
  25679. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25680. #elif JUCE_MAC
  25681. FSRef ref;
  25682. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25683. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25684. #endif
  25685. }
  25686. ~ModuleHandle()
  25687. {
  25688. activeModules.removeValue (this);
  25689. close();
  25690. }
  25691. juce_UseDebuggingNewOperator
  25692. #if JUCE_WIN32 || JUCE_LINUX
  25693. void* hModule;
  25694. String fullParentDirectoryPathName;
  25695. bool open()
  25696. {
  25697. #if JUCE_WIN32
  25698. static bool timePeriodSet = false;
  25699. if (! timePeriodSet)
  25700. {
  25701. timePeriodSet = true;
  25702. timeBeginPeriod (2);
  25703. }
  25704. #endif
  25705. pluginName = file.getFileNameWithoutExtension();
  25706. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25707. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25708. if (moduleMain == 0)
  25709. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25710. return moduleMain != 0;
  25711. }
  25712. void close()
  25713. {
  25714. _fpreset(); // (doesn't do any harm)
  25715. PlatformUtilities::freeDynamicLibrary (hModule);
  25716. }
  25717. void closeEffect (AEffect* eff)
  25718. {
  25719. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25720. }
  25721. #else
  25722. CFragConnectionID fragId;
  25723. Handle resHandle;
  25724. CFBundleRef bundleRef;
  25725. FSSpec parentDirFSSpec;
  25726. short resFileId;
  25727. bool open()
  25728. {
  25729. bool ok = false;
  25730. const String filename (file.getFullPathName());
  25731. if (file.hasFileExtension (".vst"))
  25732. {
  25733. const char* const utf8 = filename.toUTF8();
  25734. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25735. strlen (utf8), file.isDirectory());
  25736. if (url != 0)
  25737. {
  25738. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25739. CFRelease (url);
  25740. if (bundleRef != 0)
  25741. {
  25742. if (CFBundleLoadExecutable (bundleRef))
  25743. {
  25744. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25745. if (moduleMain == 0)
  25746. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25747. if (moduleMain != 0)
  25748. {
  25749. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25750. if (name != 0)
  25751. {
  25752. if (CFGetTypeID (name) == CFStringGetTypeID())
  25753. {
  25754. char buffer[1024];
  25755. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25756. pluginName = buffer;
  25757. }
  25758. }
  25759. if (pluginName.isEmpty())
  25760. pluginName = file.getFileNameWithoutExtension();
  25761. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25762. ok = true;
  25763. }
  25764. }
  25765. if (! ok)
  25766. {
  25767. CFBundleUnloadExecutable (bundleRef);
  25768. CFRelease (bundleRef);
  25769. bundleRef = 0;
  25770. }
  25771. }
  25772. }
  25773. }
  25774. #if JUCE_PPC
  25775. else
  25776. {
  25777. FSRef fn;
  25778. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25779. {
  25780. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25781. if (resFileId != -1)
  25782. {
  25783. const int numEffs = Count1Resources ('aEff');
  25784. for (int i = 0; i < numEffs; ++i)
  25785. {
  25786. resHandle = Get1IndResource ('aEff', i + 1);
  25787. if (resHandle != 0)
  25788. {
  25789. OSType type;
  25790. Str255 name;
  25791. SInt16 id;
  25792. GetResInfo (resHandle, &id, &type, name);
  25793. pluginName = String ((const char*) name + 1, name[0]);
  25794. DetachResource (resHandle);
  25795. HLock (resHandle);
  25796. Ptr ptr;
  25797. Str255 errorText;
  25798. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25799. name, kPrivateCFragCopy,
  25800. &fragId, &ptr, errorText);
  25801. if (err == noErr)
  25802. {
  25803. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25804. ok = true;
  25805. }
  25806. else
  25807. {
  25808. HUnlock (resHandle);
  25809. }
  25810. break;
  25811. }
  25812. }
  25813. if (! ok)
  25814. CloseResFile (resFileId);
  25815. }
  25816. }
  25817. }
  25818. #endif
  25819. return ok;
  25820. }
  25821. void close()
  25822. {
  25823. #if JUCE_PPC
  25824. if (fragId != 0)
  25825. {
  25826. if (moduleMain != 0)
  25827. disposeMachOFromCFM ((void*) moduleMain);
  25828. CloseConnection (&fragId);
  25829. HUnlock (resHandle);
  25830. if (resFileId != 0)
  25831. CloseResFile (resFileId);
  25832. }
  25833. else
  25834. #endif
  25835. if (bundleRef != 0)
  25836. {
  25837. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25838. if (CFGetRetainCount (bundleRef) == 1)
  25839. CFBundleUnloadExecutable (bundleRef);
  25840. if (CFGetRetainCount (bundleRef) > 0)
  25841. CFRelease (bundleRef);
  25842. }
  25843. }
  25844. void closeEffect (AEffect* eff)
  25845. {
  25846. #if JUCE_PPC
  25847. if (fragId != 0)
  25848. {
  25849. VoidArray thingsToDelete;
  25850. thingsToDelete.add ((void*) eff->dispatcher);
  25851. thingsToDelete.add ((void*) eff->process);
  25852. thingsToDelete.add ((void*) eff->setParameter);
  25853. thingsToDelete.add ((void*) eff->getParameter);
  25854. thingsToDelete.add ((void*) eff->processReplacing);
  25855. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25856. for (int i = thingsToDelete.size(); --i >= 0;)
  25857. disposeMachOFromCFM (thingsToDelete[i]);
  25858. }
  25859. else
  25860. #endif
  25861. {
  25862. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25863. }
  25864. }
  25865. #if JUCE_PPC
  25866. static void* newMachOFromCFM (void* cfmfp)
  25867. {
  25868. if (cfmfp == 0)
  25869. return 0;
  25870. UInt32* const mfp = new UInt32[6];
  25871. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25872. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25873. mfp[2] = 0x800c0000;
  25874. mfp[3] = 0x804c0004;
  25875. mfp[4] = 0x7c0903a6;
  25876. mfp[5] = 0x4e800420;
  25877. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25878. return mfp;
  25879. }
  25880. static void disposeMachOFromCFM (void* ptr)
  25881. {
  25882. delete[] static_cast <UInt32*> (ptr);
  25883. }
  25884. void coerceAEffectFunctionCalls (AEffect* eff)
  25885. {
  25886. if (fragId != 0)
  25887. {
  25888. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25889. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25890. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25891. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25892. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25893. }
  25894. }
  25895. #endif
  25896. #endif
  25897. };
  25898. /**
  25899. An instance of a plugin, created by a VSTPluginFormat.
  25900. */
  25901. class VSTPluginInstance : public AudioPluginInstance,
  25902. private Timer,
  25903. private AsyncUpdater
  25904. {
  25905. public:
  25906. ~VSTPluginInstance();
  25907. // AudioPluginInstance methods:
  25908. void fillInPluginDescription (PluginDescription& desc) const
  25909. {
  25910. desc.name = name;
  25911. desc.fileOrIdentifier = module->file.getFullPathName();
  25912. desc.uid = getUID();
  25913. desc.lastFileModTime = module->file.getLastModificationTime();
  25914. desc.pluginFormatName = "VST";
  25915. desc.category = getCategory();
  25916. {
  25917. char buffer [kVstMaxVendorStrLen + 8];
  25918. zerostruct (buffer);
  25919. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25920. desc.manufacturerName = buffer;
  25921. }
  25922. desc.version = getVersion();
  25923. desc.numInputChannels = getNumInputChannels();
  25924. desc.numOutputChannels = getNumOutputChannels();
  25925. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25926. }
  25927. const String getName() const { return name; }
  25928. int getUID() const throw();
  25929. bool acceptsMidi() const { return wantsMidiMessages; }
  25930. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25931. // AudioProcessor methods:
  25932. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25933. void releaseResources();
  25934. void processBlock (AudioSampleBuffer& buffer,
  25935. MidiBuffer& midiMessages);
  25936. AudioProcessorEditor* createEditor();
  25937. const String getInputChannelName (const int index) const;
  25938. bool isInputChannelStereoPair (int index) const;
  25939. const String getOutputChannelName (const int index) const;
  25940. bool isOutputChannelStereoPair (int index) const;
  25941. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25942. float getParameter (int index);
  25943. void setParameter (int index, float newValue);
  25944. const String getParameterName (int index);
  25945. const String getParameterText (int index);
  25946. bool isParameterAutomatable (int index) const;
  25947. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25948. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25949. void setCurrentProgram (int index);
  25950. const String getProgramName (int index);
  25951. void changeProgramName (int index, const String& newName);
  25952. void getStateInformation (MemoryBlock& destData);
  25953. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25954. void setStateInformation (const void* data, int sizeInBytes);
  25955. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25956. void timerCallback();
  25957. void handleAsyncUpdate();
  25958. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25959. juce_UseDebuggingNewOperator
  25960. private:
  25961. friend class VSTPluginWindow;
  25962. friend class VSTPluginFormat;
  25963. AEffect* effect;
  25964. String name;
  25965. CriticalSection lock;
  25966. bool wantsMidiMessages, initialised, isPowerOn;
  25967. mutable StringArray programNames;
  25968. AudioSampleBuffer tempBuffer;
  25969. CriticalSection midiInLock;
  25970. MidiBuffer incomingMidi;
  25971. VSTMidiEventList midiEventsToSend;
  25972. VstTimeInfo vstHostTime;
  25973. HeapBlock <float*> channels;
  25974. ReferenceCountedObjectPtr <ModuleHandle> module;
  25975. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25976. bool restoreProgramSettings (const fxProgram* const prog);
  25977. const String getCurrentProgramName();
  25978. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25979. void updateStoredProgramNames();
  25980. void initialise();
  25981. void handleMidiFromPlugin (const VstEvents* const events);
  25982. void createTempParameterStore (MemoryBlock& dest);
  25983. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25984. const String getParameterLabel (int index) const;
  25985. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25986. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25987. void setChunkData (const char* data, int size, bool isPreset);
  25988. bool loadFromFXBFile (const void* data, int numBytes);
  25989. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25990. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25991. const String getVersion() const throw();
  25992. const String getCategory() const throw();
  25993. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25994. void setPower (const bool on);
  25995. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25996. };
  25997. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25998. : effect (0),
  25999. wantsMidiMessages (false),
  26000. initialised (false),
  26001. isPowerOn (false),
  26002. tempBuffer (1, 1),
  26003. module (module_)
  26004. {
  26005. try
  26006. {
  26007. _fpreset();
  26008. ++insideVSTCallback;
  26009. name = module->pluginName;
  26010. log ("Creating VST instance: " + name);
  26011. #if JUCE_MAC
  26012. if (module->resFileId != 0)
  26013. UseResFile (module->resFileId);
  26014. #if JUCE_PPC
  26015. if (module->fragId != 0)
  26016. {
  26017. static void* audioMasterCoerced = 0;
  26018. if (audioMasterCoerced == 0)
  26019. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26020. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26021. }
  26022. else
  26023. #endif
  26024. #endif
  26025. {
  26026. effect = module->moduleMain (&audioMaster);
  26027. }
  26028. --insideVSTCallback;
  26029. if (effect != 0 && effect->magic == kEffectMagic)
  26030. {
  26031. #if JUCE_PPC
  26032. module->coerceAEffectFunctionCalls (effect);
  26033. #endif
  26034. jassert (effect->resvd2 == 0);
  26035. jassert (effect->object != 0);
  26036. _fpreset(); // some dodgy plugs fuck around with this
  26037. }
  26038. else
  26039. {
  26040. effect = 0;
  26041. }
  26042. }
  26043. catch (...)
  26044. {
  26045. --insideVSTCallback;
  26046. }
  26047. }
  26048. VSTPluginInstance::~VSTPluginInstance()
  26049. {
  26050. {
  26051. const ScopedLock sl (lock);
  26052. jassert (insideVSTCallback == 0);
  26053. if (effect != 0 && effect->magic == kEffectMagic)
  26054. {
  26055. try
  26056. {
  26057. #if JUCE_MAC
  26058. if (module->resFileId != 0)
  26059. UseResFile (module->resFileId);
  26060. #endif
  26061. // Must delete any editors before deleting the plugin instance!
  26062. jassert (getActiveEditor() == 0);
  26063. _fpreset(); // some dodgy plugs fuck around with this
  26064. module->closeEffect (effect);
  26065. }
  26066. catch (...)
  26067. {}
  26068. }
  26069. module = 0;
  26070. effect = 0;
  26071. }
  26072. }
  26073. void VSTPluginInstance::initialise()
  26074. {
  26075. if (initialised || effect == 0)
  26076. return;
  26077. log ("Initialising VST: " + module->pluginName);
  26078. initialised = true;
  26079. dispatch (effIdentify, 0, 0, 0, 0);
  26080. // this code would ask the plugin for its name, but so few plugins
  26081. // actually bother implementing this correctly, that it's better to
  26082. // just ignore it and use the file name instead.
  26083. /* {
  26084. char buffer [256];
  26085. zerostruct (buffer);
  26086. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26087. name = String (buffer).trim();
  26088. if (name.isEmpty())
  26089. name = module->pluginName;
  26090. }
  26091. */
  26092. if (getSampleRate() > 0)
  26093. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26094. if (getBlockSize() > 0)
  26095. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26096. dispatch (effOpen, 0, 0, 0, 0);
  26097. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26098. getSampleRate(), getBlockSize());
  26099. if (getNumPrograms() > 1)
  26100. setCurrentProgram (0);
  26101. else
  26102. dispatch (effSetProgram, 0, 0, 0, 0);
  26103. int i;
  26104. for (i = effect->numInputs; --i >= 0;)
  26105. dispatch (effConnectInput, i, 1, 0, 0);
  26106. for (i = effect->numOutputs; --i >= 0;)
  26107. dispatch (effConnectOutput, i, 1, 0, 0);
  26108. updateStoredProgramNames();
  26109. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26110. setLatencySamples (effect->initialDelay);
  26111. }
  26112. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26113. int samplesPerBlockExpected)
  26114. {
  26115. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26116. sampleRate_, samplesPerBlockExpected);
  26117. setLatencySamples (effect->initialDelay);
  26118. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26119. vstHostTime.tempo = 120.0;
  26120. vstHostTime.timeSigNumerator = 4;
  26121. vstHostTime.timeSigDenominator = 4;
  26122. vstHostTime.sampleRate = sampleRate_;
  26123. vstHostTime.samplePos = 0;
  26124. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26125. initialise();
  26126. if (initialised)
  26127. {
  26128. wantsMidiMessages = wantsMidiMessages
  26129. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26130. if (wantsMidiMessages)
  26131. midiEventsToSend.ensureSize (256);
  26132. else
  26133. midiEventsToSend.freeEvents();
  26134. incomingMidi.clear();
  26135. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26136. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26137. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26138. if (! isPowerOn)
  26139. setPower (true);
  26140. // dodgy hack to force some plugins to initialise the sample rate..
  26141. if ((! hasEditor()) && getNumParameters() > 0)
  26142. {
  26143. const float old = getParameter (0);
  26144. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26145. setParameter (0, old);
  26146. }
  26147. dispatch (effStartProcess, 0, 0, 0, 0);
  26148. }
  26149. }
  26150. void VSTPluginInstance::releaseResources()
  26151. {
  26152. if (initialised)
  26153. {
  26154. dispatch (effStopProcess, 0, 0, 0, 0);
  26155. setPower (false);
  26156. }
  26157. tempBuffer.setSize (1, 1);
  26158. incomingMidi.clear();
  26159. midiEventsToSend.freeEvents();
  26160. channels.free();
  26161. }
  26162. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26163. MidiBuffer& midiMessages)
  26164. {
  26165. const int numSamples = buffer.getNumSamples();
  26166. if (initialised)
  26167. {
  26168. AudioPlayHead* playHead = getPlayHead();
  26169. if (playHead != 0)
  26170. {
  26171. AudioPlayHead::CurrentPositionInfo position;
  26172. playHead->getCurrentPosition (position);
  26173. vstHostTime.tempo = position.bpm;
  26174. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26175. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26176. vstHostTime.ppqPos = position.ppqPosition;
  26177. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26178. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26179. if (position.isPlaying)
  26180. vstHostTime.flags |= kVstTransportPlaying;
  26181. else
  26182. vstHostTime.flags &= ~kVstTransportPlaying;
  26183. }
  26184. #if JUCE_WIN32
  26185. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26186. #elif JUCE_LINUX
  26187. timeval micro;
  26188. gettimeofday (&micro, 0);
  26189. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26190. #elif JUCE_MAC
  26191. UnsignedWide micro;
  26192. Microseconds (&micro);
  26193. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26194. #endif
  26195. if (wantsMidiMessages)
  26196. {
  26197. midiEventsToSend.clear();
  26198. midiEventsToSend.ensureSize (1);
  26199. MidiBuffer::Iterator iter (midiMessages);
  26200. const uint8* midiData;
  26201. int numBytesOfMidiData, samplePosition;
  26202. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26203. {
  26204. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26205. jlimit (0, numSamples - 1, samplePosition));
  26206. }
  26207. try
  26208. {
  26209. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26210. }
  26211. catch (...)
  26212. {}
  26213. }
  26214. int i;
  26215. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26216. for (i = 0; i < maxChans; ++i)
  26217. channels[i] = buffer.getSampleData (i);
  26218. channels [maxChans] = 0;
  26219. _clearfp();
  26220. if ((effect->flags & effFlagsCanReplacing) != 0)
  26221. {
  26222. try
  26223. {
  26224. effect->processReplacing (effect, channels, channels, numSamples);
  26225. }
  26226. catch (...)
  26227. {}
  26228. }
  26229. else
  26230. {
  26231. tempBuffer.setSize (effect->numOutputs, numSamples);
  26232. tempBuffer.clear();
  26233. float* outs [64];
  26234. for (i = effect->numOutputs; --i >= 0;)
  26235. outs[i] = tempBuffer.getSampleData (i);
  26236. outs [effect->numOutputs] = 0;
  26237. try
  26238. {
  26239. effect->process (effect, channels, outs, numSamples);
  26240. }
  26241. catch (...)
  26242. {}
  26243. for (i = effect->numOutputs; --i >= 0;)
  26244. buffer.copyFrom (i, 0, outs[i], numSamples);
  26245. }
  26246. }
  26247. else
  26248. {
  26249. // Not initialised, so just bypass..
  26250. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26251. buffer.clear (i, 0, buffer.getNumSamples());
  26252. }
  26253. {
  26254. // copy any incoming midi..
  26255. const ScopedLock sl (midiInLock);
  26256. midiMessages.swapWith (incomingMidi);
  26257. incomingMidi.clear();
  26258. }
  26259. }
  26260. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26261. {
  26262. if (events != 0)
  26263. {
  26264. const ScopedLock sl (midiInLock);
  26265. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26266. }
  26267. }
  26268. static Array <VSTPluginWindow*> activeVSTWindows;
  26269. class VSTPluginWindow : public AudioProcessorEditor,
  26270. #if ! JUCE_MAC
  26271. public ComponentMovementWatcher,
  26272. #endif
  26273. public Timer
  26274. {
  26275. public:
  26276. VSTPluginWindow (VSTPluginInstance& plugin_)
  26277. : AudioProcessorEditor (&plugin_),
  26278. #if ! JUCE_MAC
  26279. ComponentMovementWatcher (this),
  26280. #endif
  26281. plugin (plugin_),
  26282. isOpen (false),
  26283. wasShowing (false),
  26284. pluginRefusesToResize (false),
  26285. pluginWantsKeys (false),
  26286. alreadyInside (false),
  26287. recursiveResize (false)
  26288. {
  26289. #if JUCE_WIN32
  26290. sizeCheckCount = 0;
  26291. pluginHWND = 0;
  26292. #elif JUCE_LINUX
  26293. pluginWindow = None;
  26294. pluginProc = None;
  26295. #else
  26296. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26297. #endif
  26298. activeVSTWindows.add (this);
  26299. setSize (1, 1);
  26300. setOpaque (true);
  26301. setVisible (true);
  26302. }
  26303. ~VSTPluginWindow()
  26304. {
  26305. #if JUCE_MAC
  26306. innerWrapper = 0;
  26307. #else
  26308. closePluginWindow();
  26309. #endif
  26310. activeVSTWindows.removeValue (this);
  26311. plugin.editorBeingDeleted (this);
  26312. }
  26313. #if ! JUCE_MAC
  26314. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26315. {
  26316. if (recursiveResize)
  26317. return;
  26318. Component* const topComp = getTopLevelComponent();
  26319. if (topComp->getPeer() != 0)
  26320. {
  26321. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26322. recursiveResize = true;
  26323. #if JUCE_WIN32
  26324. if (pluginHWND != 0)
  26325. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26326. #elif JUCE_LINUX
  26327. if (pluginWindow != 0)
  26328. {
  26329. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26330. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26331. XMapRaised (display, pluginWindow);
  26332. }
  26333. #endif
  26334. recursiveResize = false;
  26335. }
  26336. }
  26337. void componentVisibilityChanged (Component&)
  26338. {
  26339. const bool isShowingNow = isShowing();
  26340. if (wasShowing != isShowingNow)
  26341. {
  26342. wasShowing = isShowingNow;
  26343. if (isShowingNow)
  26344. openPluginWindow();
  26345. else
  26346. closePluginWindow();
  26347. }
  26348. componentMovedOrResized (true, true);
  26349. }
  26350. void componentPeerChanged()
  26351. {
  26352. closePluginWindow();
  26353. openPluginWindow();
  26354. }
  26355. #endif
  26356. bool keyStateChanged (bool)
  26357. {
  26358. return pluginWantsKeys;
  26359. }
  26360. bool keyPressed (const KeyPress&)
  26361. {
  26362. return pluginWantsKeys;
  26363. }
  26364. #if JUCE_MAC
  26365. void paint (Graphics& g)
  26366. {
  26367. g.fillAll (Colours::black);
  26368. }
  26369. #else
  26370. void paint (Graphics& g)
  26371. {
  26372. if (isOpen)
  26373. {
  26374. ComponentPeer* const peer = getPeer();
  26375. if (peer != 0)
  26376. {
  26377. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26378. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26379. #if JUCE_LINUX
  26380. if (pluginWindow != 0)
  26381. {
  26382. const Rectangle<int> clip (g.getClipBounds());
  26383. XEvent ev;
  26384. zerostruct (ev);
  26385. ev.xexpose.type = Expose;
  26386. ev.xexpose.display = display;
  26387. ev.xexpose.window = pluginWindow;
  26388. ev.xexpose.x = clip.getX();
  26389. ev.xexpose.y = clip.getY();
  26390. ev.xexpose.width = clip.getWidth();
  26391. ev.xexpose.height = clip.getHeight();
  26392. sendEventToChild (&ev);
  26393. }
  26394. #endif
  26395. }
  26396. }
  26397. else
  26398. {
  26399. g.fillAll (Colours::black);
  26400. }
  26401. }
  26402. #endif
  26403. void timerCallback()
  26404. {
  26405. #if JUCE_WIN32
  26406. if (--sizeCheckCount <= 0)
  26407. {
  26408. sizeCheckCount = 10;
  26409. checkPluginWindowSize();
  26410. }
  26411. #endif
  26412. try
  26413. {
  26414. static bool reentrant = false;
  26415. if (! reentrant)
  26416. {
  26417. reentrant = true;
  26418. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26419. reentrant = false;
  26420. }
  26421. }
  26422. catch (...)
  26423. {}
  26424. }
  26425. void mouseDown (const MouseEvent& e)
  26426. {
  26427. #if JUCE_LINUX
  26428. if (pluginWindow == 0)
  26429. return;
  26430. toFront (true);
  26431. XEvent ev;
  26432. zerostruct (ev);
  26433. ev.xbutton.display = display;
  26434. ev.xbutton.type = ButtonPress;
  26435. ev.xbutton.window = pluginWindow;
  26436. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26437. ev.xbutton.time = CurrentTime;
  26438. ev.xbutton.x = e.x;
  26439. ev.xbutton.y = e.y;
  26440. ev.xbutton.x_root = e.getScreenX();
  26441. ev.xbutton.y_root = e.getScreenY();
  26442. translateJuceToXButtonModifiers (e, ev);
  26443. sendEventToChild (&ev);
  26444. #elif JUCE_WIN32
  26445. (void) e;
  26446. toFront (true);
  26447. #endif
  26448. }
  26449. void broughtToFront()
  26450. {
  26451. activeVSTWindows.removeValue (this);
  26452. activeVSTWindows.add (this);
  26453. #if JUCE_MAC
  26454. dispatch (effEditTop, 0, 0, 0, 0);
  26455. #endif
  26456. }
  26457. juce_UseDebuggingNewOperator
  26458. private:
  26459. VSTPluginInstance& plugin;
  26460. bool isOpen, wasShowing, recursiveResize;
  26461. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26462. #if JUCE_WIN32
  26463. HWND pluginHWND;
  26464. void* originalWndProc;
  26465. int sizeCheckCount;
  26466. #elif JUCE_LINUX
  26467. Window pluginWindow;
  26468. EventProcPtr pluginProc;
  26469. #endif
  26470. #if JUCE_MAC
  26471. void openPluginWindow (WindowRef parentWindow)
  26472. {
  26473. if (isOpen || parentWindow == 0)
  26474. return;
  26475. isOpen = true;
  26476. ERect* rect = 0;
  26477. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26478. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26479. // do this before and after like in the steinberg example
  26480. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26481. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26482. // Install keyboard hooks
  26483. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26484. // double-check it's not too tiny
  26485. int w = 250, h = 150;
  26486. if (rect != 0)
  26487. {
  26488. w = rect->right - rect->left;
  26489. h = rect->bottom - rect->top;
  26490. if (w == 0 || h == 0)
  26491. {
  26492. w = 250;
  26493. h = 150;
  26494. }
  26495. }
  26496. w = jmax (w, 32);
  26497. h = jmax (h, 32);
  26498. setSize (w, h);
  26499. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26500. repaint();
  26501. }
  26502. #else
  26503. void openPluginWindow()
  26504. {
  26505. if (isOpen || getWindowHandle() == 0)
  26506. return;
  26507. log ("Opening VST UI: " + plugin.name);
  26508. isOpen = true;
  26509. ERect* rect = 0;
  26510. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26511. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26512. // do this before and after like in the steinberg example
  26513. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26514. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26515. // Install keyboard hooks
  26516. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26517. #if JUCE_WIN32
  26518. originalWndProc = 0;
  26519. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26520. if (pluginHWND == 0)
  26521. {
  26522. isOpen = false;
  26523. setSize (300, 150);
  26524. return;
  26525. }
  26526. #pragma warning (push)
  26527. #pragma warning (disable: 4244)
  26528. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26529. if (! pluginWantsKeys)
  26530. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26531. #pragma warning (pop)
  26532. int w, h;
  26533. RECT r;
  26534. GetWindowRect (pluginHWND, &r);
  26535. w = r.right - r.left;
  26536. h = r.bottom - r.top;
  26537. if (rect != 0)
  26538. {
  26539. const int rw = rect->right - rect->left;
  26540. const int rh = rect->bottom - rect->top;
  26541. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26542. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26543. {
  26544. // very dodgy logic to decide which size is right.
  26545. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26546. {
  26547. SetWindowPos (pluginHWND, 0,
  26548. 0, 0, rw, rh,
  26549. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26550. GetWindowRect (pluginHWND, &r);
  26551. w = r.right - r.left;
  26552. h = r.bottom - r.top;
  26553. pluginRefusesToResize = (w != rw) || (h != rh);
  26554. w = rw;
  26555. h = rh;
  26556. }
  26557. }
  26558. }
  26559. #elif JUCE_LINUX
  26560. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26561. if (pluginWindow != 0)
  26562. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26563. XInternAtom (display, "_XEventProc", False));
  26564. int w = 250, h = 150;
  26565. if (rect != 0)
  26566. {
  26567. w = rect->right - rect->left;
  26568. h = rect->bottom - rect->top;
  26569. if (w == 0 || h == 0)
  26570. {
  26571. w = 250;
  26572. h = 150;
  26573. }
  26574. }
  26575. if (pluginWindow != 0)
  26576. XMapRaised (display, pluginWindow);
  26577. #endif
  26578. // double-check it's not too tiny
  26579. w = jmax (w, 32);
  26580. h = jmax (h, 32);
  26581. setSize (w, h);
  26582. #if JUCE_WIN32
  26583. checkPluginWindowSize();
  26584. #endif
  26585. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26586. repaint();
  26587. }
  26588. #endif
  26589. #if ! JUCE_MAC
  26590. void closePluginWindow()
  26591. {
  26592. if (isOpen)
  26593. {
  26594. log ("Closing VST UI: " + plugin.getName());
  26595. isOpen = false;
  26596. dispatch (effEditClose, 0, 0, 0, 0);
  26597. #if JUCE_WIN32
  26598. #pragma warning (push)
  26599. #pragma warning (disable: 4244)
  26600. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26601. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26602. #pragma warning (pop)
  26603. stopTimer();
  26604. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26605. DestroyWindow (pluginHWND);
  26606. pluginHWND = 0;
  26607. #elif JUCE_LINUX
  26608. stopTimer();
  26609. pluginWindow = 0;
  26610. pluginProc = 0;
  26611. #endif
  26612. }
  26613. }
  26614. #endif
  26615. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26616. {
  26617. return plugin.dispatch (opcode, index, value, ptr, opt);
  26618. }
  26619. #if JUCE_WIN32
  26620. void checkPluginWindowSize() throw()
  26621. {
  26622. RECT r;
  26623. GetWindowRect (pluginHWND, &r);
  26624. const int w = r.right - r.left;
  26625. const int h = r.bottom - r.top;
  26626. if (isShowing() && w > 0 && h > 0
  26627. && (w != getWidth() || h != getHeight())
  26628. && ! pluginRefusesToResize)
  26629. {
  26630. setSize (w, h);
  26631. sizeCheckCount = 0;
  26632. }
  26633. }
  26634. // hooks to get keyboard events from VST windows..
  26635. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26636. {
  26637. for (int i = activeVSTWindows.size(); --i >= 0;)
  26638. {
  26639. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26640. if (w->pluginHWND == hW)
  26641. {
  26642. if (message == WM_CHAR
  26643. || message == WM_KEYDOWN
  26644. || message == WM_SYSKEYDOWN
  26645. || message == WM_KEYUP
  26646. || message == WM_SYSKEYUP
  26647. || message == WM_APPCOMMAND)
  26648. {
  26649. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26650. message, wParam, lParam);
  26651. }
  26652. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26653. (HWND) w->pluginHWND,
  26654. message,
  26655. wParam,
  26656. lParam);
  26657. }
  26658. }
  26659. return DefWindowProc (hW, message, wParam, lParam);
  26660. }
  26661. #endif
  26662. #if JUCE_LINUX
  26663. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26664. void sendEventToChild (XEvent* event)
  26665. {
  26666. if (pluginProc != 0)
  26667. {
  26668. // if the plugin publishes an event procedure, pass the event directly..
  26669. pluginProc (event);
  26670. }
  26671. else if (pluginWindow != 0)
  26672. {
  26673. // if the plugin has a window, then send the event to the window so that
  26674. // its message thread will pick it up..
  26675. XSendEvent (display, pluginWindow, False, 0L, event);
  26676. XFlush (display);
  26677. }
  26678. }
  26679. void mouseEnter (const MouseEvent& e)
  26680. {
  26681. if (pluginWindow != 0)
  26682. {
  26683. XEvent ev;
  26684. zerostruct (ev);
  26685. ev.xcrossing.display = display;
  26686. ev.xcrossing.type = EnterNotify;
  26687. ev.xcrossing.window = pluginWindow;
  26688. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26689. ev.xcrossing.time = CurrentTime;
  26690. ev.xcrossing.x = e.x;
  26691. ev.xcrossing.y = e.y;
  26692. ev.xcrossing.x_root = e.getScreenX();
  26693. ev.xcrossing.y_root = e.getScreenY();
  26694. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26695. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26696. translateJuceToXCrossingModifiers (e, ev);
  26697. sendEventToChild (&ev);
  26698. }
  26699. }
  26700. void mouseExit (const MouseEvent& e)
  26701. {
  26702. if (pluginWindow != 0)
  26703. {
  26704. XEvent ev;
  26705. zerostruct (ev);
  26706. ev.xcrossing.display = display;
  26707. ev.xcrossing.type = LeaveNotify;
  26708. ev.xcrossing.window = pluginWindow;
  26709. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26710. ev.xcrossing.time = CurrentTime;
  26711. ev.xcrossing.x = e.x;
  26712. ev.xcrossing.y = e.y;
  26713. ev.xcrossing.x_root = e.getScreenX();
  26714. ev.xcrossing.y_root = e.getScreenY();
  26715. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26716. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26717. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26718. translateJuceToXCrossingModifiers (e, ev);
  26719. sendEventToChild (&ev);
  26720. }
  26721. }
  26722. void mouseMove (const MouseEvent& e)
  26723. {
  26724. if (pluginWindow != 0)
  26725. {
  26726. XEvent ev;
  26727. zerostruct (ev);
  26728. ev.xmotion.display = display;
  26729. ev.xmotion.type = MotionNotify;
  26730. ev.xmotion.window = pluginWindow;
  26731. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26732. ev.xmotion.time = CurrentTime;
  26733. ev.xmotion.is_hint = NotifyNormal;
  26734. ev.xmotion.x = e.x;
  26735. ev.xmotion.y = e.y;
  26736. ev.xmotion.x_root = e.getScreenX();
  26737. ev.xmotion.y_root = e.getScreenY();
  26738. sendEventToChild (&ev);
  26739. }
  26740. }
  26741. void mouseDrag (const MouseEvent& e)
  26742. {
  26743. if (pluginWindow != 0)
  26744. {
  26745. XEvent ev;
  26746. zerostruct (ev);
  26747. ev.xmotion.display = display;
  26748. ev.xmotion.type = MotionNotify;
  26749. ev.xmotion.window = pluginWindow;
  26750. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26751. ev.xmotion.time = CurrentTime;
  26752. ev.xmotion.x = e.x ;
  26753. ev.xmotion.y = e.y;
  26754. ev.xmotion.x_root = e.getScreenX();
  26755. ev.xmotion.y_root = e.getScreenY();
  26756. ev.xmotion.is_hint = NotifyNormal;
  26757. translateJuceToXMotionModifiers (e, ev);
  26758. sendEventToChild (&ev);
  26759. }
  26760. }
  26761. void mouseUp (const MouseEvent& e)
  26762. {
  26763. if (pluginWindow != 0)
  26764. {
  26765. XEvent ev;
  26766. zerostruct (ev);
  26767. ev.xbutton.display = display;
  26768. ev.xbutton.type = ButtonRelease;
  26769. ev.xbutton.window = pluginWindow;
  26770. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26771. ev.xbutton.time = CurrentTime;
  26772. ev.xbutton.x = e.x;
  26773. ev.xbutton.y = e.y;
  26774. ev.xbutton.x_root = e.getScreenX();
  26775. ev.xbutton.y_root = e.getScreenY();
  26776. translateJuceToXButtonModifiers (e, ev);
  26777. sendEventToChild (&ev);
  26778. }
  26779. }
  26780. void mouseWheelMove (const MouseEvent& e,
  26781. float incrementX,
  26782. float incrementY)
  26783. {
  26784. if (pluginWindow != 0)
  26785. {
  26786. XEvent ev;
  26787. zerostruct (ev);
  26788. ev.xbutton.display = display;
  26789. ev.xbutton.type = ButtonPress;
  26790. ev.xbutton.window = pluginWindow;
  26791. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26792. ev.xbutton.time = CurrentTime;
  26793. ev.xbutton.x = e.x;
  26794. ev.xbutton.y = e.y;
  26795. ev.xbutton.x_root = e.getScreenX();
  26796. ev.xbutton.y_root = e.getScreenY();
  26797. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26798. sendEventToChild (&ev);
  26799. // TODO - put a usleep here ?
  26800. ev.xbutton.type = ButtonRelease;
  26801. sendEventToChild (&ev);
  26802. }
  26803. }
  26804. #endif
  26805. #if JUCE_MAC
  26806. #if ! JUCE_SUPPORT_CARBON
  26807. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26808. #endif
  26809. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26810. {
  26811. public:
  26812. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26813. : owner (owner_),
  26814. alreadyInside (false)
  26815. {
  26816. }
  26817. ~InnerWrapperComponent()
  26818. {
  26819. deleteWindow();
  26820. }
  26821. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26822. {
  26823. owner->openPluginWindow (windowRef);
  26824. return 0;
  26825. }
  26826. void removeView (HIViewRef)
  26827. {
  26828. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26829. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26830. }
  26831. bool getEmbeddedViewSize (int& w, int& h)
  26832. {
  26833. ERect* rect = 0;
  26834. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26835. w = rect->right - rect->left;
  26836. h = rect->bottom - rect->top;
  26837. return true;
  26838. }
  26839. void mouseDown (int x, int y)
  26840. {
  26841. if (! alreadyInside)
  26842. {
  26843. alreadyInside = true;
  26844. getTopLevelComponent()->toFront (true);
  26845. owner->dispatch (effEditMouse, x, y, 0, 0);
  26846. alreadyInside = false;
  26847. }
  26848. else
  26849. {
  26850. PostEvent (::mouseDown, 0);
  26851. }
  26852. }
  26853. void paint()
  26854. {
  26855. ComponentPeer* const peer = getPeer();
  26856. if (peer != 0)
  26857. {
  26858. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26859. ERect r;
  26860. r.left = pos.getX();
  26861. r.right = r.left + getWidth();
  26862. r.top = pos.getY();
  26863. r.bottom = r.top + getHeight();
  26864. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26865. }
  26866. }
  26867. private:
  26868. VSTPluginWindow* const owner;
  26869. bool alreadyInside;
  26870. };
  26871. friend class InnerWrapperComponent;
  26872. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26873. void resized()
  26874. {
  26875. innerWrapper->setSize (getWidth(), getHeight());
  26876. }
  26877. #endif
  26878. };
  26879. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26880. {
  26881. if (hasEditor())
  26882. return new VSTPluginWindow (*this);
  26883. return 0;
  26884. }
  26885. void VSTPluginInstance::handleAsyncUpdate()
  26886. {
  26887. // indicates that something about the plugin has changed..
  26888. updateHostDisplay();
  26889. }
  26890. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26891. {
  26892. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26893. {
  26894. changeProgramName (getCurrentProgram(), prog->prgName);
  26895. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26896. setParameter (i, vst_swapFloat (prog->params[i]));
  26897. return true;
  26898. }
  26899. return false;
  26900. }
  26901. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26902. const int dataSize)
  26903. {
  26904. if (dataSize < 28)
  26905. return false;
  26906. const fxSet* const set = (const fxSet*) data;
  26907. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26908. || vst_swap (set->version) > fxbVersionNum)
  26909. return false;
  26910. if (vst_swap (set->fxMagic) == 'FxBk')
  26911. {
  26912. // bank of programs
  26913. if (vst_swap (set->numPrograms) >= 0)
  26914. {
  26915. const int oldProg = getCurrentProgram();
  26916. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26917. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26918. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26919. {
  26920. if (i != oldProg)
  26921. {
  26922. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26923. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26924. return false;
  26925. if (vst_swap (set->numPrograms) > 0)
  26926. setCurrentProgram (i);
  26927. if (! restoreProgramSettings (prog))
  26928. return false;
  26929. }
  26930. }
  26931. if (vst_swap (set->numPrograms) > 0)
  26932. setCurrentProgram (oldProg);
  26933. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26934. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26935. return false;
  26936. if (! restoreProgramSettings (prog))
  26937. return false;
  26938. }
  26939. }
  26940. else if (vst_swap (set->fxMagic) == 'FxCk')
  26941. {
  26942. // single program
  26943. const fxProgram* const prog = (const fxProgram*) data;
  26944. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26945. return false;
  26946. changeProgramName (getCurrentProgram(), prog->prgName);
  26947. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26948. setParameter (i, vst_swapFloat (prog->params[i]));
  26949. }
  26950. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26951. {
  26952. // non-preset chunk
  26953. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26954. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26955. return false;
  26956. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26957. }
  26958. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26959. {
  26960. // preset chunk
  26961. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26962. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26963. return false;
  26964. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26965. changeProgramName (getCurrentProgram(), cset->name);
  26966. }
  26967. else
  26968. {
  26969. return false;
  26970. }
  26971. return true;
  26972. }
  26973. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26974. {
  26975. const int numParams = getNumParameters();
  26976. prog->chunkMagic = vst_swap ('CcnK');
  26977. prog->byteSize = 0;
  26978. prog->fxMagic = vst_swap ('FxCk');
  26979. prog->version = vst_swap (fxbVersionNum);
  26980. prog->fxID = vst_swap (getUID());
  26981. prog->fxVersion = vst_swap (getVersionNumber());
  26982. prog->numParams = vst_swap (numParams);
  26983. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  26984. for (int i = 0; i < numParams; ++i)
  26985. prog->params[i] = vst_swapFloat (getParameter (i));
  26986. }
  26987. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26988. {
  26989. const int numPrograms = getNumPrograms();
  26990. const int numParams = getNumParameters();
  26991. if (usesChunks())
  26992. {
  26993. if (isFXB)
  26994. {
  26995. MemoryBlock chunk;
  26996. getChunkData (chunk, false, maxSizeMB);
  26997. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26998. dest.setSize (totalLen, true);
  26999. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27000. set->chunkMagic = vst_swap ('CcnK');
  27001. set->byteSize = 0;
  27002. set->fxMagic = vst_swap ('FBCh');
  27003. set->version = vst_swap (fxbVersionNum);
  27004. set->fxID = vst_swap (getUID());
  27005. set->fxVersion = vst_swap (getVersionNumber());
  27006. set->numPrograms = vst_swap (numPrograms);
  27007. set->chunkSize = vst_swap ((long) chunk.getSize());
  27008. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27009. }
  27010. else
  27011. {
  27012. MemoryBlock chunk;
  27013. getChunkData (chunk, true, maxSizeMB);
  27014. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27015. dest.setSize (totalLen, true);
  27016. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27017. set->chunkMagic = vst_swap ('CcnK');
  27018. set->byteSize = 0;
  27019. set->fxMagic = vst_swap ('FPCh');
  27020. set->version = vst_swap (fxbVersionNum);
  27021. set->fxID = vst_swap (getUID());
  27022. set->fxVersion = vst_swap (getVersionNumber());
  27023. set->numPrograms = vst_swap (numPrograms);
  27024. set->chunkSize = vst_swap ((long) chunk.getSize());
  27025. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27026. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27027. }
  27028. }
  27029. else
  27030. {
  27031. if (isFXB)
  27032. {
  27033. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27034. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27035. dest.setSize (len, true);
  27036. fxSet* const set = (fxSet*) dest.getData();
  27037. set->chunkMagic = vst_swap ('CcnK');
  27038. set->byteSize = 0;
  27039. set->fxMagic = vst_swap ('FxBk');
  27040. set->version = vst_swap (fxbVersionNum);
  27041. set->fxID = vst_swap (getUID());
  27042. set->fxVersion = vst_swap (getVersionNumber());
  27043. set->numPrograms = vst_swap (numPrograms);
  27044. const int oldProgram = getCurrentProgram();
  27045. MemoryBlock oldSettings;
  27046. createTempParameterStore (oldSettings);
  27047. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27048. for (int i = 0; i < numPrograms; ++i)
  27049. {
  27050. if (i != oldProgram)
  27051. {
  27052. setCurrentProgram (i);
  27053. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27054. }
  27055. }
  27056. setCurrentProgram (oldProgram);
  27057. restoreFromTempParameterStore (oldSettings);
  27058. }
  27059. else
  27060. {
  27061. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27062. dest.setSize (totalLen, true);
  27063. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27064. }
  27065. }
  27066. return true;
  27067. }
  27068. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27069. {
  27070. if (usesChunks())
  27071. {
  27072. void* data = 0;
  27073. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27074. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27075. {
  27076. mb.setSize (bytes);
  27077. mb.copyFrom (data, 0, bytes);
  27078. }
  27079. }
  27080. }
  27081. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27082. {
  27083. if (size > 0 && usesChunks())
  27084. {
  27085. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27086. if (! isPreset)
  27087. updateStoredProgramNames();
  27088. }
  27089. }
  27090. void VSTPluginInstance::timerCallback()
  27091. {
  27092. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27093. stopTimer();
  27094. }
  27095. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27096. {
  27097. const ScopedLock sl (lock);
  27098. ++insideVSTCallback;
  27099. int result = 0;
  27100. try
  27101. {
  27102. if (effect != 0)
  27103. {
  27104. #if JUCE_MAC
  27105. if (module->resFileId != 0)
  27106. UseResFile (module->resFileId);
  27107. CGrafPtr oldPort;
  27108. if (getActiveEditor() != 0)
  27109. {
  27110. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27111. GetPort (&oldPort);
  27112. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27113. SetOrigin (-pos.getX(), -pos.getY());
  27114. }
  27115. #endif
  27116. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27117. #if JUCE_MAC
  27118. if (getActiveEditor() != 0)
  27119. SetPort (oldPort);
  27120. module->resFileId = CurResFile();
  27121. #endif
  27122. --insideVSTCallback;
  27123. return result;
  27124. }
  27125. }
  27126. catch (...)
  27127. {
  27128. }
  27129. --insideVSTCallback;
  27130. return result;
  27131. }
  27132. // handles non plugin-specific callbacks..
  27133. static const int defaultVSTSampleRateValue = 16384;
  27134. static const int defaultVSTBlockSizeValue = 512;
  27135. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27136. {
  27137. (void) index;
  27138. (void) value;
  27139. (void) opt;
  27140. switch (opcode)
  27141. {
  27142. case audioMasterCanDo:
  27143. {
  27144. static const char* canDos[] = { "supplyIdle",
  27145. "sendVstEvents",
  27146. "sendVstMidiEvent",
  27147. "sendVstTimeInfo",
  27148. "receiveVstEvents",
  27149. "receiveVstMidiEvent",
  27150. "supportShell",
  27151. "shellCategory" };
  27152. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27153. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27154. return 1;
  27155. return 0;
  27156. }
  27157. case audioMasterVersion:
  27158. return 0x2400;
  27159. case audioMasterCurrentId:
  27160. return shellUIDToCreate;
  27161. case audioMasterGetNumAutomatableParameters:
  27162. return 0;
  27163. case audioMasterGetAutomationState:
  27164. return 1;
  27165. case audioMasterGetVendorVersion:
  27166. return 0x0101;
  27167. case audioMasterGetVendorString:
  27168. case audioMasterGetProductString:
  27169. {
  27170. String hostName ("Juce VST Host");
  27171. if (JUCEApplication::getInstance() != 0)
  27172. hostName = JUCEApplication::getInstance()->getApplicationName();
  27173. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27174. }
  27175. break;
  27176. case audioMasterGetSampleRate:
  27177. return (VstIntPtr) defaultVSTSampleRateValue;
  27178. case audioMasterGetBlockSize:
  27179. return (VstIntPtr) defaultVSTBlockSizeValue;
  27180. case audioMasterSetOutputSampleRate:
  27181. return 0;
  27182. default:
  27183. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27184. break;
  27185. }
  27186. return 0;
  27187. }
  27188. // handles callbacks for a specific plugin
  27189. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27190. {
  27191. switch (opcode)
  27192. {
  27193. case audioMasterAutomate:
  27194. sendParamChangeMessageToListeners (index, opt);
  27195. break;
  27196. case audioMasterProcessEvents:
  27197. handleMidiFromPlugin ((const VstEvents*) ptr);
  27198. break;
  27199. case audioMasterGetTime:
  27200. #ifdef _MSC_VER
  27201. #pragma warning (push)
  27202. #pragma warning (disable: 4311)
  27203. #endif
  27204. return (VstIntPtr) &vstHostTime;
  27205. #ifdef _MSC_VER
  27206. #pragma warning (pop)
  27207. #endif
  27208. break;
  27209. case audioMasterIdle:
  27210. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27211. {
  27212. ++insideVSTCallback;
  27213. #if JUCE_MAC
  27214. if (getActiveEditor() != 0)
  27215. dispatch (effEditIdle, 0, 0, 0, 0);
  27216. #endif
  27217. juce_callAnyTimersSynchronously();
  27218. handleUpdateNowIfNeeded();
  27219. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27220. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27221. --insideVSTCallback;
  27222. }
  27223. break;
  27224. case audioMasterUpdateDisplay:
  27225. triggerAsyncUpdate();
  27226. break;
  27227. case audioMasterTempoAt:
  27228. // returns (10000 * bpm)
  27229. break;
  27230. case audioMasterNeedIdle:
  27231. startTimer (50);
  27232. break;
  27233. case audioMasterSizeWindow:
  27234. if (getActiveEditor() != 0)
  27235. getActiveEditor()->setSize (index, value);
  27236. return 1;
  27237. case audioMasterGetSampleRate:
  27238. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27239. case audioMasterGetBlockSize:
  27240. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27241. case audioMasterWantMidi:
  27242. wantsMidiMessages = true;
  27243. break;
  27244. case audioMasterGetDirectory:
  27245. #if JUCE_MAC
  27246. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27247. #else
  27248. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27249. #endif
  27250. case audioMasterGetAutomationState:
  27251. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27252. break;
  27253. // none of these are handled (yet)..
  27254. case audioMasterBeginEdit:
  27255. case audioMasterEndEdit:
  27256. case audioMasterSetTime:
  27257. case audioMasterPinConnected:
  27258. case audioMasterGetParameterQuantization:
  27259. case audioMasterIOChanged:
  27260. case audioMasterGetInputLatency:
  27261. case audioMasterGetOutputLatency:
  27262. case audioMasterGetPreviousPlug:
  27263. case audioMasterGetNextPlug:
  27264. case audioMasterWillReplaceOrAccumulate:
  27265. case audioMasterGetCurrentProcessLevel:
  27266. case audioMasterOfflineStart:
  27267. case audioMasterOfflineRead:
  27268. case audioMasterOfflineWrite:
  27269. case audioMasterOfflineGetCurrentPass:
  27270. case audioMasterOfflineGetCurrentMetaPass:
  27271. case audioMasterVendorSpecific:
  27272. case audioMasterSetIcon:
  27273. case audioMasterGetLanguage:
  27274. case audioMasterOpenWindow:
  27275. case audioMasterCloseWindow:
  27276. break;
  27277. default:
  27278. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27279. }
  27280. return 0;
  27281. }
  27282. // entry point for all callbacks from the plugin
  27283. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27284. {
  27285. try
  27286. {
  27287. if (effect != 0 && effect->resvd2 != 0)
  27288. {
  27289. return ((VSTPluginInstance*)(effect->resvd2))
  27290. ->handleCallback (opcode, index, value, ptr, opt);
  27291. }
  27292. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27293. }
  27294. catch (...)
  27295. {
  27296. return 0;
  27297. }
  27298. }
  27299. const String VSTPluginInstance::getVersion() const throw()
  27300. {
  27301. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27302. String s;
  27303. if (v == 0 || v == -1)
  27304. v = getVersionNumber();
  27305. if (v != 0)
  27306. {
  27307. int versionBits[4];
  27308. int n = 0;
  27309. while (v != 0)
  27310. {
  27311. versionBits [n++] = (v & 0xff);
  27312. v >>= 8;
  27313. }
  27314. s << 'V';
  27315. while (n > 0)
  27316. {
  27317. s << versionBits [--n];
  27318. if (n > 0)
  27319. s << '.';
  27320. }
  27321. }
  27322. return s;
  27323. }
  27324. int VSTPluginInstance::getUID() const throw()
  27325. {
  27326. int uid = effect != 0 ? effect->uniqueID : 0;
  27327. if (uid == 0)
  27328. uid = module->file.hashCode();
  27329. return uid;
  27330. }
  27331. const String VSTPluginInstance::getCategory() const throw()
  27332. {
  27333. const char* result = 0;
  27334. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27335. {
  27336. case kPlugCategEffect:
  27337. result = "Effect";
  27338. break;
  27339. case kPlugCategSynth:
  27340. result = "Synth";
  27341. break;
  27342. case kPlugCategAnalysis:
  27343. result = "Anaylsis";
  27344. break;
  27345. case kPlugCategMastering:
  27346. result = "Mastering";
  27347. break;
  27348. case kPlugCategSpacializer:
  27349. result = "Spacial";
  27350. break;
  27351. case kPlugCategRoomFx:
  27352. result = "Reverb";
  27353. break;
  27354. case kPlugSurroundFx:
  27355. result = "Surround";
  27356. break;
  27357. case kPlugCategRestoration:
  27358. result = "Restoration";
  27359. break;
  27360. case kPlugCategGenerator:
  27361. result = "Tone generation";
  27362. break;
  27363. default:
  27364. break;
  27365. }
  27366. return result;
  27367. }
  27368. float VSTPluginInstance::getParameter (int index)
  27369. {
  27370. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27371. {
  27372. try
  27373. {
  27374. const ScopedLock sl (lock);
  27375. return effect->getParameter (effect, index);
  27376. }
  27377. catch (...)
  27378. {
  27379. }
  27380. }
  27381. return 0.0f;
  27382. }
  27383. void VSTPluginInstance::setParameter (int index, float newValue)
  27384. {
  27385. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27386. {
  27387. try
  27388. {
  27389. const ScopedLock sl (lock);
  27390. if (effect->getParameter (effect, index) != newValue)
  27391. effect->setParameter (effect, index, newValue);
  27392. }
  27393. catch (...)
  27394. {
  27395. }
  27396. }
  27397. }
  27398. const String VSTPluginInstance::getParameterName (int index)
  27399. {
  27400. if (effect != 0)
  27401. {
  27402. jassert (index >= 0 && index < effect->numParams);
  27403. char nm [256];
  27404. zerostruct (nm);
  27405. dispatch (effGetParamName, index, 0, nm, 0);
  27406. return String (nm).trim();
  27407. }
  27408. return String::empty;
  27409. }
  27410. const String VSTPluginInstance::getParameterLabel (int index) const
  27411. {
  27412. if (effect != 0)
  27413. {
  27414. jassert (index >= 0 && index < effect->numParams);
  27415. char nm [256];
  27416. zerostruct (nm);
  27417. dispatch (effGetParamLabel, index, 0, nm, 0);
  27418. return String (nm).trim();
  27419. }
  27420. return String::empty;
  27421. }
  27422. const String VSTPluginInstance::getParameterText (int index)
  27423. {
  27424. if (effect != 0)
  27425. {
  27426. jassert (index >= 0 && index < effect->numParams);
  27427. char nm [256];
  27428. zerostruct (nm);
  27429. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27430. return String (nm).trim();
  27431. }
  27432. return String::empty;
  27433. }
  27434. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27435. {
  27436. if (effect != 0)
  27437. {
  27438. jassert (index >= 0 && index < effect->numParams);
  27439. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27440. }
  27441. return false;
  27442. }
  27443. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27444. {
  27445. dest.setSize (64 + 4 * getNumParameters());
  27446. dest.fillWith (0);
  27447. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27448. float* const p = (float*) (((char*) dest.getData()) + 64);
  27449. for (int i = 0; i < getNumParameters(); ++i)
  27450. p[i] = getParameter(i);
  27451. }
  27452. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27453. {
  27454. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27455. float* p = (float*) (((char*) m.getData()) + 64);
  27456. for (int i = 0; i < getNumParameters(); ++i)
  27457. setParameter (i, p[i]);
  27458. }
  27459. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27460. {
  27461. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27462. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27463. }
  27464. const String VSTPluginInstance::getProgramName (int index)
  27465. {
  27466. if (index == getCurrentProgram())
  27467. {
  27468. return getCurrentProgramName();
  27469. }
  27470. else if (effect != 0)
  27471. {
  27472. char nm [256];
  27473. zerostruct (nm);
  27474. if (dispatch (effGetProgramNameIndexed,
  27475. jlimit (0, getNumPrograms(), index),
  27476. -1, nm, 0) != 0)
  27477. {
  27478. return String (nm).trim();
  27479. }
  27480. }
  27481. return programNames [index];
  27482. }
  27483. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27484. {
  27485. if (index == getCurrentProgram())
  27486. {
  27487. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27488. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27489. }
  27490. else
  27491. {
  27492. jassertfalse // xxx not implemented!
  27493. }
  27494. }
  27495. void VSTPluginInstance::updateStoredProgramNames()
  27496. {
  27497. if (effect != 0 && getNumPrograms() > 0)
  27498. {
  27499. char nm [256];
  27500. zerostruct (nm);
  27501. // only do this if the plugin can't use indexed names..
  27502. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27503. {
  27504. const int oldProgram = getCurrentProgram();
  27505. MemoryBlock oldSettings;
  27506. createTempParameterStore (oldSettings);
  27507. for (int i = 0; i < getNumPrograms(); ++i)
  27508. {
  27509. setCurrentProgram (i);
  27510. getCurrentProgramName(); // (this updates the list)
  27511. }
  27512. setCurrentProgram (oldProgram);
  27513. restoreFromTempParameterStore (oldSettings);
  27514. }
  27515. }
  27516. }
  27517. const String VSTPluginInstance::getCurrentProgramName()
  27518. {
  27519. if (effect != 0)
  27520. {
  27521. char nm [256];
  27522. zerostruct (nm);
  27523. dispatch (effGetProgramName, 0, 0, nm, 0);
  27524. const int index = getCurrentProgram();
  27525. if (programNames[index].isEmpty())
  27526. {
  27527. while (programNames.size() < index)
  27528. programNames.add (String::empty);
  27529. programNames.set (index, String (nm).trim());
  27530. }
  27531. return String (nm).trim();
  27532. }
  27533. return String::empty;
  27534. }
  27535. const String VSTPluginInstance::getInputChannelName (const int index) const
  27536. {
  27537. if (index >= 0 && index < getNumInputChannels())
  27538. {
  27539. VstPinProperties pinProps;
  27540. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27541. return String (pinProps.label, sizeof (pinProps.label));
  27542. }
  27543. return String::empty;
  27544. }
  27545. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27546. {
  27547. if (index < 0 || index >= getNumInputChannels())
  27548. return false;
  27549. VstPinProperties pinProps;
  27550. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27551. return (pinProps.flags & kVstPinIsStereo) != 0;
  27552. return true;
  27553. }
  27554. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27555. {
  27556. if (index >= 0 && index < getNumOutputChannels())
  27557. {
  27558. VstPinProperties pinProps;
  27559. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27560. return String (pinProps.label, sizeof (pinProps.label));
  27561. }
  27562. return String::empty;
  27563. }
  27564. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27565. {
  27566. if (index < 0 || index >= getNumOutputChannels())
  27567. return false;
  27568. VstPinProperties pinProps;
  27569. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27570. return (pinProps.flags & kVstPinIsStereo) != 0;
  27571. return true;
  27572. }
  27573. void VSTPluginInstance::setPower (const bool on)
  27574. {
  27575. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27576. isPowerOn = on;
  27577. }
  27578. const int defaultMaxSizeMB = 64;
  27579. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27580. {
  27581. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27582. }
  27583. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27584. {
  27585. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27586. }
  27587. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27588. {
  27589. loadFromFXBFile (data, sizeInBytes);
  27590. }
  27591. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27592. {
  27593. loadFromFXBFile (data, sizeInBytes);
  27594. }
  27595. VSTPluginFormat::VSTPluginFormat()
  27596. {
  27597. }
  27598. VSTPluginFormat::~VSTPluginFormat()
  27599. {
  27600. }
  27601. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27602. const String& fileOrIdentifier)
  27603. {
  27604. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27605. return;
  27606. PluginDescription desc;
  27607. desc.fileOrIdentifier = fileOrIdentifier;
  27608. desc.uid = 0;
  27609. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27610. if (instance == 0)
  27611. return;
  27612. try
  27613. {
  27614. #if JUCE_MAC
  27615. if (instance->module->resFileId != 0)
  27616. UseResFile (instance->module->resFileId);
  27617. #endif
  27618. instance->fillInPluginDescription (desc);
  27619. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27620. if (category != kPlugCategShell)
  27621. {
  27622. // Normal plugin...
  27623. results.add (new PluginDescription (desc));
  27624. ++insideVSTCallback;
  27625. instance->dispatch (effOpen, 0, 0, 0, 0);
  27626. --insideVSTCallback;
  27627. }
  27628. else
  27629. {
  27630. // It's a shell plugin, so iterate all the subtypes...
  27631. char shellEffectName [64];
  27632. for (;;)
  27633. {
  27634. zerostruct (shellEffectName);
  27635. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27636. if (uid == 0)
  27637. {
  27638. break;
  27639. }
  27640. else
  27641. {
  27642. desc.uid = uid;
  27643. desc.name = shellEffectName;
  27644. bool alreadyThere = false;
  27645. for (int i = results.size(); --i >= 0;)
  27646. {
  27647. PluginDescription* const d = results.getUnchecked(i);
  27648. if (d->isDuplicateOf (desc))
  27649. {
  27650. alreadyThere = true;
  27651. break;
  27652. }
  27653. }
  27654. if (! alreadyThere)
  27655. results.add (new PluginDescription (desc));
  27656. }
  27657. }
  27658. }
  27659. }
  27660. catch (...)
  27661. {
  27662. // crashed while loading...
  27663. }
  27664. }
  27665. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27666. {
  27667. ScopedPointer <VSTPluginInstance> result;
  27668. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27669. {
  27670. File file (desc.fileOrIdentifier);
  27671. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27672. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27673. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27674. if (module != 0)
  27675. {
  27676. shellUIDToCreate = desc.uid;
  27677. result = new VSTPluginInstance (module);
  27678. if (result->effect != 0)
  27679. {
  27680. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27681. result->initialise();
  27682. }
  27683. else
  27684. {
  27685. result = 0;
  27686. }
  27687. }
  27688. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27689. }
  27690. return result.release();
  27691. }
  27692. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27693. {
  27694. const File f (fileOrIdentifier);
  27695. #if JUCE_MAC
  27696. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27697. return true;
  27698. #if JUCE_PPC
  27699. FSRef fileRef;
  27700. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27701. {
  27702. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27703. if (resFileId != -1)
  27704. {
  27705. const int numEffects = Count1Resources ('aEff');
  27706. CloseResFile (resFileId);
  27707. if (numEffects > 0)
  27708. return true;
  27709. }
  27710. }
  27711. #endif
  27712. return false;
  27713. #elif JUCE_WIN32
  27714. return f.existsAsFile()
  27715. && f.hasFileExtension (".dll");
  27716. #elif JUCE_LINUX
  27717. return f.existsAsFile()
  27718. && f.hasFileExtension (".so");
  27719. #endif
  27720. }
  27721. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27722. {
  27723. return fileOrIdentifier;
  27724. }
  27725. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27726. {
  27727. return File (desc.fileOrIdentifier).exists();
  27728. }
  27729. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27730. {
  27731. StringArray results;
  27732. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27733. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27734. return results;
  27735. }
  27736. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27737. {
  27738. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27739. // .component or .vst directories.
  27740. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27741. while (iter.next())
  27742. {
  27743. const File f (iter.getFile());
  27744. bool isPlugin = false;
  27745. if (fileMightContainThisPluginType (f.getFullPathName()))
  27746. {
  27747. isPlugin = true;
  27748. results.add (f.getFullPathName());
  27749. }
  27750. if (recursive && (! isPlugin) && f.isDirectory())
  27751. recursiveFileSearch (results, f, true);
  27752. }
  27753. }
  27754. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27755. {
  27756. #if JUCE_MAC
  27757. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27758. #elif JUCE_WIN32
  27759. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27760. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27761. #elif JUCE_LINUX
  27762. return FileSearchPath ("/usr/lib/vst");
  27763. #endif
  27764. }
  27765. END_JUCE_NAMESPACE
  27766. #endif
  27767. #undef log
  27768. #endif
  27769. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27770. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27771. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27772. BEGIN_JUCE_NAMESPACE
  27773. AudioProcessor::AudioProcessor()
  27774. : playHead (0),
  27775. activeEditor (0),
  27776. sampleRate (0),
  27777. blockSize (0),
  27778. numInputChannels (0),
  27779. numOutputChannels (0),
  27780. latencySamples (0),
  27781. suspended (false),
  27782. nonRealtime (false)
  27783. {
  27784. }
  27785. AudioProcessor::~AudioProcessor()
  27786. {
  27787. // ooh, nasty - the editor should have been deleted before the filter
  27788. // that it refers to is deleted..
  27789. jassert (activeEditor == 0);
  27790. #if JUCE_DEBUG
  27791. // This will fail if you've called beginParameterChangeGesture() for one
  27792. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27793. jassert (changingParams.countNumberOfSetBits() == 0);
  27794. #endif
  27795. }
  27796. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27797. {
  27798. playHead = newPlayHead;
  27799. }
  27800. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27801. {
  27802. const ScopedLock sl (listenerLock);
  27803. listeners.addIfNotAlreadyThere (newListener);
  27804. }
  27805. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27806. {
  27807. const ScopedLock sl (listenerLock);
  27808. listeners.removeValue (listenerToRemove);
  27809. }
  27810. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27811. const int numOuts,
  27812. const double sampleRate_,
  27813. const int blockSize_) throw()
  27814. {
  27815. numInputChannels = numIns;
  27816. numOutputChannels = numOuts;
  27817. sampleRate = sampleRate_;
  27818. blockSize = blockSize_;
  27819. }
  27820. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27821. {
  27822. nonRealtime = nonRealtime_;
  27823. }
  27824. void AudioProcessor::setLatencySamples (const int newLatency)
  27825. {
  27826. if (latencySamples != newLatency)
  27827. {
  27828. latencySamples = newLatency;
  27829. updateHostDisplay();
  27830. }
  27831. }
  27832. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27833. const float newValue)
  27834. {
  27835. setParameter (parameterIndex, newValue);
  27836. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27837. }
  27838. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27839. {
  27840. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27841. for (int i = listeners.size(); --i >= 0;)
  27842. {
  27843. AudioProcessorListener* l;
  27844. {
  27845. const ScopedLock sl (listenerLock);
  27846. l = (AudioProcessorListener*) listeners [i];
  27847. }
  27848. if (l != 0)
  27849. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27850. }
  27851. }
  27852. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27853. {
  27854. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27855. #if JUCE_DEBUG
  27856. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27857. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27858. jassert (! changingParams [parameterIndex]);
  27859. changingParams.setBit (parameterIndex);
  27860. #endif
  27861. for (int i = listeners.size(); --i >= 0;)
  27862. {
  27863. AudioProcessorListener* l;
  27864. {
  27865. const ScopedLock sl (listenerLock);
  27866. l = (AudioProcessorListener*) listeners [i];
  27867. }
  27868. if (l != 0)
  27869. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27870. }
  27871. }
  27872. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27873. {
  27874. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27875. #if JUCE_DEBUG
  27876. // This means you've called endParameterChangeGesture without having previously called
  27877. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27878. // calls matched correctly.
  27879. jassert (changingParams [parameterIndex]);
  27880. changingParams.clearBit (parameterIndex);
  27881. #endif
  27882. for (int i = listeners.size(); --i >= 0;)
  27883. {
  27884. AudioProcessorListener* l;
  27885. {
  27886. const ScopedLock sl (listenerLock);
  27887. l = (AudioProcessorListener*) listeners [i];
  27888. }
  27889. if (l != 0)
  27890. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27891. }
  27892. }
  27893. void AudioProcessor::updateHostDisplay()
  27894. {
  27895. for (int i = listeners.size(); --i >= 0;)
  27896. {
  27897. AudioProcessorListener* l;
  27898. {
  27899. const ScopedLock sl (listenerLock);
  27900. l = (AudioProcessorListener*) listeners [i];
  27901. }
  27902. if (l != 0)
  27903. l->audioProcessorChanged (this);
  27904. }
  27905. }
  27906. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27907. {
  27908. return true;
  27909. }
  27910. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27911. {
  27912. return false;
  27913. }
  27914. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27915. {
  27916. const ScopedLock sl (callbackLock);
  27917. suspended = shouldBeSuspended;
  27918. }
  27919. void AudioProcessor::reset()
  27920. {
  27921. }
  27922. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27923. {
  27924. const ScopedLock sl (callbackLock);
  27925. jassert (activeEditor == editor);
  27926. if (activeEditor == editor)
  27927. activeEditor = 0;
  27928. }
  27929. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27930. {
  27931. if (activeEditor != 0)
  27932. return activeEditor;
  27933. AudioProcessorEditor* const ed = createEditor();
  27934. if (ed != 0)
  27935. {
  27936. // you must give your editor comp a size before returning it..
  27937. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27938. const ScopedLock sl (callbackLock);
  27939. activeEditor = ed;
  27940. }
  27941. return ed;
  27942. }
  27943. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27944. {
  27945. getStateInformation (destData);
  27946. }
  27947. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27948. {
  27949. setStateInformation (data, sizeInBytes);
  27950. }
  27951. // magic number to identify memory blocks that we've stored as XML
  27952. const uint32 magicXmlNumber = 0x21324356;
  27953. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27954. JUCE_NAMESPACE::MemoryBlock& destData)
  27955. {
  27956. const String xmlString (xml.createDocument (String::empty, true, false));
  27957. const int stringLength = xmlString.getNumBytesAsUTF8();
  27958. destData.setSize (stringLength + 10);
  27959. char* const d = (char*) destData.getData();
  27960. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  27961. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  27962. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  27963. }
  27964. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27965. const int sizeInBytes)
  27966. {
  27967. if (sizeInBytes > 8
  27968. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  27969. {
  27970. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  27971. if (stringLength > 0)
  27972. {
  27973. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  27974. jmin ((sizeInBytes - 8), stringLength)));
  27975. return doc.getDocumentElement();
  27976. }
  27977. }
  27978. return 0;
  27979. }
  27980. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27981. {
  27982. }
  27983. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27984. {
  27985. }
  27986. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  27987. {
  27988. return timeInSeconds == other.timeInSeconds
  27989. && ppqPosition == other.ppqPosition
  27990. && editOriginTime == other.editOriginTime
  27991. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  27992. && frameRate == other.frameRate
  27993. && isPlaying == other.isPlaying
  27994. && isRecording == other.isRecording
  27995. && bpm == other.bpm
  27996. && timeSigNumerator == other.timeSigNumerator
  27997. && timeSigDenominator == other.timeSigDenominator;
  27998. }
  27999. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28000. {
  28001. return ! operator== (other);
  28002. }
  28003. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28004. {
  28005. zerostruct (*this);
  28006. timeSigNumerator = 4;
  28007. timeSigDenominator = 4;
  28008. bpm = 120;
  28009. }
  28010. END_JUCE_NAMESPACE
  28011. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28012. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28013. BEGIN_JUCE_NAMESPACE
  28014. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28015. : owner (owner_)
  28016. {
  28017. // the filter must be valid..
  28018. jassert (owner != 0);
  28019. }
  28020. AudioProcessorEditor::~AudioProcessorEditor()
  28021. {
  28022. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28023. // filter for some reason..
  28024. jassert (owner->getActiveEditor() != this);
  28025. }
  28026. END_JUCE_NAMESPACE
  28027. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28028. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28029. BEGIN_JUCE_NAMESPACE
  28030. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28031. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28032. : id (id_),
  28033. processor (processor_),
  28034. isPrepared (false)
  28035. {
  28036. jassert (processor_ != 0);
  28037. }
  28038. AudioProcessorGraph::Node::~Node()
  28039. {
  28040. delete processor;
  28041. }
  28042. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28043. AudioProcessorGraph* const graph)
  28044. {
  28045. if (! isPrepared)
  28046. {
  28047. isPrepared = true;
  28048. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28049. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28050. if (ioProc != 0)
  28051. ioProc->setParentGraph (graph);
  28052. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28053. processor->getNumOutputChannels(),
  28054. sampleRate, blockSize);
  28055. processor->prepareToPlay (sampleRate, blockSize);
  28056. }
  28057. }
  28058. void AudioProcessorGraph::Node::unprepare()
  28059. {
  28060. if (isPrepared)
  28061. {
  28062. isPrepared = false;
  28063. processor->releaseResources();
  28064. }
  28065. }
  28066. AudioProcessorGraph::AudioProcessorGraph()
  28067. : lastNodeId (0),
  28068. renderingBuffers (1, 1),
  28069. currentAudioOutputBuffer (1, 1)
  28070. {
  28071. }
  28072. AudioProcessorGraph::~AudioProcessorGraph()
  28073. {
  28074. clearRenderingSequence();
  28075. clear();
  28076. }
  28077. const String AudioProcessorGraph::getName() const
  28078. {
  28079. return "Audio Graph";
  28080. }
  28081. void AudioProcessorGraph::clear()
  28082. {
  28083. nodes.clear();
  28084. connections.clear();
  28085. triggerAsyncUpdate();
  28086. }
  28087. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28088. {
  28089. for (int i = nodes.size(); --i >= 0;)
  28090. if (nodes.getUnchecked(i)->id == nodeId)
  28091. return nodes.getUnchecked(i);
  28092. return 0;
  28093. }
  28094. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28095. uint32 nodeId)
  28096. {
  28097. if (newProcessor == 0)
  28098. {
  28099. jassertfalse
  28100. return 0;
  28101. }
  28102. if (nodeId == 0)
  28103. {
  28104. nodeId = ++lastNodeId;
  28105. }
  28106. else
  28107. {
  28108. // you can't add a node with an id that already exists in the graph..
  28109. jassert (getNodeForId (nodeId) == 0);
  28110. removeNode (nodeId);
  28111. }
  28112. lastNodeId = nodeId;
  28113. Node* const n = new Node (nodeId, newProcessor);
  28114. nodes.add (n);
  28115. triggerAsyncUpdate();
  28116. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28117. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28118. if (ioProc != 0)
  28119. ioProc->setParentGraph (this);
  28120. return n;
  28121. }
  28122. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28123. {
  28124. disconnectNode (nodeId);
  28125. for (int i = nodes.size(); --i >= 0;)
  28126. {
  28127. if (nodes.getUnchecked(i)->id == nodeId)
  28128. {
  28129. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28130. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28131. if (ioProc != 0)
  28132. ioProc->setParentGraph (0);
  28133. nodes.remove (i);
  28134. triggerAsyncUpdate();
  28135. return true;
  28136. }
  28137. }
  28138. return false;
  28139. }
  28140. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28141. const int sourceChannelIndex,
  28142. const uint32 destNodeId,
  28143. const int destChannelIndex) const
  28144. {
  28145. for (int i = connections.size(); --i >= 0;)
  28146. {
  28147. const Connection* const c = connections.getUnchecked(i);
  28148. if (c->sourceNodeId == sourceNodeId
  28149. && c->destNodeId == destNodeId
  28150. && c->sourceChannelIndex == sourceChannelIndex
  28151. && c->destChannelIndex == destChannelIndex)
  28152. {
  28153. return c;
  28154. }
  28155. }
  28156. return 0;
  28157. }
  28158. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28159. const uint32 possibleDestNodeId) const
  28160. {
  28161. for (int i = connections.size(); --i >= 0;)
  28162. {
  28163. const Connection* const c = connections.getUnchecked(i);
  28164. if (c->sourceNodeId == possibleSourceNodeId
  28165. && c->destNodeId == possibleDestNodeId)
  28166. {
  28167. return true;
  28168. }
  28169. }
  28170. return false;
  28171. }
  28172. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28173. const int sourceChannelIndex,
  28174. const uint32 destNodeId,
  28175. const int destChannelIndex) const
  28176. {
  28177. if (sourceChannelIndex < 0
  28178. || destChannelIndex < 0
  28179. || sourceNodeId == destNodeId
  28180. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28181. return false;
  28182. const Node* const source = getNodeForId (sourceNodeId);
  28183. if (source == 0
  28184. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28185. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28186. return false;
  28187. const Node* const dest = getNodeForId (destNodeId);
  28188. if (dest == 0
  28189. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28190. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28191. return false;
  28192. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28193. destNodeId, destChannelIndex) == 0;
  28194. }
  28195. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28196. const int sourceChannelIndex,
  28197. const uint32 destNodeId,
  28198. const int destChannelIndex)
  28199. {
  28200. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28201. return false;
  28202. Connection* const c = new Connection();
  28203. c->sourceNodeId = sourceNodeId;
  28204. c->sourceChannelIndex = sourceChannelIndex;
  28205. c->destNodeId = destNodeId;
  28206. c->destChannelIndex = destChannelIndex;
  28207. connections.add (c);
  28208. triggerAsyncUpdate();
  28209. return true;
  28210. }
  28211. void AudioProcessorGraph::removeConnection (const int index)
  28212. {
  28213. connections.remove (index);
  28214. triggerAsyncUpdate();
  28215. }
  28216. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28217. const uint32 destNodeId, const int destChannelIndex)
  28218. {
  28219. bool doneAnything = false;
  28220. for (int i = connections.size(); --i >= 0;)
  28221. {
  28222. const Connection* const c = connections.getUnchecked(i);
  28223. if (c->sourceNodeId == sourceNodeId
  28224. && c->destNodeId == destNodeId
  28225. && c->sourceChannelIndex == sourceChannelIndex
  28226. && c->destChannelIndex == destChannelIndex)
  28227. {
  28228. removeConnection (i);
  28229. doneAnything = true;
  28230. triggerAsyncUpdate();
  28231. }
  28232. }
  28233. return doneAnything;
  28234. }
  28235. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28236. {
  28237. bool doneAnything = false;
  28238. for (int i = connections.size(); --i >= 0;)
  28239. {
  28240. const Connection* const c = connections.getUnchecked(i);
  28241. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28242. {
  28243. removeConnection (i);
  28244. doneAnything = true;
  28245. triggerAsyncUpdate();
  28246. }
  28247. }
  28248. return doneAnything;
  28249. }
  28250. bool AudioProcessorGraph::removeIllegalConnections()
  28251. {
  28252. bool doneAnything = false;
  28253. for (int i = connections.size(); --i >= 0;)
  28254. {
  28255. const Connection* const c = connections.getUnchecked(i);
  28256. const Node* const source = getNodeForId (c->sourceNodeId);
  28257. const Node* const dest = getNodeForId (c->destNodeId);
  28258. if (source == 0 || dest == 0
  28259. || (c->sourceChannelIndex != midiChannelIndex
  28260. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28261. || (c->sourceChannelIndex == midiChannelIndex
  28262. && ! source->processor->producesMidi())
  28263. || (c->destChannelIndex != midiChannelIndex
  28264. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28265. || (c->destChannelIndex == midiChannelIndex
  28266. && ! dest->processor->acceptsMidi()))
  28267. {
  28268. removeConnection (i);
  28269. doneAnything = true;
  28270. triggerAsyncUpdate();
  28271. }
  28272. }
  28273. return doneAnything;
  28274. }
  28275. namespace GraphRenderingOps
  28276. {
  28277. class AudioGraphRenderingOp
  28278. {
  28279. public:
  28280. AudioGraphRenderingOp() {}
  28281. virtual ~AudioGraphRenderingOp() {}
  28282. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28283. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28284. const int numSamples) = 0;
  28285. juce_UseDebuggingNewOperator
  28286. };
  28287. class ClearChannelOp : public AudioGraphRenderingOp
  28288. {
  28289. public:
  28290. ClearChannelOp (const int channelNum_)
  28291. : channelNum (channelNum_)
  28292. {}
  28293. ~ClearChannelOp() {}
  28294. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28295. {
  28296. sharedBufferChans.clear (channelNum, 0, numSamples);
  28297. }
  28298. private:
  28299. const int channelNum;
  28300. ClearChannelOp (const ClearChannelOp&);
  28301. ClearChannelOp& operator= (const ClearChannelOp&);
  28302. };
  28303. class CopyChannelOp : public AudioGraphRenderingOp
  28304. {
  28305. public:
  28306. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28307. : srcChannelNum (srcChannelNum_),
  28308. dstChannelNum (dstChannelNum_)
  28309. {}
  28310. ~CopyChannelOp() {}
  28311. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28312. {
  28313. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28314. }
  28315. private:
  28316. const int srcChannelNum, dstChannelNum;
  28317. CopyChannelOp (const CopyChannelOp&);
  28318. CopyChannelOp& operator= (const CopyChannelOp&);
  28319. };
  28320. class AddChannelOp : public AudioGraphRenderingOp
  28321. {
  28322. public:
  28323. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28324. : srcChannelNum (srcChannelNum_),
  28325. dstChannelNum (dstChannelNum_)
  28326. {}
  28327. ~AddChannelOp() {}
  28328. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28329. {
  28330. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28331. }
  28332. private:
  28333. const int srcChannelNum, dstChannelNum;
  28334. AddChannelOp (const AddChannelOp&);
  28335. AddChannelOp& operator= (const AddChannelOp&);
  28336. };
  28337. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28338. {
  28339. public:
  28340. ClearMidiBufferOp (const int bufferNum_)
  28341. : bufferNum (bufferNum_)
  28342. {}
  28343. ~ClearMidiBufferOp() {}
  28344. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28345. {
  28346. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28347. }
  28348. private:
  28349. const int bufferNum;
  28350. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28351. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28352. };
  28353. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28354. {
  28355. public:
  28356. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28357. : srcBufferNum (srcBufferNum_),
  28358. dstBufferNum (dstBufferNum_)
  28359. {}
  28360. ~CopyMidiBufferOp() {}
  28361. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28362. {
  28363. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28364. }
  28365. private:
  28366. const int srcBufferNum, dstBufferNum;
  28367. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28368. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28369. };
  28370. class AddMidiBufferOp : public AudioGraphRenderingOp
  28371. {
  28372. public:
  28373. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28374. : srcBufferNum (srcBufferNum_),
  28375. dstBufferNum (dstBufferNum_)
  28376. {}
  28377. ~AddMidiBufferOp() {}
  28378. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28379. {
  28380. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28381. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28382. }
  28383. private:
  28384. const int srcBufferNum, dstBufferNum;
  28385. AddMidiBufferOp (const AddMidiBufferOp&);
  28386. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28387. };
  28388. class ProcessBufferOp : public AudioGraphRenderingOp
  28389. {
  28390. public:
  28391. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28392. const Array <int>& audioChannelsToUse_,
  28393. const int totalChans_,
  28394. const int midiBufferToUse_)
  28395. : node (node_),
  28396. processor (node_->processor),
  28397. audioChannelsToUse (audioChannelsToUse_),
  28398. totalChans (jmax (1, totalChans_)),
  28399. midiBufferToUse (midiBufferToUse_)
  28400. {
  28401. channels.calloc (totalChans);
  28402. while (audioChannelsToUse.size() < totalChans)
  28403. audioChannelsToUse.add (0);
  28404. }
  28405. ~ProcessBufferOp()
  28406. {
  28407. }
  28408. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28409. {
  28410. for (int i = totalChans; --i >= 0;)
  28411. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28412. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28413. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28414. }
  28415. const AudioProcessorGraph::Node::Ptr node;
  28416. AudioProcessor* const processor;
  28417. private:
  28418. Array <int> audioChannelsToUse;
  28419. HeapBlock <float*> channels;
  28420. int totalChans;
  28421. int midiBufferToUse;
  28422. ProcessBufferOp (const ProcessBufferOp&);
  28423. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28424. };
  28425. /** Used to calculate the correct sequence of rendering ops needed, based on
  28426. the best re-use of shared buffers at each stage.
  28427. */
  28428. class RenderingOpSequenceCalculator
  28429. {
  28430. public:
  28431. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28432. const VoidArray& orderedNodes_,
  28433. VoidArray& renderingOps)
  28434. : graph (graph_),
  28435. orderedNodes (orderedNodes_)
  28436. {
  28437. nodeIds.add (-2); // first buffer is read-only zeros
  28438. channels.add (0);
  28439. midiNodeIds.add (-2);
  28440. for (int i = 0; i < orderedNodes.size(); ++i)
  28441. {
  28442. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28443. renderingOps, i);
  28444. markAnyUnusedBuffersAsFree (i);
  28445. }
  28446. }
  28447. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28448. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28449. juce_UseDebuggingNewOperator
  28450. private:
  28451. AudioProcessorGraph& graph;
  28452. const VoidArray& orderedNodes;
  28453. Array <int> nodeIds, channels, midiNodeIds;
  28454. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28455. VoidArray& renderingOps,
  28456. const int ourRenderingIndex)
  28457. {
  28458. const int numIns = node->processor->getNumInputChannels();
  28459. const int numOuts = node->processor->getNumOutputChannels();
  28460. const int totalChans = jmax (numIns, numOuts);
  28461. Array <int> audioChannelsToUse;
  28462. int midiBufferToUse = -1;
  28463. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28464. {
  28465. // get a list of all the inputs to this node
  28466. Array <int> sourceNodes, sourceOutputChans;
  28467. for (int i = graph.getNumConnections(); --i >= 0;)
  28468. {
  28469. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28470. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28471. {
  28472. sourceNodes.add (c->sourceNodeId);
  28473. sourceOutputChans.add (c->sourceChannelIndex);
  28474. }
  28475. }
  28476. int bufIndex = -1;
  28477. if (sourceNodes.size() == 0)
  28478. {
  28479. // unconnected input channel
  28480. if (inputChan >= numOuts)
  28481. {
  28482. bufIndex = getReadOnlyEmptyBuffer();
  28483. jassert (bufIndex >= 0);
  28484. }
  28485. else
  28486. {
  28487. bufIndex = getFreeBuffer (false);
  28488. renderingOps.add (new ClearChannelOp (bufIndex));
  28489. }
  28490. }
  28491. else if (sourceNodes.size() == 1)
  28492. {
  28493. // channel with a straightforward single input..
  28494. const int srcNode = sourceNodes.getUnchecked(0);
  28495. const int srcChan = sourceOutputChans.getUnchecked(0);
  28496. bufIndex = getBufferContaining (srcNode, srcChan);
  28497. if (bufIndex < 0)
  28498. {
  28499. // if not found, this is probably a feedback loop
  28500. bufIndex = getReadOnlyEmptyBuffer();
  28501. jassert (bufIndex >= 0);
  28502. }
  28503. if (inputChan < numOuts
  28504. && isBufferNeededLater (ourRenderingIndex,
  28505. inputChan,
  28506. srcNode, srcChan))
  28507. {
  28508. // can't mess up this channel because it's needed later by another node, so we
  28509. // need to use a copy of it..
  28510. const int newFreeBuffer = getFreeBuffer (false);
  28511. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28512. bufIndex = newFreeBuffer;
  28513. }
  28514. }
  28515. else
  28516. {
  28517. // channel with a mix of several inputs..
  28518. // try to find a re-usable channel from our inputs..
  28519. int reusableInputIndex = -1;
  28520. for (int i = 0; i < sourceNodes.size(); ++i)
  28521. {
  28522. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28523. sourceOutputChans.getUnchecked(i));
  28524. if (sourceBufIndex >= 0
  28525. && ! isBufferNeededLater (ourRenderingIndex,
  28526. inputChan,
  28527. sourceNodes.getUnchecked(i),
  28528. sourceOutputChans.getUnchecked(i)))
  28529. {
  28530. // we've found one of our input chans that can be re-used..
  28531. reusableInputIndex = i;
  28532. bufIndex = sourceBufIndex;
  28533. break;
  28534. }
  28535. }
  28536. if (reusableInputIndex < 0)
  28537. {
  28538. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28539. bufIndex = getFreeBuffer (false);
  28540. jassert (bufIndex != 0);
  28541. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28542. sourceOutputChans.getUnchecked (0));
  28543. if (srcIndex < 0)
  28544. {
  28545. // if not found, this is probably a feedback loop
  28546. renderingOps.add (new ClearChannelOp (bufIndex));
  28547. }
  28548. else
  28549. {
  28550. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28551. }
  28552. reusableInputIndex = 0;
  28553. }
  28554. for (int j = 0; j < sourceNodes.size(); ++j)
  28555. {
  28556. if (j != reusableInputIndex)
  28557. {
  28558. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28559. sourceOutputChans.getUnchecked(j));
  28560. if (srcIndex >= 0)
  28561. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28562. }
  28563. }
  28564. }
  28565. jassert (bufIndex >= 0);
  28566. audioChannelsToUse.add (bufIndex);
  28567. if (inputChan < numOuts)
  28568. markBufferAsContaining (bufIndex, node->id, inputChan);
  28569. }
  28570. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28571. {
  28572. const int bufIndex = getFreeBuffer (false);
  28573. jassert (bufIndex != 0);
  28574. audioChannelsToUse.add (bufIndex);
  28575. markBufferAsContaining (bufIndex, node->id, outputChan);
  28576. }
  28577. // Now the same thing for midi..
  28578. Array <int> midiSourceNodes;
  28579. for (int i = graph.getNumConnections(); --i >= 0;)
  28580. {
  28581. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28582. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28583. midiSourceNodes.add (c->sourceNodeId);
  28584. }
  28585. if (midiSourceNodes.size() == 0)
  28586. {
  28587. // No midi inputs..
  28588. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28589. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28590. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28591. }
  28592. else if (midiSourceNodes.size() == 1)
  28593. {
  28594. // One midi input..
  28595. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28596. AudioProcessorGraph::midiChannelIndex);
  28597. if (midiBufferToUse >= 0)
  28598. {
  28599. if (isBufferNeededLater (ourRenderingIndex,
  28600. AudioProcessorGraph::midiChannelIndex,
  28601. midiSourceNodes.getUnchecked(0),
  28602. AudioProcessorGraph::midiChannelIndex))
  28603. {
  28604. // can't mess up this channel because it's needed later by another node, so we
  28605. // need to use a copy of it..
  28606. const int newFreeBuffer = getFreeBuffer (true);
  28607. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28608. midiBufferToUse = newFreeBuffer;
  28609. }
  28610. }
  28611. else
  28612. {
  28613. // probably a feedback loop, so just use an empty one..
  28614. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28615. }
  28616. }
  28617. else
  28618. {
  28619. // More than one midi input being mixed..
  28620. int reusableInputIndex = -1;
  28621. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28622. {
  28623. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28624. AudioProcessorGraph::midiChannelIndex);
  28625. if (sourceBufIndex >= 0
  28626. && ! isBufferNeededLater (ourRenderingIndex,
  28627. AudioProcessorGraph::midiChannelIndex,
  28628. midiSourceNodes.getUnchecked(i),
  28629. AudioProcessorGraph::midiChannelIndex))
  28630. {
  28631. // we've found one of our input buffers that can be re-used..
  28632. reusableInputIndex = i;
  28633. midiBufferToUse = sourceBufIndex;
  28634. break;
  28635. }
  28636. }
  28637. if (reusableInputIndex < 0)
  28638. {
  28639. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28640. midiBufferToUse = getFreeBuffer (true);
  28641. jassert (midiBufferToUse >= 0);
  28642. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28643. AudioProcessorGraph::midiChannelIndex);
  28644. if (srcIndex >= 0)
  28645. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28646. else
  28647. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28648. reusableInputIndex = 0;
  28649. }
  28650. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28651. {
  28652. if (j != reusableInputIndex)
  28653. {
  28654. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28655. AudioProcessorGraph::midiChannelIndex);
  28656. if (srcIndex >= 0)
  28657. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28658. }
  28659. }
  28660. }
  28661. if (node->processor->producesMidi())
  28662. markBufferAsContaining (midiBufferToUse, node->id,
  28663. AudioProcessorGraph::midiChannelIndex);
  28664. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28665. totalChans, midiBufferToUse));
  28666. }
  28667. int getFreeBuffer (const bool forMidi)
  28668. {
  28669. if (forMidi)
  28670. {
  28671. for (int i = 1; i < midiNodeIds.size(); ++i)
  28672. if (midiNodeIds.getUnchecked(i) < 0)
  28673. return i;
  28674. midiNodeIds.add (-1);
  28675. return midiNodeIds.size() - 1;
  28676. }
  28677. else
  28678. {
  28679. for (int i = 1; i < nodeIds.size(); ++i)
  28680. if (nodeIds.getUnchecked(i) < 0)
  28681. return i;
  28682. nodeIds.add (-1);
  28683. channels.add (0);
  28684. return nodeIds.size() - 1;
  28685. }
  28686. }
  28687. int getReadOnlyEmptyBuffer() const
  28688. {
  28689. return 0;
  28690. }
  28691. int getBufferContaining (const int nodeId, const int outputChannel) const
  28692. {
  28693. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28694. {
  28695. for (int i = midiNodeIds.size(); --i >= 0;)
  28696. if (midiNodeIds.getUnchecked(i) == nodeId)
  28697. return i;
  28698. }
  28699. else
  28700. {
  28701. for (int i = nodeIds.size(); --i >= 0;)
  28702. if (nodeIds.getUnchecked(i) == nodeId
  28703. && channels.getUnchecked(i) == outputChannel)
  28704. return i;
  28705. }
  28706. return -1;
  28707. }
  28708. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28709. {
  28710. int i;
  28711. for (i = 0; i < nodeIds.size(); ++i)
  28712. {
  28713. if (nodeIds.getUnchecked(i) >= 0
  28714. && ! isBufferNeededLater (stepIndex, -1,
  28715. nodeIds.getUnchecked(i),
  28716. channels.getUnchecked(i)))
  28717. {
  28718. nodeIds.set (i, -1);
  28719. }
  28720. }
  28721. for (i = 0; i < midiNodeIds.size(); ++i)
  28722. {
  28723. if (midiNodeIds.getUnchecked(i) >= 0
  28724. && ! isBufferNeededLater (stepIndex, -1,
  28725. midiNodeIds.getUnchecked(i),
  28726. AudioProcessorGraph::midiChannelIndex))
  28727. {
  28728. midiNodeIds.set (i, -1);
  28729. }
  28730. }
  28731. }
  28732. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28733. int inputChannelOfIndexToIgnore,
  28734. const int nodeId,
  28735. const int outputChanIndex) const
  28736. {
  28737. while (stepIndexToSearchFrom < orderedNodes.size())
  28738. {
  28739. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28740. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28741. {
  28742. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28743. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28744. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28745. return true;
  28746. }
  28747. else
  28748. {
  28749. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28750. if (i != inputChannelOfIndexToIgnore
  28751. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28752. node->id, i) != 0)
  28753. return true;
  28754. }
  28755. inputChannelOfIndexToIgnore = -1;
  28756. ++stepIndexToSearchFrom;
  28757. }
  28758. return false;
  28759. }
  28760. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28761. {
  28762. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28763. {
  28764. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28765. midiNodeIds.set (bufferNum, nodeId);
  28766. }
  28767. else
  28768. {
  28769. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28770. nodeIds.set (bufferNum, nodeId);
  28771. channels.set (bufferNum, outputIndex);
  28772. }
  28773. }
  28774. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28775. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28776. };
  28777. }
  28778. void AudioProcessorGraph::clearRenderingSequence()
  28779. {
  28780. const ScopedLock sl (renderLock);
  28781. for (int i = renderingOps.size(); --i >= 0;)
  28782. {
  28783. GraphRenderingOps::AudioGraphRenderingOp* const r
  28784. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28785. renderingOps.remove (i);
  28786. delete r;
  28787. }
  28788. }
  28789. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28790. const uint32 possibleDestinationId,
  28791. const int recursionCheck) const
  28792. {
  28793. if (recursionCheck > 0)
  28794. {
  28795. for (int i = connections.size(); --i >= 0;)
  28796. {
  28797. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28798. if (c->destNodeId == possibleDestinationId
  28799. && (c->sourceNodeId == possibleInputId
  28800. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28801. return true;
  28802. }
  28803. }
  28804. return false;
  28805. }
  28806. void AudioProcessorGraph::buildRenderingSequence()
  28807. {
  28808. VoidArray newRenderingOps;
  28809. int numRenderingBuffersNeeded = 2;
  28810. int numMidiBuffersNeeded = 1;
  28811. {
  28812. MessageManagerLock mml;
  28813. VoidArray orderedNodes;
  28814. int i;
  28815. for (i = 0; i < nodes.size(); ++i)
  28816. {
  28817. Node* const node = nodes.getUnchecked(i);
  28818. node->prepare (getSampleRate(), getBlockSize(), this);
  28819. int j = 0;
  28820. for (; j < orderedNodes.size(); ++j)
  28821. if (isAnInputTo (node->id,
  28822. ((Node*) orderedNodes.getUnchecked (j))->id,
  28823. nodes.size() + 1))
  28824. break;
  28825. orderedNodes.insert (j, node);
  28826. }
  28827. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28828. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28829. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28830. }
  28831. VoidArray oldRenderingOps (renderingOps);
  28832. {
  28833. // swap over to the new rendering sequence..
  28834. const ScopedLock sl (renderLock);
  28835. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28836. renderingBuffers.clear();
  28837. for (int i = midiBuffers.size(); --i >= 0;)
  28838. midiBuffers.getUnchecked(i)->clear();
  28839. while (midiBuffers.size() < numMidiBuffersNeeded)
  28840. midiBuffers.add (new MidiBuffer());
  28841. renderingOps = newRenderingOps;
  28842. }
  28843. for (int i = oldRenderingOps.size(); --i >= 0;)
  28844. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28845. }
  28846. void AudioProcessorGraph::handleAsyncUpdate()
  28847. {
  28848. buildRenderingSequence();
  28849. }
  28850. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28851. {
  28852. currentAudioInputBuffer = 0;
  28853. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28854. currentMidiInputBuffer = 0;
  28855. currentMidiOutputBuffer.clear();
  28856. clearRenderingSequence();
  28857. buildRenderingSequence();
  28858. }
  28859. void AudioProcessorGraph::releaseResources()
  28860. {
  28861. for (int i = 0; i < nodes.size(); ++i)
  28862. nodes.getUnchecked(i)->unprepare();
  28863. renderingBuffers.setSize (1, 1);
  28864. midiBuffers.clear();
  28865. currentAudioInputBuffer = 0;
  28866. currentAudioOutputBuffer.setSize (1, 1);
  28867. currentMidiInputBuffer = 0;
  28868. currentMidiOutputBuffer.clear();
  28869. }
  28870. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28871. {
  28872. const int numSamples = buffer.getNumSamples();
  28873. const ScopedLock sl (renderLock);
  28874. currentAudioInputBuffer = &buffer;
  28875. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28876. currentAudioOutputBuffer.clear();
  28877. currentMidiInputBuffer = &midiMessages;
  28878. currentMidiOutputBuffer.clear();
  28879. int i;
  28880. for (i = 0; i < renderingOps.size(); ++i)
  28881. {
  28882. GraphRenderingOps::AudioGraphRenderingOp* const op
  28883. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28884. op->perform (renderingBuffers, midiBuffers, numSamples);
  28885. }
  28886. for (i = 0; i < buffer.getNumChannels(); ++i)
  28887. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28888. midiMessages.clear();
  28889. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28890. }
  28891. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28892. {
  28893. return "Input " + String (channelIndex + 1);
  28894. }
  28895. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28896. {
  28897. return "Output " + String (channelIndex + 1);
  28898. }
  28899. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28900. {
  28901. return true;
  28902. }
  28903. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28904. {
  28905. return true;
  28906. }
  28907. bool AudioProcessorGraph::acceptsMidi() const
  28908. {
  28909. return true;
  28910. }
  28911. bool AudioProcessorGraph::producesMidi() const
  28912. {
  28913. return true;
  28914. }
  28915. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28916. {
  28917. }
  28918. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28919. {
  28920. }
  28921. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28922. : type (type_),
  28923. graph (0)
  28924. {
  28925. }
  28926. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28927. {
  28928. }
  28929. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28930. {
  28931. switch (type)
  28932. {
  28933. case audioOutputNode:
  28934. return "Audio Output";
  28935. case audioInputNode:
  28936. return "Audio Input";
  28937. case midiOutputNode:
  28938. return "Midi Output";
  28939. case midiInputNode:
  28940. return "Midi Input";
  28941. default:
  28942. break;
  28943. }
  28944. return String::empty;
  28945. }
  28946. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28947. {
  28948. d.name = getName();
  28949. d.uid = d.name.hashCode();
  28950. d.category = "I/O devices";
  28951. d.pluginFormatName = "Internal";
  28952. d.manufacturerName = "Raw Material Software";
  28953. d.version = "1.0";
  28954. d.isInstrument = false;
  28955. d.numInputChannels = getNumInputChannels();
  28956. if (type == audioOutputNode && graph != 0)
  28957. d.numInputChannels = graph->getNumInputChannels();
  28958. d.numOutputChannels = getNumOutputChannels();
  28959. if (type == audioInputNode && graph != 0)
  28960. d.numOutputChannels = graph->getNumOutputChannels();
  28961. }
  28962. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28963. {
  28964. jassert (graph != 0);
  28965. }
  28966. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28967. {
  28968. }
  28969. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28970. MidiBuffer& midiMessages)
  28971. {
  28972. jassert (graph != 0);
  28973. switch (type)
  28974. {
  28975. case audioOutputNode:
  28976. {
  28977. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28978. buffer.getNumChannels()); --i >= 0;)
  28979. {
  28980. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28981. }
  28982. break;
  28983. }
  28984. case audioInputNode:
  28985. {
  28986. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28987. buffer.getNumChannels()); --i >= 0;)
  28988. {
  28989. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28990. }
  28991. break;
  28992. }
  28993. case midiOutputNode:
  28994. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28995. break;
  28996. case midiInputNode:
  28997. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28998. break;
  28999. default:
  29000. break;
  29001. }
  29002. }
  29003. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29004. {
  29005. return type == midiOutputNode;
  29006. }
  29007. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29008. {
  29009. return type == midiInputNode;
  29010. }
  29011. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29012. {
  29013. switch (type)
  29014. {
  29015. case audioOutputNode:
  29016. return "Output " + String (channelIndex + 1);
  29017. case midiOutputNode:
  29018. return "Midi Output";
  29019. default:
  29020. break;
  29021. }
  29022. return String::empty;
  29023. }
  29024. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29025. {
  29026. switch (type)
  29027. {
  29028. case audioInputNode:
  29029. return "Input " + String (channelIndex + 1);
  29030. case midiInputNode:
  29031. return "Midi Input";
  29032. default:
  29033. break;
  29034. }
  29035. return String::empty;
  29036. }
  29037. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29038. {
  29039. return type == audioInputNode || type == audioOutputNode;
  29040. }
  29041. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29042. {
  29043. return isInputChannelStereoPair (index);
  29044. }
  29045. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29046. {
  29047. return type == audioInputNode || type == midiInputNode;
  29048. }
  29049. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29050. {
  29051. return type == audioOutputNode || type == midiOutputNode;
  29052. }
  29053. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29054. {
  29055. return 0;
  29056. }
  29057. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29058. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29059. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29060. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29061. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29062. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29063. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29064. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29065. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29066. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29067. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29068. {
  29069. }
  29070. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29071. {
  29072. }
  29073. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29074. {
  29075. graph = newGraph;
  29076. if (graph != 0)
  29077. {
  29078. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29079. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29080. getSampleRate(),
  29081. getBlockSize());
  29082. updateHostDisplay();
  29083. }
  29084. }
  29085. END_JUCE_NAMESPACE
  29086. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29087. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29088. BEGIN_JUCE_NAMESPACE
  29089. AudioProcessorPlayer::AudioProcessorPlayer()
  29090. : processor (0),
  29091. sampleRate (0),
  29092. blockSize (0),
  29093. isPrepared (false),
  29094. numInputChans (0),
  29095. numOutputChans (0),
  29096. tempBuffer (1, 1)
  29097. {
  29098. }
  29099. AudioProcessorPlayer::~AudioProcessorPlayer()
  29100. {
  29101. setProcessor (0);
  29102. }
  29103. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29104. {
  29105. if (processor != processorToPlay)
  29106. {
  29107. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29108. {
  29109. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29110. sampleRate, blockSize);
  29111. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29112. }
  29113. AudioProcessor* oldOne;
  29114. {
  29115. const ScopedLock sl (lock);
  29116. oldOne = isPrepared ? processor : 0;
  29117. processor = processorToPlay;
  29118. isPrepared = true;
  29119. }
  29120. if (oldOne != 0)
  29121. oldOne->releaseResources();
  29122. }
  29123. }
  29124. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  29125. int numInputChannels,
  29126. float** outputChannelData,
  29127. int numOutputChannels,
  29128. int numSamples)
  29129. {
  29130. // these should have been prepared by audioDeviceAboutToStart()...
  29131. jassert (sampleRate > 0 && blockSize > 0);
  29132. incomingMidi.clear();
  29133. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29134. int i, totalNumChans = 0;
  29135. if (numInputChannels > numOutputChannels)
  29136. {
  29137. // if there aren't enough output channels for the number of
  29138. // inputs, we need to create some temporary extra ones (can't
  29139. // use the input data in case it gets written to)
  29140. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29141. false, false, true);
  29142. for (i = 0; i < numOutputChannels; ++i)
  29143. {
  29144. channels[totalNumChans] = outputChannelData[i];
  29145. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29146. ++totalNumChans;
  29147. }
  29148. for (i = numOutputChannels; i < numInputChannels; ++i)
  29149. {
  29150. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29151. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29152. ++totalNumChans;
  29153. }
  29154. }
  29155. else
  29156. {
  29157. for (i = 0; i < numInputChannels; ++i)
  29158. {
  29159. channels[totalNumChans] = outputChannelData[i];
  29160. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29161. ++totalNumChans;
  29162. }
  29163. for (i = numInputChannels; i < numOutputChannels; ++i)
  29164. {
  29165. channels[totalNumChans] = outputChannelData[i];
  29166. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29167. ++totalNumChans;
  29168. }
  29169. }
  29170. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29171. const ScopedLock sl (lock);
  29172. if (processor != 0)
  29173. processor->processBlock (buffer, incomingMidi);
  29174. }
  29175. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29176. {
  29177. const ScopedLock sl (lock);
  29178. sampleRate = device->getCurrentSampleRate();
  29179. blockSize = device->getCurrentBufferSizeSamples();
  29180. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29181. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29182. messageCollector.reset (sampleRate);
  29183. zeromem (channels, sizeof (channels));
  29184. if (processor != 0)
  29185. {
  29186. if (isPrepared)
  29187. processor->releaseResources();
  29188. AudioProcessor* const oldProcessor = processor;
  29189. setProcessor (0);
  29190. setProcessor (oldProcessor);
  29191. }
  29192. }
  29193. void AudioProcessorPlayer::audioDeviceStopped()
  29194. {
  29195. const ScopedLock sl (lock);
  29196. if (processor != 0 && isPrepared)
  29197. processor->releaseResources();
  29198. sampleRate = 0.0;
  29199. blockSize = 0;
  29200. isPrepared = false;
  29201. tempBuffer.setSize (1, 1);
  29202. }
  29203. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29204. {
  29205. messageCollector.addMessageToQueue (message);
  29206. }
  29207. END_JUCE_NAMESPACE
  29208. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29209. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29210. BEGIN_JUCE_NAMESPACE
  29211. class ProcessorParameterPropertyComp : public PropertyComponent,
  29212. public AudioProcessorListener,
  29213. public AsyncUpdater
  29214. {
  29215. public:
  29216. ProcessorParameterPropertyComp (const String& name,
  29217. AudioProcessor* const owner_,
  29218. const int index_)
  29219. : PropertyComponent (name),
  29220. owner (owner_),
  29221. index (index_)
  29222. {
  29223. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29224. owner_->addListener (this);
  29225. }
  29226. ~ProcessorParameterPropertyComp()
  29227. {
  29228. owner->removeListener (this);
  29229. deleteAllChildren();
  29230. }
  29231. void refresh()
  29232. {
  29233. slider->setValue (owner->getParameter (index), false);
  29234. }
  29235. void audioProcessorChanged (AudioProcessor*) {}
  29236. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29237. {
  29238. if (parameterIndex == index)
  29239. triggerAsyncUpdate();
  29240. }
  29241. void handleAsyncUpdate()
  29242. {
  29243. refresh();
  29244. }
  29245. juce_UseDebuggingNewOperator
  29246. private:
  29247. AudioProcessor* const owner;
  29248. const int index;
  29249. Slider* slider;
  29250. class ParamSlider : public Slider
  29251. {
  29252. public:
  29253. ParamSlider (AudioProcessor* const owner_, const int index_)
  29254. : Slider (String::empty),
  29255. owner (owner_),
  29256. index (index_)
  29257. {
  29258. setRange (0.0, 1.0, 0.0);
  29259. setSliderStyle (Slider::LinearBar);
  29260. setTextBoxIsEditable (false);
  29261. setScrollWheelEnabled (false);
  29262. }
  29263. ~ParamSlider()
  29264. {
  29265. }
  29266. void valueChanged()
  29267. {
  29268. const float newVal = (float) getValue();
  29269. if (owner->getParameter (index) != newVal)
  29270. owner->setParameter (index, newVal);
  29271. }
  29272. const String getTextFromValue (double /*value*/)
  29273. {
  29274. return owner->getParameterText (index);
  29275. }
  29276. juce_UseDebuggingNewOperator
  29277. private:
  29278. AudioProcessor* const owner;
  29279. const int index;
  29280. ParamSlider (const ParamSlider&);
  29281. ParamSlider& operator= (const ParamSlider&);
  29282. };
  29283. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29284. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29285. };
  29286. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29287. : AudioProcessorEditor (owner_)
  29288. {
  29289. setOpaque (true);
  29290. addAndMakeVisible (panel = new PropertyPanel());
  29291. Array <PropertyComponent*> params;
  29292. const int numParams = owner_->getNumParameters();
  29293. int totalHeight = 0;
  29294. for (int i = 0; i < numParams; ++i)
  29295. {
  29296. String name (owner_->getParameterName (i));
  29297. if (name.trim().isEmpty())
  29298. name = "Unnamed";
  29299. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29300. params.add (pc);
  29301. totalHeight += pc->getPreferredHeight();
  29302. }
  29303. panel->addProperties (params);
  29304. setSize (400, jlimit (25, 400, totalHeight));
  29305. }
  29306. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29307. {
  29308. deleteAllChildren();
  29309. }
  29310. void GenericAudioProcessorEditor::paint (Graphics& g)
  29311. {
  29312. g.fillAll (Colours::white);
  29313. }
  29314. void GenericAudioProcessorEditor::resized()
  29315. {
  29316. panel->setSize (getWidth(), getHeight());
  29317. }
  29318. END_JUCE_NAMESPACE
  29319. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29320. /*** Start of inlined file: juce_Sampler.cpp ***/
  29321. BEGIN_JUCE_NAMESPACE
  29322. SamplerSound::SamplerSound (const String& name_,
  29323. AudioFormatReader& source,
  29324. const BigInteger& midiNotes_,
  29325. const int midiNoteForNormalPitch,
  29326. const double attackTimeSecs,
  29327. const double releaseTimeSecs,
  29328. const double maxSampleLengthSeconds)
  29329. : name (name_),
  29330. midiNotes (midiNotes_),
  29331. midiRootNote (midiNoteForNormalPitch)
  29332. {
  29333. sourceSampleRate = source.sampleRate;
  29334. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29335. {
  29336. length = 0;
  29337. attackSamples = 0;
  29338. releaseSamples = 0;
  29339. }
  29340. else
  29341. {
  29342. length = jmin ((int) source.lengthInSamples,
  29343. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29344. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29345. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29346. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29347. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29348. }
  29349. }
  29350. SamplerSound::~SamplerSound()
  29351. {
  29352. }
  29353. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29354. {
  29355. return midiNotes [midiNoteNumber];
  29356. }
  29357. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29358. {
  29359. return true;
  29360. }
  29361. SamplerVoice::SamplerVoice()
  29362. : pitchRatio (0.0),
  29363. sourceSamplePosition (0.0),
  29364. lgain (0.0f),
  29365. rgain (0.0f),
  29366. isInAttack (false),
  29367. isInRelease (false)
  29368. {
  29369. }
  29370. SamplerVoice::~SamplerVoice()
  29371. {
  29372. }
  29373. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29374. {
  29375. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29376. }
  29377. void SamplerVoice::startNote (const int midiNoteNumber,
  29378. const float velocity,
  29379. SynthesiserSound* s,
  29380. const int /*currentPitchWheelPosition*/)
  29381. {
  29382. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29383. jassert (sound != 0); // this object can only play SamplerSounds!
  29384. if (sound != 0)
  29385. {
  29386. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29387. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29388. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29389. sourceSamplePosition = 0.0;
  29390. lgain = velocity;
  29391. rgain = velocity;
  29392. isInAttack = (sound->attackSamples > 0);
  29393. isInRelease = false;
  29394. if (isInAttack)
  29395. {
  29396. attackReleaseLevel = 0.0f;
  29397. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29398. }
  29399. else
  29400. {
  29401. attackReleaseLevel = 1.0f;
  29402. attackDelta = 0.0f;
  29403. }
  29404. if (sound->releaseSamples > 0)
  29405. {
  29406. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29407. }
  29408. else
  29409. {
  29410. releaseDelta = 0.0f;
  29411. }
  29412. }
  29413. }
  29414. void SamplerVoice::stopNote (const bool allowTailOff)
  29415. {
  29416. if (allowTailOff)
  29417. {
  29418. isInAttack = false;
  29419. isInRelease = true;
  29420. }
  29421. else
  29422. {
  29423. clearCurrentNote();
  29424. }
  29425. }
  29426. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29427. {
  29428. }
  29429. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29430. const int /*newValue*/)
  29431. {
  29432. }
  29433. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29434. {
  29435. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29436. if (playingSound != 0)
  29437. {
  29438. const float* const inL = playingSound->data->getSampleData (0, 0);
  29439. const float* const inR = playingSound->data->getNumChannels() > 1
  29440. ? playingSound->data->getSampleData (1, 0) : 0;
  29441. float* outL = outputBuffer.getSampleData (0, startSample);
  29442. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29443. while (--numSamples >= 0)
  29444. {
  29445. const int pos = (int) sourceSamplePosition;
  29446. const float alpha = (float) (sourceSamplePosition - pos);
  29447. const float invAlpha = 1.0f - alpha;
  29448. // just using a very simple linear interpolation here..
  29449. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29450. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29451. : l;
  29452. l *= lgain;
  29453. r *= rgain;
  29454. if (isInAttack)
  29455. {
  29456. l *= attackReleaseLevel;
  29457. r *= attackReleaseLevel;
  29458. attackReleaseLevel += attackDelta;
  29459. if (attackReleaseLevel >= 1.0f)
  29460. {
  29461. attackReleaseLevel = 1.0f;
  29462. isInAttack = false;
  29463. }
  29464. }
  29465. else if (isInRelease)
  29466. {
  29467. l *= attackReleaseLevel;
  29468. r *= attackReleaseLevel;
  29469. attackReleaseLevel += releaseDelta;
  29470. if (attackReleaseLevel <= 0.0f)
  29471. {
  29472. stopNote (false);
  29473. break;
  29474. }
  29475. }
  29476. if (outR != 0)
  29477. {
  29478. *outL++ += l;
  29479. *outR++ += r;
  29480. }
  29481. else
  29482. {
  29483. *outL++ += (l + r) * 0.5f;
  29484. }
  29485. sourceSamplePosition += pitchRatio;
  29486. if (sourceSamplePosition > playingSound->length)
  29487. {
  29488. stopNote (false);
  29489. break;
  29490. }
  29491. }
  29492. }
  29493. }
  29494. END_JUCE_NAMESPACE
  29495. /*** End of inlined file: juce_Sampler.cpp ***/
  29496. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29497. BEGIN_JUCE_NAMESPACE
  29498. SynthesiserSound::SynthesiserSound()
  29499. {
  29500. }
  29501. SynthesiserSound::~SynthesiserSound()
  29502. {
  29503. }
  29504. SynthesiserVoice::SynthesiserVoice()
  29505. : currentSampleRate (44100.0),
  29506. currentlyPlayingNote (-1),
  29507. noteOnTime (0),
  29508. currentlyPlayingSound (0)
  29509. {
  29510. }
  29511. SynthesiserVoice::~SynthesiserVoice()
  29512. {
  29513. }
  29514. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29515. {
  29516. return currentlyPlayingSound != 0
  29517. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29518. }
  29519. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29520. {
  29521. currentSampleRate = newRate;
  29522. }
  29523. void SynthesiserVoice::clearCurrentNote()
  29524. {
  29525. currentlyPlayingNote = -1;
  29526. currentlyPlayingSound = 0;
  29527. }
  29528. Synthesiser::Synthesiser()
  29529. : sampleRate (0),
  29530. lastNoteOnCounter (0),
  29531. shouldStealNotes (true)
  29532. {
  29533. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29534. lastPitchWheelValues[i] = 0x2000;
  29535. }
  29536. Synthesiser::~Synthesiser()
  29537. {
  29538. }
  29539. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29540. {
  29541. const ScopedLock sl (lock);
  29542. return voices [index];
  29543. }
  29544. void Synthesiser::clearVoices()
  29545. {
  29546. const ScopedLock sl (lock);
  29547. voices.clear();
  29548. }
  29549. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29550. {
  29551. const ScopedLock sl (lock);
  29552. voices.add (newVoice);
  29553. }
  29554. void Synthesiser::removeVoice (const int index)
  29555. {
  29556. const ScopedLock sl (lock);
  29557. voices.remove (index);
  29558. }
  29559. void Synthesiser::clearSounds()
  29560. {
  29561. const ScopedLock sl (lock);
  29562. sounds.clear();
  29563. }
  29564. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29565. {
  29566. const ScopedLock sl (lock);
  29567. sounds.add (newSound);
  29568. }
  29569. void Synthesiser::removeSound (const int index)
  29570. {
  29571. const ScopedLock sl (lock);
  29572. sounds.remove (index);
  29573. }
  29574. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29575. {
  29576. shouldStealNotes = shouldStealNotes_;
  29577. }
  29578. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29579. {
  29580. if (sampleRate != newRate)
  29581. {
  29582. const ScopedLock sl (lock);
  29583. allNotesOff (0, false);
  29584. sampleRate = newRate;
  29585. for (int i = voices.size(); --i >= 0;)
  29586. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29587. }
  29588. }
  29589. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29590. const MidiBuffer& midiData,
  29591. int startSample,
  29592. int numSamples)
  29593. {
  29594. // must set the sample rate before using this!
  29595. jassert (sampleRate != 0);
  29596. const ScopedLock sl (lock);
  29597. MidiBuffer::Iterator midiIterator (midiData);
  29598. midiIterator.setNextSamplePosition (startSample);
  29599. MidiMessage m (0xf4, 0.0);
  29600. while (numSamples > 0)
  29601. {
  29602. int midiEventPos;
  29603. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29604. && midiEventPos < startSample + numSamples;
  29605. const int numThisTime = useEvent ? midiEventPos - startSample
  29606. : numSamples;
  29607. if (numThisTime > 0)
  29608. {
  29609. for (int i = voices.size(); --i >= 0;)
  29610. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29611. }
  29612. if (useEvent)
  29613. {
  29614. if (m.isNoteOn())
  29615. {
  29616. const int channel = m.getChannel();
  29617. noteOn (channel,
  29618. m.getNoteNumber(),
  29619. m.getFloatVelocity());
  29620. }
  29621. else if (m.isNoteOff())
  29622. {
  29623. noteOff (m.getChannel(),
  29624. m.getNoteNumber(),
  29625. true);
  29626. }
  29627. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29628. {
  29629. allNotesOff (m.getChannel(), true);
  29630. }
  29631. else if (m.isPitchWheel())
  29632. {
  29633. const int channel = m.getChannel();
  29634. const int wheelPos = m.getPitchWheelValue();
  29635. lastPitchWheelValues [channel - 1] = wheelPos;
  29636. handlePitchWheel (channel, wheelPos);
  29637. }
  29638. else if (m.isController())
  29639. {
  29640. handleController (m.getChannel(),
  29641. m.getControllerNumber(),
  29642. m.getControllerValue());
  29643. }
  29644. }
  29645. startSample += numThisTime;
  29646. numSamples -= numThisTime;
  29647. }
  29648. }
  29649. void Synthesiser::noteOn (const int midiChannel,
  29650. const int midiNoteNumber,
  29651. const float velocity)
  29652. {
  29653. const ScopedLock sl (lock);
  29654. for (int i = sounds.size(); --i >= 0;)
  29655. {
  29656. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29657. if (sound->appliesToNote (midiNoteNumber)
  29658. && sound->appliesToChannel (midiChannel))
  29659. {
  29660. startVoice (findFreeVoice (sound, shouldStealNotes),
  29661. sound, midiChannel, midiNoteNumber, velocity);
  29662. }
  29663. }
  29664. }
  29665. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29666. SynthesiserSound* const sound,
  29667. const int midiChannel,
  29668. const int midiNoteNumber,
  29669. const float velocity)
  29670. {
  29671. if (voice != 0 && sound != 0)
  29672. {
  29673. if (voice->currentlyPlayingSound != 0)
  29674. voice->stopNote (false);
  29675. voice->startNote (midiNoteNumber,
  29676. velocity,
  29677. sound,
  29678. lastPitchWheelValues [midiChannel - 1]);
  29679. voice->currentlyPlayingNote = midiNoteNumber;
  29680. voice->noteOnTime = ++lastNoteOnCounter;
  29681. voice->currentlyPlayingSound = sound;
  29682. }
  29683. }
  29684. void Synthesiser::noteOff (const int midiChannel,
  29685. const int midiNoteNumber,
  29686. const bool allowTailOff)
  29687. {
  29688. const ScopedLock sl (lock);
  29689. for (int i = voices.size(); --i >= 0;)
  29690. {
  29691. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29692. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29693. {
  29694. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29695. if (sound != 0
  29696. && sound->appliesToNote (midiNoteNumber)
  29697. && sound->appliesToChannel (midiChannel))
  29698. {
  29699. voice->stopNote (allowTailOff);
  29700. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29701. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29702. }
  29703. }
  29704. }
  29705. }
  29706. void Synthesiser::allNotesOff (const int midiChannel,
  29707. const bool allowTailOff)
  29708. {
  29709. const ScopedLock sl (lock);
  29710. for (int i = voices.size(); --i >= 0;)
  29711. {
  29712. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29713. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29714. voice->stopNote (allowTailOff);
  29715. }
  29716. }
  29717. void Synthesiser::handlePitchWheel (const int midiChannel,
  29718. const int wheelValue)
  29719. {
  29720. const ScopedLock sl (lock);
  29721. for (int i = voices.size(); --i >= 0;)
  29722. {
  29723. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29724. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29725. {
  29726. voice->pitchWheelMoved (wheelValue);
  29727. }
  29728. }
  29729. }
  29730. void Synthesiser::handleController (const int midiChannel,
  29731. const int controllerNumber,
  29732. const int controllerValue)
  29733. {
  29734. const ScopedLock sl (lock);
  29735. for (int i = voices.size(); --i >= 0;)
  29736. {
  29737. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29738. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29739. voice->controllerMoved (controllerNumber, controllerValue);
  29740. }
  29741. }
  29742. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29743. const bool stealIfNoneAvailable) const
  29744. {
  29745. const ScopedLock sl (lock);
  29746. for (int i = voices.size(); --i >= 0;)
  29747. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29748. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29749. return voices.getUnchecked (i);
  29750. if (stealIfNoneAvailable)
  29751. {
  29752. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29753. SynthesiserVoice* oldest = 0;
  29754. for (int i = voices.size(); --i >= 0;)
  29755. {
  29756. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29757. if (voice->canPlaySound (soundToPlay)
  29758. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29759. oldest = voice;
  29760. }
  29761. jassert (oldest != 0);
  29762. return oldest;
  29763. }
  29764. return 0;
  29765. }
  29766. END_JUCE_NAMESPACE
  29767. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29768. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29769. BEGIN_JUCE_NAMESPACE
  29770. ActionBroadcaster::ActionBroadcaster() throw()
  29771. {
  29772. // are you trying to create this object before or after juce has been intialised??
  29773. jassert (MessageManager::instance != 0);
  29774. }
  29775. ActionBroadcaster::~ActionBroadcaster()
  29776. {
  29777. // all event-based objects must be deleted BEFORE juce is shut down!
  29778. jassert (MessageManager::instance != 0);
  29779. }
  29780. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29781. {
  29782. actionListenerList.addActionListener (listener);
  29783. }
  29784. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29785. {
  29786. jassert (actionListenerList.isValidMessageListener());
  29787. if (actionListenerList.isValidMessageListener())
  29788. actionListenerList.removeActionListener (listener);
  29789. }
  29790. void ActionBroadcaster::removeAllActionListeners()
  29791. {
  29792. actionListenerList.removeAllActionListeners();
  29793. }
  29794. void ActionBroadcaster::sendActionMessage (const String& message) const
  29795. {
  29796. actionListenerList.sendActionMessage (message);
  29797. }
  29798. END_JUCE_NAMESPACE
  29799. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29800. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29801. BEGIN_JUCE_NAMESPACE
  29802. // special message of our own with a string in it
  29803. class ActionMessage : public Message
  29804. {
  29805. public:
  29806. const String message;
  29807. ActionMessage (const String& messageText,
  29808. void* const listener_) throw()
  29809. : message (messageText)
  29810. {
  29811. pointerParameter = listener_;
  29812. }
  29813. ~ActionMessage() throw()
  29814. {
  29815. }
  29816. private:
  29817. ActionMessage (const ActionMessage&);
  29818. ActionMessage& operator= (const ActionMessage&);
  29819. };
  29820. ActionListenerList::ActionListenerList() throw()
  29821. {
  29822. }
  29823. ActionListenerList::~ActionListenerList() throw()
  29824. {
  29825. }
  29826. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29827. {
  29828. const ScopedLock sl (actionListenerLock_);
  29829. jassert (listener != 0);
  29830. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29831. if (listener != 0)
  29832. actionListeners_.add (listener);
  29833. }
  29834. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29835. {
  29836. const ScopedLock sl (actionListenerLock_);
  29837. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29838. actionListeners_.removeValue (listener);
  29839. }
  29840. void ActionListenerList::removeAllActionListeners() throw()
  29841. {
  29842. const ScopedLock sl (actionListenerLock_);
  29843. actionListeners_.clear();
  29844. }
  29845. void ActionListenerList::sendActionMessage (const String& message) const
  29846. {
  29847. const ScopedLock sl (actionListenerLock_);
  29848. for (int i = actionListeners_.size(); --i >= 0;)
  29849. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29850. }
  29851. void ActionListenerList::handleMessage (const Message& message)
  29852. {
  29853. const ActionMessage& am = (const ActionMessage&) message;
  29854. if (actionListeners_.contains (am.pointerParameter))
  29855. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29856. }
  29857. END_JUCE_NAMESPACE
  29858. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29859. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29860. BEGIN_JUCE_NAMESPACE
  29861. AsyncUpdater::AsyncUpdater() throw()
  29862. : asyncMessagePending (false)
  29863. {
  29864. internalAsyncHandler.owner = this;
  29865. }
  29866. AsyncUpdater::~AsyncUpdater()
  29867. {
  29868. }
  29869. void AsyncUpdater::triggerAsyncUpdate() throw()
  29870. {
  29871. if (! asyncMessagePending)
  29872. {
  29873. asyncMessagePending = true;
  29874. internalAsyncHandler.postMessage (new Message());
  29875. }
  29876. }
  29877. void AsyncUpdater::cancelPendingUpdate() throw()
  29878. {
  29879. asyncMessagePending = false;
  29880. }
  29881. void AsyncUpdater::handleUpdateNowIfNeeded()
  29882. {
  29883. if (asyncMessagePending)
  29884. {
  29885. asyncMessagePending = false;
  29886. handleAsyncUpdate();
  29887. }
  29888. }
  29889. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29890. {
  29891. owner->handleUpdateNowIfNeeded();
  29892. }
  29893. END_JUCE_NAMESPACE
  29894. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29895. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29896. BEGIN_JUCE_NAMESPACE
  29897. ChangeBroadcaster::ChangeBroadcaster() throw()
  29898. {
  29899. // are you trying to create this object before or after juce has been intialised??
  29900. jassert (MessageManager::instance != 0);
  29901. }
  29902. ChangeBroadcaster::~ChangeBroadcaster()
  29903. {
  29904. // all event-based objects must be deleted BEFORE juce is shut down!
  29905. jassert (MessageManager::instance != 0);
  29906. }
  29907. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29908. {
  29909. changeListenerList.addChangeListener (listener);
  29910. }
  29911. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29912. {
  29913. jassert (changeListenerList.isValidMessageListener());
  29914. if (changeListenerList.isValidMessageListener())
  29915. changeListenerList.removeChangeListener (listener);
  29916. }
  29917. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29918. {
  29919. changeListenerList.removeAllChangeListeners();
  29920. }
  29921. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29922. {
  29923. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29924. }
  29925. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29926. {
  29927. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29928. }
  29929. void ChangeBroadcaster::dispatchPendingMessages()
  29930. {
  29931. changeListenerList.dispatchPendingMessages();
  29932. }
  29933. END_JUCE_NAMESPACE
  29934. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29935. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29936. BEGIN_JUCE_NAMESPACE
  29937. ChangeListenerList::ChangeListenerList() throw()
  29938. : lastChangedObject (0),
  29939. messagePending (false)
  29940. {
  29941. }
  29942. ChangeListenerList::~ChangeListenerList() throw()
  29943. {
  29944. }
  29945. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29946. {
  29947. const ScopedLock sl (lock);
  29948. jassert (listener != 0);
  29949. if (listener != 0)
  29950. listeners.add (listener);
  29951. }
  29952. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29953. {
  29954. const ScopedLock sl (lock);
  29955. listeners.removeValue (listener);
  29956. }
  29957. void ChangeListenerList::removeAllChangeListeners() throw()
  29958. {
  29959. const ScopedLock sl (lock);
  29960. listeners.clear();
  29961. }
  29962. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29963. {
  29964. const ScopedLock sl (lock);
  29965. if ((! messagePending) && (listeners.size() > 0))
  29966. {
  29967. lastChangedObject = objectThatHasChanged;
  29968. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29969. messagePending = true;
  29970. }
  29971. }
  29972. void ChangeListenerList::handleMessage (const Message& message)
  29973. {
  29974. sendSynchronousChangeMessage (message.pointerParameter);
  29975. }
  29976. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29977. {
  29978. const ScopedLock sl (lock);
  29979. messagePending = false;
  29980. for (int i = listeners.size(); --i >= 0;)
  29981. {
  29982. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  29983. {
  29984. const ScopedUnlock tempUnlocker (lock);
  29985. l->changeListenerCallback (objectThatHasChanged);
  29986. }
  29987. i = jmin (i, listeners.size());
  29988. }
  29989. }
  29990. void ChangeListenerList::dispatchPendingMessages()
  29991. {
  29992. if (messagePending)
  29993. sendSynchronousChangeMessage (lastChangedObject);
  29994. }
  29995. END_JUCE_NAMESPACE
  29996. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  29997. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  29998. BEGIN_JUCE_NAMESPACE
  29999. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30000. const uint32 magicMessageHeaderNumber)
  30001. : Thread ("Juce IPC connection"),
  30002. callbackConnectionState (false),
  30003. useMessageThread (callbacksOnMessageThread),
  30004. magicMessageHeader (magicMessageHeaderNumber),
  30005. pipeReceiveMessageTimeout (-1)
  30006. {
  30007. }
  30008. InterprocessConnection::~InterprocessConnection()
  30009. {
  30010. callbackConnectionState = false;
  30011. disconnect();
  30012. }
  30013. bool InterprocessConnection::connectToSocket (const String& hostName,
  30014. const int portNumber,
  30015. const int timeOutMillisecs)
  30016. {
  30017. disconnect();
  30018. const ScopedLock sl (pipeAndSocketLock);
  30019. socket = new StreamingSocket();
  30020. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30021. {
  30022. connectionMadeInt();
  30023. startThread();
  30024. return true;
  30025. }
  30026. else
  30027. {
  30028. socket = 0;
  30029. return false;
  30030. }
  30031. }
  30032. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30033. const int pipeReceiveMessageTimeoutMs)
  30034. {
  30035. disconnect();
  30036. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30037. if (newPipe->openExisting (pipeName))
  30038. {
  30039. const ScopedLock sl (pipeAndSocketLock);
  30040. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30041. initialiseWithPipe (newPipe.release());
  30042. return true;
  30043. }
  30044. return false;
  30045. }
  30046. bool InterprocessConnection::createPipe (const String& pipeName,
  30047. const int pipeReceiveMessageTimeoutMs)
  30048. {
  30049. disconnect();
  30050. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30051. if (newPipe->createNewPipe (pipeName))
  30052. {
  30053. const ScopedLock sl (pipeAndSocketLock);
  30054. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30055. initialiseWithPipe (newPipe.release());
  30056. return true;
  30057. }
  30058. return false;
  30059. }
  30060. void InterprocessConnection::disconnect()
  30061. {
  30062. if (socket != 0)
  30063. socket->close();
  30064. if (pipe != 0)
  30065. {
  30066. pipe->cancelPendingReads();
  30067. pipe->close();
  30068. }
  30069. stopThread (4000);
  30070. {
  30071. const ScopedLock sl (pipeAndSocketLock);
  30072. socket = 0;
  30073. pipe = 0;
  30074. }
  30075. connectionLostInt();
  30076. }
  30077. bool InterprocessConnection::isConnected() const
  30078. {
  30079. const ScopedLock sl (pipeAndSocketLock);
  30080. return ((socket != 0 && socket->isConnected())
  30081. || (pipe != 0 && pipe->isOpen()))
  30082. && isThreadRunning();
  30083. }
  30084. const String InterprocessConnection::getConnectedHostName() const
  30085. {
  30086. if (pipe != 0)
  30087. {
  30088. return "localhost";
  30089. }
  30090. else if (socket != 0)
  30091. {
  30092. if (! socket->isLocal())
  30093. return socket->getHostName();
  30094. return "localhost";
  30095. }
  30096. return String::empty;
  30097. }
  30098. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30099. {
  30100. uint32 messageHeader[2];
  30101. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30102. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30103. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30104. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30105. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30106. size_t bytesWritten = 0;
  30107. const ScopedLock sl (pipeAndSocketLock);
  30108. if (socket != 0)
  30109. {
  30110. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30111. }
  30112. else if (pipe != 0)
  30113. {
  30114. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30115. }
  30116. if (bytesWritten < 0)
  30117. {
  30118. // error..
  30119. return false;
  30120. }
  30121. return (bytesWritten == messageData.getSize());
  30122. }
  30123. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30124. {
  30125. jassert (socket == 0);
  30126. socket = socket_;
  30127. connectionMadeInt();
  30128. startThread();
  30129. }
  30130. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30131. {
  30132. jassert (pipe == 0);
  30133. pipe = pipe_;
  30134. connectionMadeInt();
  30135. startThread();
  30136. }
  30137. const int messageMagicNumber = 0xb734128b;
  30138. void InterprocessConnection::handleMessage (const Message& message)
  30139. {
  30140. if (message.intParameter1 == messageMagicNumber)
  30141. {
  30142. switch (message.intParameter2)
  30143. {
  30144. case 0:
  30145. {
  30146. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30147. messageReceived (*data);
  30148. break;
  30149. }
  30150. case 1:
  30151. connectionMade();
  30152. break;
  30153. case 2:
  30154. connectionLost();
  30155. break;
  30156. }
  30157. }
  30158. }
  30159. void InterprocessConnection::connectionMadeInt()
  30160. {
  30161. if (! callbackConnectionState)
  30162. {
  30163. callbackConnectionState = true;
  30164. if (useMessageThread)
  30165. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30166. else
  30167. connectionMade();
  30168. }
  30169. }
  30170. void InterprocessConnection::connectionLostInt()
  30171. {
  30172. if (callbackConnectionState)
  30173. {
  30174. callbackConnectionState = false;
  30175. if (useMessageThread)
  30176. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30177. else
  30178. connectionLost();
  30179. }
  30180. }
  30181. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30182. {
  30183. jassert (callbackConnectionState);
  30184. if (useMessageThread)
  30185. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30186. else
  30187. messageReceived (data);
  30188. }
  30189. bool InterprocessConnection::readNextMessageInt()
  30190. {
  30191. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30192. uint32 messageHeader[2];
  30193. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30194. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30195. if (bytes == sizeof (messageHeader)
  30196. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30197. {
  30198. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30199. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30200. {
  30201. MemoryBlock messageData (bytesInMessage, true);
  30202. int bytesRead = 0;
  30203. while (bytesInMessage > 0)
  30204. {
  30205. if (threadShouldExit())
  30206. return false;
  30207. const int numThisTime = jmin (bytesInMessage, 65536);
  30208. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30209. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30210. if (bytesIn <= 0)
  30211. break;
  30212. bytesRead += bytesIn;
  30213. bytesInMessage -= bytesIn;
  30214. }
  30215. if (bytesRead >= 0)
  30216. deliverDataInt (messageData);
  30217. }
  30218. }
  30219. else if (bytes < 0)
  30220. {
  30221. {
  30222. const ScopedLock sl (pipeAndSocketLock);
  30223. socket = 0;
  30224. }
  30225. connectionLostInt();
  30226. return false;
  30227. }
  30228. return true;
  30229. }
  30230. void InterprocessConnection::run()
  30231. {
  30232. while (! threadShouldExit())
  30233. {
  30234. if (socket != 0)
  30235. {
  30236. const int ready = socket->waitUntilReady (true, 0);
  30237. if (ready < 0)
  30238. {
  30239. {
  30240. const ScopedLock sl (pipeAndSocketLock);
  30241. socket = 0;
  30242. }
  30243. connectionLostInt();
  30244. break;
  30245. }
  30246. else if (ready > 0)
  30247. {
  30248. if (! readNextMessageInt())
  30249. break;
  30250. }
  30251. else
  30252. {
  30253. Thread::sleep (2);
  30254. }
  30255. }
  30256. else if (pipe != 0)
  30257. {
  30258. if (! pipe->isOpen())
  30259. {
  30260. {
  30261. const ScopedLock sl (pipeAndSocketLock);
  30262. pipe = 0;
  30263. }
  30264. connectionLostInt();
  30265. break;
  30266. }
  30267. else
  30268. {
  30269. if (! readNextMessageInt())
  30270. break;
  30271. }
  30272. }
  30273. else
  30274. {
  30275. break;
  30276. }
  30277. }
  30278. }
  30279. END_JUCE_NAMESPACE
  30280. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30281. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30282. BEGIN_JUCE_NAMESPACE
  30283. InterprocessConnectionServer::InterprocessConnectionServer()
  30284. : Thread ("Juce IPC server")
  30285. {
  30286. }
  30287. InterprocessConnectionServer::~InterprocessConnectionServer()
  30288. {
  30289. stop();
  30290. }
  30291. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30292. {
  30293. stop();
  30294. socket = new StreamingSocket();
  30295. if (socket->createListener (portNumber))
  30296. {
  30297. startThread();
  30298. return true;
  30299. }
  30300. socket = 0;
  30301. return false;
  30302. }
  30303. void InterprocessConnectionServer::stop()
  30304. {
  30305. signalThreadShouldExit();
  30306. if (socket != 0)
  30307. socket->close();
  30308. stopThread (4000);
  30309. socket = 0;
  30310. }
  30311. void InterprocessConnectionServer::run()
  30312. {
  30313. while ((! threadShouldExit()) && socket != 0)
  30314. {
  30315. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30316. if (clientSocket != 0)
  30317. {
  30318. InterprocessConnection* newConnection = createConnectionObject();
  30319. if (newConnection != 0)
  30320. newConnection->initialiseWithSocket (clientSocket.release());
  30321. }
  30322. }
  30323. }
  30324. END_JUCE_NAMESPACE
  30325. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30326. /*** Start of inlined file: juce_Message.cpp ***/
  30327. BEGIN_JUCE_NAMESPACE
  30328. Message::Message() throw()
  30329. : intParameter1 (0),
  30330. intParameter2 (0),
  30331. intParameter3 (0),
  30332. pointerParameter (0)
  30333. {
  30334. }
  30335. Message::Message (const int intParameter1_,
  30336. const int intParameter2_,
  30337. const int intParameter3_,
  30338. void* const pointerParameter_) throw()
  30339. : intParameter1 (intParameter1_),
  30340. intParameter2 (intParameter2_),
  30341. intParameter3 (intParameter3_),
  30342. pointerParameter (pointerParameter_)
  30343. {
  30344. }
  30345. Message::~Message() throw()
  30346. {
  30347. }
  30348. END_JUCE_NAMESPACE
  30349. /*** End of inlined file: juce_Message.cpp ***/
  30350. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30351. BEGIN_JUCE_NAMESPACE
  30352. MessageListener::MessageListener() throw()
  30353. {
  30354. // are you trying to create a messagelistener before or after juce has been intialised??
  30355. jassert (MessageManager::instance != 0);
  30356. if (MessageManager::instance != 0)
  30357. MessageManager::instance->messageListeners.add (this);
  30358. }
  30359. MessageListener::~MessageListener()
  30360. {
  30361. if (MessageManager::instance != 0)
  30362. MessageManager::instance->messageListeners.removeValue (this);
  30363. }
  30364. void MessageListener::postMessage (Message* const message) const throw()
  30365. {
  30366. message->messageRecipient = const_cast <MessageListener*> (this);
  30367. if (MessageManager::instance == 0)
  30368. MessageManager::getInstance();
  30369. MessageManager::instance->postMessageToQueue (message);
  30370. }
  30371. bool MessageListener::isValidMessageListener() const throw()
  30372. {
  30373. return (MessageManager::instance != 0)
  30374. && MessageManager::instance->messageListeners.contains (this);
  30375. }
  30376. END_JUCE_NAMESPACE
  30377. /*** End of inlined file: juce_MessageListener.cpp ***/
  30378. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30379. BEGIN_JUCE_NAMESPACE
  30380. // platform-specific functions..
  30381. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30382. bool juce_postMessageToSystemQueue (void* message);
  30383. MessageManager* MessageManager::instance = 0;
  30384. static const int quitMessageId = 0xfffff321;
  30385. MessageManager::MessageManager() throw()
  30386. : quitMessagePosted (false),
  30387. quitMessageReceived (false),
  30388. threadWithLock (0)
  30389. {
  30390. messageThreadId = Thread::getCurrentThreadId();
  30391. }
  30392. MessageManager::~MessageManager() throw()
  30393. {
  30394. broadcastListeners = 0;
  30395. doPlatformSpecificShutdown();
  30396. jassert (instance == this);
  30397. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30398. }
  30399. MessageManager* MessageManager::getInstance() throw()
  30400. {
  30401. if (instance == 0)
  30402. {
  30403. instance = new MessageManager();
  30404. doPlatformSpecificInitialisation();
  30405. }
  30406. return instance;
  30407. }
  30408. void MessageManager::postMessageToQueue (Message* const message)
  30409. {
  30410. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30411. delete message;
  30412. }
  30413. CallbackMessage::CallbackMessage() throw() {}
  30414. CallbackMessage::~CallbackMessage() throw() {}
  30415. void CallbackMessage::post()
  30416. {
  30417. if (MessageManager::instance != 0)
  30418. MessageManager::instance->postCallbackMessage (this);
  30419. }
  30420. void MessageManager::postCallbackMessage (Message* const message)
  30421. {
  30422. message->messageRecipient = 0;
  30423. postMessageToQueue (message);
  30424. }
  30425. // not for public use..
  30426. void MessageManager::deliverMessage (void* const message)
  30427. {
  30428. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30429. MessageListener* const recipient = m->messageRecipient;
  30430. JUCE_TRY
  30431. {
  30432. if (messageListeners.contains (recipient))
  30433. {
  30434. recipient->handleMessage (*m);
  30435. }
  30436. else if (recipient == 0)
  30437. {
  30438. if (m->intParameter1 == quitMessageId)
  30439. {
  30440. quitMessageReceived = true;
  30441. }
  30442. else
  30443. {
  30444. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30445. if (cm != 0)
  30446. cm->messageCallback();
  30447. }
  30448. }
  30449. }
  30450. JUCE_CATCH_EXCEPTION
  30451. }
  30452. #if ! (JUCE_MAC || JUCE_IPHONE)
  30453. void MessageManager::runDispatchLoop()
  30454. {
  30455. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30456. runDispatchLoopUntil (-1);
  30457. }
  30458. void MessageManager::stopDispatchLoop()
  30459. {
  30460. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30461. m->messageRecipient = 0;
  30462. postMessageToQueue (m);
  30463. quitMessagePosted = true;
  30464. }
  30465. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30466. {
  30467. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30468. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30469. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30470. && ! quitMessageReceived)
  30471. {
  30472. JUCE_TRY
  30473. {
  30474. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30475. {
  30476. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30477. if (msToWait > 0)
  30478. Thread::sleep (jmin (5, msToWait));
  30479. }
  30480. }
  30481. JUCE_CATCH_EXCEPTION
  30482. }
  30483. return ! quitMessageReceived;
  30484. }
  30485. #endif
  30486. void MessageManager::deliverBroadcastMessage (const String& value)
  30487. {
  30488. if (broadcastListeners != 0)
  30489. broadcastListeners->sendActionMessage (value);
  30490. }
  30491. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30492. {
  30493. if (broadcastListeners == 0)
  30494. broadcastListeners = new ActionListenerList();
  30495. broadcastListeners->addActionListener (listener);
  30496. }
  30497. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30498. {
  30499. if (broadcastListeners != 0)
  30500. broadcastListeners->removeActionListener (listener);
  30501. }
  30502. bool MessageManager::isThisTheMessageThread() const throw()
  30503. {
  30504. return Thread::getCurrentThreadId() == messageThreadId;
  30505. }
  30506. void MessageManager::setCurrentThreadAsMessageThread()
  30507. {
  30508. if (messageThreadId != Thread::getCurrentThreadId())
  30509. {
  30510. messageThreadId = Thread::getCurrentThreadId();
  30511. // This is needed on windows to make sure the message window is created by this thread
  30512. doPlatformSpecificShutdown();
  30513. doPlatformSpecificInitialisation();
  30514. }
  30515. }
  30516. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30517. {
  30518. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30519. return thisThread == messageThreadId || thisThread == threadWithLock;
  30520. }
  30521. /* The only safe way to lock the message thread while another thread does
  30522. some work is by posting a special message, whose purpose is to tie up the event
  30523. loop until the other thread has finished its business.
  30524. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30525. get locked before making an event callback, because if the same OS lock gets indirectly
  30526. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30527. in Cocoa).
  30528. */
  30529. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30530. {
  30531. public:
  30532. SharedEvents() {}
  30533. ~SharedEvents() {}
  30534. /* This class just holds a couple of events to communicate between the BlockingMessage
  30535. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30536. this shared data must be kept in a separate, ref-counted container. */
  30537. WaitableEvent lockedEvent, releaseEvent;
  30538. private:
  30539. SharedEvents (const SharedEvents&);
  30540. SharedEvents& operator= (const SharedEvents&);
  30541. };
  30542. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30543. {
  30544. public:
  30545. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30546. ~BlockingMessage() throw() {}
  30547. void messageCallback()
  30548. {
  30549. events->lockedEvent.signal();
  30550. events->releaseEvent.wait();
  30551. }
  30552. juce_UseDebuggingNewOperator
  30553. private:
  30554. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30555. BlockingMessage (const BlockingMessage&);
  30556. BlockingMessage& operator= (const BlockingMessage&);
  30557. };
  30558. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30559. : sharedEvents (0),
  30560. locked (false)
  30561. {
  30562. init (threadToCheck, 0);
  30563. }
  30564. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30565. : sharedEvents (0),
  30566. locked (false)
  30567. {
  30568. init (0, jobToCheckForExitSignal);
  30569. }
  30570. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30571. {
  30572. if (MessageManager::instance != 0)
  30573. {
  30574. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30575. {
  30576. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30577. }
  30578. else
  30579. {
  30580. if (threadToCheck == 0 && job == 0)
  30581. {
  30582. MessageManager::instance->lockingLock.enter();
  30583. }
  30584. else
  30585. {
  30586. while (! MessageManager::instance->lockingLock.tryEnter())
  30587. {
  30588. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30589. || (job != 0 && job->shouldExit()))
  30590. return;
  30591. Thread::sleep (1);
  30592. }
  30593. }
  30594. sharedEvents = new SharedEvents();
  30595. sharedEvents->incReferenceCount();
  30596. (new BlockingMessage (sharedEvents))->post();
  30597. while (! sharedEvents->lockedEvent.wait (50))
  30598. {
  30599. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30600. || (job != 0 && job->shouldExit()))
  30601. {
  30602. sharedEvents->releaseEvent.signal();
  30603. sharedEvents->decReferenceCount();
  30604. sharedEvents = 0;
  30605. MessageManager::instance->lockingLock.exit();
  30606. return;
  30607. }
  30608. }
  30609. jassert (MessageManager::instance->threadWithLock == 0);
  30610. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30611. locked = true;
  30612. }
  30613. }
  30614. }
  30615. MessageManagerLock::~MessageManagerLock() throw()
  30616. {
  30617. if (sharedEvents != 0)
  30618. {
  30619. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30620. sharedEvents->releaseEvent.signal();
  30621. sharedEvents->decReferenceCount();
  30622. if (MessageManager::instance != 0)
  30623. {
  30624. MessageManager::instance->threadWithLock = 0;
  30625. MessageManager::instance->lockingLock.exit();
  30626. }
  30627. }
  30628. }
  30629. END_JUCE_NAMESPACE
  30630. /*** End of inlined file: juce_MessageManager.cpp ***/
  30631. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30632. BEGIN_JUCE_NAMESPACE
  30633. class MultiTimer::MultiTimerCallback : public Timer
  30634. {
  30635. public:
  30636. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30637. : timerId (timerId_),
  30638. owner (owner_)
  30639. {
  30640. }
  30641. ~MultiTimerCallback()
  30642. {
  30643. }
  30644. void timerCallback()
  30645. {
  30646. owner.timerCallback (timerId);
  30647. }
  30648. const int timerId;
  30649. private:
  30650. MultiTimer& owner;
  30651. };
  30652. MultiTimer::MultiTimer() throw()
  30653. {
  30654. }
  30655. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30656. {
  30657. }
  30658. MultiTimer::~MultiTimer()
  30659. {
  30660. const ScopedLock sl (timerListLock);
  30661. timers.clear();
  30662. }
  30663. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30664. {
  30665. const ScopedLock sl (timerListLock);
  30666. for (int i = timers.size(); --i >= 0;)
  30667. {
  30668. MultiTimerCallback* const t = timers.getUnchecked(i);
  30669. if (t->timerId == timerId)
  30670. {
  30671. t->startTimer (intervalInMilliseconds);
  30672. return;
  30673. }
  30674. }
  30675. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30676. timers.add (newTimer);
  30677. newTimer->startTimer (intervalInMilliseconds);
  30678. }
  30679. void MultiTimer::stopTimer (const int timerId) throw()
  30680. {
  30681. const ScopedLock sl (timerListLock);
  30682. for (int i = timers.size(); --i >= 0;)
  30683. {
  30684. MultiTimerCallback* const t = timers.getUnchecked(i);
  30685. if (t->timerId == timerId)
  30686. t->stopTimer();
  30687. }
  30688. }
  30689. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30690. {
  30691. const ScopedLock sl (timerListLock);
  30692. for (int i = timers.size(); --i >= 0;)
  30693. {
  30694. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30695. if (t->timerId == timerId)
  30696. return t->isTimerRunning();
  30697. }
  30698. return false;
  30699. }
  30700. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30701. {
  30702. const ScopedLock sl (timerListLock);
  30703. for (int i = timers.size(); --i >= 0;)
  30704. {
  30705. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30706. if (t->timerId == timerId)
  30707. return t->getTimerInterval();
  30708. }
  30709. return 0;
  30710. }
  30711. END_JUCE_NAMESPACE
  30712. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30713. /*** Start of inlined file: juce_Timer.cpp ***/
  30714. BEGIN_JUCE_NAMESPACE
  30715. class InternalTimerThread : private Thread,
  30716. private MessageListener,
  30717. private DeletedAtShutdown,
  30718. private AsyncUpdater
  30719. {
  30720. public:
  30721. InternalTimerThread()
  30722. : Thread ("Juce Timer"),
  30723. firstTimer (0),
  30724. callbackNeeded (0)
  30725. {
  30726. triggerAsyncUpdate();
  30727. }
  30728. ~InternalTimerThread() throw()
  30729. {
  30730. stopThread (4000);
  30731. jassert (instance == this || instance == 0);
  30732. if (instance == this)
  30733. instance = 0;
  30734. }
  30735. void run()
  30736. {
  30737. uint32 lastTime = Time::getMillisecondCounter();
  30738. while (! threadShouldExit())
  30739. {
  30740. const uint32 now = Time::getMillisecondCounter();
  30741. if (now <= lastTime)
  30742. {
  30743. wait (2);
  30744. continue;
  30745. }
  30746. const int elapsed = now - lastTime;
  30747. lastTime = now;
  30748. int timeUntilFirstTimer = 1000;
  30749. {
  30750. const ScopedLock sl (lock);
  30751. decrementAllCounters (elapsed);
  30752. if (firstTimer != 0)
  30753. timeUntilFirstTimer = firstTimer->countdownMs;
  30754. }
  30755. if (timeUntilFirstTimer <= 0)
  30756. {
  30757. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30758. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30759. but if it fails it means the message-thread changed the value from under us so at least
  30760. some processing is happenening and we can just loop around and try again
  30761. */
  30762. if (callbackNeeded.compareAndSetBool (1, 0))
  30763. {
  30764. postMessage (new Message());
  30765. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30766. when the app has a modal loop), so this is how long to wait before assuming the
  30767. message has been lost and trying again.
  30768. */
  30769. const uint32 messageDeliveryTimeout = now + 2000;
  30770. while (callbackNeeded.get() != 0)
  30771. {
  30772. wait (4);
  30773. if (threadShouldExit())
  30774. return;
  30775. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30776. break;
  30777. }
  30778. }
  30779. }
  30780. else
  30781. {
  30782. // don't wait for too long because running this loop also helps keep the
  30783. // Time::getApproximateMillisecondTimer value stay up-to-date
  30784. wait (jlimit (1, 50, timeUntilFirstTimer));
  30785. }
  30786. }
  30787. }
  30788. void callTimers()
  30789. {
  30790. const ScopedLock sl (lock);
  30791. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30792. {
  30793. Timer* const t = firstTimer;
  30794. t->countdownMs = t->periodMs;
  30795. removeTimer (t);
  30796. addTimer (t);
  30797. const ScopedUnlock ul (lock);
  30798. JUCE_TRY
  30799. {
  30800. t->timerCallback();
  30801. }
  30802. JUCE_CATCH_EXCEPTION
  30803. }
  30804. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30805. before the boolean is set. This set should never fail since if it was false in the first place,
  30806. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30807. get a message then the value is true and the other thread can only set it to true again and
  30808. we will get another callback to set it to false.
  30809. */
  30810. callbackNeeded.set (0);
  30811. }
  30812. void handleMessage (const Message&)
  30813. {
  30814. callTimers();
  30815. }
  30816. void callTimersSynchronously()
  30817. {
  30818. if (! isThreadRunning())
  30819. {
  30820. // (This is relied on by some plugins in cases where the MM has
  30821. // had to restart and the async callback never started)
  30822. cancelPendingUpdate();
  30823. triggerAsyncUpdate();
  30824. }
  30825. callTimers();
  30826. }
  30827. static void callAnyTimersSynchronously()
  30828. {
  30829. if (InternalTimerThread::instance != 0)
  30830. InternalTimerThread::instance->callTimersSynchronously();
  30831. }
  30832. static inline void add (Timer* const tim) throw()
  30833. {
  30834. if (instance == 0)
  30835. instance = new InternalTimerThread();
  30836. const ScopedLock sl (instance->lock);
  30837. instance->addTimer (tim);
  30838. }
  30839. static inline void remove (Timer* const tim) throw()
  30840. {
  30841. if (instance != 0)
  30842. {
  30843. const ScopedLock sl (instance->lock);
  30844. instance->removeTimer (tim);
  30845. }
  30846. }
  30847. static inline void resetCounter (Timer* const tim,
  30848. const int newCounter) throw()
  30849. {
  30850. if (instance != 0)
  30851. {
  30852. tim->countdownMs = newCounter;
  30853. tim->periodMs = newCounter;
  30854. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30855. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30856. {
  30857. const ScopedLock sl (instance->lock);
  30858. instance->removeTimer (tim);
  30859. instance->addTimer (tim);
  30860. }
  30861. }
  30862. }
  30863. private:
  30864. friend class Timer;
  30865. static InternalTimerThread* instance;
  30866. static CriticalSection lock;
  30867. Timer* volatile firstTimer;
  30868. Atomic <int> callbackNeeded;
  30869. void addTimer (Timer* const t) throw()
  30870. {
  30871. #if JUCE_DEBUG
  30872. Timer* tt = firstTimer;
  30873. while (tt != 0)
  30874. {
  30875. // trying to add a timer that's already here - shouldn't get to this point,
  30876. // so if you get this assertion, let me know!
  30877. jassert (tt != t);
  30878. tt = tt->next;
  30879. }
  30880. jassert (t->previous == 0 && t->next == 0);
  30881. #endif
  30882. Timer* i = firstTimer;
  30883. if (i == 0 || i->countdownMs > t->countdownMs)
  30884. {
  30885. t->next = firstTimer;
  30886. firstTimer = t;
  30887. }
  30888. else
  30889. {
  30890. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30891. i = i->next;
  30892. jassert (i != 0);
  30893. t->next = i->next;
  30894. t->previous = i;
  30895. i->next = t;
  30896. }
  30897. if (t->next != 0)
  30898. t->next->previous = t;
  30899. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30900. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30901. notify();
  30902. }
  30903. void removeTimer (Timer* const t) throw()
  30904. {
  30905. #if JUCE_DEBUG
  30906. Timer* tt = firstTimer;
  30907. bool found = false;
  30908. while (tt != 0)
  30909. {
  30910. if (tt == t)
  30911. {
  30912. found = true;
  30913. break;
  30914. }
  30915. tt = tt->next;
  30916. }
  30917. // trying to remove a timer that's not here - shouldn't get to this point,
  30918. // so if you get this assertion, let me know!
  30919. jassert (found);
  30920. #endif
  30921. if (t->previous != 0)
  30922. {
  30923. jassert (firstTimer != t);
  30924. t->previous->next = t->next;
  30925. }
  30926. else
  30927. {
  30928. jassert (firstTimer == t);
  30929. firstTimer = t->next;
  30930. }
  30931. if (t->next != 0)
  30932. t->next->previous = t->previous;
  30933. t->next = 0;
  30934. t->previous = 0;
  30935. }
  30936. void decrementAllCounters (const int numMillisecs) const
  30937. {
  30938. Timer* t = firstTimer;
  30939. while (t != 0)
  30940. {
  30941. t->countdownMs -= numMillisecs;
  30942. t = t->next;
  30943. }
  30944. }
  30945. void handleAsyncUpdate()
  30946. {
  30947. startThread (7);
  30948. }
  30949. InternalTimerThread (const InternalTimerThread&);
  30950. InternalTimerThread& operator= (const InternalTimerThread&);
  30951. };
  30952. InternalTimerThread* InternalTimerThread::instance = 0;
  30953. CriticalSection InternalTimerThread::lock;
  30954. void juce_callAnyTimersSynchronously()
  30955. {
  30956. InternalTimerThread::callAnyTimersSynchronously();
  30957. }
  30958. #if JUCE_DEBUG
  30959. static SortedSet <Timer*> activeTimers;
  30960. #endif
  30961. Timer::Timer() throw()
  30962. : countdownMs (0),
  30963. periodMs (0),
  30964. previous (0),
  30965. next (0)
  30966. {
  30967. #if JUCE_DEBUG
  30968. activeTimers.add (this);
  30969. #endif
  30970. }
  30971. Timer::Timer (const Timer&) throw()
  30972. : countdownMs (0),
  30973. periodMs (0),
  30974. previous (0),
  30975. next (0)
  30976. {
  30977. #if JUCE_DEBUG
  30978. activeTimers.add (this);
  30979. #endif
  30980. }
  30981. Timer::~Timer()
  30982. {
  30983. stopTimer();
  30984. #if JUCE_DEBUG
  30985. activeTimers.removeValue (this);
  30986. #endif
  30987. }
  30988. void Timer::startTimer (const int interval) throw()
  30989. {
  30990. const ScopedLock sl (InternalTimerThread::lock);
  30991. #if JUCE_DEBUG
  30992. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30993. jassert (activeTimers.contains (this));
  30994. #endif
  30995. if (periodMs == 0)
  30996. {
  30997. countdownMs = interval;
  30998. periodMs = jmax (1, interval);
  30999. InternalTimerThread::add (this);
  31000. }
  31001. else
  31002. {
  31003. InternalTimerThread::resetCounter (this, interval);
  31004. }
  31005. }
  31006. void Timer::stopTimer() throw()
  31007. {
  31008. const ScopedLock sl (InternalTimerThread::lock);
  31009. #if JUCE_DEBUG
  31010. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31011. jassert (activeTimers.contains (this));
  31012. #endif
  31013. if (periodMs > 0)
  31014. {
  31015. InternalTimerThread::remove (this);
  31016. periodMs = 0;
  31017. }
  31018. }
  31019. END_JUCE_NAMESPACE
  31020. /*** End of inlined file: juce_Timer.cpp ***/
  31021. #endif
  31022. #if JUCE_BUILD_GUI
  31023. /*** Start of inlined file: juce_Component.cpp ***/
  31024. BEGIN_JUCE_NAMESPACE
  31025. Component* Component::currentlyFocusedComponent = 0;
  31026. static Array <Component*> modalComponentStack, modalComponentReturnValueKeys;
  31027. static Array <int> modalReturnValues;
  31028. enum ComponentMessageNumbers
  31029. {
  31030. customCommandMessage = 0x7fff0001,
  31031. exitModalStateMessage = 0x7fff0002
  31032. };
  31033. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31034. static uint32 nextComponentUID = 0;
  31035. Component::Component()
  31036. : parentComponent_ (0),
  31037. componentUID (++nextComponentUID),
  31038. numDeepMouseListeners (0),
  31039. lookAndFeel_ (0),
  31040. effect_ (0),
  31041. bufferedImage_ (0),
  31042. mouseListeners_ (0),
  31043. keyListeners_ (0),
  31044. componentFlags_ (0)
  31045. {
  31046. }
  31047. Component::Component (const String& name)
  31048. : componentName_ (name),
  31049. parentComponent_ (0),
  31050. componentUID (++nextComponentUID),
  31051. numDeepMouseListeners (0),
  31052. lookAndFeel_ (0),
  31053. effect_ (0),
  31054. bufferedImage_ (0),
  31055. mouseListeners_ (0),
  31056. keyListeners_ (0),
  31057. componentFlags_ (0)
  31058. {
  31059. }
  31060. Component::~Component()
  31061. {
  31062. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31063. if (parentComponent_ != 0)
  31064. {
  31065. parentComponent_->removeChildComponent (this);
  31066. }
  31067. else if ((currentlyFocusedComponent == this)
  31068. || isParentOf (currentlyFocusedComponent))
  31069. {
  31070. giveAwayFocus();
  31071. }
  31072. if (flags.hasHeavyweightPeerFlag)
  31073. removeFromDesktop();
  31074. modalComponentStack.removeValue (this);
  31075. for (int i = childComponentList_.size(); --i >= 0;)
  31076. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31077. delete bufferedImage_;
  31078. delete mouseListeners_;
  31079. delete keyListeners_;
  31080. }
  31081. void Component::setName (const String& name)
  31082. {
  31083. // if component methods are being called from threads other than the message
  31084. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31085. checkMessageManagerIsLocked
  31086. if (componentName_ != name)
  31087. {
  31088. componentName_ = name;
  31089. if (flags.hasHeavyweightPeerFlag)
  31090. {
  31091. ComponentPeer* const peer = getPeer();
  31092. jassert (peer != 0);
  31093. if (peer != 0)
  31094. peer->setTitle (name);
  31095. }
  31096. BailOutChecker checker (this);
  31097. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31098. }
  31099. }
  31100. void Component::setVisible (bool shouldBeVisible)
  31101. {
  31102. if (flags.visibleFlag != shouldBeVisible)
  31103. {
  31104. // if component methods are being called from threads other than the message
  31105. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31106. checkMessageManagerIsLocked
  31107. SafePointer<Component> safePointer (this);
  31108. flags.visibleFlag = shouldBeVisible;
  31109. internalRepaint (0, 0, getWidth(), getHeight());
  31110. sendFakeMouseMove();
  31111. if (! shouldBeVisible)
  31112. {
  31113. if (currentlyFocusedComponent == this
  31114. || isParentOf (currentlyFocusedComponent))
  31115. {
  31116. if (parentComponent_ != 0)
  31117. parentComponent_->grabKeyboardFocus();
  31118. else
  31119. giveAwayFocus();
  31120. }
  31121. }
  31122. if (safePointer != 0)
  31123. {
  31124. sendVisibilityChangeMessage();
  31125. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31126. {
  31127. ComponentPeer* const peer = getPeer();
  31128. jassert (peer != 0);
  31129. if (peer != 0)
  31130. {
  31131. peer->setVisible (shouldBeVisible);
  31132. internalHierarchyChanged();
  31133. }
  31134. }
  31135. }
  31136. }
  31137. }
  31138. void Component::visibilityChanged()
  31139. {
  31140. }
  31141. void Component::sendVisibilityChangeMessage()
  31142. {
  31143. BailOutChecker checker (this);
  31144. visibilityChanged();
  31145. if (! checker.shouldBailOut())
  31146. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31147. }
  31148. bool Component::isShowing() const
  31149. {
  31150. if (flags.visibleFlag)
  31151. {
  31152. if (parentComponent_ != 0)
  31153. {
  31154. return parentComponent_->isShowing();
  31155. }
  31156. else
  31157. {
  31158. const ComponentPeer* const peer = getPeer();
  31159. return peer != 0 && ! peer->isMinimised();
  31160. }
  31161. }
  31162. return false;
  31163. }
  31164. class FadeOutProxyComponent : public Component,
  31165. public Timer
  31166. {
  31167. public:
  31168. FadeOutProxyComponent (Component* comp,
  31169. const int fadeLengthMs,
  31170. const int deltaXToMove,
  31171. const int deltaYToMove,
  31172. const float scaleFactorAtEnd)
  31173. : lastTime (0),
  31174. alpha (1.0f),
  31175. scale (1.0f)
  31176. {
  31177. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31178. setBounds (comp->getBounds());
  31179. comp->getParentComponent()->addAndMakeVisible (this);
  31180. toBehind (comp);
  31181. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31182. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31183. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31184. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31185. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31186. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31187. setInterceptsMouseClicks (false, false);
  31188. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31189. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31190. }
  31191. ~FadeOutProxyComponent()
  31192. {
  31193. delete image;
  31194. }
  31195. void paint (Graphics& g)
  31196. {
  31197. g.setOpacity (alpha);
  31198. g.drawImage (image,
  31199. 0, 0, getWidth(), getHeight(),
  31200. 0, 0, image->getWidth(), image->getHeight());
  31201. }
  31202. void timerCallback()
  31203. {
  31204. const uint32 now = Time::getMillisecondCounter();
  31205. if (lastTime == 0)
  31206. lastTime = now;
  31207. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31208. lastTime = now;
  31209. alpha += alphaChangePerMs * msPassed;
  31210. if (alpha > 0)
  31211. {
  31212. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31213. {
  31214. centreX += xChangePerMs * msPassed;
  31215. centreY += yChangePerMs * msPassed;
  31216. scale += scaleChangePerMs * msPassed;
  31217. const int w = roundToInt (image->getWidth() * scale);
  31218. const int h = roundToInt (image->getHeight() * scale);
  31219. setBounds (roundToInt (centreX) - w / 2,
  31220. roundToInt (centreY) - h / 2,
  31221. w, h);
  31222. }
  31223. repaint();
  31224. }
  31225. else
  31226. {
  31227. delete this;
  31228. }
  31229. }
  31230. juce_UseDebuggingNewOperator
  31231. private:
  31232. Image* image;
  31233. uint32 lastTime;
  31234. float alpha, alphaChangePerMs;
  31235. float centreX, xChangePerMs;
  31236. float centreY, yChangePerMs;
  31237. float scale, scaleChangePerMs;
  31238. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31239. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31240. };
  31241. void Component::fadeOutComponent (const int millisecondsToFade,
  31242. const int deltaXToMove,
  31243. const int deltaYToMove,
  31244. const float scaleFactorAtEnd)
  31245. {
  31246. //xxx won't work for comps without parents
  31247. if (isShowing() && millisecondsToFade > 0)
  31248. new FadeOutProxyComponent (this, millisecondsToFade,
  31249. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31250. setVisible (false);
  31251. }
  31252. bool Component::isValidComponent() const
  31253. {
  31254. return (this != 0) && isValidMessageListener();
  31255. }
  31256. void* Component::getWindowHandle() const
  31257. {
  31258. const ComponentPeer* const peer = getPeer();
  31259. if (peer != 0)
  31260. return peer->getNativeHandle();
  31261. return 0;
  31262. }
  31263. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31264. {
  31265. // if component methods are being called from threads other than the message
  31266. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31267. checkMessageManagerIsLocked
  31268. if (isOpaque())
  31269. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31270. else
  31271. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31272. int currentStyleFlags = 0;
  31273. // don't use getPeer(), so that we only get the peer that's specifically
  31274. // for this comp, and not for one of its parents.
  31275. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31276. if (peer != 0)
  31277. currentStyleFlags = peer->getStyleFlags();
  31278. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31279. {
  31280. SafePointer<Component> safePointer (this);
  31281. #if JUCE_LINUX
  31282. // it's wise to give the component a non-zero size before
  31283. // putting it on the desktop, as X windows get confused by this, and
  31284. // a (1, 1) minimum size is enforced here.
  31285. setSize (jmax (1, getWidth()),
  31286. jmax (1, getHeight()));
  31287. #endif
  31288. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31289. bool wasFullscreen = false;
  31290. bool wasMinimised = false;
  31291. ComponentBoundsConstrainer* currentConstainer = 0;
  31292. Rectangle<int> oldNonFullScreenBounds;
  31293. if (peer != 0)
  31294. {
  31295. wasFullscreen = peer->isFullScreen();
  31296. wasMinimised = peer->isMinimised();
  31297. currentConstainer = peer->getConstrainer();
  31298. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31299. removeFromDesktop();
  31300. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31301. }
  31302. if (parentComponent_ != 0)
  31303. parentComponent_->removeChildComponent (this);
  31304. if (safePointer != 0)
  31305. {
  31306. flags.hasHeavyweightPeerFlag = true;
  31307. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31308. Desktop::getInstance().addDesktopComponent (this);
  31309. bounds_.setPosition (topLeft);
  31310. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31311. peer->setVisible (isVisible());
  31312. if (wasFullscreen)
  31313. {
  31314. peer->setFullScreen (true);
  31315. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31316. }
  31317. if (wasMinimised)
  31318. peer->setMinimised (true);
  31319. if (isAlwaysOnTop())
  31320. peer->setAlwaysOnTop (true);
  31321. peer->setConstrainer (currentConstainer);
  31322. repaint();
  31323. }
  31324. internalHierarchyChanged();
  31325. }
  31326. }
  31327. void Component::removeFromDesktop()
  31328. {
  31329. // if component methods are being called from threads other than the message
  31330. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31331. checkMessageManagerIsLocked
  31332. if (flags.hasHeavyweightPeerFlag)
  31333. {
  31334. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31335. flags.hasHeavyweightPeerFlag = false;
  31336. jassert (peer != 0);
  31337. delete peer;
  31338. Desktop::getInstance().removeDesktopComponent (this);
  31339. }
  31340. }
  31341. bool Component::isOnDesktop() const throw()
  31342. {
  31343. return flags.hasHeavyweightPeerFlag;
  31344. }
  31345. void Component::userTriedToCloseWindow()
  31346. {
  31347. /* This means that the user's trying to get rid of your window with the 'close window' system
  31348. menu option (on windows) or possibly the task manager - you should really handle this
  31349. and delete or hide your component in an appropriate way.
  31350. If you want to ignore the event and don't want to trigger this assertion, just override
  31351. this method and do nothing.
  31352. */
  31353. jassertfalse
  31354. }
  31355. void Component::minimisationStateChanged (bool)
  31356. {
  31357. }
  31358. void Component::setOpaque (const bool shouldBeOpaque)
  31359. {
  31360. if (shouldBeOpaque != flags.opaqueFlag)
  31361. {
  31362. flags.opaqueFlag = shouldBeOpaque;
  31363. if (flags.hasHeavyweightPeerFlag)
  31364. {
  31365. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31366. if (peer != 0)
  31367. {
  31368. // to make it recreate the heavyweight window
  31369. addToDesktop (peer->getStyleFlags());
  31370. }
  31371. }
  31372. repaint();
  31373. }
  31374. }
  31375. bool Component::isOpaque() const throw()
  31376. {
  31377. return flags.opaqueFlag;
  31378. }
  31379. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31380. {
  31381. if (shouldBeBuffered != flags.bufferToImageFlag)
  31382. {
  31383. deleteAndZero (bufferedImage_);
  31384. flags.bufferToImageFlag = shouldBeBuffered;
  31385. }
  31386. }
  31387. void Component::toFront (const bool setAsForeground)
  31388. {
  31389. // if component methods are being called from threads other than the message
  31390. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31391. checkMessageManagerIsLocked
  31392. if (flags.hasHeavyweightPeerFlag)
  31393. {
  31394. ComponentPeer* const peer = getPeer();
  31395. if (peer != 0)
  31396. {
  31397. peer->toFront (setAsForeground);
  31398. if (setAsForeground && ! hasKeyboardFocus (true))
  31399. grabKeyboardFocus();
  31400. }
  31401. }
  31402. else if (parentComponent_ != 0)
  31403. {
  31404. Array<Component*>& childList = parentComponent_->childComponentList_;
  31405. if (childList.getLast() != this)
  31406. {
  31407. const int index = childList.indexOf (this);
  31408. if (index >= 0)
  31409. {
  31410. int insertIndex = -1;
  31411. if (! flags.alwaysOnTopFlag)
  31412. {
  31413. insertIndex = childList.size() - 1;
  31414. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31415. --insertIndex;
  31416. }
  31417. if (index != insertIndex)
  31418. {
  31419. childList.move (index, insertIndex);
  31420. sendFakeMouseMove();
  31421. repaintParent();
  31422. }
  31423. }
  31424. }
  31425. if (setAsForeground)
  31426. {
  31427. internalBroughtToFront();
  31428. grabKeyboardFocus();
  31429. }
  31430. }
  31431. }
  31432. void Component::toBehind (Component* const other)
  31433. {
  31434. if (other != 0 && other != this)
  31435. {
  31436. // the two components must belong to the same parent..
  31437. jassert (parentComponent_ == other->parentComponent_);
  31438. if (parentComponent_ != 0)
  31439. {
  31440. Array<Component*>& childList = parentComponent_->childComponentList_;
  31441. const int index = childList.indexOf (this);
  31442. if (index >= 0 && childList [index + 1] != other)
  31443. {
  31444. int otherIndex = childList.indexOf (other);
  31445. if (otherIndex >= 0)
  31446. {
  31447. if (index < otherIndex)
  31448. --otherIndex;
  31449. childList.move (index, otherIndex);
  31450. sendFakeMouseMove();
  31451. repaintParent();
  31452. }
  31453. }
  31454. }
  31455. else if (isOnDesktop())
  31456. {
  31457. jassert (other->isOnDesktop());
  31458. if (other->isOnDesktop())
  31459. {
  31460. ComponentPeer* const us = getPeer();
  31461. ComponentPeer* const them = other->getPeer();
  31462. jassert (us != 0 && them != 0);
  31463. if (us != 0 && them != 0)
  31464. us->toBehind (them);
  31465. }
  31466. }
  31467. }
  31468. }
  31469. void Component::toBack()
  31470. {
  31471. Array<Component*>& childList = parentComponent_->childComponentList_;
  31472. if (isOnDesktop())
  31473. {
  31474. jassertfalse //xxx need to add this to native window
  31475. }
  31476. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31477. {
  31478. const int index = childList.indexOf (this);
  31479. if (index > 0)
  31480. {
  31481. int insertIndex = 0;
  31482. if (flags.alwaysOnTopFlag)
  31483. {
  31484. while (insertIndex < childList.size()
  31485. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31486. {
  31487. ++insertIndex;
  31488. }
  31489. }
  31490. if (index != insertIndex)
  31491. {
  31492. childList.move (index, insertIndex);
  31493. sendFakeMouseMove();
  31494. repaintParent();
  31495. }
  31496. }
  31497. }
  31498. }
  31499. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31500. {
  31501. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31502. {
  31503. flags.alwaysOnTopFlag = shouldStayOnTop;
  31504. if (isOnDesktop())
  31505. {
  31506. ComponentPeer* const peer = getPeer();
  31507. jassert (peer != 0);
  31508. if (peer != 0)
  31509. {
  31510. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31511. {
  31512. // some kinds of peer can't change their always-on-top status, so
  31513. // for these, we'll need to create a new window
  31514. const int oldFlags = peer->getStyleFlags();
  31515. removeFromDesktop();
  31516. addToDesktop (oldFlags);
  31517. }
  31518. }
  31519. }
  31520. if (shouldStayOnTop)
  31521. toFront (false);
  31522. internalHierarchyChanged();
  31523. }
  31524. }
  31525. bool Component::isAlwaysOnTop() const throw()
  31526. {
  31527. return flags.alwaysOnTopFlag;
  31528. }
  31529. int Component::proportionOfWidth (const float proportion) const throw()
  31530. {
  31531. return roundToInt (proportion * bounds_.getWidth());
  31532. }
  31533. int Component::proportionOfHeight (const float proportion) const throw()
  31534. {
  31535. return roundToInt (proportion * bounds_.getHeight());
  31536. }
  31537. int Component::getParentWidth() const throw()
  31538. {
  31539. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31540. : getParentMonitorArea().getWidth();
  31541. }
  31542. int Component::getParentHeight() const throw()
  31543. {
  31544. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31545. : getParentMonitorArea().getHeight();
  31546. }
  31547. int Component::getScreenX() const
  31548. {
  31549. return getScreenPosition().getX();
  31550. }
  31551. int Component::getScreenY() const
  31552. {
  31553. return getScreenPosition().getY();
  31554. }
  31555. const Point<int> Component::getScreenPosition() const
  31556. {
  31557. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31558. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31559. : getPosition());
  31560. }
  31561. const Rectangle<int> Component::getScreenBounds() const
  31562. {
  31563. return bounds_.withPosition (getScreenPosition());
  31564. }
  31565. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31566. {
  31567. const Component* c = this;
  31568. Point<int> p (relativePosition);
  31569. do
  31570. {
  31571. if (c->flags.hasHeavyweightPeerFlag)
  31572. return c->getPeer()->relativePositionToGlobal (p);
  31573. p += c->getPosition();
  31574. c = c->parentComponent_;
  31575. }
  31576. while (c != 0);
  31577. return p;
  31578. }
  31579. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31580. {
  31581. if (flags.hasHeavyweightPeerFlag)
  31582. {
  31583. return getPeer()->globalPositionToRelative (screenPosition);
  31584. }
  31585. else
  31586. {
  31587. if (parentComponent_ != 0)
  31588. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31589. return screenPosition - getPosition();
  31590. }
  31591. }
  31592. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31593. {
  31594. Point<int> p (positionRelativeToThis);
  31595. if (targetComponent != 0)
  31596. {
  31597. const Component* c = this;
  31598. do
  31599. {
  31600. if (c == targetComponent)
  31601. return p;
  31602. if (c->flags.hasHeavyweightPeerFlag)
  31603. {
  31604. p = c->getPeer()->relativePositionToGlobal (p);
  31605. break;
  31606. }
  31607. p += c->getPosition();
  31608. c = c->parentComponent_;
  31609. }
  31610. while (c != 0);
  31611. p = targetComponent->globalPositionToRelative (p);
  31612. }
  31613. return p;
  31614. }
  31615. void Component::setBounds (int x, int y, int w, int h)
  31616. {
  31617. // if component methods are being called from threads other than the message
  31618. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31619. checkMessageManagerIsLocked
  31620. if (w < 0) w = 0;
  31621. if (h < 0) h = 0;
  31622. const bool wasResized = (getWidth() != w || getHeight() != h);
  31623. const bool wasMoved = (getX() != x || getY() != y);
  31624. #if JUCE_DEBUG
  31625. // It's a very bad idea to try to resize a window during its paint() method!
  31626. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31627. #endif
  31628. if (wasMoved || wasResized)
  31629. {
  31630. if (flags.visibleFlag)
  31631. {
  31632. // send a fake mouse move to trigger enter/exit messages if needed..
  31633. sendFakeMouseMove();
  31634. if (! flags.hasHeavyweightPeerFlag)
  31635. repaintParent();
  31636. }
  31637. bounds_.setBounds (x, y, w, h);
  31638. if (wasResized)
  31639. repaint();
  31640. else if (! flags.hasHeavyweightPeerFlag)
  31641. repaintParent();
  31642. if (flags.hasHeavyweightPeerFlag)
  31643. {
  31644. ComponentPeer* const peer = getPeer();
  31645. if (peer != 0)
  31646. {
  31647. if (wasMoved && wasResized)
  31648. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31649. else if (wasMoved)
  31650. peer->setPosition (getX(), getY());
  31651. else if (wasResized)
  31652. peer->setSize (getWidth(), getHeight());
  31653. }
  31654. }
  31655. sendMovedResizedMessages (wasMoved, wasResized);
  31656. }
  31657. }
  31658. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31659. {
  31660. JUCE_TRY
  31661. {
  31662. if (wasMoved)
  31663. moved();
  31664. if (wasResized)
  31665. {
  31666. resized();
  31667. for (int i = childComponentList_.size(); --i >= 0;)
  31668. {
  31669. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31670. i = jmin (i, childComponentList_.size());
  31671. }
  31672. }
  31673. BailOutChecker checker (this);
  31674. if (parentComponent_ != 0)
  31675. parentComponent_->childBoundsChanged (this);
  31676. if (! checker.shouldBailOut())
  31677. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31678. *this, wasMoved, wasResized);
  31679. }
  31680. JUCE_CATCH_EXCEPTION
  31681. }
  31682. void Component::setSize (const int w, const int h)
  31683. {
  31684. setBounds (getX(), getY(), w, h);
  31685. }
  31686. void Component::setTopLeftPosition (const int x, const int y)
  31687. {
  31688. setBounds (x, y, getWidth(), getHeight());
  31689. }
  31690. void Component::setTopRightPosition (const int x, const int y)
  31691. {
  31692. setTopLeftPosition (x - getWidth(), y);
  31693. }
  31694. void Component::setBounds (const Rectangle<int>& r)
  31695. {
  31696. setBounds (r.getX(),
  31697. r.getY(),
  31698. r.getWidth(),
  31699. r.getHeight());
  31700. }
  31701. void Component::setBoundsRelative (const float x, const float y,
  31702. const float w, const float h)
  31703. {
  31704. const int pw = getParentWidth();
  31705. const int ph = getParentHeight();
  31706. setBounds (roundToInt (x * pw),
  31707. roundToInt (y * ph),
  31708. roundToInt (w * pw),
  31709. roundToInt (h * ph));
  31710. }
  31711. void Component::setCentrePosition (const int x, const int y)
  31712. {
  31713. setTopLeftPosition (x - getWidth() / 2,
  31714. y - getHeight() / 2);
  31715. }
  31716. void Component::setCentreRelative (const float x, const float y)
  31717. {
  31718. setCentrePosition (roundToInt (getParentWidth() * x),
  31719. roundToInt (getParentHeight() * y));
  31720. }
  31721. void Component::centreWithSize (const int width, const int height)
  31722. {
  31723. setBounds ((getParentWidth() - width) / 2,
  31724. (getParentHeight() - height) / 2,
  31725. width,
  31726. height);
  31727. }
  31728. void Component::setBoundsInset (const BorderSize& borders)
  31729. {
  31730. setBounds (borders.getLeft(),
  31731. borders.getTop(),
  31732. getParentWidth() - (borders.getLeftAndRight()),
  31733. getParentHeight() - (borders.getTopAndBottom()));
  31734. }
  31735. void Component::setBoundsToFit (int x, int y, int width, int height,
  31736. const Justification& justification,
  31737. const bool onlyReduceInSize)
  31738. {
  31739. // it's no good calling this method unless both the component and
  31740. // target rectangle have a finite size.
  31741. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31742. if (getWidth() > 0 && getHeight() > 0
  31743. && width > 0 && height > 0)
  31744. {
  31745. int newW, newH;
  31746. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31747. {
  31748. newW = getWidth();
  31749. newH = getHeight();
  31750. }
  31751. else
  31752. {
  31753. const double imageRatio = getHeight() / (double) getWidth();
  31754. const double targetRatio = height / (double) width;
  31755. if (imageRatio <= targetRatio)
  31756. {
  31757. newW = width;
  31758. newH = jmin (height, roundToInt (newW * imageRatio));
  31759. }
  31760. else
  31761. {
  31762. newH = height;
  31763. newW = jmin (width, roundToInt (newH / imageRatio));
  31764. }
  31765. }
  31766. if (newW > 0 && newH > 0)
  31767. {
  31768. int newX, newY;
  31769. justification.applyToRectangle (newX, newY, newW, newH,
  31770. x, y, width, height);
  31771. setBounds (newX, newY, newW, newH);
  31772. }
  31773. }
  31774. }
  31775. bool Component::hitTest (int x, int y)
  31776. {
  31777. if (! flags.ignoresMouseClicksFlag)
  31778. return true;
  31779. if (flags.allowChildMouseClicksFlag)
  31780. {
  31781. for (int i = getNumChildComponents(); --i >= 0;)
  31782. {
  31783. Component* const c = getChildComponent (i);
  31784. if (c->isVisible()
  31785. && c->bounds_.contains (x, y)
  31786. && c->hitTest (x - c->getX(),
  31787. y - c->getY()))
  31788. {
  31789. return true;
  31790. }
  31791. }
  31792. }
  31793. return false;
  31794. }
  31795. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31796. const bool allowClicksOnChildComponents) throw()
  31797. {
  31798. flags.ignoresMouseClicksFlag = ! allowClicks;
  31799. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31800. }
  31801. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31802. bool& allowsClicksOnChildComponents) const throw()
  31803. {
  31804. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31805. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31806. }
  31807. bool Component::contains (const int x, const int y)
  31808. {
  31809. if (((unsigned int) x) < (unsigned int) getWidth()
  31810. && ((unsigned int) y) < (unsigned int) getHeight()
  31811. && hitTest (x, y))
  31812. {
  31813. if (parentComponent_ != 0)
  31814. {
  31815. return parentComponent_->contains (x + getX(),
  31816. y + getY());
  31817. }
  31818. else if (flags.hasHeavyweightPeerFlag)
  31819. {
  31820. const ComponentPeer* const peer = getPeer();
  31821. if (peer != 0)
  31822. return peer->contains (Point<int> (x, y), true);
  31823. }
  31824. }
  31825. return false;
  31826. }
  31827. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31828. {
  31829. if (! contains (x, y))
  31830. return false;
  31831. Component* p = this;
  31832. while (p->parentComponent_ != 0)
  31833. {
  31834. x += p->getX();
  31835. y += p->getY();
  31836. p = p->parentComponent_;
  31837. }
  31838. const Component* const c = p->getComponentAt (x, y);
  31839. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31840. }
  31841. Component* Component::getComponentAt (const Point<int>& position)
  31842. {
  31843. return getComponentAt (position.getX(), position.getY());
  31844. }
  31845. Component* Component::getComponentAt (const int x, const int y)
  31846. {
  31847. if (flags.visibleFlag
  31848. && ((unsigned int) x) < (unsigned int) getWidth()
  31849. && ((unsigned int) y) < (unsigned int) getHeight()
  31850. && hitTest (x, y))
  31851. {
  31852. for (int i = childComponentList_.size(); --i >= 0;)
  31853. {
  31854. Component* const child = childComponentList_.getUnchecked(i);
  31855. Component* const c = child->getComponentAt (x - child->getX(),
  31856. y - child->getY());
  31857. if (c != 0)
  31858. return c;
  31859. }
  31860. return this;
  31861. }
  31862. return 0;
  31863. }
  31864. void Component::addChildComponent (Component* const child, int zOrder)
  31865. {
  31866. // if component methods are being called from threads other than the message
  31867. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31868. checkMessageManagerIsLocked
  31869. if (child != 0 && child->parentComponent_ != this)
  31870. {
  31871. if (child->parentComponent_ != 0)
  31872. child->parentComponent_->removeChildComponent (child);
  31873. else
  31874. child->removeFromDesktop();
  31875. child->parentComponent_ = this;
  31876. if (child->isVisible())
  31877. child->repaintParent();
  31878. if (! child->isAlwaysOnTop())
  31879. {
  31880. if (zOrder < 0 || zOrder > childComponentList_.size())
  31881. zOrder = childComponentList_.size();
  31882. while (zOrder > 0)
  31883. {
  31884. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31885. break;
  31886. --zOrder;
  31887. }
  31888. }
  31889. childComponentList_.insert (zOrder, child);
  31890. child->internalHierarchyChanged();
  31891. internalChildrenChanged();
  31892. }
  31893. }
  31894. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31895. {
  31896. if (child != 0)
  31897. {
  31898. child->setVisible (true);
  31899. addChildComponent (child, zOrder);
  31900. }
  31901. }
  31902. void Component::removeChildComponent (Component* const child)
  31903. {
  31904. removeChildComponent (childComponentList_.indexOf (child));
  31905. }
  31906. Component* Component::removeChildComponent (const int index)
  31907. {
  31908. // if component methods are being called from threads other than the message
  31909. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31910. checkMessageManagerIsLocked
  31911. Component* const child = childComponentList_ [index];
  31912. if (child != 0)
  31913. {
  31914. sendFakeMouseMove();
  31915. child->repaintParent();
  31916. childComponentList_.remove (index);
  31917. child->parentComponent_ = 0;
  31918. JUCE_TRY
  31919. {
  31920. if ((currentlyFocusedComponent == child)
  31921. || child->isParentOf (currentlyFocusedComponent))
  31922. {
  31923. // get rid first to force the grabKeyboardFocus to change to us.
  31924. giveAwayFocus();
  31925. grabKeyboardFocus();
  31926. }
  31927. }
  31928. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31929. catch (const std::exception& e)
  31930. {
  31931. currentlyFocusedComponent = 0;
  31932. Desktop::getInstance().triggerFocusCallback();
  31933. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31934. }
  31935. catch (...)
  31936. {
  31937. currentlyFocusedComponent = 0;
  31938. Desktop::getInstance().triggerFocusCallback();
  31939. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31940. }
  31941. #endif
  31942. child->internalHierarchyChanged();
  31943. internalChildrenChanged();
  31944. }
  31945. return child;
  31946. }
  31947. void Component::removeAllChildren()
  31948. {
  31949. while (childComponentList_.size() > 0)
  31950. removeChildComponent (childComponentList_.size() - 1);
  31951. }
  31952. void Component::deleteAllChildren()
  31953. {
  31954. while (childComponentList_.size() > 0)
  31955. delete (removeChildComponent (childComponentList_.size() - 1));
  31956. }
  31957. int Component::getNumChildComponents() const throw()
  31958. {
  31959. return childComponentList_.size();
  31960. }
  31961. Component* Component::getChildComponent (const int index) const throw()
  31962. {
  31963. return childComponentList_ [index];
  31964. }
  31965. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31966. {
  31967. return childComponentList_.indexOf (const_cast <Component*> (child));
  31968. }
  31969. Component* Component::getTopLevelComponent() const throw()
  31970. {
  31971. const Component* comp = this;
  31972. while (comp->parentComponent_ != 0)
  31973. comp = comp->parentComponent_;
  31974. return const_cast <Component*> (comp);
  31975. }
  31976. bool Component::isParentOf (const Component* possibleChild) const throw()
  31977. {
  31978. if (! possibleChild->isValidComponent())
  31979. {
  31980. jassert (possibleChild == 0);
  31981. return false;
  31982. }
  31983. while (possibleChild != 0)
  31984. {
  31985. possibleChild = possibleChild->parentComponent_;
  31986. if (possibleChild == this)
  31987. return true;
  31988. }
  31989. return false;
  31990. }
  31991. void Component::parentHierarchyChanged()
  31992. {
  31993. }
  31994. void Component::childrenChanged()
  31995. {
  31996. }
  31997. void Component::internalChildrenChanged()
  31998. {
  31999. if (componentListeners.isEmpty())
  32000. {
  32001. childrenChanged();
  32002. }
  32003. else
  32004. {
  32005. BailOutChecker checker (this);
  32006. childrenChanged();
  32007. if (! checker.shouldBailOut())
  32008. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32009. }
  32010. }
  32011. void Component::internalHierarchyChanged()
  32012. {
  32013. BailOutChecker checker (this);
  32014. parentHierarchyChanged();
  32015. if (checker.shouldBailOut())
  32016. return;
  32017. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32018. if (checker.shouldBailOut())
  32019. return;
  32020. for (int i = childComponentList_.size(); --i >= 0;)
  32021. {
  32022. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32023. if (checker.shouldBailOut())
  32024. {
  32025. // you really shouldn't delete the parent component during a callback telling you
  32026. // that it's changed..
  32027. jassertfalse;
  32028. return;
  32029. }
  32030. i = jmin (i, childComponentList_.size());
  32031. }
  32032. }
  32033. void* Component::runModalLoopCallback (void* userData)
  32034. {
  32035. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32036. }
  32037. int Component::runModalLoop()
  32038. {
  32039. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32040. {
  32041. // use a callback so this can be called from non-gui threads
  32042. return (int) (pointer_sized_int)
  32043. MessageManager::getInstance()
  32044. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32045. }
  32046. SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  32047. if (! isCurrentlyModal())
  32048. enterModalState();
  32049. JUCE_TRY
  32050. {
  32051. while (flags.currentlyModalFlag && flags.visibleFlag)
  32052. {
  32053. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  32054. break;
  32055. // check whether this component was deleted during the last message
  32056. if (! isValidMessageListener())
  32057. break;
  32058. }
  32059. }
  32060. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32061. catch (const std::exception& e)
  32062. {
  32063. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32064. return 0;
  32065. }
  32066. catch (...)
  32067. {
  32068. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32069. return 0;
  32070. }
  32071. #endif
  32072. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32073. int returnValue = 0;
  32074. if (modalIndex >= 0)
  32075. {
  32076. modalComponentReturnValueKeys.remove (modalIndex);
  32077. returnValue = modalReturnValues.remove (modalIndex);
  32078. }
  32079. modalComponentStack.removeValue (this);
  32080. if (prevFocused != 0)
  32081. prevFocused->grabKeyboardFocus();
  32082. return returnValue;
  32083. }
  32084. void Component::enterModalState (const bool takeKeyboardFocus_)
  32085. {
  32086. // if component methods are being called from threads other than the message
  32087. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32088. checkMessageManagerIsLocked
  32089. // Check for an attempt to make a component modal when it already is!
  32090. // This can cause nasty problems..
  32091. jassert (! flags.currentlyModalFlag);
  32092. if (! isCurrentlyModal())
  32093. {
  32094. modalComponentStack.add (this);
  32095. modalComponentReturnValueKeys.add (this);
  32096. modalReturnValues.add (0);
  32097. flags.currentlyModalFlag = true;
  32098. setVisible (true);
  32099. if (takeKeyboardFocus_)
  32100. grabKeyboardFocus();
  32101. }
  32102. }
  32103. void Component::exitModalState (const int returnValue)
  32104. {
  32105. if (isCurrentlyModal())
  32106. {
  32107. if (MessageManager::getInstance()->isThisTheMessageThread())
  32108. {
  32109. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32110. if (modalIndex >= 0)
  32111. {
  32112. modalReturnValues.set (modalIndex, returnValue);
  32113. }
  32114. else
  32115. {
  32116. modalComponentReturnValueKeys.add (this);
  32117. modalReturnValues.add (returnValue);
  32118. }
  32119. modalComponentStack.removeValue (this);
  32120. flags.currentlyModalFlag = false;
  32121. bringModalComponentToFront();
  32122. }
  32123. else
  32124. {
  32125. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32126. }
  32127. }
  32128. }
  32129. bool Component::isCurrentlyModal() const throw()
  32130. {
  32131. return flags.currentlyModalFlag
  32132. && getCurrentlyModalComponent() == this;
  32133. }
  32134. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32135. {
  32136. Component* const mc = getCurrentlyModalComponent();
  32137. return mc != 0
  32138. && mc != this
  32139. && (! mc->isParentOf (this))
  32140. && ! mc->canModalEventBeSentToComponent (this);
  32141. }
  32142. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32143. {
  32144. return modalComponentStack.size();
  32145. }
  32146. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32147. {
  32148. Component* const c = static_cast <Component*> (modalComponentStack [modalComponentStack.size() - index - 1]);
  32149. return c->isValidComponent() ? c : 0;
  32150. }
  32151. void Component::bringModalComponentToFront()
  32152. {
  32153. ComponentPeer* lastOne = 0;
  32154. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32155. {
  32156. Component* const c = getCurrentlyModalComponent (i);
  32157. if (c == 0)
  32158. break;
  32159. ComponentPeer* peer = c->getPeer();
  32160. if (peer != 0 && peer != lastOne)
  32161. {
  32162. if (lastOne == 0)
  32163. {
  32164. peer->toFront (true);
  32165. peer->grabFocus();
  32166. }
  32167. else
  32168. peer->toBehind (lastOne);
  32169. lastOne = peer;
  32170. }
  32171. }
  32172. }
  32173. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32174. {
  32175. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32176. }
  32177. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32178. {
  32179. return flags.bringToFrontOnClickFlag;
  32180. }
  32181. void Component::setMouseCursor (const MouseCursor& cursor)
  32182. {
  32183. if (cursor_ != cursor)
  32184. {
  32185. cursor_ = cursor;
  32186. if (flags.visibleFlag)
  32187. updateMouseCursor();
  32188. }
  32189. }
  32190. const MouseCursor Component::getMouseCursor()
  32191. {
  32192. return cursor_;
  32193. }
  32194. void Component::updateMouseCursor() const
  32195. {
  32196. sendFakeMouseMove();
  32197. }
  32198. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32199. {
  32200. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32201. }
  32202. void Component::repaintParent()
  32203. {
  32204. if (flags.visibleFlag)
  32205. internalRepaint (0, 0, getWidth(), getHeight());
  32206. }
  32207. void Component::repaint()
  32208. {
  32209. repaint (0, 0, getWidth(), getHeight());
  32210. }
  32211. void Component::repaint (const int x, const int y,
  32212. const int w, const int h)
  32213. {
  32214. deleteAndZero (bufferedImage_);
  32215. if (flags.visibleFlag)
  32216. internalRepaint (x, y, w, h);
  32217. }
  32218. void Component::internalRepaint (int x, int y, int w, int h)
  32219. {
  32220. // if component methods are being called from threads other than the message
  32221. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32222. checkMessageManagerIsLocked
  32223. if (x < 0)
  32224. {
  32225. w += x;
  32226. x = 0;
  32227. }
  32228. if (x + w > getWidth())
  32229. w = getWidth() - x;
  32230. if (w > 0)
  32231. {
  32232. if (y < 0)
  32233. {
  32234. h += y;
  32235. y = 0;
  32236. }
  32237. if (y + h > getHeight())
  32238. h = getHeight() - y;
  32239. if (h > 0)
  32240. {
  32241. if (parentComponent_ != 0)
  32242. {
  32243. x += getX();
  32244. y += getY();
  32245. if (parentComponent_->flags.visibleFlag)
  32246. parentComponent_->internalRepaint (x, y, w, h);
  32247. }
  32248. else if (flags.hasHeavyweightPeerFlag)
  32249. {
  32250. ComponentPeer* const peer = getPeer();
  32251. if (peer != 0)
  32252. peer->repaint (x, y, w, h);
  32253. }
  32254. }
  32255. }
  32256. }
  32257. void Component::renderComponent (Graphics& g)
  32258. {
  32259. const Rectangle<int> clipBounds (g.getClipBounds());
  32260. g.saveState();
  32261. clipObscuredRegions (g, clipBounds, 0, 0);
  32262. if (! g.isClipEmpty())
  32263. {
  32264. if (flags.bufferToImageFlag)
  32265. {
  32266. if (bufferedImage_ == 0)
  32267. {
  32268. bufferedImage_ = Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32269. getWidth(), getHeight(), ! flags.opaqueFlag);
  32270. Graphics imG (*bufferedImage_);
  32271. paint (imG);
  32272. }
  32273. g.setColour (Colours::black);
  32274. g.drawImageAt (bufferedImage_, 0, 0);
  32275. }
  32276. else
  32277. {
  32278. paint (g);
  32279. }
  32280. }
  32281. g.restoreState();
  32282. for (int i = 0; i < childComponentList_.size(); ++i)
  32283. {
  32284. Component* const child = childComponentList_.getUnchecked (i);
  32285. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32286. {
  32287. g.saveState();
  32288. if (g.reduceClipRegion (child->getX(), child->getY(),
  32289. child->getWidth(), child->getHeight()))
  32290. {
  32291. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32292. {
  32293. const Component* const sibling = childComponentList_.getUnchecked (j);
  32294. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32295. g.excludeClipRegion (sibling->getBounds());
  32296. }
  32297. if (! g.isClipEmpty())
  32298. {
  32299. g.setOrigin (child->getX(), child->getY());
  32300. child->paintEntireComponent (g);
  32301. }
  32302. }
  32303. g.restoreState();
  32304. }
  32305. }
  32306. g.saveState();
  32307. paintOverChildren (g);
  32308. g.restoreState();
  32309. }
  32310. void Component::paintEntireComponent (Graphics& g)
  32311. {
  32312. jassert (! g.isClipEmpty());
  32313. #if JUCE_DEBUG
  32314. flags.isInsidePaintCall = true;
  32315. #endif
  32316. if (effect_ != 0)
  32317. {
  32318. ScopedPointer<Image> effectImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32319. getWidth(), getHeight(),
  32320. ! flags.opaqueFlag));
  32321. {
  32322. Graphics g2 (*effectImage);
  32323. renderComponent (g2);
  32324. }
  32325. effect_->applyEffect (*effectImage, g);
  32326. }
  32327. else
  32328. {
  32329. renderComponent (g);
  32330. }
  32331. #if JUCE_DEBUG
  32332. flags.isInsidePaintCall = false;
  32333. #endif
  32334. }
  32335. Image* Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32336. const bool clipImageToComponentBounds)
  32337. {
  32338. Rectangle<int> r (areaToGrab);
  32339. if (clipImageToComponentBounds)
  32340. r = r.getIntersection (getLocalBounds());
  32341. ScopedPointer<Image> componentImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32342. jmax (1, r.getWidth()),
  32343. jmax (1, r.getHeight()),
  32344. true));
  32345. Graphics imageContext (*componentImage);
  32346. imageContext.setOrigin (-r.getX(), -r.getY());
  32347. paintEntireComponent (imageContext);
  32348. return componentImage.release();
  32349. }
  32350. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32351. {
  32352. if (effect_ != effect)
  32353. {
  32354. effect_ = effect;
  32355. repaint();
  32356. }
  32357. }
  32358. LookAndFeel& Component::getLookAndFeel() const throw()
  32359. {
  32360. const Component* c = this;
  32361. do
  32362. {
  32363. if (c->lookAndFeel_ != 0)
  32364. return *(c->lookAndFeel_);
  32365. c = c->parentComponent_;
  32366. }
  32367. while (c != 0);
  32368. return LookAndFeel::getDefaultLookAndFeel();
  32369. }
  32370. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32371. {
  32372. if (lookAndFeel_ != newLookAndFeel)
  32373. {
  32374. lookAndFeel_ = newLookAndFeel;
  32375. sendLookAndFeelChange();
  32376. }
  32377. }
  32378. void Component::lookAndFeelChanged()
  32379. {
  32380. }
  32381. void Component::sendLookAndFeelChange()
  32382. {
  32383. repaint();
  32384. lookAndFeelChanged();
  32385. // (it's not a great idea to do anything that would delete this component
  32386. // during the lookAndFeelChanged() callback)
  32387. jassert (isValidComponent());
  32388. SafePointer<Component> safePointer (this);
  32389. for (int i = childComponentList_.size(); --i >= 0;)
  32390. {
  32391. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32392. if (safePointer == 0)
  32393. return;
  32394. i = jmin (i, childComponentList_.size());
  32395. }
  32396. }
  32397. static const var::identifier getColourPropertyId (const int colourId)
  32398. {
  32399. String s;
  32400. s.preallocateStorage (18);
  32401. s << "jcclr_" << String::toHexString (colourId);
  32402. return s;
  32403. }
  32404. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32405. {
  32406. var* v = properties.getItem (getColourPropertyId (colourId));
  32407. if (v != 0)
  32408. return Colour ((int) *v);
  32409. if (inheritFromParent && parentComponent_ != 0)
  32410. return parentComponent_->findColour (colourId, true);
  32411. return getLookAndFeel().findColour (colourId);
  32412. }
  32413. bool Component::isColourSpecified (const int colourId) const
  32414. {
  32415. return properties.contains (getColourPropertyId (colourId));
  32416. }
  32417. void Component::removeColour (const int colourId)
  32418. {
  32419. if (properties.remove (getColourPropertyId (colourId)))
  32420. colourChanged();
  32421. }
  32422. void Component::setColour (const int colourId, const Colour& colour)
  32423. {
  32424. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32425. colourChanged();
  32426. }
  32427. void Component::copyAllExplicitColoursTo (Component& target) const
  32428. {
  32429. bool changed = false;
  32430. for (int i = properties.size(); --i >= 0;)
  32431. {
  32432. const var::identifier name (properties.getName(i));
  32433. if (name.name.startsWith ("jcclr_"))
  32434. if (target.properties.set (name, properties [name]))
  32435. changed = true;
  32436. }
  32437. if (changed)
  32438. target.colourChanged();
  32439. }
  32440. void Component::colourChanged()
  32441. {
  32442. }
  32443. const Rectangle<int> Component::getLocalBounds() const throw()
  32444. {
  32445. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32446. }
  32447. const Rectangle<int> Component::getUnclippedArea() const
  32448. {
  32449. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32450. Component* p = parentComponent_;
  32451. int px = getX();
  32452. int py = getY();
  32453. while (p != 0)
  32454. {
  32455. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32456. return Rectangle<int>();
  32457. px += p->getX();
  32458. py += p->getY();
  32459. p = p->parentComponent_;
  32460. }
  32461. return Rectangle<int> (x, y, w, h);
  32462. }
  32463. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32464. const int deltaX, const int deltaY) const
  32465. {
  32466. for (int i = childComponentList_.size(); --i >= 0;)
  32467. {
  32468. const Component* const c = childComponentList_.getUnchecked(i);
  32469. if (c->isVisible())
  32470. {
  32471. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32472. if (! newClip.isEmpty())
  32473. {
  32474. if (c->isOpaque())
  32475. {
  32476. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32477. }
  32478. else
  32479. {
  32480. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32481. c->getX() + deltaX,
  32482. c->getY() + deltaY);
  32483. }
  32484. }
  32485. }
  32486. }
  32487. }
  32488. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32489. {
  32490. result.clear();
  32491. const Rectangle<int> unclipped (getUnclippedArea());
  32492. if (! unclipped.isEmpty())
  32493. {
  32494. result.add (unclipped);
  32495. if (includeSiblings)
  32496. {
  32497. const Component* const c = getTopLevelComponent();
  32498. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32499. c->getLocalBounds(), this);
  32500. }
  32501. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32502. result.consolidate();
  32503. }
  32504. }
  32505. void Component::subtractObscuredRegions (RectangleList& result,
  32506. const Point<int>& delta,
  32507. const Rectangle<int>& clipRect,
  32508. const Component* const compToAvoid) const
  32509. {
  32510. for (int i = childComponentList_.size(); --i >= 0;)
  32511. {
  32512. const Component* const c = childComponentList_.getUnchecked(i);
  32513. if (c != compToAvoid && c->isVisible())
  32514. {
  32515. if (c->isOpaque())
  32516. {
  32517. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32518. childBounds.translate (delta.getX(), delta.getY());
  32519. result.subtract (childBounds);
  32520. }
  32521. else
  32522. {
  32523. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32524. newClip.translate (-c->getX(), -c->getY());
  32525. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32526. newClip, compToAvoid);
  32527. }
  32528. }
  32529. }
  32530. }
  32531. void Component::mouseEnter (const MouseEvent&)
  32532. {
  32533. // base class does nothing
  32534. }
  32535. void Component::mouseExit (const MouseEvent&)
  32536. {
  32537. // base class does nothing
  32538. }
  32539. void Component::mouseDown (const MouseEvent&)
  32540. {
  32541. // base class does nothing
  32542. }
  32543. void Component::mouseUp (const MouseEvent&)
  32544. {
  32545. // base class does nothing
  32546. }
  32547. void Component::mouseDrag (const MouseEvent&)
  32548. {
  32549. // base class does nothing
  32550. }
  32551. void Component::mouseMove (const MouseEvent&)
  32552. {
  32553. // base class does nothing
  32554. }
  32555. void Component::mouseDoubleClick (const MouseEvent&)
  32556. {
  32557. // base class does nothing
  32558. }
  32559. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32560. {
  32561. // the base class just passes this event up to its parent..
  32562. if (parentComponent_ != 0)
  32563. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32564. wheelIncrementX, wheelIncrementY);
  32565. }
  32566. void Component::resized()
  32567. {
  32568. // base class does nothing
  32569. }
  32570. void Component::moved()
  32571. {
  32572. // base class does nothing
  32573. }
  32574. void Component::childBoundsChanged (Component*)
  32575. {
  32576. // base class does nothing
  32577. }
  32578. void Component::parentSizeChanged()
  32579. {
  32580. // base class does nothing
  32581. }
  32582. void Component::addComponentListener (ComponentListener* const newListener)
  32583. {
  32584. jassert (isValidComponent());
  32585. componentListeners.add (newListener);
  32586. }
  32587. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32588. {
  32589. jassert (isValidComponent());
  32590. componentListeners.remove (listenerToRemove);
  32591. }
  32592. void Component::inputAttemptWhenModal()
  32593. {
  32594. bringModalComponentToFront();
  32595. getLookAndFeel().playAlertSound();
  32596. }
  32597. bool Component::canModalEventBeSentToComponent (const Component*)
  32598. {
  32599. return false;
  32600. }
  32601. void Component::internalModalInputAttempt()
  32602. {
  32603. Component* const current = getCurrentlyModalComponent();
  32604. if (current != 0)
  32605. current->inputAttemptWhenModal();
  32606. }
  32607. void Component::paint (Graphics&)
  32608. {
  32609. // all painting is done in the subclasses
  32610. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32611. }
  32612. void Component::paintOverChildren (Graphics&)
  32613. {
  32614. // all painting is done in the subclasses
  32615. }
  32616. void Component::handleMessage (const Message& message)
  32617. {
  32618. if (message.intParameter1 == exitModalStateMessage)
  32619. {
  32620. exitModalState (message.intParameter2);
  32621. }
  32622. else if (message.intParameter1 == customCommandMessage)
  32623. {
  32624. handleCommandMessage (message.intParameter2);
  32625. }
  32626. }
  32627. void Component::postCommandMessage (const int commandId)
  32628. {
  32629. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32630. }
  32631. void Component::handleCommandMessage (int)
  32632. {
  32633. // used by subclasses
  32634. }
  32635. void Component::addMouseListener (MouseListener* const newListener,
  32636. const bool wantsEventsForAllNestedChildComponents)
  32637. {
  32638. // if component methods are being called from threads other than the message
  32639. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32640. checkMessageManagerIsLocked
  32641. if (mouseListeners_ == 0)
  32642. mouseListeners_ = new Array<MouseListener*>();
  32643. if (! mouseListeners_->contains (newListener))
  32644. {
  32645. if (wantsEventsForAllNestedChildComponents)
  32646. {
  32647. mouseListeners_->insert (0, newListener);
  32648. ++numDeepMouseListeners;
  32649. }
  32650. else
  32651. {
  32652. mouseListeners_->add (newListener);
  32653. }
  32654. }
  32655. }
  32656. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32657. {
  32658. // if component methods are being called from threads other than the message
  32659. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32660. checkMessageManagerIsLocked
  32661. if (mouseListeners_ != 0)
  32662. {
  32663. const int index = mouseListeners_->indexOf (listenerToRemove);
  32664. if (index >= 0)
  32665. {
  32666. if (index < numDeepMouseListeners)
  32667. --numDeepMouseListeners;
  32668. mouseListeners_->remove (index);
  32669. }
  32670. }
  32671. }
  32672. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32673. {
  32674. if (isCurrentlyBlockedByAnotherModalComponent())
  32675. {
  32676. // if something else is modal, always just show a normal mouse cursor
  32677. source.showMouseCursor (MouseCursor::NormalCursor);
  32678. return;
  32679. }
  32680. if (! flags.mouseInsideFlag)
  32681. {
  32682. flags.mouseInsideFlag = true;
  32683. flags.mouseOverFlag = true;
  32684. flags.draggingFlag = false;
  32685. BailOutChecker checker (this);
  32686. if (flags.repaintOnMouseActivityFlag)
  32687. repaint();
  32688. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32689. this, time, relativePos,
  32690. time, 0, false);
  32691. mouseEnter (me);
  32692. if (checker.shouldBailOut())
  32693. return;
  32694. Desktop::getInstance().resetTimer();
  32695. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32696. if (checker.shouldBailOut())
  32697. return;
  32698. if (mouseListeners_ != 0)
  32699. {
  32700. for (int i = mouseListeners_->size(); --i >= 0;)
  32701. {
  32702. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32703. if (checker.shouldBailOut())
  32704. return;
  32705. i = jmin (i, mouseListeners_->size());
  32706. }
  32707. }
  32708. Component* p = parentComponent_;
  32709. while (p != 0)
  32710. {
  32711. if (p->numDeepMouseListeners > 0)
  32712. {
  32713. BailOutChecker checker2 (this, p);
  32714. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32715. {
  32716. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32717. if (checker2.shouldBailOut())
  32718. return;
  32719. i = jmin (i, p->numDeepMouseListeners);
  32720. }
  32721. }
  32722. p = p->parentComponent_;
  32723. }
  32724. }
  32725. }
  32726. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32727. {
  32728. BailOutChecker checker (this);
  32729. if (flags.draggingFlag)
  32730. {
  32731. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32732. if (checker.shouldBailOut())
  32733. return;
  32734. }
  32735. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32736. {
  32737. flags.mouseInsideFlag = false;
  32738. flags.mouseOverFlag = false;
  32739. flags.draggingFlag = false;
  32740. if (flags.repaintOnMouseActivityFlag)
  32741. repaint();
  32742. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32743. this, time, relativePos,
  32744. time, 0, false);
  32745. mouseExit (me);
  32746. if (checker.shouldBailOut())
  32747. return;
  32748. Desktop::getInstance().resetTimer();
  32749. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32750. if (checker.shouldBailOut())
  32751. return;
  32752. if (mouseListeners_ != 0)
  32753. {
  32754. for (int i = mouseListeners_->size(); --i >= 0;)
  32755. {
  32756. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32757. if (checker.shouldBailOut())
  32758. return;
  32759. i = jmin (i, mouseListeners_->size());
  32760. }
  32761. }
  32762. Component* p = parentComponent_;
  32763. while (p != 0)
  32764. {
  32765. if (p->numDeepMouseListeners > 0)
  32766. {
  32767. BailOutChecker checker2 (this, p);
  32768. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32769. {
  32770. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32771. if (checker2.shouldBailOut())
  32772. return;
  32773. i = jmin (i, p->numDeepMouseListeners);
  32774. }
  32775. }
  32776. p = p->parentComponent_;
  32777. }
  32778. }
  32779. }
  32780. class InternalDragRepeater : public Timer
  32781. {
  32782. public:
  32783. InternalDragRepeater()
  32784. {}
  32785. ~InternalDragRepeater()
  32786. {
  32787. clearSingletonInstance();
  32788. }
  32789. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32790. void timerCallback()
  32791. {
  32792. Desktop& desktop = Desktop::getInstance();
  32793. int numMiceDown = 0;
  32794. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32795. {
  32796. MouseInputSource* const source = desktop.getMouseSource(i);
  32797. if (source->isDragging())
  32798. {
  32799. source->triggerFakeMove();
  32800. ++numMiceDown;
  32801. }
  32802. }
  32803. if (numMiceDown == 0)
  32804. deleteInstance();
  32805. }
  32806. juce_UseDebuggingNewOperator
  32807. private:
  32808. InternalDragRepeater (const InternalDragRepeater&);
  32809. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32810. };
  32811. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32812. void Component::beginDragAutoRepeat (const int interval)
  32813. {
  32814. if (interval > 0)
  32815. {
  32816. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32817. InternalDragRepeater::getInstance()->startTimer (interval);
  32818. }
  32819. else
  32820. {
  32821. InternalDragRepeater::deleteInstance();
  32822. }
  32823. }
  32824. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32825. {
  32826. Desktop& desktop = Desktop::getInstance();
  32827. BailOutChecker checker (this);
  32828. if (isCurrentlyBlockedByAnotherModalComponent())
  32829. {
  32830. internalModalInputAttempt();
  32831. if (checker.shouldBailOut())
  32832. return;
  32833. // If processing the input attempt has exited the modal loop, we'll allow the event
  32834. // to be delivered..
  32835. if (isCurrentlyBlockedByAnotherModalComponent())
  32836. {
  32837. // allow blocked mouse-events to go to global listeners..
  32838. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32839. this, time, relativePos, time,
  32840. source.getNumberOfMultipleClicks(), false);
  32841. desktop.resetTimer();
  32842. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32843. return;
  32844. }
  32845. }
  32846. {
  32847. Component* c = this;
  32848. while (c != 0)
  32849. {
  32850. if (c->isBroughtToFrontOnMouseClick())
  32851. {
  32852. c->toFront (true);
  32853. if (checker.shouldBailOut())
  32854. return;
  32855. }
  32856. c = c->parentComponent_;
  32857. }
  32858. }
  32859. if (! flags.dontFocusOnMouseClickFlag)
  32860. {
  32861. grabFocusInternal (focusChangedByMouseClick);
  32862. if (checker.shouldBailOut())
  32863. return;
  32864. }
  32865. flags.draggingFlag = true;
  32866. flags.mouseOverFlag = true;
  32867. if (flags.repaintOnMouseActivityFlag)
  32868. repaint();
  32869. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32870. this, time, relativePos, time,
  32871. source.getNumberOfMultipleClicks(), false);
  32872. mouseDown (me);
  32873. if (checker.shouldBailOut())
  32874. return;
  32875. desktop.resetTimer();
  32876. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32877. if (checker.shouldBailOut())
  32878. return;
  32879. if (mouseListeners_ != 0)
  32880. {
  32881. for (int i = mouseListeners_->size(); --i >= 0;)
  32882. {
  32883. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32884. if (checker.shouldBailOut())
  32885. return;
  32886. i = jmin (i, mouseListeners_->size());
  32887. }
  32888. }
  32889. Component* p = parentComponent_;
  32890. while (p != 0)
  32891. {
  32892. if (p->numDeepMouseListeners > 0)
  32893. {
  32894. BailOutChecker checker2 (this, p);
  32895. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32896. {
  32897. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32898. if (checker2.shouldBailOut())
  32899. return;
  32900. i = jmin (i, p->numDeepMouseListeners);
  32901. }
  32902. }
  32903. p = p->parentComponent_;
  32904. }
  32905. }
  32906. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32907. {
  32908. if (flags.draggingFlag)
  32909. {
  32910. Desktop& desktop = Desktop::getInstance();
  32911. flags.draggingFlag = false;
  32912. BailOutChecker checker (this);
  32913. if (flags.repaintOnMouseActivityFlag)
  32914. repaint();
  32915. const MouseEvent me (source, relativePos,
  32916. oldModifiers, this, time,
  32917. globalPositionToRelative (source.getLastMouseDownPosition()),
  32918. source.getLastMouseDownTime(),
  32919. source.getNumberOfMultipleClicks(),
  32920. source.hasMouseMovedSignificantlySincePressed());
  32921. mouseUp (me);
  32922. if (checker.shouldBailOut())
  32923. return;
  32924. desktop.resetTimer();
  32925. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32926. if (checker.shouldBailOut())
  32927. return;
  32928. if (mouseListeners_ != 0)
  32929. {
  32930. for (int i = mouseListeners_->size(); --i >= 0;)
  32931. {
  32932. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32933. if (checker.shouldBailOut())
  32934. return;
  32935. i = jmin (i, mouseListeners_->size());
  32936. }
  32937. }
  32938. {
  32939. Component* p = parentComponent_;
  32940. while (p != 0)
  32941. {
  32942. if (p->numDeepMouseListeners > 0)
  32943. {
  32944. BailOutChecker checker2 (this, p);
  32945. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32946. {
  32947. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32948. if (checker2.shouldBailOut())
  32949. return;
  32950. i = jmin (i, p->numDeepMouseListeners);
  32951. }
  32952. }
  32953. p = p->parentComponent_;
  32954. }
  32955. }
  32956. // check for double-click
  32957. if (me.getNumberOfClicks() >= 2)
  32958. {
  32959. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32960. mouseDoubleClick (me);
  32961. if (checker.shouldBailOut())
  32962. return;
  32963. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32964. if (checker.shouldBailOut())
  32965. return;
  32966. for (int i = numListeners; --i >= 0;)
  32967. {
  32968. if (checker.shouldBailOut())
  32969. return;
  32970. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32971. if (ml != 0)
  32972. ml->mouseDoubleClick (me);
  32973. }
  32974. if (checker.shouldBailOut())
  32975. return;
  32976. Component* p = parentComponent_;
  32977. while (p != 0)
  32978. {
  32979. if (p->numDeepMouseListeners > 0)
  32980. {
  32981. BailOutChecker checker2 (this, p);
  32982. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32983. {
  32984. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  32985. if (checker2.shouldBailOut())
  32986. return;
  32987. i = jmin (i, p->numDeepMouseListeners);
  32988. }
  32989. }
  32990. p = p->parentComponent_;
  32991. }
  32992. }
  32993. }
  32994. }
  32995. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32996. {
  32997. if (flags.draggingFlag)
  32998. {
  32999. Desktop& desktop = Desktop::getInstance();
  33000. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33001. BailOutChecker checker (this);
  33002. const MouseEvent me (source, relativePos,
  33003. source.getCurrentModifiers(), this, time,
  33004. globalPositionToRelative (source.getLastMouseDownPosition()),
  33005. source.getLastMouseDownTime(),
  33006. source.getNumberOfMultipleClicks(),
  33007. source.hasMouseMovedSignificantlySincePressed());
  33008. mouseDrag (me);
  33009. if (checker.shouldBailOut())
  33010. return;
  33011. desktop.resetTimer();
  33012. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33013. if (checker.shouldBailOut())
  33014. return;
  33015. if (mouseListeners_ != 0)
  33016. {
  33017. for (int i = mouseListeners_->size(); --i >= 0;)
  33018. {
  33019. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33020. if (checker.shouldBailOut())
  33021. return;
  33022. i = jmin (i, mouseListeners_->size());
  33023. }
  33024. }
  33025. Component* p = parentComponent_;
  33026. while (p != 0)
  33027. {
  33028. if (p->numDeepMouseListeners > 0)
  33029. {
  33030. BailOutChecker checker2 (this, p);
  33031. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33032. {
  33033. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33034. if (checker2.shouldBailOut())
  33035. return;
  33036. i = jmin (i, p->numDeepMouseListeners);
  33037. }
  33038. }
  33039. p = p->parentComponent_;
  33040. }
  33041. }
  33042. }
  33043. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33044. {
  33045. Desktop& desktop = Desktop::getInstance();
  33046. BailOutChecker checker (this);
  33047. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33048. this, time, relativePos,
  33049. time, 0, false);
  33050. if (isCurrentlyBlockedByAnotherModalComponent())
  33051. {
  33052. // allow blocked mouse-events to go to global listeners..
  33053. desktop.sendMouseMove();
  33054. }
  33055. else
  33056. {
  33057. flags.mouseOverFlag = true;
  33058. mouseMove (me);
  33059. if (checker.shouldBailOut())
  33060. return;
  33061. desktop.resetTimer();
  33062. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33063. if (checker.shouldBailOut())
  33064. return;
  33065. if (mouseListeners_ != 0)
  33066. {
  33067. for (int i = mouseListeners_->size(); --i >= 0;)
  33068. {
  33069. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33070. if (checker.shouldBailOut())
  33071. return;
  33072. i = jmin (i, mouseListeners_->size());
  33073. }
  33074. }
  33075. Component* p = parentComponent_;
  33076. while (p != 0)
  33077. {
  33078. if (p->numDeepMouseListeners > 0)
  33079. {
  33080. BailOutChecker checker2 (this, p);
  33081. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33082. {
  33083. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33084. if (checker2.shouldBailOut())
  33085. return;
  33086. i = jmin (i, p->numDeepMouseListeners);
  33087. }
  33088. }
  33089. p = p->parentComponent_;
  33090. }
  33091. }
  33092. }
  33093. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33094. const Time& time, const float amountX, const float amountY)
  33095. {
  33096. Desktop& desktop = Desktop::getInstance();
  33097. BailOutChecker checker (this);
  33098. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33099. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33100. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33101. this, time, relativePos, time, 0, false);
  33102. if (isCurrentlyBlockedByAnotherModalComponent())
  33103. {
  33104. // allow blocked mouse-events to go to global listeners..
  33105. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33106. }
  33107. else
  33108. {
  33109. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33110. if (checker.shouldBailOut())
  33111. return;
  33112. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33113. if (checker.shouldBailOut())
  33114. return;
  33115. if (mouseListeners_ != 0)
  33116. {
  33117. for (int i = mouseListeners_->size(); --i >= 0;)
  33118. {
  33119. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33120. if (checker.shouldBailOut())
  33121. return;
  33122. i = jmin (i, mouseListeners_->size());
  33123. }
  33124. }
  33125. Component* p = parentComponent_;
  33126. while (p != 0)
  33127. {
  33128. if (p->numDeepMouseListeners > 0)
  33129. {
  33130. BailOutChecker checker2 (this, p);
  33131. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33132. {
  33133. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33134. if (checker2.shouldBailOut())
  33135. return;
  33136. i = jmin (i, p->numDeepMouseListeners);
  33137. }
  33138. }
  33139. p = p->parentComponent_;
  33140. }
  33141. }
  33142. }
  33143. void Component::sendFakeMouseMove() const
  33144. {
  33145. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33146. }
  33147. void Component::broughtToFront()
  33148. {
  33149. }
  33150. void Component::internalBroughtToFront()
  33151. {
  33152. if (! isValidComponent())
  33153. return;
  33154. if (flags.hasHeavyweightPeerFlag)
  33155. Desktop::getInstance().componentBroughtToFront (this);
  33156. BailOutChecker checker (this);
  33157. broughtToFront();
  33158. if (checker.shouldBailOut())
  33159. return;
  33160. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33161. if (checker.shouldBailOut())
  33162. return;
  33163. // When brought to the front and there's a modal component blocking this one,
  33164. // we need to bring the modal one to the front instead..
  33165. Component* const cm = getCurrentlyModalComponent();
  33166. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33167. bringModalComponentToFront();
  33168. }
  33169. void Component::focusGained (FocusChangeType)
  33170. {
  33171. // base class does nothing
  33172. }
  33173. void Component::internalFocusGain (const FocusChangeType cause)
  33174. {
  33175. SafePointer<Component> safePointer (this);
  33176. focusGained (cause);
  33177. if (safePointer != 0)
  33178. internalChildFocusChange (cause);
  33179. }
  33180. void Component::focusLost (FocusChangeType)
  33181. {
  33182. // base class does nothing
  33183. }
  33184. void Component::internalFocusLoss (const FocusChangeType cause)
  33185. {
  33186. SafePointer<Component> safePointer (this);
  33187. focusLost (focusChangedDirectly);
  33188. if (safePointer != 0)
  33189. internalChildFocusChange (cause);
  33190. }
  33191. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33192. {
  33193. // base class does nothing
  33194. }
  33195. void Component::internalChildFocusChange (FocusChangeType cause)
  33196. {
  33197. const bool childIsNowFocused = hasKeyboardFocus (true);
  33198. if (flags.childCompFocusedFlag != childIsNowFocused)
  33199. {
  33200. flags.childCompFocusedFlag = childIsNowFocused;
  33201. SafePointer<Component> safePointer (this);
  33202. focusOfChildComponentChanged (cause);
  33203. if (safePointer == 0)
  33204. return;
  33205. }
  33206. if (parentComponent_ != 0)
  33207. parentComponent_->internalChildFocusChange (cause);
  33208. }
  33209. bool Component::isEnabled() const throw()
  33210. {
  33211. return (! flags.isDisabledFlag)
  33212. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33213. }
  33214. void Component::setEnabled (const bool shouldBeEnabled)
  33215. {
  33216. if (flags.isDisabledFlag == shouldBeEnabled)
  33217. {
  33218. flags.isDisabledFlag = ! shouldBeEnabled;
  33219. // if any parent components are disabled, setting our flag won't make a difference,
  33220. // so no need to send a change message
  33221. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33222. sendEnablementChangeMessage();
  33223. }
  33224. }
  33225. void Component::sendEnablementChangeMessage()
  33226. {
  33227. SafePointer<Component> safePointer (this);
  33228. enablementChanged();
  33229. if (safePointer == 0)
  33230. return;
  33231. for (int i = getNumChildComponents(); --i >= 0;)
  33232. {
  33233. Component* const c = getChildComponent (i);
  33234. if (c != 0)
  33235. {
  33236. c->sendEnablementChangeMessage();
  33237. if (safePointer == 0)
  33238. return;
  33239. }
  33240. }
  33241. }
  33242. void Component::enablementChanged()
  33243. {
  33244. }
  33245. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33246. {
  33247. flags.wantsFocusFlag = wantsFocus;
  33248. }
  33249. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33250. {
  33251. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33252. }
  33253. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33254. {
  33255. return ! flags.dontFocusOnMouseClickFlag;
  33256. }
  33257. bool Component::getWantsKeyboardFocus() const throw()
  33258. {
  33259. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33260. }
  33261. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33262. {
  33263. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33264. }
  33265. bool Component::isFocusContainer() const throw()
  33266. {
  33267. return flags.isFocusContainerFlag;
  33268. }
  33269. int Component::getExplicitFocusOrder() const
  33270. {
  33271. return properties ["_jexfo"];
  33272. }
  33273. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33274. {
  33275. properties.set ("_jexfo", newFocusOrderIndex);
  33276. }
  33277. KeyboardFocusTraverser* Component::createFocusTraverser()
  33278. {
  33279. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33280. return new KeyboardFocusTraverser();
  33281. return parentComponent_->createFocusTraverser();
  33282. }
  33283. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33284. {
  33285. // give the focus to this component
  33286. if (currentlyFocusedComponent != this)
  33287. {
  33288. JUCE_TRY
  33289. {
  33290. // get the focus onto our desktop window
  33291. ComponentPeer* const peer = getPeer();
  33292. if (peer != 0)
  33293. {
  33294. SafePointer<Component> safePointer (this);
  33295. peer->grabFocus();
  33296. if (peer->isFocused() && currentlyFocusedComponent != this)
  33297. {
  33298. Component* const componentLosingFocus = currentlyFocusedComponent;
  33299. currentlyFocusedComponent = this;
  33300. Desktop::getInstance().triggerFocusCallback();
  33301. // call this after setting currentlyFocusedComponent so that the one that's
  33302. // losing it has a chance to see where focus is going
  33303. if (componentLosingFocus->isValidComponent())
  33304. componentLosingFocus->internalFocusLoss (cause);
  33305. if (currentlyFocusedComponent == this)
  33306. {
  33307. focusGained (cause);
  33308. if (safePointer != 0)
  33309. internalChildFocusChange (cause);
  33310. }
  33311. }
  33312. }
  33313. }
  33314. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33315. catch (const std::exception& e)
  33316. {
  33317. currentlyFocusedComponent = 0;
  33318. Desktop::getInstance().triggerFocusCallback();
  33319. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33320. }
  33321. catch (...)
  33322. {
  33323. currentlyFocusedComponent = 0;
  33324. Desktop::getInstance().triggerFocusCallback();
  33325. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33326. }
  33327. #endif
  33328. }
  33329. }
  33330. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33331. {
  33332. if (isShowing())
  33333. {
  33334. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33335. {
  33336. takeKeyboardFocus (cause);
  33337. }
  33338. else
  33339. {
  33340. if (isParentOf (currentlyFocusedComponent)
  33341. && currentlyFocusedComponent->isShowing())
  33342. {
  33343. // do nothing if the focused component is actually a child of ours..
  33344. }
  33345. else
  33346. {
  33347. // find the default child component..
  33348. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33349. if (traverser != 0)
  33350. {
  33351. Component* const defaultComp = traverser->getDefaultComponent (this);
  33352. traverser = 0;
  33353. if (defaultComp != 0)
  33354. {
  33355. defaultComp->grabFocusInternal (cause, false);
  33356. return;
  33357. }
  33358. }
  33359. if (canTryParent && parentComponent_ != 0)
  33360. {
  33361. // if no children want it and we're allowed to try our parent comp,
  33362. // then pass up to parent, which will try our siblings.
  33363. parentComponent_->grabFocusInternal (cause, true);
  33364. }
  33365. }
  33366. }
  33367. }
  33368. }
  33369. void Component::grabKeyboardFocus()
  33370. {
  33371. // if component methods are being called from threads other than the message
  33372. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33373. checkMessageManagerIsLocked
  33374. grabFocusInternal (focusChangedDirectly);
  33375. }
  33376. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33377. {
  33378. // if component methods are being called from threads other than the message
  33379. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33380. checkMessageManagerIsLocked
  33381. if (parentComponent_ != 0)
  33382. {
  33383. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33384. if (traverser != 0)
  33385. {
  33386. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33387. : traverser->getPreviousComponent (this);
  33388. traverser = 0;
  33389. if (nextComp != 0)
  33390. {
  33391. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33392. {
  33393. SafePointer<Component> nextCompPointer (nextComp);
  33394. internalModalInputAttempt();
  33395. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33396. return;
  33397. }
  33398. nextComp->grabFocusInternal (focusChangedByTabKey);
  33399. return;
  33400. }
  33401. }
  33402. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33403. }
  33404. }
  33405. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33406. {
  33407. return (currentlyFocusedComponent == this)
  33408. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33409. }
  33410. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33411. {
  33412. return currentlyFocusedComponent;
  33413. }
  33414. void Component::giveAwayFocus()
  33415. {
  33416. // use a copy so we can clear the value before the call
  33417. Component* const componentLosingFocus = currentlyFocusedComponent;
  33418. currentlyFocusedComponent = 0;
  33419. Desktop::getInstance().triggerFocusCallback();
  33420. if (componentLosingFocus->isValidComponent())
  33421. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33422. }
  33423. bool Component::isMouseOver() const throw()
  33424. {
  33425. return flags.mouseOverFlag;
  33426. }
  33427. bool Component::isMouseButtonDown() const throw()
  33428. {
  33429. return flags.draggingFlag;
  33430. }
  33431. bool Component::isMouseOverOrDragging() const throw()
  33432. {
  33433. return flags.mouseOverFlag || flags.draggingFlag;
  33434. }
  33435. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33436. {
  33437. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33438. }
  33439. const Point<int> Component::getMouseXYRelative() const
  33440. {
  33441. return globalPositionToRelative (Desktop::getMousePosition());
  33442. }
  33443. const Rectangle<int> Component::getParentMonitorArea() const
  33444. {
  33445. return Desktop::getInstance()
  33446. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33447. getHeight() / 2)));
  33448. }
  33449. void Component::addKeyListener (KeyListener* const newListener)
  33450. {
  33451. if (keyListeners_ == 0)
  33452. keyListeners_ = new VoidArray();
  33453. keyListeners_->addIfNotAlreadyThere (newListener);
  33454. }
  33455. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33456. {
  33457. if (keyListeners_ != 0)
  33458. keyListeners_->removeValue (listenerToRemove);
  33459. }
  33460. bool Component::keyPressed (const KeyPress&)
  33461. {
  33462. return false;
  33463. }
  33464. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33465. {
  33466. return false;
  33467. }
  33468. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33469. {
  33470. if (parentComponent_ != 0)
  33471. parentComponent_->modifierKeysChanged (modifiers);
  33472. }
  33473. void Component::internalModifierKeysChanged()
  33474. {
  33475. sendFakeMouseMove();
  33476. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33477. }
  33478. ComponentPeer* Component::getPeer() const
  33479. {
  33480. if (flags.hasHeavyweightPeerFlag)
  33481. return ComponentPeer::getPeerFor (this);
  33482. else if (parentComponent_ != 0)
  33483. return parentComponent_->getPeer();
  33484. else
  33485. return 0;
  33486. }
  33487. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33488. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33489. {
  33490. jassert (component1 != 0);
  33491. }
  33492. bool Component::BailOutChecker::shouldBailOut() const throw()
  33493. {
  33494. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33495. }
  33496. END_JUCE_NAMESPACE
  33497. /*** End of inlined file: juce_Component.cpp ***/
  33498. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33499. BEGIN_JUCE_NAMESPACE
  33500. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33501. void ComponentListener::componentBroughtToFront (Component&) {}
  33502. void ComponentListener::componentVisibilityChanged (Component&) {}
  33503. void ComponentListener::componentChildrenChanged (Component&) {}
  33504. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33505. void ComponentListener::componentNameChanged (Component&) {}
  33506. void ComponentListener::componentBeingDeleted (Component&) {}
  33507. END_JUCE_NAMESPACE
  33508. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33509. /*** Start of inlined file: juce_Desktop.cpp ***/
  33510. BEGIN_JUCE_NAMESPACE
  33511. Desktop::Desktop()
  33512. : mouseClickCounter (0),
  33513. kioskModeComponent (0)
  33514. {
  33515. createMouseInputSources();
  33516. refreshMonitorSizes();
  33517. }
  33518. Desktop::~Desktop()
  33519. {
  33520. jassert (instance == this);
  33521. instance = 0;
  33522. // doh! If you don't delete all your windows before exiting, you're going to
  33523. // be leaking memory!
  33524. jassert (desktopComponents.size() == 0);
  33525. }
  33526. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33527. {
  33528. if (instance == 0)
  33529. instance = new Desktop();
  33530. return *instance;
  33531. }
  33532. Desktop* Desktop::instance = 0;
  33533. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33534. const bool clipToWorkArea);
  33535. void Desktop::refreshMonitorSizes()
  33536. {
  33537. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33538. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33539. monitorCoordsClipped.clear();
  33540. monitorCoordsUnclipped.clear();
  33541. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33542. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33543. jassert (monitorCoordsClipped.size() > 0
  33544. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33545. if (oldClipped != monitorCoordsClipped
  33546. || oldUnclipped != monitorCoordsUnclipped)
  33547. {
  33548. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33549. {
  33550. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33551. if (p != 0)
  33552. p->handleScreenSizeChange();
  33553. }
  33554. }
  33555. }
  33556. int Desktop::getNumDisplayMonitors() const throw()
  33557. {
  33558. return monitorCoordsClipped.size();
  33559. }
  33560. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33561. {
  33562. return clippedToWorkArea ? monitorCoordsClipped [index]
  33563. : monitorCoordsUnclipped [index];
  33564. }
  33565. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33566. {
  33567. RectangleList rl;
  33568. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33569. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33570. return rl;
  33571. }
  33572. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33573. {
  33574. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33575. }
  33576. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33577. {
  33578. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33579. double bestDistance = 1.0e10;
  33580. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33581. {
  33582. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33583. if (rect.contains (position))
  33584. return rect;
  33585. const double distance = rect.getCentre().getDistanceFrom (position);
  33586. if (distance < bestDistance)
  33587. {
  33588. bestDistance = distance;
  33589. best = rect;
  33590. }
  33591. }
  33592. return best;
  33593. }
  33594. int Desktop::getNumComponents() const throw()
  33595. {
  33596. return desktopComponents.size();
  33597. }
  33598. Component* Desktop::getComponent (const int index) const throw()
  33599. {
  33600. return desktopComponents [index];
  33601. }
  33602. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33603. {
  33604. for (int i = desktopComponents.size(); --i >= 0;)
  33605. {
  33606. Component* const c = desktopComponents.getUnchecked(i);
  33607. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33608. if (c->contains (relative.getX(), relative.getY()))
  33609. return c->getComponentAt (relative.getX(), relative.getY());
  33610. }
  33611. return 0;
  33612. }
  33613. void Desktop::addDesktopComponent (Component* const c)
  33614. {
  33615. jassert (c != 0);
  33616. jassert (! desktopComponents.contains (c));
  33617. desktopComponents.addIfNotAlreadyThere (c);
  33618. }
  33619. void Desktop::removeDesktopComponent (Component* const c)
  33620. {
  33621. desktopComponents.removeValue (c);
  33622. }
  33623. void Desktop::componentBroughtToFront (Component* const c)
  33624. {
  33625. const int index = desktopComponents.indexOf (c);
  33626. jassert (index >= 0);
  33627. if (index >= 0)
  33628. {
  33629. int newIndex = -1;
  33630. if (! c->isAlwaysOnTop())
  33631. {
  33632. newIndex = desktopComponents.size();
  33633. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33634. --newIndex;
  33635. --newIndex;
  33636. }
  33637. desktopComponents.move (index, newIndex);
  33638. }
  33639. }
  33640. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33641. {
  33642. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33643. }
  33644. int Desktop::getMouseButtonClickCounter() throw()
  33645. {
  33646. return getInstance().mouseClickCounter;
  33647. }
  33648. void Desktop::incrementMouseClickCounter() throw()
  33649. {
  33650. ++mouseClickCounter;
  33651. }
  33652. int Desktop::getNumDraggingMouseSources() const throw()
  33653. {
  33654. int num = 0;
  33655. for (int i = mouseSources.size(); --i >= 0;)
  33656. if (mouseSources.getUnchecked(i)->isDragging())
  33657. ++num;
  33658. return num;
  33659. }
  33660. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33661. {
  33662. int num = 0;
  33663. for (int i = mouseSources.size(); --i >= 0;)
  33664. {
  33665. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33666. if (mi->isDragging())
  33667. {
  33668. if (index == num)
  33669. return mi;
  33670. ++num;
  33671. }
  33672. }
  33673. return 0;
  33674. }
  33675. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33676. {
  33677. focusListeners.add (listener);
  33678. }
  33679. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33680. {
  33681. focusListeners.remove (listener);
  33682. }
  33683. void Desktop::triggerFocusCallback()
  33684. {
  33685. triggerAsyncUpdate();
  33686. }
  33687. void Desktop::handleAsyncUpdate()
  33688. {
  33689. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33690. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33691. }
  33692. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33693. {
  33694. mouseListeners.add (listener);
  33695. resetTimer();
  33696. }
  33697. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33698. {
  33699. mouseListeners.remove (listener);
  33700. resetTimer();
  33701. }
  33702. void Desktop::timerCallback()
  33703. {
  33704. if (lastFakeMouseMove != getMousePosition())
  33705. sendMouseMove();
  33706. }
  33707. void Desktop::sendMouseMove()
  33708. {
  33709. if (! mouseListeners.isEmpty())
  33710. {
  33711. startTimer (20);
  33712. lastFakeMouseMove = getMousePosition();
  33713. Component* const target = findComponentAt (lastFakeMouseMove);
  33714. if (target != 0)
  33715. {
  33716. Component::BailOutChecker checker (target);
  33717. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33718. const Time now (Time::getCurrentTime());
  33719. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33720. target, now, pos, now, 0, false);
  33721. if (me.mods.isAnyMouseButtonDown())
  33722. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33723. else
  33724. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33725. }
  33726. }
  33727. }
  33728. void Desktop::resetTimer()
  33729. {
  33730. if (mouseListeners.size() == 0)
  33731. stopTimer();
  33732. else
  33733. startTimer (100);
  33734. lastFakeMouseMove = getMousePosition();
  33735. }
  33736. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33737. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33738. {
  33739. if (kioskModeComponent != componentToUse)
  33740. {
  33741. // agh! Don't delete a component without first stopping it being the kiosk comp
  33742. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33743. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33744. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33745. if (kioskModeComponent->isValidComponent())
  33746. {
  33747. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33748. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33749. }
  33750. kioskModeComponent = componentToUse;
  33751. if (kioskModeComponent != 0)
  33752. {
  33753. jassert (kioskModeComponent->isValidComponent());
  33754. // Only components that are already on the desktop can be put into kiosk mode!
  33755. jassert (kioskModeComponent->isOnDesktop());
  33756. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33757. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33758. }
  33759. }
  33760. }
  33761. END_JUCE_NAMESPACE
  33762. /*** End of inlined file: juce_Desktop.cpp ***/
  33763. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33764. BEGIN_JUCE_NAMESPACE
  33765. ArrowButton::ArrowButton (const String& name,
  33766. float arrowDirectionInRadians,
  33767. const Colour& arrowColour)
  33768. : Button (name),
  33769. colour (arrowColour)
  33770. {
  33771. path.lineTo (0.0f, 1.0f);
  33772. path.lineTo (1.0f, 0.5f);
  33773. path.closeSubPath();
  33774. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33775. 0.5f, 0.5f));
  33776. setComponentEffect (&shadow);
  33777. buttonStateChanged();
  33778. }
  33779. ArrowButton::~ArrowButton()
  33780. {
  33781. }
  33782. void ArrowButton::paintButton (Graphics& g,
  33783. bool /*isMouseOverButton*/,
  33784. bool /*isButtonDown*/)
  33785. {
  33786. g.setColour (colour);
  33787. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33788. (float) offset,
  33789. (float) (getWidth() - 3),
  33790. (float) (getHeight() - 3),
  33791. false));
  33792. }
  33793. void ArrowButton::buttonStateChanged()
  33794. {
  33795. offset = (isDown()) ? 1 : 0;
  33796. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33797. 0.3f, -1, 0);
  33798. }
  33799. END_JUCE_NAMESPACE
  33800. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33801. /*** Start of inlined file: juce_Button.cpp ***/
  33802. BEGIN_JUCE_NAMESPACE
  33803. class Button::RepeatTimer : public Timer
  33804. {
  33805. public:
  33806. RepeatTimer (Button& owner_) : owner (owner_) {}
  33807. void timerCallback() { owner.repeatTimerCallback(); }
  33808. juce_UseDebuggingNewOperator
  33809. private:
  33810. Button& owner;
  33811. RepeatTimer (const RepeatTimer&);
  33812. RepeatTimer& operator= (const RepeatTimer&);
  33813. };
  33814. Button::Button (const String& name)
  33815. : Component (name),
  33816. text (name),
  33817. buttonPressTime (0),
  33818. lastTimeCallbackTime (0),
  33819. commandManagerToUse (0),
  33820. autoRepeatDelay (-1),
  33821. autoRepeatSpeed (0),
  33822. autoRepeatMinimumDelay (-1),
  33823. radioGroupId (0),
  33824. commandID (0),
  33825. connectedEdgeFlags (0),
  33826. buttonState (buttonNormal),
  33827. lastToggleState (false),
  33828. clickTogglesState (false),
  33829. needsToRelease (false),
  33830. needsRepainting (false),
  33831. isKeyDown (false),
  33832. triggerOnMouseDown (false),
  33833. generateTooltip (false)
  33834. {
  33835. setWantsKeyboardFocus (true);
  33836. isOn.addListener (this);
  33837. }
  33838. Button::~Button()
  33839. {
  33840. isOn.removeListener (this);
  33841. if (commandManagerToUse != 0)
  33842. commandManagerToUse->removeListener (this);
  33843. repeatTimer = 0;
  33844. clearShortcuts();
  33845. }
  33846. void Button::setButtonText (const String& newText)
  33847. {
  33848. if (text != newText)
  33849. {
  33850. text = newText;
  33851. repaint();
  33852. }
  33853. }
  33854. void Button::setTooltip (const String& newTooltip)
  33855. {
  33856. SettableTooltipClient::setTooltip (newTooltip);
  33857. generateTooltip = false;
  33858. }
  33859. const String Button::getTooltip()
  33860. {
  33861. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33862. {
  33863. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33864. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33865. for (int i = 0; i < keyPresses.size(); ++i)
  33866. {
  33867. const String key (keyPresses.getReference(i).getTextDescription());
  33868. tt << " [";
  33869. if (key.length() == 1)
  33870. tt << TRANS("shortcut") << ": '" << key << "']";
  33871. else
  33872. tt << key << ']';
  33873. }
  33874. return tt;
  33875. }
  33876. return SettableTooltipClient::getTooltip();
  33877. }
  33878. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  33879. {
  33880. if (connectedEdgeFlags != connectedEdgeFlags_)
  33881. {
  33882. connectedEdgeFlags = connectedEdgeFlags_;
  33883. repaint();
  33884. }
  33885. }
  33886. void Button::setToggleState (const bool shouldBeOn,
  33887. const bool sendChangeNotification)
  33888. {
  33889. if (shouldBeOn != lastToggleState)
  33890. {
  33891. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  33892. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  33893. lastToggleState = shouldBeOn;
  33894. repaint();
  33895. if (sendChangeNotification)
  33896. {
  33897. Component::SafePointer<Component> deletionWatcher (this);
  33898. sendClickMessage (ModifierKeys());
  33899. if (deletionWatcher == 0)
  33900. return;
  33901. }
  33902. if (lastToggleState)
  33903. turnOffOtherButtonsInGroup (sendChangeNotification);
  33904. }
  33905. }
  33906. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33907. {
  33908. clickTogglesState = shouldToggle;
  33909. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33910. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33911. // it is that this button represents, and the button will update its state to reflect this
  33912. // in the applicationCommandListChanged() method.
  33913. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33914. }
  33915. bool Button::getClickingTogglesState() const throw()
  33916. {
  33917. return clickTogglesState;
  33918. }
  33919. void Button::valueChanged (Value& value)
  33920. {
  33921. if (value.refersToSameSourceAs (isOn))
  33922. setToggleState (isOn.getValue(), true);
  33923. }
  33924. void Button::setRadioGroupId (const int newGroupId)
  33925. {
  33926. if (radioGroupId != newGroupId)
  33927. {
  33928. radioGroupId = newGroupId;
  33929. if (lastToggleState)
  33930. turnOffOtherButtonsInGroup (true);
  33931. }
  33932. }
  33933. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33934. {
  33935. Component* const p = getParentComponent();
  33936. if (p != 0 && radioGroupId != 0)
  33937. {
  33938. Component::SafePointer<Component> deletionWatcher (this);
  33939. for (int i = p->getNumChildComponents(); --i >= 0;)
  33940. {
  33941. Component* const c = p->getChildComponent (i);
  33942. if (c != this)
  33943. {
  33944. Button* const b = dynamic_cast <Button*> (c);
  33945. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33946. {
  33947. b->setToggleState (false, sendChangeNotification);
  33948. if (deletionWatcher == 0)
  33949. return;
  33950. }
  33951. }
  33952. }
  33953. }
  33954. }
  33955. void Button::enablementChanged()
  33956. {
  33957. updateState (0);
  33958. repaint();
  33959. }
  33960. Button::ButtonState Button::updateState (const MouseEvent* const e)
  33961. {
  33962. ButtonState state = buttonNormal;
  33963. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33964. {
  33965. Point<int> mousePos;
  33966. if (e == 0)
  33967. mousePos = getMouseXYRelative();
  33968. else
  33969. mousePos = e->getEventRelativeTo (this).getPosition();
  33970. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  33971. const bool down = isMouseButtonDown();
  33972. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33973. state = buttonDown;
  33974. else if (over)
  33975. state = buttonOver;
  33976. }
  33977. setState (state);
  33978. return state;
  33979. }
  33980. void Button::setState (const ButtonState newState)
  33981. {
  33982. if (buttonState != newState)
  33983. {
  33984. buttonState = newState;
  33985. repaint();
  33986. if (buttonState == buttonDown)
  33987. {
  33988. buttonPressTime = Time::getApproximateMillisecondCounter();
  33989. lastTimeCallbackTime = buttonPressTime;
  33990. }
  33991. sendStateMessage();
  33992. }
  33993. }
  33994. bool Button::isDown() const throw()
  33995. {
  33996. return buttonState == buttonDown;
  33997. }
  33998. bool Button::isOver() const throw()
  33999. {
  34000. return buttonState != buttonNormal;
  34001. }
  34002. void Button::buttonStateChanged()
  34003. {
  34004. }
  34005. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34006. {
  34007. const uint32 now = Time::getApproximateMillisecondCounter();
  34008. return now > buttonPressTime ? now - buttonPressTime : 0;
  34009. }
  34010. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34011. {
  34012. triggerOnMouseDown = isTriggeredOnMouseDown;
  34013. }
  34014. void Button::clicked()
  34015. {
  34016. }
  34017. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34018. {
  34019. clicked();
  34020. }
  34021. static const int clickMessageId = 0x2f3f4f99;
  34022. void Button::triggerClick()
  34023. {
  34024. postCommandMessage (clickMessageId);
  34025. }
  34026. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34027. {
  34028. if (clickTogglesState)
  34029. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34030. sendClickMessage (modifiers);
  34031. }
  34032. void Button::flashButtonState()
  34033. {
  34034. if (isEnabled())
  34035. {
  34036. needsToRelease = true;
  34037. setState (buttonDown);
  34038. getRepeatTimer().startTimer (100);
  34039. }
  34040. }
  34041. void Button::handleCommandMessage (int commandId)
  34042. {
  34043. if (commandId == clickMessageId)
  34044. {
  34045. if (isEnabled())
  34046. {
  34047. flashButtonState();
  34048. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34049. }
  34050. }
  34051. else
  34052. {
  34053. Component::handleCommandMessage (commandId);
  34054. }
  34055. }
  34056. void Button::addButtonListener (ButtonListener* const newListener)
  34057. {
  34058. buttonListeners.add (newListener);
  34059. }
  34060. void Button::removeButtonListener (ButtonListener* const listener)
  34061. {
  34062. buttonListeners.remove (listener);
  34063. }
  34064. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34065. {
  34066. Component::BailOutChecker checker (this);
  34067. if (commandManagerToUse != 0 && commandID != 0)
  34068. {
  34069. ApplicationCommandTarget::InvocationInfo info (commandID);
  34070. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34071. info.originatingComponent = this;
  34072. commandManagerToUse->invoke (info, true);
  34073. }
  34074. clicked (modifiers);
  34075. if (! checker.shouldBailOut())
  34076. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34077. }
  34078. void Button::sendStateMessage()
  34079. {
  34080. Component::BailOutChecker checker (this);
  34081. buttonStateChanged();
  34082. if (! checker.shouldBailOut())
  34083. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34084. }
  34085. void Button::paint (Graphics& g)
  34086. {
  34087. if (needsToRelease && isEnabled())
  34088. {
  34089. needsToRelease = false;
  34090. needsRepainting = true;
  34091. }
  34092. paintButton (g, isOver(), isDown());
  34093. }
  34094. void Button::mouseEnter (const MouseEvent& e)
  34095. {
  34096. updateState (&e);
  34097. }
  34098. void Button::mouseExit (const MouseEvent& e)
  34099. {
  34100. updateState (&e);
  34101. }
  34102. void Button::mouseDown (const MouseEvent& e)
  34103. {
  34104. updateState (&e);
  34105. if (isDown())
  34106. {
  34107. if (autoRepeatDelay >= 0)
  34108. getRepeatTimer().startTimer (autoRepeatDelay);
  34109. if (triggerOnMouseDown)
  34110. internalClickCallback (e.mods);
  34111. }
  34112. }
  34113. void Button::mouseUp (const MouseEvent& e)
  34114. {
  34115. const bool wasDown = isDown();
  34116. updateState (&e);
  34117. if (wasDown && isOver() && ! triggerOnMouseDown)
  34118. internalClickCallback (e.mods);
  34119. }
  34120. void Button::mouseDrag (const MouseEvent& e)
  34121. {
  34122. const ButtonState oldState = buttonState;
  34123. updateState (&e);
  34124. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34125. getRepeatTimer().startTimer (autoRepeatSpeed);
  34126. }
  34127. void Button::focusGained (FocusChangeType)
  34128. {
  34129. updateState (0);
  34130. repaint();
  34131. }
  34132. void Button::focusLost (FocusChangeType)
  34133. {
  34134. updateState (0);
  34135. repaint();
  34136. }
  34137. void Button::setVisible (bool shouldBeVisible)
  34138. {
  34139. if (shouldBeVisible != isVisible())
  34140. {
  34141. Component::setVisible (shouldBeVisible);
  34142. if (! shouldBeVisible)
  34143. needsToRelease = false;
  34144. updateState (0);
  34145. }
  34146. else
  34147. {
  34148. Component::setVisible (shouldBeVisible);
  34149. }
  34150. }
  34151. void Button::parentHierarchyChanged()
  34152. {
  34153. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34154. if (newKeySource != keySource.getComponent())
  34155. {
  34156. if (keySource != 0)
  34157. keySource->removeKeyListener (this);
  34158. keySource = newKeySource;
  34159. if (keySource != 0)
  34160. keySource->addKeyListener (this);
  34161. }
  34162. }
  34163. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34164. const int commandID_,
  34165. const bool generateTooltip_)
  34166. {
  34167. commandID = commandID_;
  34168. generateTooltip = generateTooltip_;
  34169. if (commandManagerToUse != commandManagerToUse_)
  34170. {
  34171. if (commandManagerToUse != 0)
  34172. commandManagerToUse->removeListener (this);
  34173. commandManagerToUse = commandManagerToUse_;
  34174. if (commandManagerToUse != 0)
  34175. commandManagerToUse->addListener (this);
  34176. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34177. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34178. // it is that this button represents, and the button will update its state to reflect this
  34179. // in the applicationCommandListChanged() method.
  34180. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34181. }
  34182. if (commandManagerToUse != 0)
  34183. applicationCommandListChanged();
  34184. else
  34185. setEnabled (true);
  34186. }
  34187. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34188. {
  34189. if (info.commandID == commandID
  34190. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34191. {
  34192. flashButtonState();
  34193. }
  34194. }
  34195. void Button::applicationCommandListChanged()
  34196. {
  34197. if (commandManagerToUse != 0)
  34198. {
  34199. ApplicationCommandInfo info (0);
  34200. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34201. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34202. if (target != 0)
  34203. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34204. }
  34205. }
  34206. void Button::addShortcut (const KeyPress& key)
  34207. {
  34208. if (key.isValid())
  34209. {
  34210. jassert (! isRegisteredForShortcut (key)); // already registered!
  34211. shortcuts.add (key);
  34212. parentHierarchyChanged();
  34213. }
  34214. }
  34215. void Button::clearShortcuts()
  34216. {
  34217. shortcuts.clear();
  34218. parentHierarchyChanged();
  34219. }
  34220. bool Button::isShortcutPressed() const
  34221. {
  34222. if (! isCurrentlyBlockedByAnotherModalComponent())
  34223. {
  34224. for (int i = shortcuts.size(); --i >= 0;)
  34225. if (shortcuts.getReference(i).isCurrentlyDown())
  34226. return true;
  34227. }
  34228. return false;
  34229. }
  34230. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34231. {
  34232. for (int i = shortcuts.size(); --i >= 0;)
  34233. if (key == shortcuts.getReference(i))
  34234. return true;
  34235. return false;
  34236. }
  34237. bool Button::keyStateChanged (const bool, Component*)
  34238. {
  34239. if (! isEnabled())
  34240. return false;
  34241. const bool wasDown = isKeyDown;
  34242. isKeyDown = isShortcutPressed();
  34243. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34244. getRepeatTimer().startTimer (autoRepeatDelay);
  34245. updateState (0);
  34246. if (isEnabled() && wasDown && ! isKeyDown)
  34247. {
  34248. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34249. // (return immediately - this button may now have been deleted)
  34250. return true;
  34251. }
  34252. return wasDown || isKeyDown;
  34253. }
  34254. bool Button::keyPressed (const KeyPress&, Component*)
  34255. {
  34256. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34257. return isShortcutPressed();
  34258. }
  34259. bool Button::keyPressed (const KeyPress& key)
  34260. {
  34261. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34262. {
  34263. triggerClick();
  34264. return true;
  34265. }
  34266. return false;
  34267. }
  34268. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34269. const int repeatMillisecs,
  34270. const int minimumDelayInMillisecs) throw()
  34271. {
  34272. autoRepeatDelay = initialDelayMillisecs;
  34273. autoRepeatSpeed = repeatMillisecs;
  34274. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34275. }
  34276. void Button::repeatTimerCallback()
  34277. {
  34278. if (needsRepainting)
  34279. {
  34280. getRepeatTimer().stopTimer();
  34281. updateState (0);
  34282. needsRepainting = false;
  34283. }
  34284. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34285. {
  34286. int repeatSpeed = autoRepeatSpeed;
  34287. if (autoRepeatMinimumDelay >= 0)
  34288. {
  34289. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34290. timeHeldDown *= timeHeldDown;
  34291. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34292. }
  34293. repeatSpeed = jmax (1, repeatSpeed);
  34294. getRepeatTimer().startTimer (repeatSpeed);
  34295. const uint32 now = Time::getApproximateMillisecondCounter();
  34296. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34297. lastTimeCallbackTime = now;
  34298. Component::SafePointer<Component> deletionWatcher (this);
  34299. for (int i = numTimesToCallback; --i >= 0;)
  34300. {
  34301. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34302. if (deletionWatcher == 0 || ! isDown())
  34303. return;
  34304. }
  34305. }
  34306. else if (! needsToRelease)
  34307. {
  34308. getRepeatTimer().stopTimer();
  34309. }
  34310. }
  34311. Button::RepeatTimer& Button::getRepeatTimer()
  34312. {
  34313. if (repeatTimer == 0)
  34314. repeatTimer = new RepeatTimer (*this);
  34315. return *repeatTimer;
  34316. }
  34317. END_JUCE_NAMESPACE
  34318. /*** End of inlined file: juce_Button.cpp ***/
  34319. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34320. BEGIN_JUCE_NAMESPACE
  34321. DrawableButton::DrawableButton (const String& name,
  34322. const DrawableButton::ButtonStyle buttonStyle)
  34323. : Button (name),
  34324. style (buttonStyle),
  34325. edgeIndent (3)
  34326. {
  34327. if (buttonStyle == ImageOnButtonBackground)
  34328. {
  34329. backgroundOff = Colour (0xffbbbbff);
  34330. backgroundOn = Colour (0xff3333ff);
  34331. }
  34332. else
  34333. {
  34334. backgroundOff = Colours::transparentBlack;
  34335. backgroundOn = Colour (0xaabbbbff);
  34336. }
  34337. }
  34338. DrawableButton::~DrawableButton()
  34339. {
  34340. deleteImages();
  34341. }
  34342. void DrawableButton::deleteImages()
  34343. {
  34344. }
  34345. void DrawableButton::setImages (const Drawable* normal,
  34346. const Drawable* over,
  34347. const Drawable* down,
  34348. const Drawable* disabled,
  34349. const Drawable* normalOn,
  34350. const Drawable* overOn,
  34351. const Drawable* downOn,
  34352. const Drawable* disabledOn)
  34353. {
  34354. deleteImages();
  34355. jassert (normal != 0); // you really need to give it at least a normal image..
  34356. if (normal != 0)
  34357. normalImage = normal->createCopy();
  34358. if (over != 0)
  34359. overImage = over->createCopy();
  34360. if (down != 0)
  34361. downImage = down->createCopy();
  34362. if (disabled != 0)
  34363. disabledImage = disabled->createCopy();
  34364. if (normalOn != 0)
  34365. normalImageOn = normalOn->createCopy();
  34366. if (overOn != 0)
  34367. overImageOn = overOn->createCopy();
  34368. if (downOn != 0)
  34369. downImageOn = downOn->createCopy();
  34370. if (disabledOn != 0)
  34371. disabledImageOn = disabledOn->createCopy();
  34372. repaint();
  34373. }
  34374. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34375. {
  34376. if (style != newStyle)
  34377. {
  34378. style = newStyle;
  34379. repaint();
  34380. }
  34381. }
  34382. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34383. const Colour& toggledOnColour)
  34384. {
  34385. if (backgroundOff != toggledOffColour
  34386. || backgroundOn != toggledOnColour)
  34387. {
  34388. backgroundOff = toggledOffColour;
  34389. backgroundOn = toggledOnColour;
  34390. repaint();
  34391. }
  34392. }
  34393. const Colour& DrawableButton::getBackgroundColour() const throw()
  34394. {
  34395. return getToggleState() ? backgroundOn
  34396. : backgroundOff;
  34397. }
  34398. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34399. {
  34400. edgeIndent = numPixelsIndent;
  34401. repaint();
  34402. }
  34403. void DrawableButton::paintButton (Graphics& g,
  34404. bool isMouseOverButton,
  34405. bool isButtonDown)
  34406. {
  34407. Rectangle<int> imageSpace;
  34408. if (style == ImageOnButtonBackground)
  34409. {
  34410. const int insetX = getWidth() / 4;
  34411. const int insetY = getHeight() / 4;
  34412. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34413. getLookAndFeel().drawButtonBackground (g, *this,
  34414. getBackgroundColour(),
  34415. isMouseOverButton,
  34416. isButtonDown);
  34417. }
  34418. else
  34419. {
  34420. g.fillAll (getBackgroundColour());
  34421. const int textH = (style == ImageAboveTextLabel)
  34422. ? jmin (16, proportionOfHeight (0.25f))
  34423. : 0;
  34424. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34425. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34426. imageSpace.setBounds (indentX, indentY,
  34427. getWidth() - indentX * 2,
  34428. getHeight() - indentY * 2 - textH);
  34429. if (textH > 0)
  34430. {
  34431. g.setFont ((float) textH);
  34432. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34433. g.drawFittedText (getButtonText(),
  34434. 2, getHeight() - textH - 1,
  34435. getWidth() - 4, textH,
  34436. Justification::centred, 1);
  34437. }
  34438. }
  34439. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34440. g.setOpacity (1.0f);
  34441. const Drawable* imageToDraw = 0;
  34442. if (isEnabled())
  34443. {
  34444. imageToDraw = getCurrentImage();
  34445. }
  34446. else
  34447. {
  34448. imageToDraw = getToggleState() ? disabledImageOn
  34449. : disabledImage;
  34450. if (imageToDraw == 0)
  34451. {
  34452. g.setOpacity (0.4f);
  34453. imageToDraw = getNormalImage();
  34454. }
  34455. }
  34456. if (imageToDraw != 0)
  34457. {
  34458. if (style == ImageRaw)
  34459. {
  34460. imageToDraw->draw (g, 1.0f);
  34461. }
  34462. else
  34463. {
  34464. imageToDraw->drawWithin (g,
  34465. imageSpace.getX(),
  34466. imageSpace.getY(),
  34467. imageSpace.getWidth(),
  34468. imageSpace.getHeight(),
  34469. RectanglePlacement::centred,
  34470. 1.0f);
  34471. }
  34472. }
  34473. }
  34474. const Drawable* DrawableButton::getCurrentImage() const throw()
  34475. {
  34476. if (isDown())
  34477. return getDownImage();
  34478. if (isOver())
  34479. return getOverImage();
  34480. return getNormalImage();
  34481. }
  34482. const Drawable* DrawableButton::getNormalImage() const throw()
  34483. {
  34484. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34485. : normalImage;
  34486. }
  34487. const Drawable* DrawableButton::getOverImage() const throw()
  34488. {
  34489. const Drawable* d = normalImage;
  34490. if (getToggleState())
  34491. {
  34492. if (overImageOn != 0)
  34493. d = overImageOn;
  34494. else if (normalImageOn != 0)
  34495. d = normalImageOn;
  34496. else if (overImage != 0)
  34497. d = overImage;
  34498. }
  34499. else
  34500. {
  34501. if (overImage != 0)
  34502. d = overImage;
  34503. }
  34504. return d;
  34505. }
  34506. const Drawable* DrawableButton::getDownImage() const throw()
  34507. {
  34508. const Drawable* d = normalImage;
  34509. if (getToggleState())
  34510. {
  34511. if (downImageOn != 0)
  34512. d = downImageOn;
  34513. else if (overImageOn != 0)
  34514. d = overImageOn;
  34515. else if (normalImageOn != 0)
  34516. d = normalImageOn;
  34517. else if (downImage != 0)
  34518. d = downImage;
  34519. else
  34520. d = getOverImage();
  34521. }
  34522. else
  34523. {
  34524. if (downImage != 0)
  34525. d = downImage;
  34526. else
  34527. d = getOverImage();
  34528. }
  34529. return d;
  34530. }
  34531. END_JUCE_NAMESPACE
  34532. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34533. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34534. BEGIN_JUCE_NAMESPACE
  34535. HyperlinkButton::HyperlinkButton (const String& linkText,
  34536. const URL& linkURL)
  34537. : Button (linkText),
  34538. url (linkURL),
  34539. font (14.0f, Font::underlined),
  34540. resizeFont (true),
  34541. justification (Justification::centred)
  34542. {
  34543. setMouseCursor (MouseCursor::PointingHandCursor);
  34544. setTooltip (linkURL.toString (false));
  34545. }
  34546. HyperlinkButton::~HyperlinkButton()
  34547. {
  34548. }
  34549. void HyperlinkButton::setFont (const Font& newFont,
  34550. const bool resizeToMatchComponentHeight,
  34551. const Justification& justificationType)
  34552. {
  34553. font = newFont;
  34554. resizeFont = resizeToMatchComponentHeight;
  34555. justification = justificationType;
  34556. repaint();
  34557. }
  34558. void HyperlinkButton::setURL (const URL& newURL) throw()
  34559. {
  34560. url = newURL;
  34561. setTooltip (newURL.toString (false));
  34562. }
  34563. const Font HyperlinkButton::getFontToUse() const
  34564. {
  34565. Font f (font);
  34566. if (resizeFont)
  34567. f.setHeight (getHeight() * 0.7f);
  34568. return f;
  34569. }
  34570. void HyperlinkButton::changeWidthToFitText()
  34571. {
  34572. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34573. }
  34574. void HyperlinkButton::colourChanged()
  34575. {
  34576. repaint();
  34577. }
  34578. void HyperlinkButton::clicked()
  34579. {
  34580. if (url.isWellFormed())
  34581. url.launchInDefaultBrowser();
  34582. }
  34583. void HyperlinkButton::paintButton (Graphics& g,
  34584. bool isMouseOverButton,
  34585. bool isButtonDown)
  34586. {
  34587. const Colour textColour (findColour (textColourId));
  34588. if (isEnabled())
  34589. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34590. : textColour);
  34591. else
  34592. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34593. g.setFont (getFontToUse());
  34594. g.drawText (getButtonText(),
  34595. 2, 0, getWidth() - 2, getHeight(),
  34596. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34597. true);
  34598. }
  34599. END_JUCE_NAMESPACE
  34600. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34601. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34602. BEGIN_JUCE_NAMESPACE
  34603. ImageButton::ImageButton (const String& text_)
  34604. : Button (text_),
  34605. scaleImageToFit (true),
  34606. preserveProportions (true),
  34607. alphaThreshold (0),
  34608. imageX (0),
  34609. imageY (0),
  34610. imageW (0),
  34611. imageH (0),
  34612. normalImage (0),
  34613. overImage (0),
  34614. downImage (0)
  34615. {
  34616. }
  34617. ImageButton::~ImageButton()
  34618. {
  34619. deleteImages();
  34620. }
  34621. void ImageButton::deleteImages()
  34622. {
  34623. ImageCache::releaseOrDelete (normalImage);
  34624. ImageCache::releaseOrDelete (overImage);
  34625. ImageCache::releaseOrDelete (downImage);
  34626. }
  34627. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34628. const bool rescaleImagesWhenButtonSizeChanges,
  34629. const bool preserveImageProportions,
  34630. Image* const normalImage_,
  34631. const float imageOpacityWhenNormal,
  34632. const Colour& overlayColourWhenNormal,
  34633. Image* const overImage_,
  34634. const float imageOpacityWhenOver,
  34635. const Colour& overlayColourWhenOver,
  34636. Image* const downImage_,
  34637. const float imageOpacityWhenDown,
  34638. const Colour& overlayColourWhenDown,
  34639. const float hitTestAlphaThreshold)
  34640. {
  34641. deleteImages();
  34642. normalImage = normalImage_;
  34643. overImage = overImage_;
  34644. downImage = downImage_;
  34645. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34646. {
  34647. imageW = normalImage->getWidth();
  34648. imageH = normalImage->getHeight();
  34649. setSize (imageW, imageH);
  34650. }
  34651. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34652. preserveProportions = preserveImageProportions;
  34653. normalOpacity = imageOpacityWhenNormal;
  34654. normalOverlay = overlayColourWhenNormal;
  34655. overOpacity = imageOpacityWhenOver;
  34656. overOverlay = overlayColourWhenOver;
  34657. downOpacity = imageOpacityWhenDown;
  34658. downOverlay = overlayColourWhenDown;
  34659. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34660. repaint();
  34661. }
  34662. Image* ImageButton::getCurrentImage() const
  34663. {
  34664. if (isDown() || getToggleState())
  34665. return getDownImage();
  34666. if (isOver())
  34667. return getOverImage();
  34668. return getNormalImage();
  34669. }
  34670. Image* ImageButton::getNormalImage() const throw()
  34671. {
  34672. return normalImage;
  34673. }
  34674. Image* ImageButton::getOverImage() const throw()
  34675. {
  34676. return (overImage != 0) ? overImage
  34677. : normalImage;
  34678. }
  34679. Image* ImageButton::getDownImage() const throw()
  34680. {
  34681. return (downImage != 0) ? downImage
  34682. : getOverImage();
  34683. }
  34684. void ImageButton::paintButton (Graphics& g,
  34685. bool isMouseOverButton,
  34686. bool isButtonDown)
  34687. {
  34688. if (! isEnabled())
  34689. {
  34690. isMouseOverButton = false;
  34691. isButtonDown = false;
  34692. }
  34693. Image* const im = getCurrentImage();
  34694. if (im != 0)
  34695. {
  34696. const int iw = im->getWidth();
  34697. const int ih = im->getHeight();
  34698. imageW = getWidth();
  34699. imageH = getHeight();
  34700. imageX = (imageW - iw) >> 1;
  34701. imageY = (imageH - ih) >> 1;
  34702. if (scaleImageToFit)
  34703. {
  34704. if (preserveProportions)
  34705. {
  34706. int newW, newH;
  34707. const float imRatio = ih / (float)iw;
  34708. const float destRatio = imageH / (float)imageW;
  34709. if (imRatio > destRatio)
  34710. {
  34711. newW = roundToInt (imageH / imRatio);
  34712. newH = imageH;
  34713. }
  34714. else
  34715. {
  34716. newW = imageW;
  34717. newH = roundToInt (imageW * imRatio);
  34718. }
  34719. imageX = (imageW - newW) / 2;
  34720. imageY = (imageH - newH) / 2;
  34721. imageW = newW;
  34722. imageH = newH;
  34723. }
  34724. else
  34725. {
  34726. imageX = 0;
  34727. imageY = 0;
  34728. }
  34729. }
  34730. if (! scaleImageToFit)
  34731. {
  34732. imageW = iw;
  34733. imageH = ih;
  34734. }
  34735. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34736. isButtonDown ? downOverlay
  34737. : (isMouseOverButton ? overOverlay
  34738. : normalOverlay),
  34739. isButtonDown ? downOpacity
  34740. : (isMouseOverButton ? overOpacity
  34741. : normalOpacity),
  34742. *this);
  34743. }
  34744. }
  34745. bool ImageButton::hitTest (int x, int y)
  34746. {
  34747. if (alphaThreshold == 0)
  34748. return true;
  34749. Image* const im = getCurrentImage();
  34750. return im == 0
  34751. || (imageW > 0 && imageH > 0
  34752. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34753. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34754. }
  34755. END_JUCE_NAMESPACE
  34756. /*** End of inlined file: juce_ImageButton.cpp ***/
  34757. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34758. BEGIN_JUCE_NAMESPACE
  34759. ShapeButton::ShapeButton (const String& text_,
  34760. const Colour& normalColour_,
  34761. const Colour& overColour_,
  34762. const Colour& downColour_)
  34763. : Button (text_),
  34764. normalColour (normalColour_),
  34765. overColour (overColour_),
  34766. downColour (downColour_),
  34767. maintainShapeProportions (false),
  34768. outlineWidth (0.0f)
  34769. {
  34770. }
  34771. ShapeButton::~ShapeButton()
  34772. {
  34773. }
  34774. void ShapeButton::setColours (const Colour& newNormalColour,
  34775. const Colour& newOverColour,
  34776. const Colour& newDownColour)
  34777. {
  34778. normalColour = newNormalColour;
  34779. overColour = newOverColour;
  34780. downColour = newDownColour;
  34781. }
  34782. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34783. const float newOutlineWidth)
  34784. {
  34785. outlineColour = newOutlineColour;
  34786. outlineWidth = newOutlineWidth;
  34787. }
  34788. void ShapeButton::setShape (const Path& newShape,
  34789. const bool resizeNowToFitThisShape,
  34790. const bool maintainShapeProportions_,
  34791. const bool hasShadow)
  34792. {
  34793. shape = newShape;
  34794. maintainShapeProportions = maintainShapeProportions_;
  34795. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34796. setComponentEffect ((hasShadow) ? &shadow : 0);
  34797. if (resizeNowToFitThisShape)
  34798. {
  34799. Rectangle<float> bounds (shape.getBounds());
  34800. if (hasShadow)
  34801. bounds.expand (4.0f, 4.0f);
  34802. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34803. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34804. 1 + (int) (bounds.getHeight() + outlineWidth));
  34805. }
  34806. }
  34807. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34808. {
  34809. if (! isEnabled())
  34810. {
  34811. isMouseOverButton = false;
  34812. isButtonDown = false;
  34813. }
  34814. g.setColour ((isButtonDown) ? downColour
  34815. : (isMouseOverButton) ? overColour
  34816. : normalColour);
  34817. int w = getWidth();
  34818. int h = getHeight();
  34819. if (getComponentEffect() != 0)
  34820. {
  34821. w -= 4;
  34822. h -= 4;
  34823. }
  34824. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34825. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34826. w - offset - outlineWidth,
  34827. h - offset - outlineWidth,
  34828. maintainShapeProportions));
  34829. g.fillPath (shape, trans);
  34830. if (outlineWidth > 0.0f)
  34831. {
  34832. g.setColour (outlineColour);
  34833. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34834. }
  34835. }
  34836. END_JUCE_NAMESPACE
  34837. /*** End of inlined file: juce_ShapeButton.cpp ***/
  34838. /*** Start of inlined file: juce_TextButton.cpp ***/
  34839. BEGIN_JUCE_NAMESPACE
  34840. TextButton::TextButton (const String& name,
  34841. const String& toolTip)
  34842. : Button (name)
  34843. {
  34844. setTooltip (toolTip);
  34845. }
  34846. TextButton::~TextButton()
  34847. {
  34848. }
  34849. void TextButton::paintButton (Graphics& g,
  34850. bool isMouseOverButton,
  34851. bool isButtonDown)
  34852. {
  34853. getLookAndFeel().drawButtonBackground (g, *this,
  34854. findColour (getToggleState() ? buttonOnColourId
  34855. : buttonColourId),
  34856. isMouseOverButton,
  34857. isButtonDown);
  34858. getLookAndFeel().drawButtonText (g, *this,
  34859. isMouseOverButton,
  34860. isButtonDown);
  34861. }
  34862. void TextButton::colourChanged()
  34863. {
  34864. repaint();
  34865. }
  34866. const Font TextButton::getFont()
  34867. {
  34868. return Font (jmin (15.0f, getHeight() * 0.6f));
  34869. }
  34870. void TextButton::changeWidthToFitText (const int newHeight)
  34871. {
  34872. if (newHeight >= 0)
  34873. setSize (jmax (1, getWidth()), newHeight);
  34874. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34875. getHeight());
  34876. }
  34877. END_JUCE_NAMESPACE
  34878. /*** End of inlined file: juce_TextButton.cpp ***/
  34879. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  34880. BEGIN_JUCE_NAMESPACE
  34881. ToggleButton::ToggleButton (const String& buttonText)
  34882. : Button (buttonText)
  34883. {
  34884. setClickingTogglesState (true);
  34885. }
  34886. ToggleButton::~ToggleButton()
  34887. {
  34888. }
  34889. void ToggleButton::paintButton (Graphics& g,
  34890. bool isMouseOverButton,
  34891. bool isButtonDown)
  34892. {
  34893. getLookAndFeel().drawToggleButton (g, *this,
  34894. isMouseOverButton,
  34895. isButtonDown);
  34896. }
  34897. void ToggleButton::changeWidthToFitText()
  34898. {
  34899. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34900. }
  34901. void ToggleButton::colourChanged()
  34902. {
  34903. repaint();
  34904. }
  34905. END_JUCE_NAMESPACE
  34906. /*** End of inlined file: juce_ToggleButton.cpp ***/
  34907. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  34908. BEGIN_JUCE_NAMESPACE
  34909. ToolbarButton::ToolbarButton (const int itemId_,
  34910. const String& buttonText,
  34911. Drawable* const normalImage_,
  34912. Drawable* const toggledOnImage_)
  34913. : ToolbarItemComponent (itemId_, buttonText, true),
  34914. normalImage (normalImage_),
  34915. toggledOnImage (toggledOnImage_)
  34916. {
  34917. jassert (normalImage_ != 0);
  34918. }
  34919. ToolbarButton::~ToolbarButton()
  34920. {
  34921. }
  34922. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34923. bool /*isToolbarVertical*/,
  34924. int& preferredSize,
  34925. int& minSize, int& maxSize)
  34926. {
  34927. preferredSize = minSize = maxSize = toolbarDepth;
  34928. return true;
  34929. }
  34930. void ToolbarButton::paintButtonArea (Graphics& g,
  34931. int width, int height,
  34932. bool /*isMouseOver*/,
  34933. bool /*isMouseDown*/)
  34934. {
  34935. Drawable* d = normalImage;
  34936. if (getToggleState() && toggledOnImage != 0)
  34937. d = toggledOnImage;
  34938. if (! isEnabled())
  34939. {
  34940. Image im (Image::ARGB, width, height, true);
  34941. Graphics g2 (im);
  34942. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34943. im.desaturate();
  34944. g.drawImageAt (&im, 0, 0);
  34945. }
  34946. else
  34947. {
  34948. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34949. }
  34950. }
  34951. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  34952. {
  34953. }
  34954. END_JUCE_NAMESPACE
  34955. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  34956. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  34957. BEGIN_JUCE_NAMESPACE
  34958. class CodeDocumentLine
  34959. {
  34960. public:
  34961. CodeDocumentLine (const juce_wchar* const line_,
  34962. const int lineLength_,
  34963. const int numNewLineChars,
  34964. const int lineStartInFile_)
  34965. : line (line_, lineLength_),
  34966. lineStartInFile (lineStartInFile_),
  34967. lineLength (lineLength_),
  34968. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  34969. {
  34970. }
  34971. ~CodeDocumentLine()
  34972. {
  34973. }
  34974. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  34975. {
  34976. const juce_wchar* const t = text;
  34977. int pos = 0;
  34978. while (t [pos] != 0)
  34979. {
  34980. const int startOfLine = pos;
  34981. int numNewLineChars = 0;
  34982. while (t[pos] != 0)
  34983. {
  34984. if (t[pos] == '\r')
  34985. {
  34986. ++numNewLineChars;
  34987. ++pos;
  34988. if (t[pos] == '\n')
  34989. {
  34990. ++numNewLineChars;
  34991. ++pos;
  34992. }
  34993. break;
  34994. }
  34995. if (t[pos] == '\n')
  34996. {
  34997. ++numNewLineChars;
  34998. ++pos;
  34999. break;
  35000. }
  35001. ++pos;
  35002. }
  35003. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35004. numNewLineChars, startOfLine));
  35005. }
  35006. jassert (pos == text.length());
  35007. }
  35008. bool endsWithLineBreak() const throw()
  35009. {
  35010. return lineLengthWithoutNewLines != lineLength;
  35011. }
  35012. void updateLength() throw()
  35013. {
  35014. lineLengthWithoutNewLines = lineLength = line.length();
  35015. while (lineLengthWithoutNewLines > 0
  35016. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35017. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35018. {
  35019. --lineLengthWithoutNewLines;
  35020. }
  35021. }
  35022. String line;
  35023. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35024. };
  35025. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35026. : document (document_),
  35027. currentLine (document_->lines[0]),
  35028. line (0),
  35029. position (0)
  35030. {
  35031. }
  35032. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35033. : document (other.document),
  35034. currentLine (other.currentLine),
  35035. line (other.line),
  35036. position (other.position)
  35037. {
  35038. }
  35039. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35040. {
  35041. document = other.document;
  35042. currentLine = other.currentLine;
  35043. line = other.line;
  35044. position = other.position;
  35045. return *this;
  35046. }
  35047. CodeDocument::Iterator::~Iterator() throw()
  35048. {
  35049. }
  35050. juce_wchar CodeDocument::Iterator::nextChar()
  35051. {
  35052. if (currentLine == 0)
  35053. return 0;
  35054. jassert (currentLine == document->lines.getUnchecked (line));
  35055. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35056. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35057. {
  35058. ++line;
  35059. currentLine = document->lines [line];
  35060. }
  35061. return result;
  35062. }
  35063. void CodeDocument::Iterator::skip()
  35064. {
  35065. if (currentLine != 0)
  35066. {
  35067. jassert (currentLine == document->lines.getUnchecked (line));
  35068. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35069. {
  35070. ++line;
  35071. currentLine = document->lines [line];
  35072. }
  35073. }
  35074. }
  35075. void CodeDocument::Iterator::skipToEndOfLine()
  35076. {
  35077. if (currentLine != 0)
  35078. {
  35079. jassert (currentLine == document->lines.getUnchecked (line));
  35080. ++line;
  35081. currentLine = document->lines [line];
  35082. if (currentLine != 0)
  35083. position = currentLine->lineStartInFile;
  35084. else
  35085. position = document->getNumCharacters();
  35086. }
  35087. }
  35088. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35089. {
  35090. if (currentLine == 0)
  35091. return 0;
  35092. jassert (currentLine == document->lines.getUnchecked (line));
  35093. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35094. }
  35095. void CodeDocument::Iterator::skipWhitespace()
  35096. {
  35097. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35098. skip();
  35099. }
  35100. bool CodeDocument::Iterator::isEOF() const throw()
  35101. {
  35102. return currentLine == 0;
  35103. }
  35104. CodeDocument::Position::Position() throw()
  35105. : owner (0), characterPos (0), line (0),
  35106. indexInLine (0), positionMaintained (false)
  35107. {
  35108. }
  35109. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35110. const int line_, const int indexInLine_) throw()
  35111. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35112. characterPos (0), line (line_),
  35113. indexInLine (indexInLine_), positionMaintained (false)
  35114. {
  35115. setLineAndIndex (line_, indexInLine_);
  35116. }
  35117. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35118. const int characterPos_) throw()
  35119. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35120. positionMaintained (false)
  35121. {
  35122. setPosition (characterPos_);
  35123. }
  35124. CodeDocument::Position::Position (const Position& other) throw()
  35125. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35126. indexInLine (other.indexInLine), positionMaintained (false)
  35127. {
  35128. jassert (*this == other);
  35129. }
  35130. CodeDocument::Position::~Position() throw()
  35131. {
  35132. setPositionMaintained (false);
  35133. }
  35134. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35135. {
  35136. if (this != &other)
  35137. {
  35138. const bool wasPositionMaintained = positionMaintained;
  35139. if (owner != other.owner)
  35140. setPositionMaintained (false);
  35141. owner = other.owner;
  35142. line = other.line;
  35143. indexInLine = other.indexInLine;
  35144. characterPos = other.characterPos;
  35145. setPositionMaintained (wasPositionMaintained);
  35146. jassert (*this == other);
  35147. }
  35148. return *this;
  35149. }
  35150. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35151. {
  35152. jassert ((characterPos == other.characterPos)
  35153. == (line == other.line && indexInLine == other.indexInLine));
  35154. return characterPos == other.characterPos
  35155. && line == other.line
  35156. && indexInLine == other.indexInLine
  35157. && owner == other.owner;
  35158. }
  35159. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35160. {
  35161. return ! operator== (other);
  35162. }
  35163. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35164. {
  35165. jassert (owner != 0);
  35166. if (owner->lines.size() == 0)
  35167. {
  35168. line = 0;
  35169. indexInLine = 0;
  35170. characterPos = 0;
  35171. }
  35172. else
  35173. {
  35174. if (newLine >= owner->lines.size())
  35175. {
  35176. line = owner->lines.size() - 1;
  35177. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35178. jassert (l != 0);
  35179. indexInLine = l->lineLengthWithoutNewLines;
  35180. characterPos = l->lineStartInFile + indexInLine;
  35181. }
  35182. else
  35183. {
  35184. line = jmax (0, newLine);
  35185. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35186. jassert (l != 0);
  35187. if (l->lineLengthWithoutNewLines > 0)
  35188. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35189. else
  35190. indexInLine = 0;
  35191. characterPos = l->lineStartInFile + indexInLine;
  35192. }
  35193. }
  35194. }
  35195. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35196. {
  35197. jassert (owner != 0);
  35198. line = 0;
  35199. indexInLine = 0;
  35200. characterPos = 0;
  35201. if (newPosition > 0)
  35202. {
  35203. int lineStart = 0;
  35204. int lineEnd = owner->lines.size();
  35205. for (;;)
  35206. {
  35207. if (lineEnd - lineStart < 4)
  35208. {
  35209. for (int i = lineStart; i < lineEnd; ++i)
  35210. {
  35211. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35212. int index = newPosition - l->lineStartInFile;
  35213. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35214. {
  35215. line = i;
  35216. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35217. characterPos = l->lineStartInFile + indexInLine;
  35218. }
  35219. }
  35220. break;
  35221. }
  35222. else
  35223. {
  35224. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35225. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35226. if (newPosition >= mid->lineStartInFile)
  35227. lineStart = midIndex;
  35228. else
  35229. lineEnd = midIndex;
  35230. }
  35231. }
  35232. }
  35233. }
  35234. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35235. {
  35236. jassert (owner != 0);
  35237. if (characterDelta == 1)
  35238. {
  35239. setPosition (getPosition());
  35240. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35241. if (line < owner->lines.size())
  35242. {
  35243. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35244. if (indexInLine + characterDelta < l->lineLength
  35245. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35246. ++characterDelta;
  35247. }
  35248. }
  35249. setPosition (characterPos + characterDelta);
  35250. }
  35251. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35252. {
  35253. CodeDocument::Position p (*this);
  35254. p.moveBy (characterDelta);
  35255. return p;
  35256. }
  35257. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35258. {
  35259. CodeDocument::Position p (*this);
  35260. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35261. return p;
  35262. }
  35263. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35264. {
  35265. const CodeDocumentLine* const l = owner->lines [line];
  35266. return l == 0 ? 0 : l->line [getIndexInLine()];
  35267. }
  35268. const String CodeDocument::Position::getLineText() const throw()
  35269. {
  35270. const CodeDocumentLine* const l = owner->lines [line];
  35271. return l == 0 ? String::empty : l->line;
  35272. }
  35273. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35274. {
  35275. if (isMaintained != positionMaintained)
  35276. {
  35277. positionMaintained = isMaintained;
  35278. if (owner != 0)
  35279. {
  35280. if (isMaintained)
  35281. {
  35282. jassert (! owner->positionsToMaintain.contains (this));
  35283. owner->positionsToMaintain.add (this);
  35284. }
  35285. else
  35286. {
  35287. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35288. jassert (owner->positionsToMaintain.contains (this));
  35289. owner->positionsToMaintain.removeValue (this);
  35290. }
  35291. }
  35292. }
  35293. }
  35294. CodeDocument::CodeDocument()
  35295. : undoManager (std::numeric_limits<int>::max(), 10000),
  35296. currentActionIndex (0),
  35297. indexOfSavedState (-1),
  35298. maximumLineLength (-1),
  35299. newLineChars ("\r\n")
  35300. {
  35301. }
  35302. CodeDocument::~CodeDocument()
  35303. {
  35304. }
  35305. const String CodeDocument::getAllContent() const throw()
  35306. {
  35307. return getTextBetween (Position (this, 0),
  35308. Position (this, lines.size(), 0));
  35309. }
  35310. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35311. {
  35312. if (end.getPosition() <= start.getPosition())
  35313. return String::empty;
  35314. const int startLine = start.getLineNumber();
  35315. const int endLine = end.getLineNumber();
  35316. if (startLine == endLine)
  35317. {
  35318. CodeDocumentLine* const line = lines [startLine];
  35319. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35320. }
  35321. String result;
  35322. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35323. String::Concatenator concatenator (result);
  35324. const int maxLine = jmin (lines.size() - 1, endLine);
  35325. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35326. {
  35327. const CodeDocumentLine* line = lines.getUnchecked(i);
  35328. int len = line->lineLength;
  35329. if (i == startLine)
  35330. {
  35331. const int index = start.getIndexInLine();
  35332. concatenator.append (line->line.substring (index, len));
  35333. }
  35334. else if (i == endLine)
  35335. {
  35336. len = end.getIndexInLine();
  35337. concatenator.append (line->line.substring (0, len));
  35338. }
  35339. else
  35340. {
  35341. concatenator.append (line->line);
  35342. }
  35343. }
  35344. return result;
  35345. }
  35346. int CodeDocument::getNumCharacters() const throw()
  35347. {
  35348. const CodeDocumentLine* const lastLine = lines.getLast();
  35349. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35350. }
  35351. const String CodeDocument::getLine (const int lineIndex) const throw()
  35352. {
  35353. const CodeDocumentLine* const line = lines [lineIndex];
  35354. return (line == 0) ? String::empty : line->line;
  35355. }
  35356. int CodeDocument::getMaximumLineLength() throw()
  35357. {
  35358. if (maximumLineLength < 0)
  35359. {
  35360. maximumLineLength = 0;
  35361. for (int i = lines.size(); --i >= 0;)
  35362. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35363. }
  35364. return maximumLineLength;
  35365. }
  35366. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35367. {
  35368. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35369. }
  35370. void CodeDocument::insertText (const Position& position, const String& text)
  35371. {
  35372. insert (text, position.getPosition(), true);
  35373. }
  35374. void CodeDocument::replaceAllContent (const String& newContent)
  35375. {
  35376. remove (0, getNumCharacters(), true);
  35377. insert (newContent, 0, true);
  35378. }
  35379. bool CodeDocument::loadFromStream (InputStream& stream)
  35380. {
  35381. replaceAllContent (stream.readEntireStreamAsString());
  35382. setSavePoint();
  35383. clearUndoHistory();
  35384. return true;
  35385. }
  35386. bool CodeDocument::writeToStream (OutputStream& stream)
  35387. {
  35388. for (int i = 0; i < lines.size(); ++i)
  35389. {
  35390. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35391. const char* utf8 = temp.toUTF8();
  35392. if (! stream.write (utf8, (int) strlen (utf8)))
  35393. return false;
  35394. }
  35395. return true;
  35396. }
  35397. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35398. {
  35399. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35400. newLineChars = newLine;
  35401. }
  35402. void CodeDocument::newTransaction()
  35403. {
  35404. undoManager.beginNewTransaction (String::empty);
  35405. }
  35406. void CodeDocument::undo()
  35407. {
  35408. newTransaction();
  35409. undoManager.undo();
  35410. }
  35411. void CodeDocument::redo()
  35412. {
  35413. undoManager.redo();
  35414. }
  35415. void CodeDocument::clearUndoHistory()
  35416. {
  35417. undoManager.clearUndoHistory();
  35418. }
  35419. void CodeDocument::setSavePoint() throw()
  35420. {
  35421. indexOfSavedState = currentActionIndex;
  35422. }
  35423. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35424. {
  35425. return currentActionIndex != indexOfSavedState;
  35426. }
  35427. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35428. {
  35429. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35430. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35431. }
  35432. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35433. {
  35434. Position p (position);
  35435. const int maxDistance = 256;
  35436. int i = 0;
  35437. while (i < maxDistance
  35438. && CharacterFunctions::isWhitespace (p.getCharacter())
  35439. && (i == 0 || (p.getCharacter() != '\n'
  35440. && p.getCharacter() != '\r')))
  35441. {
  35442. ++i;
  35443. p.moveBy (1);
  35444. }
  35445. if (i == 0)
  35446. {
  35447. const int type = getCodeCharacterCategory (p.getCharacter());
  35448. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35449. {
  35450. ++i;
  35451. p.moveBy (1);
  35452. }
  35453. while (i < maxDistance
  35454. && CharacterFunctions::isWhitespace (p.getCharacter())
  35455. && (i == 0 || (p.getCharacter() != '\n'
  35456. && p.getCharacter() != '\r')))
  35457. {
  35458. ++i;
  35459. p.moveBy (1);
  35460. }
  35461. }
  35462. return p;
  35463. }
  35464. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35465. {
  35466. Position p (position);
  35467. const int maxDistance = 256;
  35468. int i = 0;
  35469. bool stoppedAtLineStart = false;
  35470. while (i < maxDistance)
  35471. {
  35472. const juce_wchar c = p.movedBy (-1).getCharacter();
  35473. if (c == '\r' || c == '\n')
  35474. {
  35475. stoppedAtLineStart = true;
  35476. if (i > 0)
  35477. break;
  35478. }
  35479. if (! CharacterFunctions::isWhitespace (c))
  35480. break;
  35481. p.moveBy (-1);
  35482. ++i;
  35483. }
  35484. if (i < maxDistance && ! stoppedAtLineStart)
  35485. {
  35486. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35487. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35488. {
  35489. p.moveBy (-1);
  35490. ++i;
  35491. }
  35492. }
  35493. return p;
  35494. }
  35495. void CodeDocument::checkLastLineStatus()
  35496. {
  35497. while (lines.size() > 0
  35498. && lines.getLast()->lineLength == 0
  35499. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35500. {
  35501. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35502. lines.removeLast();
  35503. }
  35504. const CodeDocumentLine* const lastLine = lines.getLast();
  35505. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35506. {
  35507. // check that there's an empty line at the end if the preceding one ends in a newline..
  35508. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35509. }
  35510. }
  35511. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35512. {
  35513. listeners.add (listener);
  35514. }
  35515. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35516. {
  35517. listeners.remove (listener);
  35518. }
  35519. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35520. {
  35521. Position startPos (this, startLine, 0);
  35522. Position endPos (this, endLine, 0);
  35523. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35524. }
  35525. class CodeDocumentInsertAction : public UndoableAction
  35526. {
  35527. CodeDocument& owner;
  35528. const String text;
  35529. int insertPos;
  35530. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35531. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35532. public:
  35533. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35534. : owner (owner_),
  35535. text (text_),
  35536. insertPos (insertPos_)
  35537. {
  35538. }
  35539. ~CodeDocumentInsertAction() {}
  35540. bool perform()
  35541. {
  35542. owner.currentActionIndex++;
  35543. owner.insert (text, insertPos, false);
  35544. return true;
  35545. }
  35546. bool undo()
  35547. {
  35548. owner.currentActionIndex--;
  35549. owner.remove (insertPos, insertPos + text.length(), false);
  35550. return true;
  35551. }
  35552. int getSizeInUnits() { return text.length() + 32; }
  35553. };
  35554. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35555. {
  35556. if (text.isEmpty())
  35557. return;
  35558. if (undoable)
  35559. {
  35560. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35561. }
  35562. else
  35563. {
  35564. Position pos (this, insertPos);
  35565. const int firstAffectedLine = pos.getLineNumber();
  35566. int lastAffectedLine = firstAffectedLine + 1;
  35567. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35568. String textInsideOriginalLine (text);
  35569. if (firstLine != 0)
  35570. {
  35571. const int index = pos.getIndexInLine();
  35572. textInsideOriginalLine = firstLine->line.substring (0, index)
  35573. + textInsideOriginalLine
  35574. + firstLine->line.substring (index);
  35575. }
  35576. maximumLineLength = -1;
  35577. Array <CodeDocumentLine*> newLines;
  35578. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35579. jassert (newLines.size() > 0);
  35580. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35581. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35582. lines.set (firstAffectedLine, newFirstLine);
  35583. if (newLines.size() > 1)
  35584. {
  35585. for (int i = 1; i < newLines.size(); ++i)
  35586. {
  35587. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35588. lines.insert (firstAffectedLine + i, l);
  35589. }
  35590. lastAffectedLine = lines.size();
  35591. }
  35592. int i, lineStart = newFirstLine->lineStartInFile;
  35593. for (i = firstAffectedLine; i < lines.size(); ++i)
  35594. {
  35595. CodeDocumentLine* const l = lines.getUnchecked (i);
  35596. l->lineStartInFile = lineStart;
  35597. lineStart += l->lineLength;
  35598. }
  35599. checkLastLineStatus();
  35600. const int newTextLength = text.length();
  35601. for (i = 0; i < positionsToMaintain.size(); ++i)
  35602. {
  35603. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35604. if (p->getPosition() >= insertPos)
  35605. p->setPosition (p->getPosition() + newTextLength);
  35606. }
  35607. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35608. }
  35609. }
  35610. class CodeDocumentDeleteAction : public UndoableAction
  35611. {
  35612. CodeDocument& owner;
  35613. int startPos, endPos;
  35614. String removedText;
  35615. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35616. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35617. public:
  35618. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35619. : owner (owner_),
  35620. startPos (startPos_),
  35621. endPos (endPos_)
  35622. {
  35623. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35624. CodeDocument::Position (&owner, endPos));
  35625. }
  35626. ~CodeDocumentDeleteAction() {}
  35627. bool perform()
  35628. {
  35629. owner.currentActionIndex++;
  35630. owner.remove (startPos, endPos, false);
  35631. return true;
  35632. }
  35633. bool undo()
  35634. {
  35635. owner.currentActionIndex--;
  35636. owner.insert (removedText, startPos, false);
  35637. return true;
  35638. }
  35639. int getSizeInUnits() { return removedText.length() + 32; }
  35640. };
  35641. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35642. {
  35643. if (endPos <= startPos)
  35644. return;
  35645. if (undoable)
  35646. {
  35647. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35648. }
  35649. else
  35650. {
  35651. Position startPosition (this, startPos);
  35652. Position endPosition (this, endPos);
  35653. maximumLineLength = -1;
  35654. const int firstAffectedLine = startPosition.getLineNumber();
  35655. const int endLine = endPosition.getLineNumber();
  35656. int lastAffectedLine = firstAffectedLine + 1;
  35657. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35658. if (firstAffectedLine == endLine)
  35659. {
  35660. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35661. + firstLine->line.substring (endPosition.getIndexInLine());
  35662. firstLine->updateLength();
  35663. }
  35664. else
  35665. {
  35666. lastAffectedLine = lines.size();
  35667. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35668. jassert (lastLine != 0);
  35669. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35670. + lastLine->line.substring (endPosition.getIndexInLine());
  35671. firstLine->updateLength();
  35672. int numLinesToRemove = endLine - firstAffectedLine;
  35673. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35674. }
  35675. int i;
  35676. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35677. {
  35678. CodeDocumentLine* const l = lines.getUnchecked (i);
  35679. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35680. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35681. }
  35682. checkLastLineStatus();
  35683. const int totalChars = getNumCharacters();
  35684. for (i = 0; i < positionsToMaintain.size(); ++i)
  35685. {
  35686. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35687. if (p->getPosition() > startPosition.getPosition())
  35688. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35689. if (p->getPosition() > totalChars)
  35690. p->setPosition (totalChars);
  35691. }
  35692. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35693. }
  35694. }
  35695. END_JUCE_NAMESPACE
  35696. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35697. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35698. BEGIN_JUCE_NAMESPACE
  35699. class CodeEditorComponent::CaretComponent : public Component,
  35700. public Timer
  35701. {
  35702. public:
  35703. CaretComponent (CodeEditorComponent& owner_)
  35704. : owner (owner_)
  35705. {
  35706. setAlwaysOnTop (true);
  35707. setInterceptsMouseClicks (false, false);
  35708. }
  35709. ~CaretComponent()
  35710. {
  35711. }
  35712. void paint (Graphics& g)
  35713. {
  35714. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35715. }
  35716. void timerCallback()
  35717. {
  35718. setVisible (shouldBeShown() && ! isVisible());
  35719. }
  35720. void updatePosition()
  35721. {
  35722. startTimer (400);
  35723. setVisible (shouldBeShown());
  35724. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35725. }
  35726. private:
  35727. CodeEditorComponent& owner;
  35728. CaretComponent (const CaretComponent&);
  35729. CaretComponent& operator= (const CaretComponent&);
  35730. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35731. };
  35732. class CodeEditorComponent::CodeEditorLine
  35733. {
  35734. public:
  35735. CodeEditorLine() throw()
  35736. : highlightColumnStart (0), highlightColumnEnd (0)
  35737. {
  35738. }
  35739. ~CodeEditorLine() throw()
  35740. {
  35741. }
  35742. bool update (CodeDocument& document, int lineNum,
  35743. CodeDocument::Iterator& source,
  35744. CodeTokeniser* analyser, const int spacesPerTab,
  35745. const CodeDocument::Position& selectionStart,
  35746. const CodeDocument::Position& selectionEnd)
  35747. {
  35748. Array <SyntaxToken> newTokens;
  35749. newTokens.ensureStorageAllocated (8);
  35750. if (analyser == 0)
  35751. {
  35752. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35753. }
  35754. else if (lineNum < document.getNumLines())
  35755. {
  35756. const CodeDocument::Position pos (&document, lineNum, 0);
  35757. createTokens (pos.getPosition(), pos.getLineText(),
  35758. source, analyser, newTokens);
  35759. }
  35760. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35761. int newHighlightStart = 0;
  35762. int newHighlightEnd = 0;
  35763. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35764. {
  35765. const String line (document.getLine (lineNum));
  35766. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35767. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35768. line, spacesPerTab);
  35769. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35770. line, spacesPerTab);
  35771. }
  35772. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35773. {
  35774. highlightColumnStart = newHighlightStart;
  35775. highlightColumnEnd = newHighlightEnd;
  35776. }
  35777. else
  35778. {
  35779. if (tokens.size() == newTokens.size())
  35780. {
  35781. bool allTheSame = true;
  35782. for (int i = newTokens.size(); --i >= 0;)
  35783. {
  35784. if (tokens.getReference(i) != newTokens.getReference(i))
  35785. {
  35786. allTheSame = false;
  35787. break;
  35788. }
  35789. }
  35790. if (allTheSame)
  35791. return false;
  35792. }
  35793. }
  35794. tokens.swapWithArray (newTokens);
  35795. return true;
  35796. }
  35797. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35798. float x, const int y, const int baselineOffset, const int lineHeight,
  35799. const Colour& highlightColour) const throw()
  35800. {
  35801. if (highlightColumnStart < highlightColumnEnd)
  35802. {
  35803. g.setColour (highlightColour);
  35804. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35805. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35806. }
  35807. int lastType = std::numeric_limits<int>::min();
  35808. for (int i = 0; i < tokens.size(); ++i)
  35809. {
  35810. SyntaxToken& token = tokens.getReference(i);
  35811. if (lastType != token.tokenType)
  35812. {
  35813. lastType = token.tokenType;
  35814. g.setColour (owner.getColourForTokenType (lastType));
  35815. }
  35816. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  35817. if (i < tokens.size() - 1)
  35818. {
  35819. if (token.width < 0)
  35820. token.width = font.getStringWidthFloat (token.text);
  35821. x += token.width;
  35822. }
  35823. }
  35824. }
  35825. private:
  35826. struct SyntaxToken
  35827. {
  35828. String text;
  35829. int tokenType;
  35830. float width;
  35831. SyntaxToken (const String& text_, const int type) throw()
  35832. : text (text_), tokenType (type), width (-1.0f)
  35833. {
  35834. }
  35835. bool operator!= (const SyntaxToken& other) const throw()
  35836. {
  35837. return text != other.text || tokenType != other.tokenType;
  35838. }
  35839. };
  35840. Array <SyntaxToken> tokens;
  35841. int highlightColumnStart, highlightColumnEnd;
  35842. static void createTokens (int startPosition, const String& lineText,
  35843. CodeDocument::Iterator& source,
  35844. CodeTokeniser* analyser,
  35845. Array <SyntaxToken>& newTokens)
  35846. {
  35847. CodeDocument::Iterator lastIterator (source);
  35848. const int lineLength = lineText.length();
  35849. for (;;)
  35850. {
  35851. int tokenType = analyser->readNextToken (source);
  35852. int tokenStart = lastIterator.getPosition();
  35853. int tokenEnd = source.getPosition();
  35854. if (tokenEnd <= tokenStart)
  35855. break;
  35856. tokenEnd -= startPosition;
  35857. if (tokenEnd > 0)
  35858. {
  35859. tokenStart -= startPosition;
  35860. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  35861. tokenType));
  35862. if (tokenEnd >= lineLength)
  35863. break;
  35864. }
  35865. lastIterator = source;
  35866. }
  35867. source = lastIterator;
  35868. }
  35869. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  35870. {
  35871. int x = 0;
  35872. for (int i = 0; i < tokens.size(); ++i)
  35873. {
  35874. SyntaxToken& t = tokens.getReference(i);
  35875. for (;;)
  35876. {
  35877. int tabPos = t.text.indexOfChar ('\t');
  35878. if (tabPos < 0)
  35879. break;
  35880. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  35881. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  35882. }
  35883. x += t.text.length();
  35884. }
  35885. }
  35886. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  35887. {
  35888. jassert (index <= line.length());
  35889. int col = 0;
  35890. for (int i = 0; i < index; ++i)
  35891. {
  35892. if (line[i] != '\t')
  35893. ++col;
  35894. else
  35895. col += spacesPerTab - (col % spacesPerTab);
  35896. }
  35897. return col;
  35898. }
  35899. };
  35900. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  35901. CodeTokeniser* const codeTokeniser_)
  35902. : document (document_),
  35903. firstLineOnScreen (0),
  35904. gutter (5),
  35905. spacesPerTab (4),
  35906. lineHeight (0),
  35907. linesOnScreen (0),
  35908. columnsOnScreen (0),
  35909. scrollbarThickness (16),
  35910. columnToTryToMaintain (-1),
  35911. useSpacesForTabs (false),
  35912. xOffset (0),
  35913. codeTokeniser (codeTokeniser_)
  35914. {
  35915. caretPos = CodeDocument::Position (&document_, 0, 0);
  35916. caretPos.setPositionMaintained (true);
  35917. selectionStart = CodeDocument::Position (&document_, 0, 0);
  35918. selectionStart.setPositionMaintained (true);
  35919. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  35920. selectionEnd.setPositionMaintained (true);
  35921. setOpaque (true);
  35922. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  35923. setWantsKeyboardFocus (true);
  35924. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  35925. verticalScrollBar->setSingleStepSize (1.0);
  35926. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  35927. horizontalScrollBar->setSingleStepSize (1.0);
  35928. addAndMakeVisible (caret = new CaretComponent (*this));
  35929. Font f (12.0f);
  35930. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  35931. setFont (f);
  35932. resetToDefaultColours();
  35933. verticalScrollBar->addListener (this);
  35934. horizontalScrollBar->addListener (this);
  35935. document.addListener (this);
  35936. }
  35937. CodeEditorComponent::~CodeEditorComponent()
  35938. {
  35939. document.removeListener (this);
  35940. deleteAllChildren();
  35941. }
  35942. void CodeEditorComponent::loadContent (const String& newContent)
  35943. {
  35944. clearCachedIterators (0);
  35945. document.replaceAllContent (newContent);
  35946. document.clearUndoHistory();
  35947. document.setSavePoint();
  35948. caretPos.setPosition (0);
  35949. selectionStart.setPosition (0);
  35950. selectionEnd.setPosition (0);
  35951. scrollToLine (0);
  35952. }
  35953. bool CodeEditorComponent::isTextInputActive() const
  35954. {
  35955. return true;
  35956. }
  35957. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  35958. const CodeDocument::Position& affectedTextEnd)
  35959. {
  35960. clearCachedIterators (affectedTextStart.getLineNumber());
  35961. triggerAsyncUpdate();
  35962. caret->updatePosition();
  35963. columnToTryToMaintain = -1;
  35964. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  35965. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  35966. deselectAll();
  35967. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  35968. || caretPos.getPosition() < affectedTextStart.getPosition())
  35969. moveCaretTo (affectedTextStart, false);
  35970. updateScrollBars();
  35971. }
  35972. void CodeEditorComponent::resized()
  35973. {
  35974. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  35975. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  35976. lines.clear();
  35977. rebuildLineTokens();
  35978. caret->updatePosition();
  35979. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  35980. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  35981. updateScrollBars();
  35982. }
  35983. void CodeEditorComponent::paint (Graphics& g)
  35984. {
  35985. handleUpdateNowIfNeeded();
  35986. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  35987. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  35988. g.setFont (font);
  35989. const int baselineOffset = (int) font.getAscent();
  35990. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  35991. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  35992. const Rectangle<int> clip (g.getClipBounds());
  35993. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  35994. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  35995. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  35996. {
  35997. lines.getUnchecked(j)->draw (*this, g, font,
  35998. (float) (gutter - xOffset * charWidth),
  35999. lineHeight * j, baselineOffset, lineHeight,
  36000. highlightColour);
  36001. }
  36002. }
  36003. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36004. {
  36005. if (scrollbarThickness != thickness)
  36006. {
  36007. scrollbarThickness = thickness;
  36008. resized();
  36009. }
  36010. }
  36011. void CodeEditorComponent::handleAsyncUpdate()
  36012. {
  36013. rebuildLineTokens();
  36014. }
  36015. void CodeEditorComponent::rebuildLineTokens()
  36016. {
  36017. cancelPendingUpdate();
  36018. const int numNeeded = linesOnScreen + 1;
  36019. int minLineToRepaint = numNeeded;
  36020. int maxLineToRepaint = 0;
  36021. if (numNeeded != lines.size())
  36022. {
  36023. lines.clear();
  36024. for (int i = numNeeded; --i >= 0;)
  36025. lines.add (new CodeEditorLine());
  36026. minLineToRepaint = 0;
  36027. maxLineToRepaint = numNeeded;
  36028. }
  36029. jassert (numNeeded == lines.size());
  36030. CodeDocument::Iterator source (&document);
  36031. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36032. for (int i = 0; i < numNeeded; ++i)
  36033. {
  36034. CodeEditorLine* const line = lines.getUnchecked(i);
  36035. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36036. selectionStart, selectionEnd))
  36037. {
  36038. minLineToRepaint = jmin (minLineToRepaint, i);
  36039. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36040. }
  36041. }
  36042. if (minLineToRepaint <= maxLineToRepaint)
  36043. {
  36044. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36045. verticalScrollBar->getX() - gutter,
  36046. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36047. }
  36048. }
  36049. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36050. {
  36051. caretPos = newPos;
  36052. columnToTryToMaintain = -1;
  36053. if (highlighting)
  36054. {
  36055. if (dragType == notDragging)
  36056. {
  36057. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36058. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36059. dragType = draggingSelectionStart;
  36060. else
  36061. dragType = draggingSelectionEnd;
  36062. }
  36063. if (dragType == draggingSelectionStart)
  36064. {
  36065. selectionStart = caretPos;
  36066. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36067. {
  36068. const CodeDocument::Position temp (selectionStart);
  36069. selectionStart = selectionEnd;
  36070. selectionEnd = temp;
  36071. dragType = draggingSelectionEnd;
  36072. }
  36073. }
  36074. else
  36075. {
  36076. selectionEnd = caretPos;
  36077. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36078. {
  36079. const CodeDocument::Position temp (selectionStart);
  36080. selectionStart = selectionEnd;
  36081. selectionEnd = temp;
  36082. dragType = draggingSelectionStart;
  36083. }
  36084. }
  36085. triggerAsyncUpdate();
  36086. }
  36087. else
  36088. {
  36089. deselectAll();
  36090. }
  36091. caret->updatePosition();
  36092. scrollToKeepCaretOnScreen();
  36093. updateScrollBars();
  36094. }
  36095. void CodeEditorComponent::deselectAll()
  36096. {
  36097. if (selectionStart != selectionEnd)
  36098. triggerAsyncUpdate();
  36099. selectionStart = caretPos;
  36100. selectionEnd = caretPos;
  36101. }
  36102. void CodeEditorComponent::updateScrollBars()
  36103. {
  36104. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36105. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36106. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36107. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36108. }
  36109. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36110. {
  36111. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36112. newFirstLineOnScreen);
  36113. if (newFirstLineOnScreen != firstLineOnScreen)
  36114. {
  36115. firstLineOnScreen = newFirstLineOnScreen;
  36116. caret->updatePosition();
  36117. updateCachedIterators (firstLineOnScreen);
  36118. triggerAsyncUpdate();
  36119. }
  36120. }
  36121. void CodeEditorComponent::scrollToColumnInternal (double column)
  36122. {
  36123. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36124. if (xOffset != newOffset)
  36125. {
  36126. xOffset = newOffset;
  36127. caret->updatePosition();
  36128. repaint();
  36129. }
  36130. }
  36131. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36132. {
  36133. scrollToLineInternal (newFirstLineOnScreen);
  36134. updateScrollBars();
  36135. }
  36136. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36137. {
  36138. scrollToColumnInternal (newFirstColumnOnScreen);
  36139. updateScrollBars();
  36140. }
  36141. void CodeEditorComponent::scrollBy (int deltaLines)
  36142. {
  36143. scrollToLine (firstLineOnScreen + deltaLines);
  36144. }
  36145. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36146. {
  36147. if (caretPos.getLineNumber() < firstLineOnScreen)
  36148. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36149. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36150. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36151. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36152. if (column >= xOffset + columnsOnScreen - 1)
  36153. scrollToColumn (column + 1 - columnsOnScreen);
  36154. else if (column < xOffset)
  36155. scrollToColumn (column);
  36156. }
  36157. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36158. {
  36159. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36160. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36161. roundToInt (charWidth),
  36162. lineHeight);
  36163. }
  36164. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36165. {
  36166. const int line = y / lineHeight + firstLineOnScreen;
  36167. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36168. const int index = columnToIndex (line, column);
  36169. return CodeDocument::Position (&document, line, index);
  36170. }
  36171. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36172. {
  36173. document.deleteSection (selectionStart, selectionEnd);
  36174. if (newText.isNotEmpty())
  36175. document.insertText (caretPos, newText);
  36176. scrollToKeepCaretOnScreen();
  36177. }
  36178. void CodeEditorComponent::insertTabAtCaret()
  36179. {
  36180. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36181. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36182. {
  36183. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36184. }
  36185. if (useSpacesForTabs)
  36186. {
  36187. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36188. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36189. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36190. }
  36191. else
  36192. {
  36193. insertTextAtCaret ("\t");
  36194. }
  36195. }
  36196. void CodeEditorComponent::cut()
  36197. {
  36198. insertTextAtCaret (String::empty);
  36199. }
  36200. void CodeEditorComponent::copy()
  36201. {
  36202. newTransaction();
  36203. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36204. if (selection.isNotEmpty())
  36205. SystemClipboard::copyTextToClipboard (selection);
  36206. }
  36207. void CodeEditorComponent::copyThenCut()
  36208. {
  36209. copy();
  36210. cut();
  36211. newTransaction();
  36212. }
  36213. void CodeEditorComponent::paste()
  36214. {
  36215. newTransaction();
  36216. const String clip (SystemClipboard::getTextFromClipboard());
  36217. if (clip.isNotEmpty())
  36218. insertTextAtCaret (clip);
  36219. newTransaction();
  36220. }
  36221. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36222. {
  36223. newTransaction();
  36224. if (moveInWholeWordSteps)
  36225. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36226. else
  36227. moveCaretTo (caretPos.movedBy (-1), selecting);
  36228. }
  36229. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36230. {
  36231. newTransaction();
  36232. if (moveInWholeWordSteps)
  36233. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36234. else
  36235. moveCaretTo (caretPos.movedBy (1), selecting);
  36236. }
  36237. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36238. {
  36239. CodeDocument::Position pos (caretPos);
  36240. const int newLineNum = pos.getLineNumber() + delta;
  36241. if (columnToTryToMaintain < 0)
  36242. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36243. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36244. const int colToMaintain = columnToTryToMaintain;
  36245. moveCaretTo (pos, selecting);
  36246. columnToTryToMaintain = colToMaintain;
  36247. }
  36248. void CodeEditorComponent::cursorDown (const bool selecting)
  36249. {
  36250. newTransaction();
  36251. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36252. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36253. else
  36254. moveLineDelta (1, selecting);
  36255. }
  36256. void CodeEditorComponent::cursorUp (const bool selecting)
  36257. {
  36258. newTransaction();
  36259. if (caretPos.getLineNumber() == 0)
  36260. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36261. else
  36262. moveLineDelta (-1, selecting);
  36263. }
  36264. void CodeEditorComponent::pageDown (const bool selecting)
  36265. {
  36266. newTransaction();
  36267. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36268. moveLineDelta (linesOnScreen, selecting);
  36269. }
  36270. void CodeEditorComponent::pageUp (const bool selecting)
  36271. {
  36272. newTransaction();
  36273. scrollBy (-linesOnScreen);
  36274. moveLineDelta (-linesOnScreen, selecting);
  36275. }
  36276. void CodeEditorComponent::scrollUp()
  36277. {
  36278. newTransaction();
  36279. scrollBy (1);
  36280. if (caretPos.getLineNumber() < firstLineOnScreen)
  36281. moveLineDelta (1, false);
  36282. }
  36283. void CodeEditorComponent::scrollDown()
  36284. {
  36285. newTransaction();
  36286. scrollBy (-1);
  36287. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36288. moveLineDelta (-1, false);
  36289. }
  36290. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36291. {
  36292. newTransaction();
  36293. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36294. }
  36295. static int findFirstNonWhitespaceChar (const String& line) throw()
  36296. {
  36297. const int len = line.length();
  36298. for (int i = 0; i < len; ++i)
  36299. if (! CharacterFunctions::isWhitespace (line [i]))
  36300. return i;
  36301. return 0;
  36302. }
  36303. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36304. {
  36305. newTransaction();
  36306. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36307. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36308. index = 0;
  36309. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36310. }
  36311. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36312. {
  36313. newTransaction();
  36314. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36315. }
  36316. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36317. {
  36318. newTransaction();
  36319. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36320. }
  36321. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36322. {
  36323. if (moveInWholeWordSteps)
  36324. {
  36325. cut(); // in case something is already highlighted
  36326. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36327. }
  36328. else
  36329. {
  36330. if (selectionStart == selectionEnd)
  36331. selectionStart.moveBy (-1);
  36332. }
  36333. cut();
  36334. }
  36335. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36336. {
  36337. if (moveInWholeWordSteps)
  36338. {
  36339. cut(); // in case something is already highlighted
  36340. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36341. }
  36342. else
  36343. {
  36344. if (selectionStart == selectionEnd)
  36345. selectionEnd.moveBy (1);
  36346. else
  36347. newTransaction();
  36348. }
  36349. cut();
  36350. }
  36351. void CodeEditorComponent::selectAll()
  36352. {
  36353. newTransaction();
  36354. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36355. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36356. }
  36357. void CodeEditorComponent::undo()
  36358. {
  36359. document.undo();
  36360. scrollToKeepCaretOnScreen();
  36361. }
  36362. void CodeEditorComponent::redo()
  36363. {
  36364. document.redo();
  36365. scrollToKeepCaretOnScreen();
  36366. }
  36367. void CodeEditorComponent::newTransaction()
  36368. {
  36369. document.newTransaction();
  36370. startTimer (600);
  36371. }
  36372. void CodeEditorComponent::timerCallback()
  36373. {
  36374. newTransaction();
  36375. }
  36376. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36377. {
  36378. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36379. }
  36380. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36381. {
  36382. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36383. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36384. }
  36385. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36386. {
  36387. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36388. CodeDocument::Position (&document, range.getEnd()));
  36389. }
  36390. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36391. {
  36392. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36393. const bool shiftDown = key.getModifiers().isShiftDown();
  36394. if (key.isKeyCode (KeyPress::leftKey))
  36395. {
  36396. cursorLeft (moveInWholeWordSteps, shiftDown);
  36397. }
  36398. else if (key.isKeyCode (KeyPress::rightKey))
  36399. {
  36400. cursorRight (moveInWholeWordSteps, shiftDown);
  36401. }
  36402. else if (key.isKeyCode (KeyPress::upKey))
  36403. {
  36404. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36405. scrollDown();
  36406. #if JUCE_MAC
  36407. else if (key.getModifiers().isCommandDown())
  36408. goToStartOfDocument (shiftDown);
  36409. #endif
  36410. else
  36411. cursorUp (shiftDown);
  36412. }
  36413. else if (key.isKeyCode (KeyPress::downKey))
  36414. {
  36415. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36416. scrollUp();
  36417. #if JUCE_MAC
  36418. else if (key.getModifiers().isCommandDown())
  36419. goToEndOfDocument (shiftDown);
  36420. #endif
  36421. else
  36422. cursorDown (shiftDown);
  36423. }
  36424. else if (key.isKeyCode (KeyPress::pageDownKey))
  36425. {
  36426. pageDown (shiftDown);
  36427. }
  36428. else if (key.isKeyCode (KeyPress::pageUpKey))
  36429. {
  36430. pageUp (shiftDown);
  36431. }
  36432. else if (key.isKeyCode (KeyPress::homeKey))
  36433. {
  36434. if (moveInWholeWordSteps)
  36435. goToStartOfDocument (shiftDown);
  36436. else
  36437. goToStartOfLine (shiftDown);
  36438. }
  36439. else if (key.isKeyCode (KeyPress::endKey))
  36440. {
  36441. if (moveInWholeWordSteps)
  36442. goToEndOfDocument (shiftDown);
  36443. else
  36444. goToEndOfLine (shiftDown);
  36445. }
  36446. else if (key.isKeyCode (KeyPress::backspaceKey))
  36447. {
  36448. backspace (moveInWholeWordSteps);
  36449. }
  36450. else if (key.isKeyCode (KeyPress::deleteKey))
  36451. {
  36452. deleteForward (moveInWholeWordSteps);
  36453. }
  36454. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36455. {
  36456. copy();
  36457. }
  36458. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36459. {
  36460. copyThenCut();
  36461. }
  36462. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36463. {
  36464. paste();
  36465. }
  36466. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36467. {
  36468. undo();
  36469. }
  36470. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36471. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36472. {
  36473. redo();
  36474. }
  36475. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36476. {
  36477. selectAll();
  36478. }
  36479. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36480. {
  36481. insertTabAtCaret();
  36482. }
  36483. else if (key == KeyPress::returnKey)
  36484. {
  36485. newTransaction();
  36486. insertTextAtCaret (document.getNewLineCharacters());
  36487. }
  36488. else if (key.isKeyCode (KeyPress::escapeKey))
  36489. {
  36490. newTransaction();
  36491. }
  36492. else if (key.getTextCharacter() >= ' ')
  36493. {
  36494. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36495. }
  36496. else
  36497. {
  36498. return false;
  36499. }
  36500. return true;
  36501. }
  36502. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36503. {
  36504. newTransaction();
  36505. dragType = notDragging;
  36506. if (! e.mods.isPopupMenu())
  36507. {
  36508. beginDragAutoRepeat (100);
  36509. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36510. }
  36511. else
  36512. {
  36513. /*PopupMenu m;
  36514. addPopupMenuItems (m, &e);
  36515. const int result = m.show();
  36516. if (result != 0)
  36517. performPopupMenuAction (result);
  36518. */
  36519. }
  36520. }
  36521. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36522. {
  36523. if (! e.mods.isPopupMenu())
  36524. moveCaretTo (getPositionAt (e.x, e.y), true);
  36525. }
  36526. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36527. {
  36528. newTransaction();
  36529. beginDragAutoRepeat (0);
  36530. dragType = notDragging;
  36531. }
  36532. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36533. {
  36534. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36535. CodeDocument::Position tokenEnd (tokenStart);
  36536. if (e.getNumberOfClicks() > 2)
  36537. {
  36538. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36539. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36540. }
  36541. else
  36542. {
  36543. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36544. tokenEnd.moveBy (1);
  36545. tokenStart = tokenEnd;
  36546. while (tokenStart.getIndexInLine() > 0
  36547. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36548. tokenStart.moveBy (-1);
  36549. }
  36550. moveCaretTo (tokenEnd, false);
  36551. moveCaretTo (tokenStart, true);
  36552. }
  36553. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36554. {
  36555. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36556. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36557. {
  36558. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36559. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36560. }
  36561. else
  36562. {
  36563. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36564. }
  36565. }
  36566. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36567. {
  36568. if (scrollBarThatHasMoved == verticalScrollBar)
  36569. scrollToLineInternal ((int) newRangeStart);
  36570. else
  36571. scrollToColumnInternal (newRangeStart);
  36572. }
  36573. void CodeEditorComponent::focusGained (FocusChangeType)
  36574. {
  36575. caret->updatePosition();
  36576. }
  36577. void CodeEditorComponent::focusLost (FocusChangeType)
  36578. {
  36579. caret->updatePosition();
  36580. }
  36581. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36582. {
  36583. useSpacesForTabs = insertSpaces;
  36584. if (spacesPerTab != numSpaces)
  36585. {
  36586. spacesPerTab = numSpaces;
  36587. triggerAsyncUpdate();
  36588. }
  36589. }
  36590. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36591. {
  36592. const String line (document.getLine (lineNum));
  36593. jassert (index <= line.length());
  36594. int col = 0;
  36595. for (int i = 0; i < index; ++i)
  36596. {
  36597. if (line[i] != '\t')
  36598. ++col;
  36599. else
  36600. col += getTabSize() - (col % getTabSize());
  36601. }
  36602. return col;
  36603. }
  36604. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36605. {
  36606. const String line (document.getLine (lineNum));
  36607. const int lineLength = line.length();
  36608. int i, col = 0;
  36609. for (i = 0; i < lineLength; ++i)
  36610. {
  36611. if (line[i] != '\t')
  36612. ++col;
  36613. else
  36614. col += getTabSize() - (col % getTabSize());
  36615. if (col > column)
  36616. break;
  36617. }
  36618. return i;
  36619. }
  36620. void CodeEditorComponent::setFont (const Font& newFont)
  36621. {
  36622. font = newFont;
  36623. charWidth = font.getStringWidthFloat ("0");
  36624. lineHeight = roundToInt (font.getHeight());
  36625. resized();
  36626. }
  36627. void CodeEditorComponent::resetToDefaultColours()
  36628. {
  36629. coloursForTokenCategories.clear();
  36630. if (codeTokeniser != 0)
  36631. {
  36632. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36633. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36634. }
  36635. }
  36636. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36637. {
  36638. jassert (tokenType < 256);
  36639. while (coloursForTokenCategories.size() < tokenType)
  36640. coloursForTokenCategories.add (Colours::black);
  36641. coloursForTokenCategories.set (tokenType, colour);
  36642. repaint();
  36643. }
  36644. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36645. {
  36646. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36647. return findColour (CodeEditorComponent::defaultTextColourId);
  36648. return coloursForTokenCategories.getReference (tokenType);
  36649. }
  36650. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36651. {
  36652. int i;
  36653. for (i = cachedIterators.size(); --i >= 0;)
  36654. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36655. break;
  36656. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36657. }
  36658. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36659. {
  36660. const int maxNumCachedPositions = 5000;
  36661. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36662. if (cachedIterators.size() == 0)
  36663. cachedIterators.add (new CodeDocument::Iterator (&document));
  36664. if (codeTokeniser == 0)
  36665. return;
  36666. for (;;)
  36667. {
  36668. CodeDocument::Iterator* last = cachedIterators.getLast();
  36669. if (last->getLine() >= maxLineNum)
  36670. break;
  36671. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36672. cachedIterators.add (t);
  36673. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36674. for (;;)
  36675. {
  36676. codeTokeniser->readNextToken (*t);
  36677. if (t->getLine() >= targetLine)
  36678. break;
  36679. if (t->isEOF())
  36680. return;
  36681. }
  36682. }
  36683. }
  36684. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36685. {
  36686. if (codeTokeniser == 0)
  36687. return;
  36688. for (int i = cachedIterators.size(); --i >= 0;)
  36689. {
  36690. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36691. if (t->getPosition() <= position)
  36692. {
  36693. source = *t;
  36694. break;
  36695. }
  36696. }
  36697. while (source.getPosition() < position)
  36698. {
  36699. const CodeDocument::Iterator original (source);
  36700. codeTokeniser->readNextToken (source);
  36701. if (source.getPosition() > position || source.isEOF())
  36702. {
  36703. source = original;
  36704. break;
  36705. }
  36706. }
  36707. }
  36708. END_JUCE_NAMESPACE
  36709. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36710. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36711. BEGIN_JUCE_NAMESPACE
  36712. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36713. {
  36714. }
  36715. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36716. {
  36717. }
  36718. namespace CppTokeniser
  36719. {
  36720. static bool isIdentifierStart (const juce_wchar c) throw()
  36721. {
  36722. return CharacterFunctions::isLetter (c)
  36723. || c == '_' || c == '@';
  36724. }
  36725. static bool isIdentifierBody (const juce_wchar c) throw()
  36726. {
  36727. return CharacterFunctions::isLetter (c)
  36728. || CharacterFunctions::isDigit (c)
  36729. || c == '_' || c == '@';
  36730. }
  36731. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36732. {
  36733. static const juce_wchar* keywords2Char[] =
  36734. { T("if"), T("do"), T("or"), 0 };
  36735. static const juce_wchar* keywords3Char[] =
  36736. { T("for"), T("int"), T("new"), T("try"), T("xor"), T("and"), T("asm"), T("not"), 0 };
  36737. static const juce_wchar* keywords4Char[] =
  36738. { T("bool"), T("void"), T("this"), T("true"), T("long"), T("else"), T("char"),
  36739. T("enum"), T("case"), T("goto"), T("auto"), 0 };
  36740. static const juce_wchar* keywords5Char[] =
  36741. { T("while"), T("bitor"), T("break"), T("catch"), T("class"), T("compl"), T("const"), T("false"),
  36742. T("float"), T("short"), T("throw"), T("union"), T("using"), T("or_eq"), 0 };
  36743. static const juce_wchar* keywords6Char[] =
  36744. { T("return"), T("struct"), T("and_eq"), T("bitand"), T("delete"), T("double"), T("extern"),
  36745. T("friend"), T("inline"), T("not_eq"), T("public"), T("sizeof"), T("static"), T("signed"),
  36746. T("switch"), T("typeid"), T("wchar_t"), T("xor_eq"), 0};
  36747. static const juce_wchar* keywordsOther[] =
  36748. { T("const_cast"), T("continue"), T("default"), T("explicit"), T("mutable"), T("namespace"),
  36749. T("operator"), T("private"), T("protected"), T("register"), T("reinterpret_cast"), T("static_cast"),
  36750. T("template"), T("typedef"), T("typename"), T("unsigned"), T("virtual"), T("volatile"),
  36751. T("@implementation"), T("@interface"), T("@end"), T("@synthesize"), T("@dynamic"), T("@public"),
  36752. T("@private"), T("@property"), T("@protected"), T("@class"), 0 };
  36753. int tokenLength = 0;
  36754. juce_wchar possibleIdentifier [19];
  36755. while (isIdentifierBody (source.peekNextChar()))
  36756. {
  36757. const juce_wchar c = source.nextChar();
  36758. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36759. possibleIdentifier [tokenLength] = c;
  36760. ++tokenLength;
  36761. }
  36762. if (tokenLength > 1 && tokenLength <= 16)
  36763. {
  36764. possibleIdentifier [tokenLength] = 0;
  36765. const juce_wchar** k;
  36766. switch (tokenLength)
  36767. {
  36768. case 2: k = keywords2Char; break;
  36769. case 3: k = keywords3Char; break;
  36770. case 4: k = keywords4Char; break;
  36771. case 5: k = keywords5Char; break;
  36772. case 6: k = keywords6Char; break;
  36773. default: k = keywordsOther; break;
  36774. }
  36775. int i = 0;
  36776. while (k[i] != 0)
  36777. {
  36778. if (k[i][0] == possibleIdentifier[0] && CharacterFunctions::compare (k[i], possibleIdentifier) == 0)
  36779. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36780. ++i;
  36781. }
  36782. }
  36783. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36784. }
  36785. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36786. {
  36787. const juce_wchar c = source.peekNextChar();
  36788. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36789. source.skip();
  36790. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36791. return false;
  36792. return true;
  36793. }
  36794. static bool isHexDigit (const juce_wchar c) throw()
  36795. {
  36796. return (c >= '0' && c <= '9')
  36797. || (c >= 'a' && c <= 'f')
  36798. || (c >= 'A' && c <= 'F');
  36799. }
  36800. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36801. {
  36802. if (source.nextChar() != '0')
  36803. return false;
  36804. juce_wchar c = source.nextChar();
  36805. if (c != 'x' && c != 'X')
  36806. return false;
  36807. int numDigits = 0;
  36808. while (isHexDigit (source.peekNextChar()))
  36809. {
  36810. ++numDigits;
  36811. source.skip();
  36812. }
  36813. if (numDigits == 0)
  36814. return false;
  36815. return skipNumberSuffix (source);
  36816. }
  36817. static bool isOctalDigit (const juce_wchar c) throw()
  36818. {
  36819. return c >= '0' && c <= '7';
  36820. }
  36821. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  36822. {
  36823. if (source.nextChar() != '0')
  36824. return false;
  36825. if (! isOctalDigit (source.nextChar()))
  36826. return false;
  36827. while (isOctalDigit (source.peekNextChar()))
  36828. source.skip();
  36829. return skipNumberSuffix (source);
  36830. }
  36831. static bool isDecimalDigit (const juce_wchar c) throw()
  36832. {
  36833. return c >= '0' && c <= '9';
  36834. }
  36835. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  36836. {
  36837. int numChars = 0;
  36838. while (isDecimalDigit (source.peekNextChar()))
  36839. {
  36840. ++numChars;
  36841. source.skip();
  36842. }
  36843. if (numChars == 0)
  36844. return false;
  36845. return skipNumberSuffix (source);
  36846. }
  36847. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  36848. {
  36849. int numDigits = 0;
  36850. while (isDecimalDigit (source.peekNextChar()))
  36851. {
  36852. source.skip();
  36853. ++numDigits;
  36854. }
  36855. const bool hasPoint = (source.peekNextChar() == '.');
  36856. if (hasPoint)
  36857. {
  36858. source.skip();
  36859. while (isDecimalDigit (source.peekNextChar()))
  36860. {
  36861. source.skip();
  36862. ++numDigits;
  36863. }
  36864. }
  36865. if (numDigits == 0)
  36866. return false;
  36867. juce_wchar c = source.peekNextChar();
  36868. const bool hasExponent = (c == 'e' || c == 'E');
  36869. if (hasExponent)
  36870. {
  36871. source.skip();
  36872. c = source.peekNextChar();
  36873. if (c == '+' || c == '-')
  36874. source.skip();
  36875. int numExpDigits = 0;
  36876. while (isDecimalDigit (source.peekNextChar()))
  36877. {
  36878. source.skip();
  36879. ++numExpDigits;
  36880. }
  36881. if (numExpDigits == 0)
  36882. return false;
  36883. }
  36884. c = source.peekNextChar();
  36885. if (c == 'f' || c == 'F')
  36886. source.skip();
  36887. else if (! (hasExponent || hasPoint))
  36888. return false;
  36889. return true;
  36890. }
  36891. static int parseNumber (CodeDocument::Iterator& source)
  36892. {
  36893. const CodeDocument::Iterator original (source);
  36894. if (parseFloatLiteral (source))
  36895. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  36896. source = original;
  36897. if (parseHexLiteral (source))
  36898. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36899. source = original;
  36900. if (parseOctalLiteral (source))
  36901. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36902. source = original;
  36903. if (parseDecimalLiteral (source))
  36904. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36905. source = original;
  36906. source.skip();
  36907. return CPlusPlusCodeTokeniser::tokenType_error;
  36908. }
  36909. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  36910. {
  36911. const juce_wchar quote = source.nextChar();
  36912. for (;;)
  36913. {
  36914. const juce_wchar c = source.nextChar();
  36915. if (c == quote || c == 0)
  36916. break;
  36917. if (c == '\\')
  36918. source.skip();
  36919. }
  36920. }
  36921. static void skipComment (CodeDocument::Iterator& source) throw()
  36922. {
  36923. bool lastWasStar = false;
  36924. for (;;)
  36925. {
  36926. const juce_wchar c = source.nextChar();
  36927. if (c == 0 || (c == '/' && lastWasStar))
  36928. break;
  36929. lastWasStar = (c == '*');
  36930. }
  36931. }
  36932. }
  36933. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  36934. {
  36935. int result = tokenType_error;
  36936. source.skipWhitespace();
  36937. juce_wchar firstChar = source.peekNextChar();
  36938. switch (firstChar)
  36939. {
  36940. case 0:
  36941. source.skip();
  36942. break;
  36943. case '0':
  36944. case '1':
  36945. case '2':
  36946. case '3':
  36947. case '4':
  36948. case '5':
  36949. case '6':
  36950. case '7':
  36951. case '8':
  36952. case '9':
  36953. result = CppTokeniser::parseNumber (source);
  36954. break;
  36955. case '.':
  36956. result = CppTokeniser::parseNumber (source);
  36957. if (result == tokenType_error)
  36958. result = tokenType_punctuation;
  36959. break;
  36960. case ',':
  36961. case ';':
  36962. case ':':
  36963. source.skip();
  36964. result = tokenType_punctuation;
  36965. break;
  36966. case '(':
  36967. case ')':
  36968. case '{':
  36969. case '}':
  36970. case '[':
  36971. case ']':
  36972. source.skip();
  36973. result = tokenType_bracket;
  36974. break;
  36975. case '"':
  36976. case '\'':
  36977. CppTokeniser::skipQuotedString (source);
  36978. result = tokenType_stringLiteral;
  36979. break;
  36980. case '+':
  36981. result = tokenType_operator;
  36982. source.skip();
  36983. if (source.peekNextChar() == '+')
  36984. source.skip();
  36985. else if (source.peekNextChar() == '=')
  36986. source.skip();
  36987. break;
  36988. case '-':
  36989. source.skip();
  36990. result = CppTokeniser::parseNumber (source);
  36991. if (result == tokenType_error)
  36992. {
  36993. result = tokenType_operator;
  36994. if (source.peekNextChar() == '-')
  36995. source.skip();
  36996. else if (source.peekNextChar() == '=')
  36997. source.skip();
  36998. }
  36999. break;
  37000. case '*':
  37001. case '%':
  37002. case '=':
  37003. case '!':
  37004. result = tokenType_operator;
  37005. source.skip();
  37006. if (source.peekNextChar() == '=')
  37007. source.skip();
  37008. break;
  37009. case '/':
  37010. result = tokenType_operator;
  37011. source.skip();
  37012. if (source.peekNextChar() == '=')
  37013. {
  37014. source.skip();
  37015. }
  37016. else if (source.peekNextChar() == '/')
  37017. {
  37018. result = tokenType_comment;
  37019. source.skipToEndOfLine();
  37020. }
  37021. else if (source.peekNextChar() == '*')
  37022. {
  37023. source.skip();
  37024. result = tokenType_comment;
  37025. CppTokeniser::skipComment (source);
  37026. }
  37027. break;
  37028. case '?':
  37029. case '~':
  37030. source.skip();
  37031. result = tokenType_operator;
  37032. break;
  37033. case '<':
  37034. source.skip();
  37035. result = tokenType_operator;
  37036. if (source.peekNextChar() == '=')
  37037. {
  37038. source.skip();
  37039. }
  37040. else if (source.peekNextChar() == '<')
  37041. {
  37042. source.skip();
  37043. if (source.peekNextChar() == '=')
  37044. source.skip();
  37045. }
  37046. break;
  37047. case '>':
  37048. source.skip();
  37049. result = tokenType_operator;
  37050. if (source.peekNextChar() == '=')
  37051. {
  37052. source.skip();
  37053. }
  37054. else if (source.peekNextChar() == '<')
  37055. {
  37056. source.skip();
  37057. if (source.peekNextChar() == '=')
  37058. source.skip();
  37059. }
  37060. break;
  37061. case '|':
  37062. source.skip();
  37063. result = tokenType_operator;
  37064. if (source.peekNextChar() == '=')
  37065. {
  37066. source.skip();
  37067. }
  37068. else if (source.peekNextChar() == '|')
  37069. {
  37070. source.skip();
  37071. if (source.peekNextChar() == '=')
  37072. source.skip();
  37073. }
  37074. break;
  37075. case '&':
  37076. source.skip();
  37077. result = tokenType_operator;
  37078. if (source.peekNextChar() == '=')
  37079. {
  37080. source.skip();
  37081. }
  37082. else if (source.peekNextChar() == '&')
  37083. {
  37084. source.skip();
  37085. if (source.peekNextChar() == '=')
  37086. source.skip();
  37087. }
  37088. break;
  37089. case '^':
  37090. source.skip();
  37091. result = tokenType_operator;
  37092. if (source.peekNextChar() == '=')
  37093. {
  37094. source.skip();
  37095. }
  37096. else if (source.peekNextChar() == '^')
  37097. {
  37098. source.skip();
  37099. if (source.peekNextChar() == '=')
  37100. source.skip();
  37101. }
  37102. break;
  37103. case '#':
  37104. result = tokenType_preprocessor;
  37105. source.skipToEndOfLine();
  37106. break;
  37107. default:
  37108. if (CppTokeniser::isIdentifierStart (firstChar))
  37109. result = CppTokeniser::parseIdentifier (source);
  37110. else
  37111. source.skip();
  37112. break;
  37113. }
  37114. //jassert (result != tokenType_unknown);
  37115. return result;
  37116. }
  37117. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37118. {
  37119. StringArray s;
  37120. s.add ("Error");
  37121. s.add ("Comment");
  37122. s.add ("C++ keyword");
  37123. s.add ("Identifier");
  37124. s.add ("Integer literal");
  37125. s.add ("Float literal");
  37126. s.add ("String literal");
  37127. s.add ("Operator");
  37128. s.add ("Bracket");
  37129. s.add ("Punctuation");
  37130. s.add ("Preprocessor line");
  37131. return s;
  37132. }
  37133. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37134. {
  37135. const uint32 colours[] =
  37136. {
  37137. 0xffcc0000, // error
  37138. 0xff00aa00, // comment
  37139. 0xff0000cc, // keyword
  37140. 0xff000000, // identifier
  37141. 0xff880000, // int literal
  37142. 0xff885500, // float literal
  37143. 0xff990099, // string literal
  37144. 0xff225500, // operator
  37145. 0xff000055, // bracket
  37146. 0xff004400, // punctuation
  37147. 0xff660000 // preprocessor
  37148. };
  37149. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37150. return Colour (colours [tokenType]);
  37151. return Colours::black;
  37152. }
  37153. END_JUCE_NAMESPACE
  37154. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37155. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37156. BEGIN_JUCE_NAMESPACE
  37157. ComboBox::ComboBox (const String& name)
  37158. : Component (name),
  37159. lastCurrentId (0),
  37160. isButtonDown (false),
  37161. separatorPending (false),
  37162. menuActive (false),
  37163. label (0)
  37164. {
  37165. noChoicesMessage = TRANS("(no choices)");
  37166. setRepaintsOnMouseActivity (true);
  37167. lookAndFeelChanged();
  37168. currentId.addListener (this);
  37169. }
  37170. ComboBox::~ComboBox()
  37171. {
  37172. currentId.removeListener (this);
  37173. if (menuActive)
  37174. PopupMenu::dismissAllActiveMenus();
  37175. label = 0;
  37176. deleteAllChildren();
  37177. }
  37178. void ComboBox::setEditableText (const bool isEditable)
  37179. {
  37180. label->setEditable (isEditable, isEditable, false);
  37181. setWantsKeyboardFocus (! isEditable);
  37182. resized();
  37183. }
  37184. bool ComboBox::isTextEditable() const throw()
  37185. {
  37186. return label->isEditable();
  37187. }
  37188. void ComboBox::setJustificationType (const Justification& justification) throw()
  37189. {
  37190. label->setJustificationType (justification);
  37191. }
  37192. const Justification ComboBox::getJustificationType() const throw()
  37193. {
  37194. return label->getJustificationType();
  37195. }
  37196. void ComboBox::setTooltip (const String& newTooltip)
  37197. {
  37198. SettableTooltipClient::setTooltip (newTooltip);
  37199. label->setTooltip (newTooltip);
  37200. }
  37201. void ComboBox::addItem (const String& newItemText,
  37202. const int newItemId) throw()
  37203. {
  37204. // you can't add empty strings to the list..
  37205. jassert (newItemText.isNotEmpty());
  37206. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37207. jassert (newItemId != 0);
  37208. // you shouldn't use duplicate item IDs!
  37209. jassert (getItemForId (newItemId) == 0);
  37210. if (newItemText.isNotEmpty() && newItemId != 0)
  37211. {
  37212. if (separatorPending)
  37213. {
  37214. separatorPending = false;
  37215. ItemInfo* const item = new ItemInfo();
  37216. item->itemId = 0;
  37217. item->isEnabled = false;
  37218. item->isHeading = false;
  37219. items.add (item);
  37220. }
  37221. ItemInfo* const item = new ItemInfo();
  37222. item->name = newItemText;
  37223. item->itemId = newItemId;
  37224. item->isEnabled = true;
  37225. item->isHeading = false;
  37226. items.add (item);
  37227. }
  37228. }
  37229. void ComboBox::addSeparator() throw()
  37230. {
  37231. separatorPending = (items.size() > 0);
  37232. }
  37233. void ComboBox::addSectionHeading (const String& headingName) throw()
  37234. {
  37235. // you can't add empty strings to the list..
  37236. jassert (headingName.isNotEmpty());
  37237. if (headingName.isNotEmpty())
  37238. {
  37239. if (separatorPending)
  37240. {
  37241. separatorPending = false;
  37242. ItemInfo* const item = new ItemInfo();
  37243. item->itemId = 0;
  37244. item->isEnabled = false;
  37245. item->isHeading = false;
  37246. items.add (item);
  37247. }
  37248. ItemInfo* const item = new ItemInfo();
  37249. item->name = headingName;
  37250. item->itemId = 0;
  37251. item->isEnabled = true;
  37252. item->isHeading = true;
  37253. items.add (item);
  37254. }
  37255. }
  37256. void ComboBox::setItemEnabled (const int itemId,
  37257. const bool shouldBeEnabled) throw()
  37258. {
  37259. ItemInfo* const item = getItemForId (itemId);
  37260. if (item != 0)
  37261. item->isEnabled = shouldBeEnabled;
  37262. }
  37263. void ComboBox::changeItemText (const int itemId,
  37264. const String& newText) throw()
  37265. {
  37266. ItemInfo* const item = getItemForId (itemId);
  37267. jassert (item != 0);
  37268. if (item != 0)
  37269. item->name = newText;
  37270. }
  37271. void ComboBox::clear (const bool dontSendChangeMessage)
  37272. {
  37273. items.clear();
  37274. separatorPending = false;
  37275. if (! label->isEditable())
  37276. setSelectedItemIndex (-1, dontSendChangeMessage);
  37277. }
  37278. bool ComboBox::ItemInfo::isSeparator() const throw()
  37279. {
  37280. return name.isEmpty();
  37281. }
  37282. bool ComboBox::ItemInfo::isRealItem() const throw()
  37283. {
  37284. return ! (isHeading || name.isEmpty());
  37285. }
  37286. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37287. {
  37288. if (itemId != 0)
  37289. {
  37290. for (int i = items.size(); --i >= 0;)
  37291. if (items.getUnchecked(i)->itemId == itemId)
  37292. return items.getUnchecked(i);
  37293. }
  37294. return 0;
  37295. }
  37296. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37297. {
  37298. int n = 0;
  37299. for (int i = 0; i < items.size(); ++i)
  37300. {
  37301. ItemInfo* const item = items.getUnchecked(i);
  37302. if (item->isRealItem())
  37303. if (n++ == index)
  37304. return item;
  37305. }
  37306. return 0;
  37307. }
  37308. int ComboBox::getNumItems() const throw()
  37309. {
  37310. int n = 0;
  37311. for (int i = items.size(); --i >= 0;)
  37312. if (items.getUnchecked(i)->isRealItem())
  37313. ++n;
  37314. return n;
  37315. }
  37316. const String ComboBox::getItemText (const int index) const throw()
  37317. {
  37318. const ItemInfo* const item = getItemForIndex (index);
  37319. if (item != 0)
  37320. return item->name;
  37321. return String::empty;
  37322. }
  37323. int ComboBox::getItemId (const int index) const throw()
  37324. {
  37325. const ItemInfo* const item = getItemForIndex (index);
  37326. return (item != 0) ? item->itemId : 0;
  37327. }
  37328. int ComboBox::indexOfItemId (const int itemId) const throw()
  37329. {
  37330. int n = 0;
  37331. for (int i = 0; i < items.size(); ++i)
  37332. {
  37333. const ItemInfo* const item = items.getUnchecked(i);
  37334. if (item->isRealItem())
  37335. {
  37336. if (item->itemId == itemId)
  37337. return n;
  37338. ++n;
  37339. }
  37340. }
  37341. return -1;
  37342. }
  37343. int ComboBox::getSelectedItemIndex() const throw()
  37344. {
  37345. int index = indexOfItemId (currentId.getValue());
  37346. if (getText() != getItemText (index))
  37347. index = -1;
  37348. return index;
  37349. }
  37350. void ComboBox::setSelectedItemIndex (const int index,
  37351. const bool dontSendChangeMessage) throw()
  37352. {
  37353. setSelectedId (getItemId (index), dontSendChangeMessage);
  37354. }
  37355. int ComboBox::getSelectedId() const throw()
  37356. {
  37357. const ItemInfo* const item = getItemForId (currentId.getValue());
  37358. return (item != 0 && getText() == item->name)
  37359. ? item->itemId
  37360. : 0;
  37361. }
  37362. void ComboBox::setSelectedId (const int newItemId,
  37363. const bool dontSendChangeMessage) throw()
  37364. {
  37365. const ItemInfo* const item = getItemForId (newItemId);
  37366. const String newItemText (item != 0 ? item->name : String::empty);
  37367. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37368. {
  37369. if (! dontSendChangeMessage)
  37370. triggerAsyncUpdate();
  37371. label->setText (newItemText, false);
  37372. lastCurrentId = newItemId;
  37373. currentId = newItemId;
  37374. repaint(); // for the benefit of the 'none selected' text
  37375. }
  37376. }
  37377. void ComboBox::valueChanged (Value&)
  37378. {
  37379. if (lastCurrentId != (int) currentId.getValue())
  37380. setSelectedId (currentId.getValue(), false);
  37381. }
  37382. const String ComboBox::getText() const throw()
  37383. {
  37384. return label->getText();
  37385. }
  37386. void ComboBox::setText (const String& newText,
  37387. const bool dontSendChangeMessage) throw()
  37388. {
  37389. for (int i = items.size(); --i >= 0;)
  37390. {
  37391. const ItemInfo* const item = items.getUnchecked(i);
  37392. if (item->isRealItem()
  37393. && item->name == newText)
  37394. {
  37395. setSelectedId (item->itemId, dontSendChangeMessage);
  37396. return;
  37397. }
  37398. }
  37399. lastCurrentId = 0;
  37400. currentId = 0;
  37401. if (label->getText() != newText)
  37402. {
  37403. label->setText (newText, false);
  37404. if (! dontSendChangeMessage)
  37405. triggerAsyncUpdate();
  37406. }
  37407. repaint();
  37408. }
  37409. void ComboBox::showEditor()
  37410. {
  37411. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37412. label->showEditor();
  37413. }
  37414. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37415. {
  37416. textWhenNothingSelected = newMessage;
  37417. repaint();
  37418. }
  37419. const String ComboBox::getTextWhenNothingSelected() const throw()
  37420. {
  37421. return textWhenNothingSelected;
  37422. }
  37423. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37424. {
  37425. noChoicesMessage = newMessage;
  37426. }
  37427. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37428. {
  37429. return noChoicesMessage;
  37430. }
  37431. void ComboBox::paint (Graphics& g)
  37432. {
  37433. getLookAndFeel().drawComboBox (g,
  37434. getWidth(),
  37435. getHeight(),
  37436. isButtonDown,
  37437. label->getRight(),
  37438. 0,
  37439. getWidth() - label->getRight(),
  37440. getHeight(),
  37441. *this);
  37442. if (textWhenNothingSelected.isNotEmpty()
  37443. && label->getText().isEmpty()
  37444. && ! label->isBeingEdited())
  37445. {
  37446. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37447. g.setFont (label->getFont());
  37448. g.drawFittedText (textWhenNothingSelected,
  37449. label->getX() + 2, label->getY() + 1,
  37450. label->getWidth() - 4, label->getHeight() - 2,
  37451. label->getJustificationType(),
  37452. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37453. }
  37454. }
  37455. void ComboBox::resized()
  37456. {
  37457. if (getHeight() > 0 && getWidth() > 0)
  37458. getLookAndFeel().positionComboBoxText (*this, *label);
  37459. }
  37460. void ComboBox::enablementChanged()
  37461. {
  37462. repaint();
  37463. }
  37464. void ComboBox::lookAndFeelChanged()
  37465. {
  37466. repaint();
  37467. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37468. if (label != 0)
  37469. {
  37470. newLabel->setEditable (label->isEditable());
  37471. newLabel->setJustificationType (label->getJustificationType());
  37472. newLabel->setTooltip (label->getTooltip());
  37473. newLabel->setText (label->getText(), false);
  37474. }
  37475. label = newLabel;
  37476. addAndMakeVisible (newLabel);
  37477. newLabel->addListener (this);
  37478. newLabel->addMouseListener (this, false);
  37479. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37480. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37481. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37482. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37483. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37484. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37485. resized();
  37486. }
  37487. void ComboBox::colourChanged()
  37488. {
  37489. lookAndFeelChanged();
  37490. }
  37491. bool ComboBox::keyPressed (const KeyPress& key)
  37492. {
  37493. bool used = false;
  37494. if (key.isKeyCode (KeyPress::upKey)
  37495. || key.isKeyCode (KeyPress::leftKey))
  37496. {
  37497. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37498. used = true;
  37499. }
  37500. else if (key.isKeyCode (KeyPress::downKey)
  37501. || key.isKeyCode (KeyPress::rightKey))
  37502. {
  37503. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37504. used = true;
  37505. }
  37506. else if (key.isKeyCode (KeyPress::returnKey))
  37507. {
  37508. showPopup();
  37509. used = true;
  37510. }
  37511. return used;
  37512. }
  37513. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37514. {
  37515. // only forward key events that aren't used by this component
  37516. return isKeyDown
  37517. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37518. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37519. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37520. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37521. }
  37522. void ComboBox::focusGained (FocusChangeType)
  37523. {
  37524. repaint();
  37525. }
  37526. void ComboBox::focusLost (FocusChangeType)
  37527. {
  37528. repaint();
  37529. }
  37530. void ComboBox::labelTextChanged (Label*)
  37531. {
  37532. triggerAsyncUpdate();
  37533. }
  37534. void ComboBox::showPopup()
  37535. {
  37536. if (! menuActive)
  37537. {
  37538. const int selectedId = getSelectedId();
  37539. Component::SafePointer<Component> deletionWatcher (this);
  37540. PopupMenu menu;
  37541. menu.setLookAndFeel (&getLookAndFeel());
  37542. for (int i = 0; i < items.size(); ++i)
  37543. {
  37544. const ItemInfo* const item = items.getUnchecked(i);
  37545. if (item->isSeparator())
  37546. menu.addSeparator();
  37547. else if (item->isHeading)
  37548. menu.addSectionHeader (item->name);
  37549. else
  37550. menu.addItem (item->itemId, item->name,
  37551. item->isEnabled, item->itemId == selectedId);
  37552. }
  37553. if (items.size() == 0)
  37554. menu.addItem (1, noChoicesMessage, false);
  37555. const int itemHeight = jlimit (12, 24, getHeight());
  37556. menuActive = true;
  37557. const int resultId = menu.showAt (this, selectedId,
  37558. getWidth(), 1, itemHeight);
  37559. if (deletionWatcher == 0)
  37560. return;
  37561. menuActive = false;
  37562. if (resultId != 0)
  37563. setSelectedId (resultId);
  37564. }
  37565. }
  37566. void ComboBox::mouseDown (const MouseEvent& e)
  37567. {
  37568. beginDragAutoRepeat (300);
  37569. isButtonDown = isEnabled();
  37570. if (isButtonDown
  37571. && (e.eventComponent == this || ! label->isEditable()))
  37572. {
  37573. showPopup();
  37574. }
  37575. }
  37576. void ComboBox::mouseDrag (const MouseEvent& e)
  37577. {
  37578. beginDragAutoRepeat (50);
  37579. if (isButtonDown && ! e.mouseWasClicked())
  37580. showPopup();
  37581. }
  37582. void ComboBox::mouseUp (const MouseEvent& e2)
  37583. {
  37584. if (isButtonDown)
  37585. {
  37586. isButtonDown = false;
  37587. repaint();
  37588. const MouseEvent e (e2.getEventRelativeTo (this));
  37589. if (reallyContains (e.x, e.y, true)
  37590. && (e2.eventComponent == this || ! label->isEditable()))
  37591. {
  37592. showPopup();
  37593. }
  37594. }
  37595. }
  37596. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37597. {
  37598. listeners.add (listener);
  37599. }
  37600. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37601. {
  37602. listeners.remove (listener);
  37603. }
  37604. void ComboBox::handleAsyncUpdate()
  37605. {
  37606. Component::BailOutChecker checker (this);
  37607. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37608. }
  37609. END_JUCE_NAMESPACE
  37610. /*** End of inlined file: juce_ComboBox.cpp ***/
  37611. /*** Start of inlined file: juce_Label.cpp ***/
  37612. BEGIN_JUCE_NAMESPACE
  37613. Label::Label (const String& componentName,
  37614. const String& labelText)
  37615. : Component (componentName),
  37616. textValue (labelText),
  37617. lastTextValue (labelText),
  37618. font (15.0f),
  37619. justification (Justification::centredLeft),
  37620. ownerComponent (0),
  37621. horizontalBorderSize (5),
  37622. verticalBorderSize (1),
  37623. minimumHorizontalScale (0.7f),
  37624. editSingleClick (false),
  37625. editDoubleClick (false),
  37626. lossOfFocusDiscardsChanges (false)
  37627. {
  37628. setColour (TextEditor::textColourId, Colours::black);
  37629. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37630. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37631. textValue.addListener (this);
  37632. }
  37633. Label::~Label()
  37634. {
  37635. textValue.removeListener (this);
  37636. if (ownerComponent != 0)
  37637. ownerComponent->removeComponentListener (this);
  37638. editor = 0;
  37639. }
  37640. void Label::setText (const String& newText,
  37641. const bool broadcastChangeMessage)
  37642. {
  37643. hideEditor (true);
  37644. if (lastTextValue != newText)
  37645. {
  37646. lastTextValue = newText;
  37647. textValue = newText;
  37648. repaint();
  37649. textWasChanged();
  37650. if (ownerComponent != 0)
  37651. componentMovedOrResized (*ownerComponent, true, true);
  37652. if (broadcastChangeMessage)
  37653. callChangeListeners();
  37654. }
  37655. }
  37656. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37657. {
  37658. return (returnActiveEditorContents && isBeingEdited())
  37659. ? editor->getText()
  37660. : textValue.toString();
  37661. }
  37662. void Label::valueChanged (Value&)
  37663. {
  37664. if (lastTextValue != textValue.toString())
  37665. setText (textValue.toString(), true);
  37666. }
  37667. void Label::setFont (const Font& newFont) throw()
  37668. {
  37669. font = newFont;
  37670. repaint();
  37671. }
  37672. const Font& Label::getFont() const throw()
  37673. {
  37674. return font;
  37675. }
  37676. void Label::setEditable (const bool editOnSingleClick,
  37677. const bool editOnDoubleClick,
  37678. const bool lossOfFocusDiscardsChanges_) throw()
  37679. {
  37680. editSingleClick = editOnSingleClick;
  37681. editDoubleClick = editOnDoubleClick;
  37682. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37683. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37684. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37685. }
  37686. void Label::setJustificationType (const Justification& justification_) throw()
  37687. {
  37688. justification = justification_;
  37689. repaint();
  37690. }
  37691. void Label::setBorderSize (int h, int v)
  37692. {
  37693. horizontalBorderSize = h;
  37694. verticalBorderSize = v;
  37695. repaint();
  37696. }
  37697. Component* Label::getAttachedComponent() const
  37698. {
  37699. return static_cast<Component*> (ownerComponent);
  37700. }
  37701. void Label::attachToComponent (Component* owner,
  37702. const bool onLeft)
  37703. {
  37704. if (ownerComponent != 0)
  37705. ownerComponent->removeComponentListener (this);
  37706. ownerComponent = owner;
  37707. leftOfOwnerComp = onLeft;
  37708. if (ownerComponent != 0)
  37709. {
  37710. setVisible (owner->isVisible());
  37711. ownerComponent->addComponentListener (this);
  37712. componentParentHierarchyChanged (*ownerComponent);
  37713. componentMovedOrResized (*ownerComponent, true, true);
  37714. }
  37715. }
  37716. void Label::componentMovedOrResized (Component& component,
  37717. bool /*wasMoved*/,
  37718. bool /*wasResized*/)
  37719. {
  37720. if (leftOfOwnerComp)
  37721. {
  37722. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37723. component.getHeight());
  37724. setTopRightPosition (component.getX(), component.getY());
  37725. }
  37726. else
  37727. {
  37728. setSize (component.getWidth(),
  37729. 8 + roundToInt (getFont().getHeight()));
  37730. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37731. }
  37732. }
  37733. void Label::componentParentHierarchyChanged (Component& component)
  37734. {
  37735. if (component.getParentComponent() != 0)
  37736. component.getParentComponent()->addChildComponent (this);
  37737. }
  37738. void Label::componentVisibilityChanged (Component& component)
  37739. {
  37740. setVisible (component.isVisible());
  37741. }
  37742. void Label::textWasEdited()
  37743. {
  37744. }
  37745. void Label::textWasChanged()
  37746. {
  37747. }
  37748. void Label::showEditor()
  37749. {
  37750. if (editor == 0)
  37751. {
  37752. addAndMakeVisible (editor = createEditorComponent());
  37753. editor->setText (getText(), false);
  37754. editor->addListener (this);
  37755. editor->grabKeyboardFocus();
  37756. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37757. editor->addListener (this);
  37758. resized();
  37759. repaint();
  37760. editorShown (editor);
  37761. enterModalState (false);
  37762. editor->grabKeyboardFocus();
  37763. }
  37764. }
  37765. void Label::editorShown (TextEditor* /*editorComponent*/)
  37766. {
  37767. }
  37768. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  37769. {
  37770. }
  37771. bool Label::updateFromTextEditorContents()
  37772. {
  37773. jassert (editor != 0);
  37774. const String newText (editor->getText());
  37775. if (textValue.toString() != newText)
  37776. {
  37777. lastTextValue = newText;
  37778. textValue = newText;
  37779. repaint();
  37780. textWasChanged();
  37781. if (ownerComponent != 0)
  37782. componentMovedOrResized (*ownerComponent, true, true);
  37783. return true;
  37784. }
  37785. return false;
  37786. }
  37787. void Label::hideEditor (const bool discardCurrentEditorContents)
  37788. {
  37789. if (editor != 0)
  37790. {
  37791. Component::SafePointer<Component> deletionChecker (this);
  37792. editorAboutToBeHidden (editor);
  37793. const bool changed = (! discardCurrentEditorContents)
  37794. && updateFromTextEditorContents();
  37795. editor = 0;
  37796. repaint();
  37797. if (changed)
  37798. textWasEdited();
  37799. if (deletionChecker != 0)
  37800. exitModalState (0);
  37801. if (changed && deletionChecker != 0)
  37802. callChangeListeners();
  37803. }
  37804. }
  37805. void Label::inputAttemptWhenModal()
  37806. {
  37807. if (editor != 0)
  37808. {
  37809. if (lossOfFocusDiscardsChanges)
  37810. textEditorEscapeKeyPressed (*editor);
  37811. else
  37812. textEditorReturnKeyPressed (*editor);
  37813. }
  37814. }
  37815. bool Label::isBeingEdited() const throw()
  37816. {
  37817. return editor != 0;
  37818. }
  37819. TextEditor* Label::createEditorComponent()
  37820. {
  37821. TextEditor* const ed = new TextEditor (getName());
  37822. ed->setFont (font);
  37823. // copy these colours from our own settings..
  37824. const int cols[] = { TextEditor::backgroundColourId,
  37825. TextEditor::textColourId,
  37826. TextEditor::highlightColourId,
  37827. TextEditor::highlightedTextColourId,
  37828. TextEditor::caretColourId,
  37829. TextEditor::outlineColourId,
  37830. TextEditor::focusedOutlineColourId,
  37831. TextEditor::shadowColourId };
  37832. for (int i = 0; i < numElementsInArray (cols); ++i)
  37833. ed->setColour (cols[i], findColour (cols[i]));
  37834. return ed;
  37835. }
  37836. void Label::paint (Graphics& g)
  37837. {
  37838. getLookAndFeel().drawLabel (g, *this);
  37839. }
  37840. void Label::mouseUp (const MouseEvent& e)
  37841. {
  37842. if (editSingleClick
  37843. && e.mouseWasClicked()
  37844. && contains (e.x, e.y)
  37845. && ! e.mods.isPopupMenu())
  37846. {
  37847. showEditor();
  37848. }
  37849. }
  37850. void Label::mouseDoubleClick (const MouseEvent& e)
  37851. {
  37852. if (editDoubleClick && ! e.mods.isPopupMenu())
  37853. showEditor();
  37854. }
  37855. void Label::resized()
  37856. {
  37857. if (editor != 0)
  37858. editor->setBoundsInset (BorderSize (0));
  37859. }
  37860. void Label::focusGained (FocusChangeType cause)
  37861. {
  37862. if (editSingleClick && cause == focusChangedByTabKey)
  37863. showEditor();
  37864. }
  37865. void Label::enablementChanged()
  37866. {
  37867. repaint();
  37868. }
  37869. void Label::colourChanged()
  37870. {
  37871. repaint();
  37872. }
  37873. void Label::setMinimumHorizontalScale (const float newScale)
  37874. {
  37875. if (minimumHorizontalScale != newScale)
  37876. {
  37877. minimumHorizontalScale = newScale;
  37878. repaint();
  37879. }
  37880. }
  37881. // We'll use a custom focus traverser here to make sure focus goes from the
  37882. // text editor to another component rather than back to the label itself.
  37883. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  37884. {
  37885. public:
  37886. LabelKeyboardFocusTraverser() {}
  37887. Component* getNextComponent (Component* current)
  37888. {
  37889. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  37890. ? current->getParentComponent() : current);
  37891. }
  37892. Component* getPreviousComponent (Component* current)
  37893. {
  37894. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  37895. ? current->getParentComponent() : current);
  37896. }
  37897. };
  37898. KeyboardFocusTraverser* Label::createFocusTraverser()
  37899. {
  37900. return new LabelKeyboardFocusTraverser();
  37901. }
  37902. void Label::addListener (LabelListener* const listener) throw()
  37903. {
  37904. listeners.add (listener);
  37905. }
  37906. void Label::removeListener (LabelListener* const listener) throw()
  37907. {
  37908. listeners.remove (listener);
  37909. }
  37910. void Label::callChangeListeners()
  37911. {
  37912. Component::BailOutChecker checker (this);
  37913. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  37914. }
  37915. void Label::textEditorTextChanged (TextEditor& ed)
  37916. {
  37917. if (editor != 0)
  37918. {
  37919. jassert (&ed == editor);
  37920. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  37921. {
  37922. if (lossOfFocusDiscardsChanges)
  37923. textEditorEscapeKeyPressed (ed);
  37924. else
  37925. textEditorReturnKeyPressed (ed);
  37926. }
  37927. }
  37928. }
  37929. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  37930. {
  37931. if (editor != 0)
  37932. {
  37933. jassert (&ed == editor);
  37934. (void) ed;
  37935. const bool changed = updateFromTextEditorContents();
  37936. hideEditor (true);
  37937. if (changed)
  37938. {
  37939. Component::SafePointer<Component> deletionChecker (this);
  37940. textWasEdited();
  37941. if (deletionChecker != 0)
  37942. callChangeListeners();
  37943. }
  37944. }
  37945. }
  37946. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  37947. {
  37948. if (editor != 0)
  37949. {
  37950. jassert (&ed == editor);
  37951. (void) ed;
  37952. editor->setText (textValue.toString(), false);
  37953. hideEditor (true);
  37954. }
  37955. }
  37956. void Label::textEditorFocusLost (TextEditor& ed)
  37957. {
  37958. textEditorTextChanged (ed);
  37959. }
  37960. END_JUCE_NAMESPACE
  37961. /*** End of inlined file: juce_Label.cpp ***/
  37962. /*** Start of inlined file: juce_ListBox.cpp ***/
  37963. BEGIN_JUCE_NAMESPACE
  37964. class ListBoxRowComponent : public Component,
  37965. public TooltipClient
  37966. {
  37967. public:
  37968. ListBoxRowComponent (ListBox& owner_)
  37969. : owner (owner_),
  37970. row (-1),
  37971. selected (false),
  37972. isDragging (false)
  37973. {
  37974. }
  37975. ~ListBoxRowComponent()
  37976. {
  37977. deleteAllChildren();
  37978. }
  37979. void paint (Graphics& g)
  37980. {
  37981. if (owner.getModel() != 0)
  37982. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  37983. }
  37984. void update (const int row_, const bool selected_)
  37985. {
  37986. if (row != row_ || selected != selected_)
  37987. {
  37988. repaint();
  37989. row = row_;
  37990. selected = selected_;
  37991. }
  37992. if (owner.getModel() != 0)
  37993. {
  37994. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  37995. if (customComp != 0)
  37996. {
  37997. addAndMakeVisible (customComp);
  37998. customComp->setBounds (0, 0, getWidth(), getHeight());
  37999. for (int i = getNumChildComponents(); --i >= 0;)
  38000. if (getChildComponent (i) != customComp)
  38001. delete getChildComponent (i);
  38002. }
  38003. else
  38004. {
  38005. deleteAllChildren();
  38006. }
  38007. }
  38008. }
  38009. void mouseDown (const MouseEvent& e)
  38010. {
  38011. isDragging = false;
  38012. selectRowOnMouseUp = false;
  38013. if (isEnabled())
  38014. {
  38015. if (! selected)
  38016. {
  38017. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38018. if (owner.getModel() != 0)
  38019. owner.getModel()->listBoxItemClicked (row, e);
  38020. }
  38021. else
  38022. {
  38023. selectRowOnMouseUp = true;
  38024. }
  38025. }
  38026. }
  38027. void mouseUp (const MouseEvent& e)
  38028. {
  38029. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38030. {
  38031. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38032. if (owner.getModel() != 0)
  38033. owner.getModel()->listBoxItemClicked (row, e);
  38034. }
  38035. }
  38036. void mouseDoubleClick (const MouseEvent& e)
  38037. {
  38038. if (owner.getModel() != 0 && isEnabled())
  38039. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38040. }
  38041. void mouseDrag (const MouseEvent& e)
  38042. {
  38043. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38044. {
  38045. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38046. if (selectedRows.size() > 0)
  38047. {
  38048. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38049. if (dragDescription.isNotEmpty())
  38050. {
  38051. isDragging = true;
  38052. owner.startDragAndDrop (e, dragDescription);
  38053. }
  38054. }
  38055. }
  38056. }
  38057. void resized()
  38058. {
  38059. if (getNumChildComponents() > 0)
  38060. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  38061. }
  38062. const String getTooltip()
  38063. {
  38064. if (owner.getModel() != 0)
  38065. return owner.getModel()->getTooltipForRow (row);
  38066. return String::empty;
  38067. }
  38068. juce_UseDebuggingNewOperator
  38069. bool neededFlag;
  38070. private:
  38071. ListBox& owner;
  38072. int row;
  38073. bool selected, isDragging, selectRowOnMouseUp;
  38074. ListBoxRowComponent (const ListBoxRowComponent&);
  38075. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38076. };
  38077. class ListViewport : public Viewport
  38078. {
  38079. public:
  38080. int firstIndex, firstWholeIndex, lastWholeIndex;
  38081. bool hasUpdated;
  38082. ListViewport (ListBox& owner_)
  38083. : owner (owner_)
  38084. {
  38085. setWantsKeyboardFocus (false);
  38086. setViewedComponent (new Component());
  38087. getViewedComponent()->addMouseListener (this, false);
  38088. getViewedComponent()->setWantsKeyboardFocus (false);
  38089. }
  38090. ~ListViewport()
  38091. {
  38092. getViewedComponent()->removeMouseListener (this);
  38093. getViewedComponent()->deleteAllChildren();
  38094. }
  38095. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38096. {
  38097. return static_cast <ListBoxRowComponent*>
  38098. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38099. }
  38100. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38101. {
  38102. const int index = getIndexOfChildComponent (rowComponent);
  38103. const int num = getViewedComponent()->getNumChildComponents();
  38104. for (int i = num; --i >= 0;)
  38105. if (((firstIndex + i) % jmax (1, num)) == index)
  38106. return firstIndex + i;
  38107. return -1;
  38108. }
  38109. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38110. {
  38111. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38112. ? getComponentForRow (row) : 0;
  38113. }
  38114. void visibleAreaChanged (int, int, int, int)
  38115. {
  38116. updateVisibleArea (true);
  38117. if (owner.getModel() != 0)
  38118. owner.getModel()->listWasScrolled();
  38119. }
  38120. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38121. {
  38122. hasUpdated = false;
  38123. const int newX = getViewedComponent()->getX();
  38124. int newY = getViewedComponent()->getY();
  38125. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38126. const int newH = owner.totalItems * owner.getRowHeight();
  38127. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38128. newY = getMaximumVisibleHeight() - newH;
  38129. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38130. if (makeSureItUpdatesContent && ! hasUpdated)
  38131. updateContents();
  38132. }
  38133. void updateContents()
  38134. {
  38135. hasUpdated = true;
  38136. const int rowHeight = owner.getRowHeight();
  38137. if (rowHeight > 0)
  38138. {
  38139. const int y = getViewPositionY();
  38140. const int w = getViewedComponent()->getWidth();
  38141. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38142. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38143. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38144. jassert (numNeeded >= 0);
  38145. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38146. {
  38147. Component* const rowToRemove
  38148. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38149. delete rowToRemove;
  38150. }
  38151. firstIndex = y / rowHeight;
  38152. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38153. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38154. for (int i = 0; i < numNeeded; ++i)
  38155. {
  38156. const int row = i + firstIndex;
  38157. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38158. if (rowComp != 0)
  38159. {
  38160. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38161. rowComp->update (row, owner.isRowSelected (row));
  38162. }
  38163. }
  38164. }
  38165. if (owner.headerComponent != 0)
  38166. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38167. owner.outlineThickness,
  38168. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38169. getViewedComponent()->getWidth()),
  38170. owner.headerComponent->getHeight());
  38171. }
  38172. void paint (Graphics& g)
  38173. {
  38174. if (isOpaque())
  38175. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38176. }
  38177. bool keyPressed (const KeyPress& key)
  38178. {
  38179. if (key.isKeyCode (KeyPress::upKey)
  38180. || key.isKeyCode (KeyPress::downKey)
  38181. || key.isKeyCode (KeyPress::pageUpKey)
  38182. || key.isKeyCode (KeyPress::pageDownKey)
  38183. || key.isKeyCode (KeyPress::homeKey)
  38184. || key.isKeyCode (KeyPress::endKey))
  38185. {
  38186. // we want to avoid these keypresses going to the viewport, and instead allow
  38187. // them to pass up to our listbox..
  38188. return false;
  38189. }
  38190. return Viewport::keyPressed (key);
  38191. }
  38192. juce_UseDebuggingNewOperator
  38193. private:
  38194. ListBox& owner;
  38195. ListViewport (const ListViewport&);
  38196. ListViewport& operator= (const ListViewport&);
  38197. };
  38198. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38199. : Component (name),
  38200. model (model_),
  38201. headerComponent (0),
  38202. totalItems (0),
  38203. rowHeight (22),
  38204. minimumRowWidth (0),
  38205. outlineThickness (0),
  38206. lastRowSelected (-1),
  38207. mouseMoveSelects (false),
  38208. multipleSelection (false),
  38209. hasDoneInitialUpdate (false)
  38210. {
  38211. addAndMakeVisible (viewport = new ListViewport (*this));
  38212. setWantsKeyboardFocus (true);
  38213. colourChanged();
  38214. }
  38215. ListBox::~ListBox()
  38216. {
  38217. deleteAllChildren();
  38218. }
  38219. void ListBox::setModel (ListBoxModel* const newModel)
  38220. {
  38221. if (model != newModel)
  38222. {
  38223. model = newModel;
  38224. updateContent();
  38225. }
  38226. }
  38227. void ListBox::setMultipleSelectionEnabled (bool b)
  38228. {
  38229. multipleSelection = b;
  38230. }
  38231. void ListBox::setMouseMoveSelectsRows (bool b)
  38232. {
  38233. mouseMoveSelects = b;
  38234. if (b)
  38235. addMouseListener (this, true);
  38236. }
  38237. void ListBox::paint (Graphics& g)
  38238. {
  38239. if (! hasDoneInitialUpdate)
  38240. updateContent();
  38241. g.fillAll (findColour (backgroundColourId));
  38242. }
  38243. void ListBox::paintOverChildren (Graphics& g)
  38244. {
  38245. if (outlineThickness > 0)
  38246. {
  38247. g.setColour (findColour (outlineColourId));
  38248. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38249. }
  38250. }
  38251. void ListBox::resized()
  38252. {
  38253. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38254. outlineThickness,
  38255. outlineThickness,
  38256. outlineThickness));
  38257. viewport->setSingleStepSizes (20, getRowHeight());
  38258. viewport->updateVisibleArea (false);
  38259. }
  38260. void ListBox::visibilityChanged()
  38261. {
  38262. viewport->updateVisibleArea (true);
  38263. }
  38264. Viewport* ListBox::getViewport() const throw()
  38265. {
  38266. return viewport;
  38267. }
  38268. void ListBox::updateContent()
  38269. {
  38270. hasDoneInitialUpdate = true;
  38271. totalItems = (model != 0) ? model->getNumRows() : 0;
  38272. bool selectionChanged = false;
  38273. if (selected [selected.size() - 1] >= totalItems)
  38274. {
  38275. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38276. lastRowSelected = getSelectedRow (0);
  38277. selectionChanged = true;
  38278. }
  38279. viewport->updateVisibleArea (isVisible());
  38280. viewport->resized();
  38281. if (selectionChanged && model != 0)
  38282. model->selectedRowsChanged (lastRowSelected);
  38283. }
  38284. void ListBox::selectRow (const int row,
  38285. bool dontScroll,
  38286. bool deselectOthersFirst)
  38287. {
  38288. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38289. }
  38290. void ListBox::selectRowInternal (const int row,
  38291. bool dontScroll,
  38292. bool deselectOthersFirst,
  38293. bool isMouseClick)
  38294. {
  38295. if (! multipleSelection)
  38296. deselectOthersFirst = true;
  38297. if ((! isRowSelected (row))
  38298. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38299. {
  38300. if (((unsigned int) row) < (unsigned int) totalItems)
  38301. {
  38302. if (deselectOthersFirst)
  38303. selected.clear();
  38304. selected.addRange (Range<int> (row, row + 1));
  38305. if (getHeight() == 0 || getWidth() == 0)
  38306. dontScroll = true;
  38307. viewport->hasUpdated = false;
  38308. if (row < viewport->firstWholeIndex && ! dontScroll)
  38309. {
  38310. viewport->setViewPosition (viewport->getViewPositionX(),
  38311. row * getRowHeight());
  38312. }
  38313. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38314. {
  38315. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38316. if (row >= lastRowSelected + rowsOnScreen
  38317. && rowsOnScreen < totalItems - 1
  38318. && ! isMouseClick)
  38319. {
  38320. viewport->setViewPosition (viewport->getViewPositionX(),
  38321. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38322. * getRowHeight());
  38323. }
  38324. else
  38325. {
  38326. viewport->setViewPosition (viewport->getViewPositionX(),
  38327. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38328. }
  38329. }
  38330. if (! viewport->hasUpdated)
  38331. viewport->updateContents();
  38332. lastRowSelected = row;
  38333. model->selectedRowsChanged (row);
  38334. }
  38335. else
  38336. {
  38337. if (deselectOthersFirst)
  38338. deselectAllRows();
  38339. }
  38340. }
  38341. }
  38342. void ListBox::deselectRow (const int row)
  38343. {
  38344. if (selected.contains (row))
  38345. {
  38346. selected.removeRange (Range <int> (row, row + 1));
  38347. if (row == lastRowSelected)
  38348. lastRowSelected = getSelectedRow (0);
  38349. viewport->updateContents();
  38350. model->selectedRowsChanged (lastRowSelected);
  38351. }
  38352. }
  38353. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38354. const bool sendNotificationEventToModel)
  38355. {
  38356. selected = setOfRowsToBeSelected;
  38357. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38358. if (! isRowSelected (lastRowSelected))
  38359. lastRowSelected = getSelectedRow (0);
  38360. viewport->updateContents();
  38361. if ((model != 0) && sendNotificationEventToModel)
  38362. model->selectedRowsChanged (lastRowSelected);
  38363. }
  38364. const SparseSet<int> ListBox::getSelectedRows() const
  38365. {
  38366. return selected;
  38367. }
  38368. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38369. {
  38370. if (multipleSelection && (firstRow != lastRow))
  38371. {
  38372. const int numRows = totalItems - 1;
  38373. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38374. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38375. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38376. jmax (firstRow, lastRow) + 1));
  38377. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38378. }
  38379. selectRowInternal (lastRow, false, false, true);
  38380. }
  38381. void ListBox::flipRowSelection (const int row)
  38382. {
  38383. if (isRowSelected (row))
  38384. deselectRow (row);
  38385. else
  38386. selectRowInternal (row, false, false, true);
  38387. }
  38388. void ListBox::deselectAllRows()
  38389. {
  38390. if (! selected.isEmpty())
  38391. {
  38392. selected.clear();
  38393. lastRowSelected = -1;
  38394. viewport->updateContents();
  38395. if (model != 0)
  38396. model->selectedRowsChanged (lastRowSelected);
  38397. }
  38398. }
  38399. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38400. const ModifierKeys& mods)
  38401. {
  38402. if (multipleSelection && mods.isCommandDown())
  38403. {
  38404. flipRowSelection (row);
  38405. }
  38406. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38407. {
  38408. selectRangeOfRows (lastRowSelected, row);
  38409. }
  38410. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38411. {
  38412. selectRowInternal (row, false, true, true);
  38413. }
  38414. }
  38415. int ListBox::getNumSelectedRows() const
  38416. {
  38417. return selected.size();
  38418. }
  38419. int ListBox::getSelectedRow (const int index) const
  38420. {
  38421. return (((unsigned int) index) < (unsigned int) selected.size())
  38422. ? selected [index] : -1;
  38423. }
  38424. bool ListBox::isRowSelected (const int row) const
  38425. {
  38426. return selected.contains (row);
  38427. }
  38428. int ListBox::getLastRowSelected() const
  38429. {
  38430. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38431. }
  38432. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38433. {
  38434. if (((unsigned int) x) < (unsigned int) getWidth())
  38435. {
  38436. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38437. if (((unsigned int) row) < (unsigned int) totalItems)
  38438. return row;
  38439. }
  38440. return -1;
  38441. }
  38442. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38443. {
  38444. if (((unsigned int) x) < (unsigned int) getWidth())
  38445. {
  38446. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38447. return jlimit (0, totalItems, row);
  38448. }
  38449. return -1;
  38450. }
  38451. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38452. {
  38453. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38454. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38455. }
  38456. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38457. {
  38458. return viewport->getRowNumberOfComponent (rowComponent);
  38459. }
  38460. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38461. const bool relativeToComponentTopLeft) const throw()
  38462. {
  38463. int y = viewport->getY() + rowHeight * rowNumber;
  38464. if (relativeToComponentTopLeft)
  38465. y -= viewport->getViewPositionY();
  38466. return Rectangle<int> (viewport->getX(), y,
  38467. viewport->getViewedComponent()->getWidth(), rowHeight);
  38468. }
  38469. void ListBox::setVerticalPosition (const double proportion)
  38470. {
  38471. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38472. viewport->setViewPosition (viewport->getViewPositionX(),
  38473. jmax (0, roundToInt (proportion * offscreen)));
  38474. }
  38475. double ListBox::getVerticalPosition() const
  38476. {
  38477. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38478. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38479. : 0;
  38480. }
  38481. int ListBox::getVisibleRowWidth() const throw()
  38482. {
  38483. return viewport->getViewWidth();
  38484. }
  38485. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38486. {
  38487. if (row < viewport->firstWholeIndex)
  38488. {
  38489. viewport->setViewPosition (viewport->getViewPositionX(),
  38490. row * getRowHeight());
  38491. }
  38492. else if (row >= viewport->lastWholeIndex)
  38493. {
  38494. viewport->setViewPosition (viewport->getViewPositionX(),
  38495. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38496. }
  38497. }
  38498. bool ListBox::keyPressed (const KeyPress& key)
  38499. {
  38500. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38501. const bool multiple = multipleSelection
  38502. && (lastRowSelected >= 0)
  38503. && (key.getModifiers().isShiftDown()
  38504. || key.getModifiers().isCtrlDown()
  38505. || key.getModifiers().isCommandDown());
  38506. if (key.isKeyCode (KeyPress::upKey))
  38507. {
  38508. if (multiple)
  38509. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38510. else
  38511. selectRow (jmax (0, lastRowSelected - 1));
  38512. }
  38513. else if (key.isKeyCode (KeyPress::returnKey)
  38514. && isRowSelected (lastRowSelected))
  38515. {
  38516. if (model != 0)
  38517. model->returnKeyPressed (lastRowSelected);
  38518. }
  38519. else if (key.isKeyCode (KeyPress::pageUpKey))
  38520. {
  38521. if (multiple)
  38522. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38523. else
  38524. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38525. }
  38526. else if (key.isKeyCode (KeyPress::pageDownKey))
  38527. {
  38528. if (multiple)
  38529. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38530. else
  38531. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38532. }
  38533. else if (key.isKeyCode (KeyPress::homeKey))
  38534. {
  38535. if (multiple && key.getModifiers().isShiftDown())
  38536. selectRangeOfRows (lastRowSelected, 0);
  38537. else
  38538. selectRow (0);
  38539. }
  38540. else if (key.isKeyCode (KeyPress::endKey))
  38541. {
  38542. if (multiple && key.getModifiers().isShiftDown())
  38543. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38544. else
  38545. selectRow (totalItems - 1);
  38546. }
  38547. else if (key.isKeyCode (KeyPress::downKey))
  38548. {
  38549. if (multiple)
  38550. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38551. else
  38552. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38553. }
  38554. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38555. && isRowSelected (lastRowSelected))
  38556. {
  38557. if (model != 0)
  38558. model->deleteKeyPressed (lastRowSelected);
  38559. }
  38560. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38561. {
  38562. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38563. }
  38564. else
  38565. {
  38566. return false;
  38567. }
  38568. return true;
  38569. }
  38570. bool ListBox::keyStateChanged (const bool isKeyDown)
  38571. {
  38572. return isKeyDown
  38573. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38574. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38575. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38576. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38577. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38578. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38579. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38580. }
  38581. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38582. {
  38583. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38584. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38585. }
  38586. void ListBox::mouseMove (const MouseEvent& e)
  38587. {
  38588. if (mouseMoveSelects)
  38589. {
  38590. const MouseEvent e2 (e.getEventRelativeTo (this));
  38591. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38592. }
  38593. }
  38594. void ListBox::mouseExit (const MouseEvent& e)
  38595. {
  38596. mouseMove (e);
  38597. }
  38598. void ListBox::mouseUp (const MouseEvent& e)
  38599. {
  38600. if (e.mouseWasClicked() && model != 0)
  38601. model->backgroundClicked();
  38602. }
  38603. void ListBox::setRowHeight (const int newHeight)
  38604. {
  38605. rowHeight = jmax (1, newHeight);
  38606. viewport->setSingleStepSizes (20, rowHeight);
  38607. updateContent();
  38608. }
  38609. int ListBox::getNumRowsOnScreen() const throw()
  38610. {
  38611. return viewport->getMaximumVisibleHeight() / rowHeight;
  38612. }
  38613. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38614. {
  38615. minimumRowWidth = newMinimumWidth;
  38616. updateContent();
  38617. }
  38618. int ListBox::getVisibleContentWidth() const throw()
  38619. {
  38620. return viewport->getMaximumVisibleWidth();
  38621. }
  38622. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38623. {
  38624. return viewport->getVerticalScrollBar();
  38625. }
  38626. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38627. {
  38628. return viewport->getHorizontalScrollBar();
  38629. }
  38630. void ListBox::colourChanged()
  38631. {
  38632. setOpaque (findColour (backgroundColourId).isOpaque());
  38633. viewport->setOpaque (isOpaque());
  38634. repaint();
  38635. }
  38636. void ListBox::setOutlineThickness (const int outlineThickness_)
  38637. {
  38638. outlineThickness = outlineThickness_;
  38639. resized();
  38640. }
  38641. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38642. {
  38643. if (headerComponent != newHeaderComponent)
  38644. {
  38645. delete headerComponent;
  38646. headerComponent = newHeaderComponent;
  38647. addAndMakeVisible (newHeaderComponent);
  38648. ListBox::resized();
  38649. }
  38650. }
  38651. void ListBox::repaintRow (const int rowNumber) throw()
  38652. {
  38653. const Rectangle<int> r (getRowPosition (rowNumber, true));
  38654. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  38655. }
  38656. Image* ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38657. {
  38658. Rectangle<int> imageArea;
  38659. const int firstRow = getRowContainingPosition (0, 0);
  38660. int i;
  38661. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38662. {
  38663. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38664. if (rowComp != 0 && isRowSelected (firstRow + i))
  38665. {
  38666. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38667. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38668. if (imageArea.isEmpty())
  38669. imageArea = rowRect;
  38670. else
  38671. imageArea = imageArea.getUnion (rowRect);
  38672. }
  38673. }
  38674. imageArea = imageArea.getIntersection (getLocalBounds());
  38675. imageX = imageArea.getX();
  38676. imageY = imageArea.getY();
  38677. Image* snapshot = Image::createNativeImage (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true);
  38678. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38679. {
  38680. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38681. if (rowComp != 0 && isRowSelected (firstRow + i))
  38682. {
  38683. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38684. Graphics g (*snapshot);
  38685. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38686. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38687. rowComp->paintEntireComponent (g);
  38688. }
  38689. }
  38690. return snapshot;
  38691. }
  38692. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38693. {
  38694. DragAndDropContainer* const dragContainer
  38695. = DragAndDropContainer::findParentDragContainerFor (this);
  38696. if (dragContainer != 0)
  38697. {
  38698. int x, y;
  38699. Image* dragImage = createSnapshotOfSelectedRows (x, y);
  38700. dragImage->multiplyAllAlphas (0.6f);
  38701. MouseEvent e2 (e.getEventRelativeTo (this));
  38702. const Point<int> p (x - e2.x, y - e2.y);
  38703. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38704. }
  38705. else
  38706. {
  38707. // to be able to do a drag-and-drop operation, the listbox needs to
  38708. // be inside a component which is also a DragAndDropContainer.
  38709. jassertfalse
  38710. }
  38711. }
  38712. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38713. {
  38714. (void) existingComponentToUpdate;
  38715. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38716. return 0;
  38717. }
  38718. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38719. {
  38720. }
  38721. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38722. {
  38723. }
  38724. void ListBoxModel::backgroundClicked()
  38725. {
  38726. }
  38727. void ListBoxModel::selectedRowsChanged (int)
  38728. {
  38729. }
  38730. void ListBoxModel::deleteKeyPressed (int)
  38731. {
  38732. }
  38733. void ListBoxModel::returnKeyPressed (int)
  38734. {
  38735. }
  38736. void ListBoxModel::listWasScrolled()
  38737. {
  38738. }
  38739. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38740. {
  38741. return String::empty;
  38742. }
  38743. const String ListBoxModel::getTooltipForRow (int)
  38744. {
  38745. return String::empty;
  38746. }
  38747. END_JUCE_NAMESPACE
  38748. /*** End of inlined file: juce_ListBox.cpp ***/
  38749. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38750. BEGIN_JUCE_NAMESPACE
  38751. ProgressBar::ProgressBar (double& progress_)
  38752. : progress (progress_),
  38753. displayPercentage (true),
  38754. lastCallbackTime (0)
  38755. {
  38756. currentValue = jlimit (0.0, 1.0, progress);
  38757. }
  38758. ProgressBar::~ProgressBar()
  38759. {
  38760. }
  38761. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38762. {
  38763. displayPercentage = shouldDisplayPercentage;
  38764. repaint();
  38765. }
  38766. void ProgressBar::setTextToDisplay (const String& text)
  38767. {
  38768. displayPercentage = false;
  38769. displayedMessage = text;
  38770. }
  38771. void ProgressBar::lookAndFeelChanged()
  38772. {
  38773. setOpaque (findColour (backgroundColourId).isOpaque());
  38774. }
  38775. void ProgressBar::colourChanged()
  38776. {
  38777. lookAndFeelChanged();
  38778. }
  38779. void ProgressBar::paint (Graphics& g)
  38780. {
  38781. String text;
  38782. if (displayPercentage)
  38783. {
  38784. if (currentValue >= 0 && currentValue <= 1.0)
  38785. text << roundToInt (currentValue * 100.0) << '%';
  38786. }
  38787. else
  38788. {
  38789. text = displayedMessage;
  38790. }
  38791. getLookAndFeel().drawProgressBar (g, *this,
  38792. getWidth(), getHeight(),
  38793. currentValue, text);
  38794. }
  38795. void ProgressBar::visibilityChanged()
  38796. {
  38797. if (isVisible())
  38798. startTimer (30);
  38799. else
  38800. stopTimer();
  38801. }
  38802. void ProgressBar::timerCallback()
  38803. {
  38804. double newProgress = progress;
  38805. const uint32 now = Time::getMillisecondCounter();
  38806. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  38807. lastCallbackTime = now;
  38808. if (currentValue != newProgress
  38809. || newProgress < 0 || newProgress >= 1.0
  38810. || currentMessage != displayedMessage)
  38811. {
  38812. if (currentValue < newProgress
  38813. && newProgress >= 0 && newProgress < 1.0
  38814. && currentValue >= 0 && currentValue < 1.0)
  38815. {
  38816. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  38817. newProgress);
  38818. }
  38819. currentValue = newProgress;
  38820. currentMessage = displayedMessage;
  38821. repaint();
  38822. }
  38823. }
  38824. END_JUCE_NAMESPACE
  38825. /*** End of inlined file: juce_ProgressBar.cpp ***/
  38826. /*** Start of inlined file: juce_Slider.cpp ***/
  38827. BEGIN_JUCE_NAMESPACE
  38828. class SliderPopupDisplayComponent : public BubbleComponent
  38829. {
  38830. public:
  38831. SliderPopupDisplayComponent (Slider* const owner_)
  38832. : owner (owner_),
  38833. font (15.0f, Font::bold)
  38834. {
  38835. setAlwaysOnTop (true);
  38836. }
  38837. ~SliderPopupDisplayComponent()
  38838. {
  38839. }
  38840. void paintContent (Graphics& g, int w, int h)
  38841. {
  38842. g.setFont (font);
  38843. g.setColour (Colours::black);
  38844. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  38845. }
  38846. void getContentSize (int& w, int& h)
  38847. {
  38848. w = font.getStringWidth (text) + 18;
  38849. h = (int) (font.getHeight() * 1.6f);
  38850. }
  38851. void updatePosition (const String& newText)
  38852. {
  38853. if (text != newText)
  38854. {
  38855. text = newText;
  38856. repaint();
  38857. }
  38858. BubbleComponent::setPosition (owner);
  38859. }
  38860. juce_UseDebuggingNewOperator
  38861. private:
  38862. Slider* owner;
  38863. Font font;
  38864. String text;
  38865. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  38866. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  38867. };
  38868. Slider::Slider (const String& name)
  38869. : Component (name),
  38870. lastCurrentValue (0),
  38871. lastValueMin (0),
  38872. lastValueMax (0),
  38873. minimum (0),
  38874. maximum (10),
  38875. interval (0),
  38876. skewFactor (1.0),
  38877. velocityModeSensitivity (1.0),
  38878. velocityModeOffset (0.0),
  38879. velocityModeThreshold (1),
  38880. rotaryStart (float_Pi * 1.2f),
  38881. rotaryEnd (float_Pi * 2.8f),
  38882. numDecimalPlaces (7),
  38883. sliderRegionStart (0),
  38884. sliderRegionSize (1),
  38885. sliderBeingDragged (-1),
  38886. pixelsForFullDragExtent (250),
  38887. style (LinearHorizontal),
  38888. textBoxPos (TextBoxLeft),
  38889. textBoxWidth (80),
  38890. textBoxHeight (20),
  38891. incDecButtonMode (incDecButtonsNotDraggable),
  38892. editableText (true),
  38893. doubleClickToValue (false),
  38894. isVelocityBased (false),
  38895. userKeyOverridesVelocity (true),
  38896. rotaryStop (true),
  38897. incDecButtonsSideBySide (false),
  38898. sendChangeOnlyOnRelease (false),
  38899. popupDisplayEnabled (false),
  38900. menuEnabled (false),
  38901. menuShown (false),
  38902. scrollWheelEnabled (true),
  38903. snapsToMousePos (true),
  38904. valueBox (0),
  38905. incButton (0),
  38906. decButton (0),
  38907. popupDisplay (0),
  38908. parentForPopupDisplay (0)
  38909. {
  38910. setWantsKeyboardFocus (false);
  38911. setRepaintsOnMouseActivity (true);
  38912. lookAndFeelChanged();
  38913. updateText();
  38914. currentValue.addListener (this);
  38915. valueMin.addListener (this);
  38916. valueMax.addListener (this);
  38917. }
  38918. Slider::~Slider()
  38919. {
  38920. currentValue.removeListener (this);
  38921. valueMin.removeListener (this);
  38922. valueMax.removeListener (this);
  38923. popupDisplay = 0;
  38924. deleteAllChildren();
  38925. }
  38926. void Slider::handleAsyncUpdate()
  38927. {
  38928. cancelPendingUpdate();
  38929. Component::BailOutChecker checker (this);
  38930. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  38931. }
  38932. void Slider::sendDragStart()
  38933. {
  38934. startedDragging();
  38935. Component::BailOutChecker checker (this);
  38936. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  38937. }
  38938. void Slider::sendDragEnd()
  38939. {
  38940. stoppedDragging();
  38941. sliderBeingDragged = -1;
  38942. Component::BailOutChecker checker (this);
  38943. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  38944. }
  38945. void Slider::addListener (SliderListener* const listener)
  38946. {
  38947. listeners.add (listener);
  38948. }
  38949. void Slider::removeListener (SliderListener* const listener)
  38950. {
  38951. listeners.remove (listener);
  38952. }
  38953. void Slider::setSliderStyle (const SliderStyle newStyle)
  38954. {
  38955. if (style != newStyle)
  38956. {
  38957. style = newStyle;
  38958. repaint();
  38959. lookAndFeelChanged();
  38960. }
  38961. }
  38962. void Slider::setRotaryParameters (const float startAngleRadians,
  38963. const float endAngleRadians,
  38964. const bool stopAtEnd)
  38965. {
  38966. // make sure the values are sensible..
  38967. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  38968. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  38969. jassert (rotaryStart < rotaryEnd);
  38970. rotaryStart = startAngleRadians;
  38971. rotaryEnd = endAngleRadians;
  38972. rotaryStop = stopAtEnd;
  38973. }
  38974. void Slider::setVelocityBasedMode (const bool velBased)
  38975. {
  38976. isVelocityBased = velBased;
  38977. }
  38978. void Slider::setVelocityModeParameters (const double sensitivity,
  38979. const int threshold,
  38980. const double offset,
  38981. const bool userCanPressKeyToSwapMode)
  38982. {
  38983. jassert (threshold >= 0);
  38984. jassert (sensitivity > 0);
  38985. jassert (offset >= 0);
  38986. velocityModeSensitivity = sensitivity;
  38987. velocityModeOffset = offset;
  38988. velocityModeThreshold = threshold;
  38989. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  38990. }
  38991. void Slider::setSkewFactor (const double factor)
  38992. {
  38993. skewFactor = factor;
  38994. }
  38995. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  38996. {
  38997. if (maximum > minimum)
  38998. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  38999. / (maximum - minimum));
  39000. }
  39001. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39002. {
  39003. jassert (distanceForFullScaleDrag > 0);
  39004. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39005. }
  39006. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39007. {
  39008. if (incDecButtonMode != mode)
  39009. {
  39010. incDecButtonMode = mode;
  39011. lookAndFeelChanged();
  39012. }
  39013. }
  39014. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39015. const bool isReadOnly,
  39016. const int textEntryBoxWidth,
  39017. const int textEntryBoxHeight)
  39018. {
  39019. textBoxPos = newPosition;
  39020. editableText = ! isReadOnly;
  39021. textBoxWidth = textEntryBoxWidth;
  39022. textBoxHeight = textEntryBoxHeight;
  39023. repaint();
  39024. lookAndFeelChanged();
  39025. }
  39026. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39027. {
  39028. editableText = shouldBeEditable;
  39029. if (valueBox != 0)
  39030. valueBox->setEditable (shouldBeEditable && isEnabled());
  39031. }
  39032. void Slider::showTextBox()
  39033. {
  39034. jassert (editableText); // this should probably be avoided in read-only sliders.
  39035. if (valueBox != 0)
  39036. valueBox->showEditor();
  39037. }
  39038. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39039. {
  39040. if (valueBox != 0)
  39041. {
  39042. valueBox->hideEditor (discardCurrentEditorContents);
  39043. if (discardCurrentEditorContents)
  39044. updateText();
  39045. }
  39046. }
  39047. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39048. {
  39049. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39050. }
  39051. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39052. {
  39053. snapsToMousePos = shouldSnapToMouse;
  39054. }
  39055. void Slider::setPopupDisplayEnabled (const bool enabled,
  39056. Component* const parentComponentToUse)
  39057. {
  39058. popupDisplayEnabled = enabled;
  39059. parentForPopupDisplay = parentComponentToUse;
  39060. }
  39061. void Slider::colourChanged()
  39062. {
  39063. lookAndFeelChanged();
  39064. }
  39065. void Slider::lookAndFeelChanged()
  39066. {
  39067. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39068. : getTextFromValue (currentValue.getValue()));
  39069. deleteAllChildren();
  39070. valueBox = 0;
  39071. LookAndFeel& lf = getLookAndFeel();
  39072. if (textBoxPos != NoTextBox)
  39073. {
  39074. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39075. valueBox->setWantsKeyboardFocus (false);
  39076. valueBox->setText (previousTextBoxContent, false);
  39077. valueBox->setEditable (editableText && isEnabled());
  39078. valueBox->addListener (this);
  39079. if (style == LinearBar)
  39080. valueBox->addMouseListener (this, false);
  39081. valueBox->setTooltip (getTooltip());
  39082. }
  39083. if (style == IncDecButtons)
  39084. {
  39085. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39086. incButton->addButtonListener (this);
  39087. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39088. decButton->addButtonListener (this);
  39089. if (incDecButtonMode != incDecButtonsNotDraggable)
  39090. {
  39091. incButton->addMouseListener (this, false);
  39092. decButton->addMouseListener (this, false);
  39093. }
  39094. else
  39095. {
  39096. incButton->setRepeatSpeed (300, 100, 20);
  39097. incButton->addMouseListener (decButton, false);
  39098. decButton->setRepeatSpeed (300, 100, 20);
  39099. decButton->addMouseListener (incButton, false);
  39100. }
  39101. incButton->setTooltip (getTooltip());
  39102. decButton->setTooltip (getTooltip());
  39103. }
  39104. setComponentEffect (lf.getSliderEffect());
  39105. resized();
  39106. repaint();
  39107. }
  39108. void Slider::setRange (const double newMin,
  39109. const double newMax,
  39110. const double newInt)
  39111. {
  39112. if (minimum != newMin
  39113. || maximum != newMax
  39114. || interval != newInt)
  39115. {
  39116. minimum = newMin;
  39117. maximum = newMax;
  39118. interval = newInt;
  39119. // figure out the number of DPs needed to display all values at this
  39120. // interval setting.
  39121. numDecimalPlaces = 7;
  39122. if (newInt != 0)
  39123. {
  39124. int v = abs ((int) (newInt * 10000000));
  39125. while ((v % 10) == 0)
  39126. {
  39127. --numDecimalPlaces;
  39128. v /= 10;
  39129. }
  39130. }
  39131. // keep the current values inside the new range..
  39132. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39133. {
  39134. setValue (getValue(), false, false);
  39135. }
  39136. else
  39137. {
  39138. setMinValue (getMinValue(), false, false);
  39139. setMaxValue (getMaxValue(), false, false);
  39140. }
  39141. updateText();
  39142. }
  39143. }
  39144. void Slider::triggerChangeMessage (const bool synchronous)
  39145. {
  39146. if (synchronous)
  39147. handleAsyncUpdate();
  39148. else
  39149. triggerAsyncUpdate();
  39150. valueChanged();
  39151. }
  39152. void Slider::valueChanged (Value& value)
  39153. {
  39154. if (value.refersToSameSourceAs (currentValue))
  39155. {
  39156. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39157. setValue (currentValue.getValue(), false, false);
  39158. }
  39159. else if (value.refersToSameSourceAs (valueMin))
  39160. setMinValue (valueMin.getValue(), false, false, true);
  39161. else if (value.refersToSameSourceAs (valueMax))
  39162. setMaxValue (valueMax.getValue(), false, false, true);
  39163. }
  39164. double Slider::getValue() const
  39165. {
  39166. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39167. // methods to get the two values.
  39168. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39169. return currentValue.getValue();
  39170. }
  39171. void Slider::setValue (double newValue,
  39172. const bool sendUpdateMessage,
  39173. const bool sendMessageSynchronously)
  39174. {
  39175. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39176. // methods to set the two values.
  39177. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39178. newValue = constrainedValue (newValue);
  39179. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39180. {
  39181. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39182. newValue = jlimit ((double) valueMin.getValue(),
  39183. (double) valueMax.getValue(),
  39184. newValue);
  39185. }
  39186. if (newValue != lastCurrentValue)
  39187. {
  39188. if (valueBox != 0)
  39189. valueBox->hideEditor (true);
  39190. lastCurrentValue = newValue;
  39191. currentValue = newValue;
  39192. updateText();
  39193. repaint();
  39194. if (popupDisplay != 0)
  39195. {
  39196. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39197. ->updatePosition (getTextFromValue (newValue));
  39198. popupDisplay->repaint();
  39199. }
  39200. if (sendUpdateMessage)
  39201. triggerChangeMessage (sendMessageSynchronously);
  39202. }
  39203. }
  39204. double Slider::getMinValue() const
  39205. {
  39206. // The minimum value only applies to sliders that are in two- or three-value mode.
  39207. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39208. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39209. return valueMin.getValue();
  39210. }
  39211. double Slider::getMaxValue() const
  39212. {
  39213. // The maximum value only applies to sliders that are in two- or three-value mode.
  39214. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39215. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39216. return valueMax.getValue();
  39217. }
  39218. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39219. {
  39220. // The minimum value only applies to sliders that are in two- or three-value mode.
  39221. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39222. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39223. newValue = constrainedValue (newValue);
  39224. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39225. {
  39226. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39227. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39228. newValue = jmin ((double) valueMax.getValue(), newValue);
  39229. }
  39230. else
  39231. {
  39232. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39233. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39234. newValue = jmin (lastCurrentValue, newValue);
  39235. }
  39236. if (lastValueMin != newValue)
  39237. {
  39238. lastValueMin = newValue;
  39239. valueMin = newValue;
  39240. repaint();
  39241. if (popupDisplay != 0)
  39242. {
  39243. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39244. ->updatePosition (getTextFromValue (newValue));
  39245. popupDisplay->repaint();
  39246. }
  39247. if (sendUpdateMessage)
  39248. triggerChangeMessage (sendMessageSynchronously);
  39249. }
  39250. }
  39251. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39252. {
  39253. // The maximum value only applies to sliders that are in two- or three-value mode.
  39254. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39255. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39256. newValue = constrainedValue (newValue);
  39257. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39258. {
  39259. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39260. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39261. newValue = jmax ((double) valueMin.getValue(), newValue);
  39262. }
  39263. else
  39264. {
  39265. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39266. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39267. newValue = jmax (lastCurrentValue, newValue);
  39268. }
  39269. if (lastValueMax != newValue)
  39270. {
  39271. lastValueMax = newValue;
  39272. valueMax = newValue;
  39273. repaint();
  39274. if (popupDisplay != 0)
  39275. {
  39276. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39277. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39278. popupDisplay->repaint();
  39279. }
  39280. if (sendUpdateMessage)
  39281. triggerChangeMessage (sendMessageSynchronously);
  39282. }
  39283. }
  39284. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39285. const double valueToSetOnDoubleClick)
  39286. {
  39287. doubleClickToValue = isDoubleClickEnabled;
  39288. doubleClickReturnValue = valueToSetOnDoubleClick;
  39289. }
  39290. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39291. {
  39292. isEnabled_ = doubleClickToValue;
  39293. return doubleClickReturnValue;
  39294. }
  39295. void Slider::updateText()
  39296. {
  39297. if (valueBox != 0)
  39298. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39299. }
  39300. void Slider::setTextValueSuffix (const String& suffix)
  39301. {
  39302. if (textSuffix != suffix)
  39303. {
  39304. textSuffix = suffix;
  39305. updateText();
  39306. }
  39307. }
  39308. const String Slider::getTextValueSuffix() const
  39309. {
  39310. return textSuffix;
  39311. }
  39312. const String Slider::getTextFromValue (double v)
  39313. {
  39314. if (getNumDecimalPlacesToDisplay() > 0)
  39315. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39316. else
  39317. return String (roundToInt (v)) + getTextValueSuffix();
  39318. }
  39319. double Slider::getValueFromText (const String& text)
  39320. {
  39321. String t (text.trimStart());
  39322. if (t.endsWith (textSuffix))
  39323. t = t.substring (0, t.length() - textSuffix.length());
  39324. while (t.startsWithChar ('+'))
  39325. t = t.substring (1).trimStart();
  39326. return t.initialSectionContainingOnly ("0123456789.,-")
  39327. .getDoubleValue();
  39328. }
  39329. double Slider::proportionOfLengthToValue (double proportion)
  39330. {
  39331. if (skewFactor != 1.0 && proportion > 0.0)
  39332. proportion = exp (log (proportion) / skewFactor);
  39333. return minimum + (maximum - minimum) * proportion;
  39334. }
  39335. double Slider::valueToProportionOfLength (double value)
  39336. {
  39337. const double n = (value - minimum) / (maximum - minimum);
  39338. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39339. }
  39340. double Slider::snapValue (double attemptedValue, const bool)
  39341. {
  39342. return attemptedValue;
  39343. }
  39344. void Slider::startedDragging()
  39345. {
  39346. }
  39347. void Slider::stoppedDragging()
  39348. {
  39349. }
  39350. void Slider::valueChanged()
  39351. {
  39352. }
  39353. void Slider::enablementChanged()
  39354. {
  39355. repaint();
  39356. }
  39357. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39358. {
  39359. menuEnabled = menuEnabled_;
  39360. }
  39361. void Slider::setScrollWheelEnabled (const bool enabled)
  39362. {
  39363. scrollWheelEnabled = enabled;
  39364. }
  39365. void Slider::labelTextChanged (Label* label)
  39366. {
  39367. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39368. if (newValue != (double) currentValue.getValue())
  39369. {
  39370. sendDragStart();
  39371. setValue (newValue, true, true);
  39372. sendDragEnd();
  39373. }
  39374. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39375. }
  39376. void Slider::buttonClicked (Button* button)
  39377. {
  39378. if (style == IncDecButtons)
  39379. {
  39380. sendDragStart();
  39381. if (button == incButton)
  39382. setValue (snapValue (getValue() + interval, false), true, true);
  39383. else if (button == decButton)
  39384. setValue (snapValue (getValue() - interval, false), true, true);
  39385. sendDragEnd();
  39386. }
  39387. }
  39388. double Slider::constrainedValue (double value) const
  39389. {
  39390. if (interval > 0)
  39391. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  39392. if (value <= minimum || maximum <= minimum)
  39393. value = minimum;
  39394. else if (value >= maximum)
  39395. value = maximum;
  39396. return value;
  39397. }
  39398. float Slider::getLinearSliderPos (const double value)
  39399. {
  39400. double sliderPosProportional;
  39401. if (maximum > minimum)
  39402. {
  39403. if (value < minimum)
  39404. {
  39405. sliderPosProportional = 0.0;
  39406. }
  39407. else if (value > maximum)
  39408. {
  39409. sliderPosProportional = 1.0;
  39410. }
  39411. else
  39412. {
  39413. sliderPosProportional = valueToProportionOfLength (value);
  39414. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39415. }
  39416. }
  39417. else
  39418. {
  39419. sliderPosProportional = 0.5;
  39420. }
  39421. if (isVertical() || style == IncDecButtons)
  39422. sliderPosProportional = 1.0 - sliderPosProportional;
  39423. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39424. }
  39425. bool Slider::isHorizontal() const
  39426. {
  39427. return style == LinearHorizontal
  39428. || style == LinearBar
  39429. || style == TwoValueHorizontal
  39430. || style == ThreeValueHorizontal;
  39431. }
  39432. bool Slider::isVertical() const
  39433. {
  39434. return style == LinearVertical
  39435. || style == TwoValueVertical
  39436. || style == ThreeValueVertical;
  39437. }
  39438. bool Slider::incDecDragDirectionIsHorizontal() const
  39439. {
  39440. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39441. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39442. }
  39443. float Slider::getPositionOfValue (const double value)
  39444. {
  39445. if (isHorizontal() || isVertical())
  39446. {
  39447. return getLinearSliderPos (value);
  39448. }
  39449. else
  39450. {
  39451. jassertfalse // not a valid call on a slider that doesn't work linearly!
  39452. return 0.0f;
  39453. }
  39454. }
  39455. void Slider::paint (Graphics& g)
  39456. {
  39457. if (style != IncDecButtons)
  39458. {
  39459. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39460. {
  39461. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39462. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39463. getLookAndFeel().drawRotarySlider (g,
  39464. sliderRect.getX(),
  39465. sliderRect.getY(),
  39466. sliderRect.getWidth(),
  39467. sliderRect.getHeight(),
  39468. sliderPos,
  39469. rotaryStart, rotaryEnd,
  39470. *this);
  39471. }
  39472. else
  39473. {
  39474. getLookAndFeel().drawLinearSlider (g,
  39475. sliderRect.getX(),
  39476. sliderRect.getY(),
  39477. sliderRect.getWidth(),
  39478. sliderRect.getHeight(),
  39479. getLinearSliderPos (lastCurrentValue),
  39480. getLinearSliderPos (lastValueMin),
  39481. getLinearSliderPos (lastValueMax),
  39482. style,
  39483. *this);
  39484. }
  39485. if (style == LinearBar && valueBox == 0)
  39486. {
  39487. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39488. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39489. }
  39490. }
  39491. }
  39492. void Slider::resized()
  39493. {
  39494. int minXSpace = 0;
  39495. int minYSpace = 0;
  39496. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39497. minXSpace = 30;
  39498. else
  39499. minYSpace = 15;
  39500. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39501. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39502. if (style == LinearBar)
  39503. {
  39504. if (valueBox != 0)
  39505. valueBox->setBounds (0, 0, getWidth(), getHeight());
  39506. }
  39507. else
  39508. {
  39509. if (textBoxPos == NoTextBox)
  39510. {
  39511. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  39512. }
  39513. else if (textBoxPos == TextBoxLeft)
  39514. {
  39515. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39516. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39517. }
  39518. else if (textBoxPos == TextBoxRight)
  39519. {
  39520. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39521. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39522. }
  39523. else if (textBoxPos == TextBoxAbove)
  39524. {
  39525. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39526. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39527. }
  39528. else if (textBoxPos == TextBoxBelow)
  39529. {
  39530. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39531. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39532. }
  39533. }
  39534. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39535. if (style == LinearBar)
  39536. {
  39537. const int barIndent = 1;
  39538. sliderRegionStart = barIndent;
  39539. sliderRegionSize = getWidth() - barIndent * 2;
  39540. sliderRect.setBounds (sliderRegionStart, barIndent,
  39541. sliderRegionSize, getHeight() - barIndent * 2);
  39542. }
  39543. else if (isHorizontal())
  39544. {
  39545. sliderRegionStart = sliderRect.getX() + indent;
  39546. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39547. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39548. sliderRegionSize, sliderRect.getHeight());
  39549. }
  39550. else if (isVertical())
  39551. {
  39552. sliderRegionStart = sliderRect.getY() + indent;
  39553. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39554. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39555. sliderRect.getWidth(), sliderRegionSize);
  39556. }
  39557. else
  39558. {
  39559. sliderRegionStart = 0;
  39560. sliderRegionSize = 100;
  39561. }
  39562. if (style == IncDecButtons)
  39563. {
  39564. Rectangle<int> buttonRect (sliderRect);
  39565. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39566. buttonRect.expand (-2, 0);
  39567. else
  39568. buttonRect.expand (0, -2);
  39569. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39570. if (incDecButtonsSideBySide)
  39571. {
  39572. decButton->setBounds (buttonRect.getX(),
  39573. buttonRect.getY(),
  39574. buttonRect.getWidth() / 2,
  39575. buttonRect.getHeight());
  39576. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39577. incButton->setBounds (buttonRect.getCentreX(),
  39578. buttonRect.getY(),
  39579. buttonRect.getWidth() / 2,
  39580. buttonRect.getHeight());
  39581. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39582. }
  39583. else
  39584. {
  39585. incButton->setBounds (buttonRect.getX(),
  39586. buttonRect.getY(),
  39587. buttonRect.getWidth(),
  39588. buttonRect.getHeight() / 2);
  39589. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39590. decButton->setBounds (buttonRect.getX(),
  39591. buttonRect.getCentreY(),
  39592. buttonRect.getWidth(),
  39593. buttonRect.getHeight() / 2);
  39594. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39595. }
  39596. }
  39597. }
  39598. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39599. {
  39600. repaint();
  39601. }
  39602. void Slider::mouseDown (const MouseEvent& e)
  39603. {
  39604. mouseWasHidden = false;
  39605. incDecDragged = false;
  39606. mouseXWhenLastDragged = e.x;
  39607. mouseYWhenLastDragged = e.y;
  39608. mouseDragStartX = e.getMouseDownX();
  39609. mouseDragStartY = e.getMouseDownY();
  39610. if (isEnabled())
  39611. {
  39612. if (e.mods.isPopupMenu() && menuEnabled)
  39613. {
  39614. menuShown = true;
  39615. PopupMenu m;
  39616. m.setLookAndFeel (&getLookAndFeel());
  39617. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39618. m.addSeparator();
  39619. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39620. {
  39621. PopupMenu rotaryMenu;
  39622. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39623. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39624. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39625. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39626. }
  39627. const int r = m.show();
  39628. if (r == 1)
  39629. {
  39630. setVelocityBasedMode (! isVelocityBased);
  39631. }
  39632. else if (r == 2)
  39633. {
  39634. setSliderStyle (Rotary);
  39635. }
  39636. else if (r == 3)
  39637. {
  39638. setSliderStyle (RotaryHorizontalDrag);
  39639. }
  39640. else if (r == 4)
  39641. {
  39642. setSliderStyle (RotaryVerticalDrag);
  39643. }
  39644. }
  39645. else if (maximum > minimum)
  39646. {
  39647. menuShown = false;
  39648. if (valueBox != 0)
  39649. valueBox->hideEditor (true);
  39650. sliderBeingDragged = 0;
  39651. if (style == TwoValueHorizontal
  39652. || style == TwoValueVertical
  39653. || style == ThreeValueHorizontal
  39654. || style == ThreeValueVertical)
  39655. {
  39656. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39657. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39658. const float minPosDistance = fabsf (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39659. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39660. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39661. {
  39662. if (maxPosDistance <= minPosDistance)
  39663. sliderBeingDragged = 2;
  39664. else
  39665. sliderBeingDragged = 1;
  39666. }
  39667. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39668. {
  39669. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39670. sliderBeingDragged = 1;
  39671. else if (normalPosDistance >= maxPosDistance)
  39672. sliderBeingDragged = 2;
  39673. }
  39674. }
  39675. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39676. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39677. * valueToProportionOfLength (currentValue.getValue());
  39678. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39679. : ((sliderBeingDragged == 1) ? valueMin
  39680. : currentValue)).getValue();
  39681. valueOnMouseDown = valueWhenLastDragged;
  39682. if (popupDisplayEnabled)
  39683. {
  39684. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39685. popupDisplay = popup;
  39686. if (parentForPopupDisplay != 0)
  39687. {
  39688. parentForPopupDisplay->addChildComponent (popup);
  39689. }
  39690. else
  39691. {
  39692. popup->addToDesktop (0);
  39693. }
  39694. popup->setVisible (true);
  39695. }
  39696. sendDragStart();
  39697. mouseDrag (e);
  39698. }
  39699. }
  39700. }
  39701. void Slider::mouseUp (const MouseEvent&)
  39702. {
  39703. if (isEnabled()
  39704. && (! menuShown)
  39705. && (maximum > minimum)
  39706. && (style != IncDecButtons || incDecDragged))
  39707. {
  39708. restoreMouseIfHidden();
  39709. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39710. triggerChangeMessage (false);
  39711. sendDragEnd();
  39712. popupDisplay = 0;
  39713. if (style == IncDecButtons)
  39714. {
  39715. incButton->setState (Button::buttonNormal);
  39716. decButton->setState (Button::buttonNormal);
  39717. }
  39718. }
  39719. }
  39720. void Slider::restoreMouseIfHidden()
  39721. {
  39722. if (mouseWasHidden)
  39723. {
  39724. mouseWasHidden = false;
  39725. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39726. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39727. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39728. : ((sliderBeingDragged == 1) ? getMinValue()
  39729. : (double) currentValue.getValue());
  39730. Point<int> mousePos;
  39731. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39732. {
  39733. mousePos = Desktop::getLastMouseDownPosition();
  39734. if (style == RotaryHorizontalDrag)
  39735. {
  39736. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39737. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39738. }
  39739. else
  39740. {
  39741. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39742. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39743. }
  39744. }
  39745. else
  39746. {
  39747. const int pixelPos = (int) getLinearSliderPos (pos);
  39748. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39749. isVertical() ? pixelPos : (getHeight() / 2)));
  39750. }
  39751. Desktop::setMousePosition (mousePos);
  39752. }
  39753. }
  39754. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39755. {
  39756. if (isEnabled()
  39757. && style != IncDecButtons
  39758. && style != Rotary
  39759. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39760. {
  39761. restoreMouseIfHidden();
  39762. }
  39763. }
  39764. static double smallestAngleBetween (double a1, double a2)
  39765. {
  39766. return jmin (fabs (a1 - a2),
  39767. fabs (a1 + double_Pi * 2.0 - a2),
  39768. fabs (a2 + double_Pi * 2.0 - a1));
  39769. }
  39770. void Slider::mouseDrag (const MouseEvent& e)
  39771. {
  39772. if (isEnabled()
  39773. && (! menuShown)
  39774. && (maximum > minimum))
  39775. {
  39776. if (style == Rotary)
  39777. {
  39778. int dx = e.x - sliderRect.getCentreX();
  39779. int dy = e.y - sliderRect.getCentreY();
  39780. if (dx * dx + dy * dy > 25)
  39781. {
  39782. double angle = atan2 ((double) dx, (double) -dy);
  39783. while (angle < 0.0)
  39784. angle += double_Pi * 2.0;
  39785. if (rotaryStop && ! e.mouseWasClicked())
  39786. {
  39787. if (fabs (angle - lastAngle) > double_Pi)
  39788. {
  39789. if (angle >= lastAngle)
  39790. angle -= double_Pi * 2.0;
  39791. else
  39792. angle += double_Pi * 2.0;
  39793. }
  39794. if (angle >= lastAngle)
  39795. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  39796. else
  39797. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  39798. }
  39799. else
  39800. {
  39801. while (angle < rotaryStart)
  39802. angle += double_Pi * 2.0;
  39803. if (angle > rotaryEnd)
  39804. {
  39805. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  39806. angle = rotaryStart;
  39807. else
  39808. angle = rotaryEnd;
  39809. }
  39810. }
  39811. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  39812. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  39813. lastAngle = angle;
  39814. }
  39815. }
  39816. else
  39817. {
  39818. if (style == LinearBar && e.mouseWasClicked()
  39819. && valueBox != 0 && valueBox->isEditable())
  39820. return;
  39821. if (style == IncDecButtons && ! incDecDragged)
  39822. {
  39823. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  39824. return;
  39825. incDecDragged = true;
  39826. mouseDragStartX = e.x;
  39827. mouseDragStartY = e.y;
  39828. }
  39829. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  39830. : false))
  39831. || ((maximum - minimum) / sliderRegionSize < interval))
  39832. {
  39833. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  39834. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  39835. if (style == RotaryHorizontalDrag
  39836. || style == RotaryVerticalDrag
  39837. || style == IncDecButtons
  39838. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  39839. && ! snapsToMousePos))
  39840. {
  39841. const int mouseDiff = (style == RotaryHorizontalDrag
  39842. || style == LinearHorizontal
  39843. || style == LinearBar
  39844. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39845. ? e.x - mouseDragStartX
  39846. : mouseDragStartY - e.y;
  39847. double newPos = valueToProportionOfLength (valueOnMouseDown)
  39848. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  39849. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  39850. if (style == IncDecButtons)
  39851. {
  39852. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  39853. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  39854. }
  39855. }
  39856. else
  39857. {
  39858. if (isVertical())
  39859. scaledMousePos = 1.0 - scaledMousePos;
  39860. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  39861. }
  39862. }
  39863. else
  39864. {
  39865. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  39866. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39867. ? e.x - mouseXWhenLastDragged
  39868. : e.y - mouseYWhenLastDragged;
  39869. const double maxSpeed = jmax (200, sliderRegionSize);
  39870. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  39871. if (speed != 0)
  39872. {
  39873. speed = 0.2 * velocityModeSensitivity
  39874. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  39875. + jmax (0.0, (double) (speed - velocityModeThreshold))
  39876. / maxSpeed))));
  39877. if (mouseDiff < 0)
  39878. speed = -speed;
  39879. if (isVertical() || style == RotaryVerticalDrag
  39880. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  39881. speed = -speed;
  39882. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  39883. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  39884. e.source.enableUnboundedMouseMovement (true, false);
  39885. mouseWasHidden = true;
  39886. }
  39887. }
  39888. }
  39889. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  39890. if (sliderBeingDragged == 0)
  39891. {
  39892. setValue (snapValue (valueWhenLastDragged, true),
  39893. ! sendChangeOnlyOnRelease, true);
  39894. }
  39895. else if (sliderBeingDragged == 1)
  39896. {
  39897. setMinValue (snapValue (valueWhenLastDragged, true),
  39898. ! sendChangeOnlyOnRelease, false, true);
  39899. if (e.mods.isShiftDown())
  39900. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  39901. else
  39902. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39903. }
  39904. else
  39905. {
  39906. jassert (sliderBeingDragged == 2);
  39907. setMaxValue (snapValue (valueWhenLastDragged, true),
  39908. ! sendChangeOnlyOnRelease, false, true);
  39909. if (e.mods.isShiftDown())
  39910. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  39911. else
  39912. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39913. }
  39914. mouseXWhenLastDragged = e.x;
  39915. mouseYWhenLastDragged = e.y;
  39916. }
  39917. }
  39918. void Slider::mouseDoubleClick (const MouseEvent&)
  39919. {
  39920. if (doubleClickToValue
  39921. && isEnabled()
  39922. && style != IncDecButtons
  39923. && minimum <= doubleClickReturnValue
  39924. && maximum >= doubleClickReturnValue)
  39925. {
  39926. sendDragStart();
  39927. setValue (doubleClickReturnValue, true, true);
  39928. sendDragEnd();
  39929. }
  39930. }
  39931. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39932. {
  39933. if (scrollWheelEnabled && isEnabled()
  39934. && style != TwoValueHorizontal
  39935. && style != TwoValueVertical)
  39936. {
  39937. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  39938. {
  39939. if (valueBox != 0)
  39940. valueBox->hideEditor (false);
  39941. const double value = (double) currentValue.getValue();
  39942. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  39943. const double currentPos = valueToProportionOfLength (value);
  39944. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  39945. double delta = (newValue != value)
  39946. ? jmax (fabs (newValue - value), interval) : 0;
  39947. if (value > newValue)
  39948. delta = -delta;
  39949. sendDragStart();
  39950. setValue (snapValue (value + delta, false), true, true);
  39951. sendDragEnd();
  39952. }
  39953. }
  39954. else
  39955. {
  39956. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  39957. }
  39958. }
  39959. void SliderListener::sliderDragStarted (Slider*)
  39960. {
  39961. }
  39962. void SliderListener::sliderDragEnded (Slider*)
  39963. {
  39964. }
  39965. END_JUCE_NAMESPACE
  39966. /*** End of inlined file: juce_Slider.cpp ***/
  39967. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  39968. BEGIN_JUCE_NAMESPACE
  39969. class DragOverlayComp : public Component
  39970. {
  39971. public:
  39972. DragOverlayComp (Image* const image_)
  39973. : image (image_)
  39974. {
  39975. image->multiplyAllAlphas (0.8f);
  39976. setAlwaysOnTop (true);
  39977. }
  39978. ~DragOverlayComp()
  39979. {
  39980. }
  39981. void paint (Graphics& g)
  39982. {
  39983. g.drawImageAt (image, 0, 0);
  39984. }
  39985. private:
  39986. ScopedPointer <Image> image;
  39987. DragOverlayComp (const DragOverlayComp&);
  39988. DragOverlayComp& operator= (const DragOverlayComp&);
  39989. };
  39990. TableHeaderComponent::TableHeaderComponent()
  39991. : columnsChanged (false),
  39992. columnsResized (false),
  39993. sortChanged (false),
  39994. menuActive (true),
  39995. stretchToFit (false),
  39996. columnIdBeingResized (0),
  39997. columnIdBeingDragged (0),
  39998. columnIdUnderMouse (0),
  39999. lastDeliberateWidth (0)
  40000. {
  40001. }
  40002. TableHeaderComponent::~TableHeaderComponent()
  40003. {
  40004. dragOverlayComp = 0;
  40005. }
  40006. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40007. {
  40008. menuActive = hasMenu;
  40009. }
  40010. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40011. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40012. {
  40013. if (onlyCountVisibleColumns)
  40014. {
  40015. int num = 0;
  40016. for (int i = columns.size(); --i >= 0;)
  40017. if (columns.getUnchecked(i)->isVisible())
  40018. ++num;
  40019. return num;
  40020. }
  40021. else
  40022. {
  40023. return columns.size();
  40024. }
  40025. }
  40026. const String TableHeaderComponent::getColumnName (const int columnId) const
  40027. {
  40028. const ColumnInfo* const ci = getInfoForId (columnId);
  40029. return ci != 0 ? ci->name : String::empty;
  40030. }
  40031. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40032. {
  40033. ColumnInfo* const ci = getInfoForId (columnId);
  40034. if (ci != 0 && ci->name != newName)
  40035. {
  40036. ci->name = newName;
  40037. sendColumnsChanged();
  40038. }
  40039. }
  40040. void TableHeaderComponent::addColumn (const String& columnName,
  40041. const int columnId,
  40042. const int width,
  40043. const int minimumWidth,
  40044. const int maximumWidth,
  40045. const int propertyFlags,
  40046. const int insertIndex)
  40047. {
  40048. // can't have a duplicate or null ID!
  40049. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40050. jassert (width > 0);
  40051. ColumnInfo* const ci = new ColumnInfo();
  40052. ci->name = columnName;
  40053. ci->id = columnId;
  40054. ci->width = width;
  40055. ci->lastDeliberateWidth = width;
  40056. ci->minimumWidth = minimumWidth;
  40057. ci->maximumWidth = maximumWidth;
  40058. if (ci->maximumWidth < 0)
  40059. ci->maximumWidth = std::numeric_limits<int>::max();
  40060. jassert (ci->maximumWidth >= ci->minimumWidth);
  40061. ci->propertyFlags = propertyFlags;
  40062. columns.insert (insertIndex, ci);
  40063. sendColumnsChanged();
  40064. }
  40065. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40066. {
  40067. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40068. if (index >= 0)
  40069. {
  40070. columns.remove (index);
  40071. sortChanged = true;
  40072. sendColumnsChanged();
  40073. }
  40074. }
  40075. void TableHeaderComponent::removeAllColumns()
  40076. {
  40077. if (columns.size() > 0)
  40078. {
  40079. columns.clear();
  40080. sendColumnsChanged();
  40081. }
  40082. }
  40083. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40084. {
  40085. const int currentIndex = getIndexOfColumnId (columnId, false);
  40086. newIndex = visibleIndexToTotalIndex (newIndex);
  40087. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40088. {
  40089. columns.move (currentIndex, newIndex);
  40090. sendColumnsChanged();
  40091. }
  40092. }
  40093. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40094. {
  40095. const ColumnInfo* const ci = getInfoForId (columnId);
  40096. return ci != 0 ? ci->width : 0;
  40097. }
  40098. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40099. {
  40100. ColumnInfo* const ci = getInfoForId (columnId);
  40101. if (ci != 0 && ci->width != newWidth)
  40102. {
  40103. const int numColumns = getNumColumns (true);
  40104. ci->lastDeliberateWidth = ci->width
  40105. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40106. if (stretchToFit)
  40107. {
  40108. const int index = getIndexOfColumnId (columnId, true) + 1;
  40109. if (((unsigned int) index) < (unsigned int) numColumns)
  40110. {
  40111. const int x = getColumnPosition (index).getX();
  40112. if (lastDeliberateWidth == 0)
  40113. lastDeliberateWidth = getTotalWidth();
  40114. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40115. }
  40116. }
  40117. repaint();
  40118. columnsResized = true;
  40119. triggerAsyncUpdate();
  40120. }
  40121. }
  40122. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40123. {
  40124. int n = 0;
  40125. for (int i = 0; i < columns.size(); ++i)
  40126. {
  40127. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40128. {
  40129. if (columns.getUnchecked(i)->id == columnId)
  40130. return n;
  40131. ++n;
  40132. }
  40133. }
  40134. return -1;
  40135. }
  40136. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40137. {
  40138. if (onlyCountVisibleColumns)
  40139. index = visibleIndexToTotalIndex (index);
  40140. const ColumnInfo* const ci = columns [index];
  40141. return (ci != 0) ? ci->id : 0;
  40142. }
  40143. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40144. {
  40145. int x = 0, width = 0, n = 0;
  40146. for (int i = 0; i < columns.size(); ++i)
  40147. {
  40148. x += width;
  40149. if (columns.getUnchecked(i)->isVisible())
  40150. {
  40151. width = columns.getUnchecked(i)->width;
  40152. if (n++ == index)
  40153. break;
  40154. }
  40155. else
  40156. {
  40157. width = 0;
  40158. }
  40159. }
  40160. return Rectangle<int> (x, 0, width, getHeight());
  40161. }
  40162. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40163. {
  40164. if (xToFind >= 0)
  40165. {
  40166. int x = 0;
  40167. for (int i = 0; i < columns.size(); ++i)
  40168. {
  40169. const ColumnInfo* const ci = columns.getUnchecked(i);
  40170. if (ci->isVisible())
  40171. {
  40172. x += ci->width;
  40173. if (xToFind < x)
  40174. return ci->id;
  40175. }
  40176. }
  40177. }
  40178. return 0;
  40179. }
  40180. int TableHeaderComponent::getTotalWidth() const
  40181. {
  40182. int w = 0;
  40183. for (int i = columns.size(); --i >= 0;)
  40184. if (columns.getUnchecked(i)->isVisible())
  40185. w += columns.getUnchecked(i)->width;
  40186. return w;
  40187. }
  40188. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40189. {
  40190. stretchToFit = shouldStretchToFit;
  40191. lastDeliberateWidth = getTotalWidth();
  40192. resized();
  40193. }
  40194. bool TableHeaderComponent::isStretchToFitActive() const
  40195. {
  40196. return stretchToFit;
  40197. }
  40198. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40199. {
  40200. if (stretchToFit && getWidth() > 0
  40201. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40202. {
  40203. lastDeliberateWidth = targetTotalWidth;
  40204. resizeColumnsToFit (0, targetTotalWidth);
  40205. }
  40206. }
  40207. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40208. {
  40209. targetTotalWidth = jmax (targetTotalWidth, 0);
  40210. StretchableObjectResizer sor;
  40211. int i;
  40212. for (i = firstColumnIndex; i < columns.size(); ++i)
  40213. {
  40214. ColumnInfo* const ci = columns.getUnchecked(i);
  40215. if (ci->isVisible())
  40216. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40217. }
  40218. sor.resizeToFit (targetTotalWidth);
  40219. int visIndex = 0;
  40220. for (i = firstColumnIndex; i < columns.size(); ++i)
  40221. {
  40222. ColumnInfo* const ci = columns.getUnchecked(i);
  40223. if (ci->isVisible())
  40224. {
  40225. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40226. (int) floor (sor.getItemSize (visIndex++)));
  40227. if (newWidth != ci->width)
  40228. {
  40229. ci->width = newWidth;
  40230. repaint();
  40231. columnsResized = true;
  40232. triggerAsyncUpdate();
  40233. }
  40234. }
  40235. }
  40236. }
  40237. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40238. {
  40239. ColumnInfo* const ci = getInfoForId (columnId);
  40240. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40241. {
  40242. if (shouldBeVisible)
  40243. ci->propertyFlags |= visible;
  40244. else
  40245. ci->propertyFlags &= ~visible;
  40246. sendColumnsChanged();
  40247. resized();
  40248. }
  40249. }
  40250. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40251. {
  40252. const ColumnInfo* const ci = getInfoForId (columnId);
  40253. return ci != 0 && ci->isVisible();
  40254. }
  40255. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40256. {
  40257. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40258. {
  40259. for (int i = columns.size(); --i >= 0;)
  40260. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40261. ColumnInfo* const ci = getInfoForId (columnId);
  40262. if (ci != 0)
  40263. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40264. reSortTable();
  40265. }
  40266. }
  40267. int TableHeaderComponent::getSortColumnId() const
  40268. {
  40269. for (int i = columns.size(); --i >= 0;)
  40270. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40271. return columns.getUnchecked(i)->id;
  40272. return 0;
  40273. }
  40274. bool TableHeaderComponent::isSortedForwards() const
  40275. {
  40276. for (int i = columns.size(); --i >= 0;)
  40277. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40278. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40279. return true;
  40280. }
  40281. void TableHeaderComponent::reSortTable()
  40282. {
  40283. sortChanged = true;
  40284. repaint();
  40285. triggerAsyncUpdate();
  40286. }
  40287. const String TableHeaderComponent::toString() const
  40288. {
  40289. String s;
  40290. XmlElement doc ("TABLELAYOUT");
  40291. doc.setAttribute ("sortedCol", getSortColumnId());
  40292. doc.setAttribute ("sortForwards", isSortedForwards());
  40293. for (int i = 0; i < columns.size(); ++i)
  40294. {
  40295. const ColumnInfo* const ci = columns.getUnchecked (i);
  40296. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40297. e->setAttribute ("id", ci->id);
  40298. e->setAttribute ("visible", ci->isVisible());
  40299. e->setAttribute ("width", ci->width);
  40300. }
  40301. return doc.createDocument (String::empty, true, false);
  40302. }
  40303. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40304. {
  40305. XmlDocument doc (storedVersion);
  40306. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40307. int index = 0;
  40308. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40309. {
  40310. forEachXmlChildElement (*storedXml, col)
  40311. {
  40312. const int tabId = col->getIntAttribute ("id");
  40313. ColumnInfo* const ci = getInfoForId (tabId);
  40314. if (ci != 0)
  40315. {
  40316. columns.move (columns.indexOf (ci), index);
  40317. ci->width = col->getIntAttribute ("width");
  40318. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40319. }
  40320. ++index;
  40321. }
  40322. columnsResized = true;
  40323. sendColumnsChanged();
  40324. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40325. storedXml->getBoolAttribute ("sortForwards", true));
  40326. }
  40327. }
  40328. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40329. {
  40330. listeners.addIfNotAlreadyThere (newListener);
  40331. }
  40332. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40333. {
  40334. listeners.removeValue (listenerToRemove);
  40335. }
  40336. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40337. {
  40338. const ColumnInfo* const ci = getInfoForId (columnId);
  40339. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40340. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40341. }
  40342. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40343. {
  40344. for (int i = 0; i < columns.size(); ++i)
  40345. {
  40346. const ColumnInfo* const ci = columns.getUnchecked(i);
  40347. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40348. menu.addItem (ci->id, ci->name,
  40349. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40350. isColumnVisible (ci->id));
  40351. }
  40352. }
  40353. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40354. {
  40355. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40356. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40357. }
  40358. void TableHeaderComponent::paint (Graphics& g)
  40359. {
  40360. LookAndFeel& lf = getLookAndFeel();
  40361. lf.drawTableHeaderBackground (g, *this);
  40362. const Rectangle<int> clip (g.getClipBounds());
  40363. int x = 0;
  40364. for (int i = 0; i < columns.size(); ++i)
  40365. {
  40366. const ColumnInfo* const ci = columns.getUnchecked(i);
  40367. if (ci->isVisible())
  40368. {
  40369. if (x + ci->width > clip.getX()
  40370. && (ci->id != columnIdBeingDragged
  40371. || dragOverlayComp == 0
  40372. || ! dragOverlayComp->isVisible()))
  40373. {
  40374. g.saveState();
  40375. g.setOrigin (x, 0);
  40376. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40377. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40378. ci->id == columnIdUnderMouse,
  40379. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40380. ci->propertyFlags);
  40381. g.restoreState();
  40382. }
  40383. x += ci->width;
  40384. if (x >= clip.getRight())
  40385. break;
  40386. }
  40387. }
  40388. }
  40389. void TableHeaderComponent::resized()
  40390. {
  40391. }
  40392. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40393. {
  40394. updateColumnUnderMouse (e.x, e.y);
  40395. }
  40396. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40397. {
  40398. updateColumnUnderMouse (e.x, e.y);
  40399. }
  40400. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40401. {
  40402. updateColumnUnderMouse (e.x, e.y);
  40403. }
  40404. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40405. {
  40406. repaint();
  40407. columnIdBeingResized = 0;
  40408. columnIdBeingDragged = 0;
  40409. if (columnIdUnderMouse != 0)
  40410. {
  40411. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40412. if (e.mods.isPopupMenu())
  40413. columnClicked (columnIdUnderMouse, e.mods);
  40414. }
  40415. if (menuActive && e.mods.isPopupMenu())
  40416. showColumnChooserMenu (columnIdUnderMouse);
  40417. }
  40418. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40419. {
  40420. if (columnIdBeingResized == 0
  40421. && columnIdBeingDragged == 0
  40422. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40423. {
  40424. dragOverlayComp = 0;
  40425. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40426. if (columnIdBeingResized != 0)
  40427. {
  40428. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40429. initialColumnWidth = ci->width;
  40430. }
  40431. else
  40432. {
  40433. beginDrag (e);
  40434. }
  40435. }
  40436. if (columnIdBeingResized != 0)
  40437. {
  40438. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40439. if (ci != 0)
  40440. {
  40441. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40442. initialColumnWidth + e.getDistanceFromDragStartX());
  40443. if (stretchToFit)
  40444. {
  40445. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40446. int minWidthOnRight = 0;
  40447. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40448. if (columns.getUnchecked (i)->isVisible())
  40449. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40450. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40451. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40452. }
  40453. setColumnWidth (columnIdBeingResized, w);
  40454. }
  40455. }
  40456. else if (columnIdBeingDragged != 0)
  40457. {
  40458. if (e.y >= -50 && e.y < getHeight() + 50)
  40459. {
  40460. if (dragOverlayComp != 0)
  40461. {
  40462. dragOverlayComp->setVisible (true);
  40463. dragOverlayComp->setBounds (jlimit (0,
  40464. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40465. e.x - draggingColumnOffset),
  40466. 0,
  40467. dragOverlayComp->getWidth(),
  40468. getHeight());
  40469. for (int i = columns.size(); --i >= 0;)
  40470. {
  40471. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40472. int newIndex = currentIndex;
  40473. if (newIndex > 0)
  40474. {
  40475. // if the previous column isn't draggable, we can't move our column
  40476. // past it, because that'd change the undraggable column's position..
  40477. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40478. if ((previous->propertyFlags & draggable) != 0)
  40479. {
  40480. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40481. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40482. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40483. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40484. {
  40485. --newIndex;
  40486. }
  40487. }
  40488. }
  40489. if (newIndex < columns.size() - 1)
  40490. {
  40491. // if the next column isn't draggable, we can't move our column
  40492. // past it, because that'd change the undraggable column's position..
  40493. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40494. if ((nextCol->propertyFlags & draggable) != 0)
  40495. {
  40496. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40497. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40498. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40499. > abs (dragOverlayComp->getRight() - rightOfNext))
  40500. {
  40501. ++newIndex;
  40502. }
  40503. }
  40504. }
  40505. if (newIndex != currentIndex)
  40506. moveColumn (columnIdBeingDragged, newIndex);
  40507. else
  40508. break;
  40509. }
  40510. }
  40511. }
  40512. else
  40513. {
  40514. endDrag (draggingColumnOriginalIndex);
  40515. }
  40516. }
  40517. }
  40518. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40519. {
  40520. if (columnIdBeingDragged == 0)
  40521. {
  40522. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40523. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40524. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40525. {
  40526. columnIdBeingDragged = 0;
  40527. }
  40528. else
  40529. {
  40530. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40531. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40532. const int temp = columnIdBeingDragged;
  40533. columnIdBeingDragged = 0;
  40534. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40535. columnIdBeingDragged = temp;
  40536. dragOverlayComp->setBounds (columnRect);
  40537. for (int i = listeners.size(); --i >= 0;)
  40538. {
  40539. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40540. i = jmin (i, listeners.size() - 1);
  40541. }
  40542. }
  40543. }
  40544. }
  40545. void TableHeaderComponent::endDrag (const int finalIndex)
  40546. {
  40547. if (columnIdBeingDragged != 0)
  40548. {
  40549. moveColumn (columnIdBeingDragged, finalIndex);
  40550. columnIdBeingDragged = 0;
  40551. repaint();
  40552. for (int i = listeners.size(); --i >= 0;)
  40553. {
  40554. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40555. i = jmin (i, listeners.size() - 1);
  40556. }
  40557. }
  40558. }
  40559. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40560. {
  40561. mouseDrag (e);
  40562. for (int i = columns.size(); --i >= 0;)
  40563. if (columns.getUnchecked (i)->isVisible())
  40564. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40565. columnIdBeingResized = 0;
  40566. repaint();
  40567. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40568. updateColumnUnderMouse (e.x, e.y);
  40569. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40570. columnClicked (columnIdUnderMouse, e.mods);
  40571. dragOverlayComp = 0;
  40572. }
  40573. const MouseCursor TableHeaderComponent::getMouseCursor()
  40574. {
  40575. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40576. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40577. return Component::getMouseCursor();
  40578. }
  40579. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40580. {
  40581. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40582. }
  40583. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40584. {
  40585. for (int i = columns.size(); --i >= 0;)
  40586. if (columns.getUnchecked(i)->id == id)
  40587. return columns.getUnchecked(i);
  40588. return 0;
  40589. }
  40590. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40591. {
  40592. int n = 0;
  40593. for (int i = 0; i < columns.size(); ++i)
  40594. {
  40595. if (columns.getUnchecked(i)->isVisible())
  40596. {
  40597. if (n == visibleIndex)
  40598. return i;
  40599. ++n;
  40600. }
  40601. }
  40602. return -1;
  40603. }
  40604. void TableHeaderComponent::sendColumnsChanged()
  40605. {
  40606. if (stretchToFit && lastDeliberateWidth > 0)
  40607. resizeAllColumnsToFit (lastDeliberateWidth);
  40608. repaint();
  40609. columnsChanged = true;
  40610. triggerAsyncUpdate();
  40611. }
  40612. void TableHeaderComponent::handleAsyncUpdate()
  40613. {
  40614. const bool changed = columnsChanged || sortChanged;
  40615. const bool sized = columnsResized || changed;
  40616. const bool sorted = sortChanged;
  40617. columnsChanged = false;
  40618. columnsResized = false;
  40619. sortChanged = false;
  40620. if (sorted)
  40621. {
  40622. for (int i = listeners.size(); --i >= 0;)
  40623. {
  40624. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40625. i = jmin (i, listeners.size() - 1);
  40626. }
  40627. }
  40628. if (changed)
  40629. {
  40630. for (int i = listeners.size(); --i >= 0;)
  40631. {
  40632. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40633. i = jmin (i, listeners.size() - 1);
  40634. }
  40635. }
  40636. if (sized)
  40637. {
  40638. for (int i = listeners.size(); --i >= 0;)
  40639. {
  40640. listeners.getUnchecked(i)->tableColumnsResized (this);
  40641. i = jmin (i, listeners.size() - 1);
  40642. }
  40643. }
  40644. }
  40645. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40646. {
  40647. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40648. {
  40649. const int draggableDistance = 3;
  40650. int x = 0;
  40651. for (int i = 0; i < columns.size(); ++i)
  40652. {
  40653. const ColumnInfo* const ci = columns.getUnchecked(i);
  40654. if (ci->isVisible())
  40655. {
  40656. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40657. && (ci->propertyFlags & resizable) != 0)
  40658. return ci->id;
  40659. x += ci->width;
  40660. }
  40661. }
  40662. }
  40663. return 0;
  40664. }
  40665. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40666. {
  40667. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40668. ? getColumnIdAtX (x) : 0;
  40669. if (newCol != columnIdUnderMouse)
  40670. {
  40671. columnIdUnderMouse = newCol;
  40672. repaint();
  40673. }
  40674. }
  40675. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40676. {
  40677. PopupMenu m;
  40678. addMenuItems (m, columnIdClicked);
  40679. if (m.getNumItems() > 0)
  40680. {
  40681. m.setLookAndFeel (&getLookAndFeel());
  40682. const int result = m.show();
  40683. if (result != 0)
  40684. reactToMenuItem (result, columnIdClicked);
  40685. }
  40686. }
  40687. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40688. {
  40689. }
  40690. END_JUCE_NAMESPACE
  40691. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40692. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40693. BEGIN_JUCE_NAMESPACE
  40694. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40695. class TableListRowComp : public Component,
  40696. public TooltipClient
  40697. {
  40698. public:
  40699. TableListRowComp (TableListBox& owner_)
  40700. : owner (owner_),
  40701. row (-1),
  40702. isSelected (false)
  40703. {
  40704. }
  40705. ~TableListRowComp()
  40706. {
  40707. deleteAllChildren();
  40708. }
  40709. void paint (Graphics& g)
  40710. {
  40711. TableListBoxModel* const model = owner.getModel();
  40712. if (model != 0)
  40713. {
  40714. const TableHeaderComponent* const header = owner.getHeader();
  40715. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40716. const int numColumns = header->getNumColumns (true);
  40717. for (int i = 0; i < numColumns; ++i)
  40718. {
  40719. if (! columnsWithComponents [i])
  40720. {
  40721. const int columnId = header->getColumnIdOfIndex (i, true);
  40722. Rectangle<int> columnRect (header->getColumnPosition (i));
  40723. columnRect.setSize (columnRect.getWidth(), getHeight());
  40724. g.saveState();
  40725. g.reduceClipRegion (columnRect);
  40726. g.setOrigin (columnRect.getX(), 0);
  40727. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40728. g.restoreState();
  40729. }
  40730. }
  40731. }
  40732. }
  40733. void update (const int newRow, const bool isNowSelected)
  40734. {
  40735. if (newRow != row || isNowSelected != isSelected)
  40736. {
  40737. row = newRow;
  40738. isSelected = isNowSelected;
  40739. repaint();
  40740. }
  40741. if (row < owner.getNumRows())
  40742. {
  40743. jassert (row >= 0);
  40744. const var::identifier tagPropertyName ("_tableLastUseNum");
  40745. const int newTag = Random::getSystemRandom().nextInt();
  40746. const TableHeaderComponent* const header = owner.getHeader();
  40747. const int numColumns = header->getNumColumns (true);
  40748. int i;
  40749. columnsWithComponents.clear();
  40750. if (owner.getModel() != 0)
  40751. {
  40752. for (i = 0; i < numColumns; ++i)
  40753. {
  40754. const int columnId = header->getColumnIdOfIndex (i, true);
  40755. Component* const newComp
  40756. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40757. findChildComponentForColumn (columnId));
  40758. if (newComp != 0)
  40759. {
  40760. addAndMakeVisible (newComp);
  40761. newComp->getProperties().set (tagPropertyName, newTag);
  40762. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40763. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40764. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40765. columnsWithComponents.setBit (i);
  40766. }
  40767. }
  40768. }
  40769. for (i = getNumChildComponents(); --i >= 0;)
  40770. {
  40771. Component* const c = getChildComponent (i);
  40772. if ((int) c->getProperties() [tagPropertyName] != newTag)
  40773. delete c;
  40774. }
  40775. }
  40776. else
  40777. {
  40778. columnsWithComponents.clear();
  40779. deleteAllChildren();
  40780. }
  40781. }
  40782. void resized()
  40783. {
  40784. for (int i = getNumChildComponents(); --i >= 0;)
  40785. {
  40786. Component* const c = getChildComponent (i);
  40787. const int columnId = c->getProperties() [tableColumnPropertyTag];
  40788. if (columnId != 0)
  40789. {
  40790. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  40791. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40792. }
  40793. }
  40794. }
  40795. void mouseDown (const MouseEvent& e)
  40796. {
  40797. isDragging = false;
  40798. selectRowOnMouseUp = false;
  40799. if (isEnabled())
  40800. {
  40801. if (! isSelected)
  40802. {
  40803. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40804. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40805. if (columnId != 0 && owner.getModel() != 0)
  40806. owner.getModel()->cellClicked (row, columnId, e);
  40807. }
  40808. else
  40809. {
  40810. selectRowOnMouseUp = true;
  40811. }
  40812. }
  40813. }
  40814. void mouseDrag (const MouseEvent& e)
  40815. {
  40816. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  40817. {
  40818. const SparseSet<int> selectedRows (owner.getSelectedRows());
  40819. if (selectedRows.size() > 0)
  40820. {
  40821. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  40822. if (dragDescription.isNotEmpty())
  40823. {
  40824. isDragging = true;
  40825. owner.startDragAndDrop (e, dragDescription);
  40826. }
  40827. }
  40828. }
  40829. }
  40830. void mouseUp (const MouseEvent& e)
  40831. {
  40832. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  40833. {
  40834. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40835. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40836. if (columnId != 0 && owner.getModel() != 0)
  40837. owner.getModel()->cellClicked (row, columnId, e);
  40838. }
  40839. }
  40840. void mouseDoubleClick (const MouseEvent& e)
  40841. {
  40842. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40843. if (columnId != 0 && owner.getModel() != 0)
  40844. owner.getModel()->cellDoubleClicked (row, columnId, e);
  40845. }
  40846. const String getTooltip()
  40847. {
  40848. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  40849. if (columnId != 0 && owner.getModel() != 0)
  40850. return owner.getModel()->getCellTooltip (row, columnId);
  40851. return String::empty;
  40852. }
  40853. juce_UseDebuggingNewOperator
  40854. private:
  40855. TableListBox& owner;
  40856. int row;
  40857. bool isSelected, isDragging, selectRowOnMouseUp;
  40858. BigInteger columnsWithComponents;
  40859. Component* findChildComponentForColumn (const int columnId) const
  40860. {
  40861. for (int i = getNumChildComponents(); --i >= 0;)
  40862. {
  40863. Component* const c = getChildComponent (i);
  40864. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  40865. return c;
  40866. }
  40867. return 0;
  40868. }
  40869. TableListRowComp (const TableListRowComp&);
  40870. TableListRowComp& operator= (const TableListRowComp&);
  40871. };
  40872. class TableListBoxHeader : public TableHeaderComponent
  40873. {
  40874. public:
  40875. TableListBoxHeader (TableListBox& owner_)
  40876. : owner (owner_)
  40877. {
  40878. }
  40879. ~TableListBoxHeader()
  40880. {
  40881. }
  40882. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  40883. {
  40884. if (owner.isAutoSizeMenuOptionShown())
  40885. {
  40886. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  40887. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  40888. menu.addSeparator();
  40889. }
  40890. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  40891. }
  40892. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  40893. {
  40894. if (menuReturnId == 0xf836743)
  40895. {
  40896. owner.autoSizeColumn (columnIdClicked);
  40897. }
  40898. else if (menuReturnId == 0xf836744)
  40899. {
  40900. owner.autoSizeAllColumns();
  40901. }
  40902. else
  40903. {
  40904. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  40905. }
  40906. }
  40907. juce_UseDebuggingNewOperator
  40908. private:
  40909. TableListBox& owner;
  40910. TableListBoxHeader (const TableListBoxHeader&);
  40911. TableListBoxHeader& operator= (const TableListBoxHeader&);
  40912. };
  40913. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  40914. : ListBox (name, 0),
  40915. model (model_),
  40916. autoSizeOptionsShown (true)
  40917. {
  40918. ListBox::model = this;
  40919. header = new TableListBoxHeader (*this);
  40920. header->setSize (100, 28);
  40921. header->addListener (this);
  40922. setHeaderComponent (header);
  40923. }
  40924. TableListBox::~TableListBox()
  40925. {
  40926. deleteAllChildren();
  40927. }
  40928. void TableListBox::setModel (TableListBoxModel* const newModel)
  40929. {
  40930. if (model != newModel)
  40931. {
  40932. model = newModel;
  40933. updateContent();
  40934. }
  40935. }
  40936. int TableListBox::getHeaderHeight() const
  40937. {
  40938. return header->getHeight();
  40939. }
  40940. void TableListBox::setHeaderHeight (const int newHeight)
  40941. {
  40942. header->setSize (header->getWidth(), newHeight);
  40943. resized();
  40944. }
  40945. void TableListBox::autoSizeColumn (const int columnId)
  40946. {
  40947. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  40948. if (width > 0)
  40949. header->setColumnWidth (columnId, width);
  40950. }
  40951. void TableListBox::autoSizeAllColumns()
  40952. {
  40953. for (int i = 0; i < header->getNumColumns (true); ++i)
  40954. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  40955. }
  40956. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  40957. {
  40958. autoSizeOptionsShown = shouldBeShown;
  40959. }
  40960. bool TableListBox::isAutoSizeMenuOptionShown() const
  40961. {
  40962. return autoSizeOptionsShown;
  40963. }
  40964. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  40965. const int rowNumber,
  40966. const bool relativeToComponentTopLeft) const
  40967. {
  40968. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  40969. if (relativeToComponentTopLeft)
  40970. headerCell.translate (header->getX(), 0);
  40971. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  40972. return Rectangle<int> (headerCell.getX(), row.getY(),
  40973. headerCell.getWidth(), row.getHeight());
  40974. }
  40975. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  40976. {
  40977. ScrollBar* const scrollbar = getHorizontalScrollBar();
  40978. if (scrollbar != 0)
  40979. {
  40980. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  40981. double x = scrollbar->getCurrentRangeStart();
  40982. const double w = scrollbar->getCurrentRangeSize();
  40983. if (pos.getX() < x)
  40984. x = pos.getX();
  40985. else if (pos.getRight() > x + w)
  40986. x += jmax (0.0, pos.getRight() - (x + w));
  40987. scrollbar->setCurrentRangeStart (x);
  40988. }
  40989. }
  40990. int TableListBox::getNumRows()
  40991. {
  40992. return model != 0 ? model->getNumRows() : 0;
  40993. }
  40994. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  40995. {
  40996. }
  40997. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  40998. {
  40999. if (existingComponentToUpdate == 0)
  41000. existingComponentToUpdate = new TableListRowComp (*this);
  41001. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41002. return existingComponentToUpdate;
  41003. }
  41004. void TableListBox::selectedRowsChanged (int row)
  41005. {
  41006. if (model != 0)
  41007. model->selectedRowsChanged (row);
  41008. }
  41009. void TableListBox::deleteKeyPressed (int row)
  41010. {
  41011. if (model != 0)
  41012. model->deleteKeyPressed (row);
  41013. }
  41014. void TableListBox::returnKeyPressed (int row)
  41015. {
  41016. if (model != 0)
  41017. model->returnKeyPressed (row);
  41018. }
  41019. void TableListBox::backgroundClicked()
  41020. {
  41021. if (model != 0)
  41022. model->backgroundClicked();
  41023. }
  41024. void TableListBox::listWasScrolled()
  41025. {
  41026. if (model != 0)
  41027. model->listWasScrolled();
  41028. }
  41029. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41030. {
  41031. setMinimumContentWidth (header->getTotalWidth());
  41032. repaint();
  41033. updateColumnComponents();
  41034. }
  41035. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41036. {
  41037. setMinimumContentWidth (header->getTotalWidth());
  41038. repaint();
  41039. updateColumnComponents();
  41040. }
  41041. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41042. {
  41043. if (model != 0)
  41044. model->sortOrderChanged (header->getSortColumnId(),
  41045. header->isSortedForwards());
  41046. }
  41047. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41048. {
  41049. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41050. repaint();
  41051. }
  41052. void TableListBox::resized()
  41053. {
  41054. ListBox::resized();
  41055. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41056. setMinimumContentWidth (header->getTotalWidth());
  41057. }
  41058. void TableListBox::updateColumnComponents() const
  41059. {
  41060. const int firstRow = getRowContainingPosition (0, 0);
  41061. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41062. {
  41063. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41064. if (rowComp != 0)
  41065. rowComp->resized();
  41066. }
  41067. }
  41068. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41069. {
  41070. }
  41071. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41072. {
  41073. }
  41074. void TableListBoxModel::backgroundClicked()
  41075. {
  41076. }
  41077. void TableListBoxModel::sortOrderChanged (int, const bool)
  41078. {
  41079. }
  41080. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41081. {
  41082. return 0;
  41083. }
  41084. void TableListBoxModel::selectedRowsChanged (int)
  41085. {
  41086. }
  41087. void TableListBoxModel::deleteKeyPressed (int)
  41088. {
  41089. }
  41090. void TableListBoxModel::returnKeyPressed (int)
  41091. {
  41092. }
  41093. void TableListBoxModel::listWasScrolled()
  41094. {
  41095. }
  41096. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41097. {
  41098. return String::empty;
  41099. }
  41100. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41101. {
  41102. return String::empty;
  41103. }
  41104. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41105. {
  41106. (void) existingComponentToUpdate;
  41107. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41108. return 0;
  41109. }
  41110. END_JUCE_NAMESPACE
  41111. /*** End of inlined file: juce_TableListBox.cpp ***/
  41112. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41113. BEGIN_JUCE_NAMESPACE
  41114. // a word or space that can't be broken down any further
  41115. struct TextAtom
  41116. {
  41117. String atomText;
  41118. float width;
  41119. uint16 numChars;
  41120. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41121. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41122. const String getText (const juce_wchar passwordCharacter) const
  41123. {
  41124. if (passwordCharacter == 0)
  41125. return atomText;
  41126. else
  41127. return String::repeatedString (String::charToString (passwordCharacter),
  41128. atomText.length());
  41129. }
  41130. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41131. {
  41132. if (passwordCharacter == 0)
  41133. return atomText.substring (0, numChars);
  41134. else if (isNewLine())
  41135. return String::empty;
  41136. else
  41137. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41138. }
  41139. };
  41140. // a run of text with a single font and colour
  41141. class TextEditor::UniformTextSection
  41142. {
  41143. public:
  41144. UniformTextSection (const String& text,
  41145. const Font& font_,
  41146. const Colour& colour_,
  41147. const juce_wchar passwordCharacter)
  41148. : font (font_),
  41149. colour (colour_)
  41150. {
  41151. initialiseAtoms (text, passwordCharacter);
  41152. }
  41153. UniformTextSection (const UniformTextSection& other)
  41154. : font (other.font),
  41155. colour (other.colour)
  41156. {
  41157. atoms.ensureStorageAllocated (other.atoms.size());
  41158. for (int i = 0; i < other.atoms.size(); ++i)
  41159. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41160. }
  41161. ~UniformTextSection()
  41162. {
  41163. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41164. }
  41165. void clear()
  41166. {
  41167. for (int i = atoms.size(); --i >= 0;)
  41168. delete getAtom(i);
  41169. atoms.clear();
  41170. }
  41171. int getNumAtoms() const
  41172. {
  41173. return atoms.size();
  41174. }
  41175. TextAtom* getAtom (const int index) const throw()
  41176. {
  41177. return atoms.getUnchecked (index);
  41178. }
  41179. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41180. {
  41181. if (other.atoms.size() > 0)
  41182. {
  41183. TextAtom* const lastAtom = atoms.getLast();
  41184. int i = 0;
  41185. if (lastAtom != 0)
  41186. {
  41187. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41188. {
  41189. TextAtom* const first = other.getAtom(0);
  41190. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41191. {
  41192. lastAtom->atomText += first->atomText;
  41193. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41194. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41195. delete first;
  41196. ++i;
  41197. }
  41198. }
  41199. }
  41200. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41201. while (i < other.atoms.size())
  41202. {
  41203. atoms.add (other.getAtom(i));
  41204. ++i;
  41205. }
  41206. }
  41207. }
  41208. UniformTextSection* split (const int indexToBreakAt,
  41209. const juce_wchar passwordCharacter)
  41210. {
  41211. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41212. font, colour,
  41213. passwordCharacter);
  41214. int index = 0;
  41215. for (int i = 0; i < atoms.size(); ++i)
  41216. {
  41217. TextAtom* const atom = getAtom(i);
  41218. const int nextIndex = index + atom->numChars;
  41219. if (index == indexToBreakAt)
  41220. {
  41221. int j;
  41222. for (j = i; j < atoms.size(); ++j)
  41223. section2->atoms.add (getAtom (j));
  41224. for (j = atoms.size(); --j >= i;)
  41225. atoms.remove (j);
  41226. break;
  41227. }
  41228. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41229. {
  41230. TextAtom* const secondAtom = new TextAtom();
  41231. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41232. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41233. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41234. section2->atoms.add (secondAtom);
  41235. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41236. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41237. atom->numChars = (uint16) (indexToBreakAt - index);
  41238. int j;
  41239. for (j = i + 1; j < atoms.size(); ++j)
  41240. section2->atoms.add (getAtom (j));
  41241. for (j = atoms.size(); --j > i;)
  41242. atoms.remove (j);
  41243. break;
  41244. }
  41245. index = nextIndex;
  41246. }
  41247. return section2;
  41248. }
  41249. void appendAllText (String::Concatenator& concatenator) const
  41250. {
  41251. for (int i = 0; i < atoms.size(); ++i)
  41252. concatenator.append (getAtom(i)->atomText);
  41253. }
  41254. void appendSubstring (String::Concatenator& concatenator,
  41255. const Range<int>& range) const
  41256. {
  41257. int index = 0;
  41258. for (int i = 0; i < atoms.size(); ++i)
  41259. {
  41260. const TextAtom* const atom = getAtom (i);
  41261. const int nextIndex = index + atom->numChars;
  41262. if (range.getStart() < nextIndex)
  41263. {
  41264. if (range.getEnd() <= index)
  41265. break;
  41266. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41267. if (! r.isEmpty())
  41268. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41269. }
  41270. index = nextIndex;
  41271. }
  41272. }
  41273. int getTotalLength() const
  41274. {
  41275. int total = 0;
  41276. for (int i = atoms.size(); --i >= 0;)
  41277. total += getAtom(i)->numChars;
  41278. return total;
  41279. }
  41280. void setFont (const Font& newFont,
  41281. const juce_wchar passwordCharacter)
  41282. {
  41283. if (font != newFont)
  41284. {
  41285. font = newFont;
  41286. for (int i = atoms.size(); --i >= 0;)
  41287. {
  41288. TextAtom* const atom = atoms.getUnchecked(i);
  41289. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41290. }
  41291. }
  41292. }
  41293. juce_UseDebuggingNewOperator
  41294. Font font;
  41295. Colour colour;
  41296. private:
  41297. Array <TextAtom*> atoms;
  41298. void initialiseAtoms (const String& textToParse,
  41299. const juce_wchar passwordCharacter)
  41300. {
  41301. int i = 0;
  41302. const int len = textToParse.length();
  41303. const juce_wchar* const text = textToParse;
  41304. while (i < len)
  41305. {
  41306. int start = i;
  41307. // create a whitespace atom unless it starts with non-ws
  41308. if (CharacterFunctions::isWhitespace (text[i])
  41309. && text[i] != '\r'
  41310. && text[i] != '\n')
  41311. {
  41312. while (i < len
  41313. && CharacterFunctions::isWhitespace (text[i])
  41314. && text[i] != '\r'
  41315. && text[i] != '\n')
  41316. {
  41317. ++i;
  41318. }
  41319. }
  41320. else
  41321. {
  41322. if (text[i] == '\r')
  41323. {
  41324. ++i;
  41325. if ((i < len) && (text[i] == '\n'))
  41326. {
  41327. ++start;
  41328. ++i;
  41329. }
  41330. }
  41331. else if (text[i] == '\n')
  41332. {
  41333. ++i;
  41334. }
  41335. else
  41336. {
  41337. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41338. ++i;
  41339. }
  41340. }
  41341. TextAtom* const atom = new TextAtom();
  41342. atom->atomText = String (text + start, i - start);
  41343. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41344. atom->numChars = (uint16) (i - start);
  41345. atoms.add (atom);
  41346. }
  41347. }
  41348. UniformTextSection& operator= (const UniformTextSection& other);
  41349. };
  41350. class TextEditor::Iterator
  41351. {
  41352. public:
  41353. Iterator (const Array <UniformTextSection*>& sections_,
  41354. const float wordWrapWidth_,
  41355. const juce_wchar passwordCharacter_)
  41356. : indexInText (0),
  41357. lineY (0),
  41358. lineHeight (0),
  41359. maxDescent (0),
  41360. atomX (0),
  41361. atomRight (0),
  41362. atom (0),
  41363. currentSection (0),
  41364. sections (sections_),
  41365. sectionIndex (0),
  41366. atomIndex (0),
  41367. wordWrapWidth (wordWrapWidth_),
  41368. passwordCharacter (passwordCharacter_)
  41369. {
  41370. jassert (wordWrapWidth_ > 0);
  41371. if (sections.size() > 0)
  41372. {
  41373. currentSection = sections.getUnchecked (sectionIndex);
  41374. if (currentSection != 0)
  41375. beginNewLine();
  41376. }
  41377. }
  41378. Iterator (const Iterator& other)
  41379. : indexInText (other.indexInText),
  41380. lineY (other.lineY),
  41381. lineHeight (other.lineHeight),
  41382. maxDescent (other.maxDescent),
  41383. atomX (other.atomX),
  41384. atomRight (other.atomRight),
  41385. atom (other.atom),
  41386. currentSection (other.currentSection),
  41387. sections (other.sections),
  41388. sectionIndex (other.sectionIndex),
  41389. atomIndex (other.atomIndex),
  41390. wordWrapWidth (other.wordWrapWidth),
  41391. passwordCharacter (other.passwordCharacter),
  41392. tempAtom (other.tempAtom)
  41393. {
  41394. }
  41395. ~Iterator()
  41396. {
  41397. }
  41398. bool next()
  41399. {
  41400. if (atom == &tempAtom)
  41401. {
  41402. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41403. if (numRemaining > 0)
  41404. {
  41405. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41406. atomX = 0;
  41407. if (tempAtom.numChars > 0)
  41408. lineY += lineHeight;
  41409. indexInText += tempAtom.numChars;
  41410. GlyphArrangement g;
  41411. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41412. int split;
  41413. for (split = 0; split < g.getNumGlyphs(); ++split)
  41414. if (shouldWrap (g.getGlyph (split).getRight()))
  41415. break;
  41416. if (split > 0 && split <= numRemaining)
  41417. {
  41418. tempAtom.numChars = (uint16) split;
  41419. tempAtom.width = g.getGlyph (split - 1).getRight();
  41420. atomRight = atomX + tempAtom.width;
  41421. return true;
  41422. }
  41423. }
  41424. }
  41425. bool forceNewLine = false;
  41426. if (sectionIndex >= sections.size())
  41427. {
  41428. moveToEndOfLastAtom();
  41429. return false;
  41430. }
  41431. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41432. {
  41433. if (atomIndex >= currentSection->getNumAtoms())
  41434. {
  41435. if (++sectionIndex >= sections.size())
  41436. {
  41437. moveToEndOfLastAtom();
  41438. return false;
  41439. }
  41440. atomIndex = 0;
  41441. currentSection = sections.getUnchecked (sectionIndex);
  41442. }
  41443. else
  41444. {
  41445. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41446. if (! lastAtom->isWhitespace())
  41447. {
  41448. // handle the case where the last atom in a section is actually part of the same
  41449. // word as the first atom of the next section...
  41450. float right = atomRight + lastAtom->width;
  41451. float lineHeight2 = lineHeight;
  41452. float maxDescent2 = maxDescent;
  41453. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41454. {
  41455. const UniformTextSection* const s = sections.getUnchecked (section);
  41456. if (s->getNumAtoms() == 0)
  41457. break;
  41458. const TextAtom* const nextAtom = s->getAtom (0);
  41459. if (nextAtom->isWhitespace())
  41460. break;
  41461. right += nextAtom->width;
  41462. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41463. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41464. if (shouldWrap (right))
  41465. {
  41466. lineHeight = lineHeight2;
  41467. maxDescent = maxDescent2;
  41468. forceNewLine = true;
  41469. break;
  41470. }
  41471. if (s->getNumAtoms() > 1)
  41472. break;
  41473. }
  41474. }
  41475. }
  41476. }
  41477. if (atom != 0)
  41478. {
  41479. atomX = atomRight;
  41480. indexInText += atom->numChars;
  41481. if (atom->isNewLine())
  41482. beginNewLine();
  41483. }
  41484. atom = currentSection->getAtom (atomIndex);
  41485. atomRight = atomX + atom->width;
  41486. ++atomIndex;
  41487. if (shouldWrap (atomRight) || forceNewLine)
  41488. {
  41489. if (atom->isWhitespace())
  41490. {
  41491. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41492. atomRight = jmin (atomRight, wordWrapWidth);
  41493. }
  41494. else
  41495. {
  41496. atomRight = atom->width;
  41497. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41498. {
  41499. tempAtom = *atom;
  41500. tempAtom.width = 0;
  41501. tempAtom.numChars = 0;
  41502. atom = &tempAtom;
  41503. if (atomX > 0)
  41504. beginNewLine();
  41505. return next();
  41506. }
  41507. beginNewLine();
  41508. return true;
  41509. }
  41510. }
  41511. return true;
  41512. }
  41513. void beginNewLine()
  41514. {
  41515. atomX = 0;
  41516. lineY += lineHeight;
  41517. int tempSectionIndex = sectionIndex;
  41518. int tempAtomIndex = atomIndex;
  41519. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41520. lineHeight = section->font.getHeight();
  41521. maxDescent = section->font.getDescent();
  41522. float x = (atom != 0) ? atom->width : 0;
  41523. while (! shouldWrap (x))
  41524. {
  41525. if (tempSectionIndex >= sections.size())
  41526. break;
  41527. bool checkSize = false;
  41528. if (tempAtomIndex >= section->getNumAtoms())
  41529. {
  41530. if (++tempSectionIndex >= sections.size())
  41531. break;
  41532. tempAtomIndex = 0;
  41533. section = sections.getUnchecked (tempSectionIndex);
  41534. checkSize = true;
  41535. }
  41536. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41537. if (nextAtom == 0)
  41538. break;
  41539. x += nextAtom->width;
  41540. if (shouldWrap (x) || nextAtom->isNewLine())
  41541. break;
  41542. if (checkSize)
  41543. {
  41544. lineHeight = jmax (lineHeight, section->font.getHeight());
  41545. maxDescent = jmax (maxDescent, section->font.getDescent());
  41546. }
  41547. ++tempAtomIndex;
  41548. }
  41549. }
  41550. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41551. {
  41552. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41553. {
  41554. if (lastSection != currentSection)
  41555. {
  41556. lastSection = currentSection;
  41557. g.setColour (currentSection->colour);
  41558. g.setFont (currentSection->font);
  41559. }
  41560. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41561. GlyphArrangement ga;
  41562. ga.addLineOfText (currentSection->font,
  41563. atom->getTrimmedText (passwordCharacter),
  41564. atomX,
  41565. (float) roundToInt (lineY + lineHeight - maxDescent));
  41566. ga.draw (g);
  41567. }
  41568. }
  41569. void drawSelection (Graphics& g,
  41570. const Range<int>& selection) const
  41571. {
  41572. const int startX = roundToInt (indexToX (selection.getStart()));
  41573. const int endX = roundToInt (indexToX (selection.getEnd()));
  41574. const int y = roundToInt (lineY);
  41575. const int nextY = roundToInt (lineY + lineHeight);
  41576. g.fillRect (startX, y, endX - startX, nextY - y);
  41577. }
  41578. void drawSelectedText (Graphics& g,
  41579. const Range<int>& selection,
  41580. const Colour& selectedTextColour) const
  41581. {
  41582. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41583. {
  41584. GlyphArrangement ga;
  41585. ga.addLineOfText (currentSection->font,
  41586. atom->getTrimmedText (passwordCharacter),
  41587. atomX,
  41588. (float) roundToInt (lineY + lineHeight - maxDescent));
  41589. if (selection.getEnd() < indexInText + atom->numChars)
  41590. {
  41591. GlyphArrangement ga2 (ga);
  41592. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41593. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41594. g.setColour (currentSection->colour);
  41595. ga2.draw (g);
  41596. }
  41597. if (selection.getStart() > indexInText)
  41598. {
  41599. GlyphArrangement ga2 (ga);
  41600. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41601. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41602. g.setColour (currentSection->colour);
  41603. ga2.draw (g);
  41604. }
  41605. g.setColour (selectedTextColour);
  41606. ga.draw (g);
  41607. }
  41608. }
  41609. float indexToX (const int indexToFind) const
  41610. {
  41611. if (indexToFind <= indexInText)
  41612. return atomX;
  41613. if (indexToFind >= indexInText + atom->numChars)
  41614. return atomRight;
  41615. GlyphArrangement g;
  41616. g.addLineOfText (currentSection->font,
  41617. atom->getText (passwordCharacter),
  41618. atomX, 0.0f);
  41619. if (indexToFind - indexInText >= g.getNumGlyphs())
  41620. return atomRight;
  41621. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41622. }
  41623. int xToIndex (const float xToFind) const
  41624. {
  41625. if (xToFind <= atomX || atom->isNewLine())
  41626. return indexInText;
  41627. if (xToFind >= atomRight)
  41628. return indexInText + atom->numChars;
  41629. GlyphArrangement g;
  41630. g.addLineOfText (currentSection->font,
  41631. atom->getText (passwordCharacter),
  41632. atomX, 0.0f);
  41633. int j;
  41634. for (j = 0; j < g.getNumGlyphs(); ++j)
  41635. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41636. break;
  41637. return indexInText + j;
  41638. }
  41639. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41640. {
  41641. while (next())
  41642. {
  41643. if (indexInText + atom->numChars > index)
  41644. {
  41645. cx = indexToX (index);
  41646. cy = lineY;
  41647. lineHeight_ = lineHeight;
  41648. return true;
  41649. }
  41650. }
  41651. cx = atomX;
  41652. cy = lineY;
  41653. lineHeight_ = lineHeight;
  41654. return false;
  41655. }
  41656. juce_UseDebuggingNewOperator
  41657. int indexInText;
  41658. float lineY, lineHeight, maxDescent;
  41659. float atomX, atomRight;
  41660. const TextAtom* atom;
  41661. const UniformTextSection* currentSection;
  41662. private:
  41663. const Array <UniformTextSection*>& sections;
  41664. int sectionIndex, atomIndex;
  41665. const float wordWrapWidth;
  41666. const juce_wchar passwordCharacter;
  41667. TextAtom tempAtom;
  41668. Iterator& operator= (const Iterator&);
  41669. void moveToEndOfLastAtom()
  41670. {
  41671. if (atom != 0)
  41672. {
  41673. atomX = atomRight;
  41674. if (atom->isNewLine())
  41675. {
  41676. atomX = 0.0f;
  41677. lineY += lineHeight;
  41678. }
  41679. }
  41680. }
  41681. bool shouldWrap (const float x) const
  41682. {
  41683. return (x - 0.0001f) >= wordWrapWidth;
  41684. }
  41685. };
  41686. class TextEditor::InsertAction : public UndoableAction
  41687. {
  41688. TextEditor& owner;
  41689. const String text;
  41690. const int insertIndex, oldCaretPos, newCaretPos;
  41691. const Font font;
  41692. const Colour colour;
  41693. InsertAction (const InsertAction&);
  41694. InsertAction& operator= (const InsertAction&);
  41695. public:
  41696. InsertAction (TextEditor& owner_,
  41697. const String& text_,
  41698. const int insertIndex_,
  41699. const Font& font_,
  41700. const Colour& colour_,
  41701. const int oldCaretPos_,
  41702. const int newCaretPos_)
  41703. : owner (owner_),
  41704. text (text_),
  41705. insertIndex (insertIndex_),
  41706. oldCaretPos (oldCaretPos_),
  41707. newCaretPos (newCaretPos_),
  41708. font (font_),
  41709. colour (colour_)
  41710. {
  41711. }
  41712. ~InsertAction()
  41713. {
  41714. }
  41715. bool perform()
  41716. {
  41717. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41718. return true;
  41719. }
  41720. bool undo()
  41721. {
  41722. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41723. return true;
  41724. }
  41725. int getSizeInUnits()
  41726. {
  41727. return text.length() + 16;
  41728. }
  41729. };
  41730. class TextEditor::RemoveAction : public UndoableAction
  41731. {
  41732. TextEditor& owner;
  41733. const Range<int> range;
  41734. const int oldCaretPos, newCaretPos;
  41735. Array <UniformTextSection*> removedSections;
  41736. RemoveAction (const RemoveAction&);
  41737. RemoveAction& operator= (const RemoveAction&);
  41738. public:
  41739. RemoveAction (TextEditor& owner_,
  41740. const Range<int> range_,
  41741. const int oldCaretPos_,
  41742. const int newCaretPos_,
  41743. const Array <UniformTextSection*>& removedSections_)
  41744. : owner (owner_),
  41745. range (range_),
  41746. oldCaretPos (oldCaretPos_),
  41747. newCaretPos (newCaretPos_),
  41748. removedSections (removedSections_)
  41749. {
  41750. }
  41751. ~RemoveAction()
  41752. {
  41753. for (int i = removedSections.size(); --i >= 0;)
  41754. {
  41755. UniformTextSection* const section = removedSections.getUnchecked (i);
  41756. section->clear();
  41757. delete section;
  41758. }
  41759. }
  41760. bool perform()
  41761. {
  41762. owner.remove (range, 0, newCaretPos);
  41763. return true;
  41764. }
  41765. bool undo()
  41766. {
  41767. owner.reinsert (range.getStart(), removedSections);
  41768. owner.moveCursorTo (oldCaretPos, false);
  41769. return true;
  41770. }
  41771. int getSizeInUnits()
  41772. {
  41773. int n = 0;
  41774. for (int i = removedSections.size(); --i >= 0;)
  41775. n += removedSections.getUnchecked (i)->getTotalLength();
  41776. return n + 16;
  41777. }
  41778. };
  41779. class TextEditor::TextHolderComponent : public Component,
  41780. public Timer,
  41781. public Value::Listener
  41782. {
  41783. public:
  41784. TextHolderComponent (TextEditor& owner_)
  41785. : owner (owner_)
  41786. {
  41787. setWantsKeyboardFocus (false);
  41788. setInterceptsMouseClicks (false, true);
  41789. owner.getTextValue().addListener (this);
  41790. }
  41791. ~TextHolderComponent()
  41792. {
  41793. owner.getTextValue().removeListener (this);
  41794. }
  41795. void paint (Graphics& g)
  41796. {
  41797. owner.drawContent (g);
  41798. }
  41799. void timerCallback()
  41800. {
  41801. owner.timerCallbackInt();
  41802. }
  41803. const MouseCursor getMouseCursor()
  41804. {
  41805. return owner.getMouseCursor();
  41806. }
  41807. void valueChanged (Value&)
  41808. {
  41809. owner.textWasChangedByValue();
  41810. }
  41811. private:
  41812. TextEditor& owner;
  41813. TextHolderComponent (const TextHolderComponent&);
  41814. TextHolderComponent& operator= (const TextHolderComponent&);
  41815. };
  41816. class TextEditorViewport : public Viewport
  41817. {
  41818. public:
  41819. TextEditorViewport (TextEditor* const owner_)
  41820. : owner (owner_),
  41821. lastWordWrapWidth (0)
  41822. {
  41823. }
  41824. ~TextEditorViewport()
  41825. {
  41826. }
  41827. void visibleAreaChanged (int, int, int, int)
  41828. {
  41829. const float wordWrapWidth = owner->getWordWrapWidth();
  41830. if (wordWrapWidth != lastWordWrapWidth)
  41831. {
  41832. lastWordWrapWidth = wordWrapWidth;
  41833. owner->updateTextHolderSize();
  41834. }
  41835. }
  41836. private:
  41837. TextEditor* const owner;
  41838. float lastWordWrapWidth;
  41839. TextEditorViewport (const TextEditorViewport&);
  41840. TextEditorViewport& operator= (const TextEditorViewport&);
  41841. };
  41842. namespace TextEditorDefs
  41843. {
  41844. const int flashSpeedIntervalMs = 380;
  41845. const int textChangeMessageId = 0x10003001;
  41846. const int returnKeyMessageId = 0x10003002;
  41847. const int escapeKeyMessageId = 0x10003003;
  41848. const int focusLossMessageId = 0x10003004;
  41849. const int maxActionsPerTransaction = 100;
  41850. }
  41851. TextEditor::TextEditor (const String& name,
  41852. const juce_wchar passwordCharacter_)
  41853. : Component (name),
  41854. borderSize (1, 1, 1, 3),
  41855. readOnly (false),
  41856. multiline (false),
  41857. wordWrap (false),
  41858. returnKeyStartsNewLine (false),
  41859. caretVisible (true),
  41860. popupMenuEnabled (true),
  41861. selectAllTextWhenFocused (false),
  41862. scrollbarVisible (true),
  41863. wasFocused (false),
  41864. caretFlashState (true),
  41865. keepCursorOnScreen (true),
  41866. tabKeyUsed (false),
  41867. menuActive (false),
  41868. valueTextNeedsUpdating (false),
  41869. cursorX (0),
  41870. cursorY (0),
  41871. cursorHeight (0),
  41872. maxTextLength (0),
  41873. leftIndent (4),
  41874. topIndent (4),
  41875. lastTransactionTime (0),
  41876. currentFont (14.0f),
  41877. totalNumChars (0),
  41878. caretPosition (0),
  41879. passwordCharacter (passwordCharacter_),
  41880. dragType (notDragging)
  41881. {
  41882. setOpaque (true);
  41883. addAndMakeVisible (viewport = new TextEditorViewport (this));
  41884. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  41885. viewport->setWantsKeyboardFocus (false);
  41886. viewport->setScrollBarsShown (false, false);
  41887. setMouseCursor (MouseCursor::IBeamCursor);
  41888. setWantsKeyboardFocus (true);
  41889. }
  41890. TextEditor::~TextEditor()
  41891. {
  41892. textValue.referTo (Value());
  41893. clearInternal (0);
  41894. viewport = 0;
  41895. textHolder = 0;
  41896. }
  41897. void TextEditor::newTransaction()
  41898. {
  41899. lastTransactionTime = Time::getApproximateMillisecondCounter();
  41900. undoManager.beginNewTransaction();
  41901. }
  41902. void TextEditor::doUndoRedo (const bool isRedo)
  41903. {
  41904. if (! isReadOnly())
  41905. {
  41906. if (isRedo ? undoManager.redo()
  41907. : undoManager.undo())
  41908. {
  41909. scrollToMakeSureCursorIsVisible();
  41910. repaint();
  41911. textChanged();
  41912. }
  41913. }
  41914. }
  41915. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  41916. const bool shouldWordWrap)
  41917. {
  41918. multiline = shouldBeMultiLine;
  41919. wordWrap = shouldWordWrap && shouldBeMultiLine;
  41920. setScrollbarsShown (scrollbarVisible);
  41921. viewport->setViewPosition (0, 0);
  41922. resized();
  41923. scrollToMakeSureCursorIsVisible();
  41924. }
  41925. bool TextEditor::isMultiLine() const
  41926. {
  41927. return multiline;
  41928. }
  41929. void TextEditor::setScrollbarsShown (bool enabled)
  41930. {
  41931. scrollbarVisible = enabled;
  41932. enabled = enabled && isMultiLine();
  41933. viewport->setScrollBarsShown (enabled, enabled);
  41934. }
  41935. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  41936. {
  41937. readOnly = shouldBeReadOnly;
  41938. enablementChanged();
  41939. }
  41940. bool TextEditor::isReadOnly() const
  41941. {
  41942. return readOnly || ! isEnabled();
  41943. }
  41944. bool TextEditor::isTextInputActive() const
  41945. {
  41946. return ! isReadOnly();
  41947. }
  41948. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  41949. {
  41950. returnKeyStartsNewLine = shouldStartNewLine;
  41951. }
  41952. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  41953. {
  41954. tabKeyUsed = shouldTabKeyBeUsed;
  41955. }
  41956. void TextEditor::setPopupMenuEnabled (const bool b)
  41957. {
  41958. popupMenuEnabled = b;
  41959. }
  41960. void TextEditor::setSelectAllWhenFocused (const bool b)
  41961. {
  41962. selectAllTextWhenFocused = b;
  41963. }
  41964. const Font TextEditor::getFont() const
  41965. {
  41966. return currentFont;
  41967. }
  41968. void TextEditor::setFont (const Font& newFont)
  41969. {
  41970. currentFont = newFont;
  41971. scrollToMakeSureCursorIsVisible();
  41972. }
  41973. void TextEditor::applyFontToAllText (const Font& newFont)
  41974. {
  41975. currentFont = newFont;
  41976. const Colour overallColour (findColour (textColourId));
  41977. for (int i = sections.size(); --i >= 0;)
  41978. {
  41979. UniformTextSection* const uts = sections.getUnchecked (i);
  41980. uts->setFont (newFont, passwordCharacter);
  41981. uts->colour = overallColour;
  41982. }
  41983. coalesceSimilarSections();
  41984. updateTextHolderSize();
  41985. scrollToMakeSureCursorIsVisible();
  41986. repaint();
  41987. }
  41988. void TextEditor::colourChanged()
  41989. {
  41990. setOpaque (findColour (backgroundColourId).isOpaque());
  41991. repaint();
  41992. }
  41993. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  41994. {
  41995. caretVisible = shouldCaretBeVisible;
  41996. if (shouldCaretBeVisible)
  41997. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  41998. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  41999. : MouseCursor::NormalCursor);
  42000. }
  42001. void TextEditor::setInputRestrictions (const int maxLen,
  42002. const String& chars)
  42003. {
  42004. maxTextLength = jmax (0, maxLen);
  42005. allowedCharacters = chars;
  42006. }
  42007. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42008. {
  42009. textToShowWhenEmpty = text;
  42010. colourForTextWhenEmpty = colourToUse;
  42011. }
  42012. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42013. {
  42014. if (passwordCharacter != newPasswordCharacter)
  42015. {
  42016. passwordCharacter = newPasswordCharacter;
  42017. resized();
  42018. repaint();
  42019. }
  42020. }
  42021. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42022. {
  42023. viewport->setScrollBarThickness (newThicknessPixels);
  42024. }
  42025. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42026. {
  42027. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42028. }
  42029. void TextEditor::clear()
  42030. {
  42031. clearInternal (0);
  42032. updateTextHolderSize();
  42033. undoManager.clearUndoHistory();
  42034. }
  42035. void TextEditor::setText (const String& newText,
  42036. const bool sendTextChangeMessage)
  42037. {
  42038. const int newLength = newText.length();
  42039. if (newLength != getTotalNumChars() || getText() != newText)
  42040. {
  42041. const int oldCursorPos = caretPosition;
  42042. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42043. clearInternal (0);
  42044. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42045. // if you're adding text with line-feeds to a single-line text editor, it
  42046. // ain't gonna look right!
  42047. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42048. if (cursorWasAtEnd && ! isMultiLine())
  42049. moveCursorTo (getTotalNumChars(), false);
  42050. else
  42051. moveCursorTo (oldCursorPos, false);
  42052. if (sendTextChangeMessage)
  42053. textChanged();
  42054. repaint();
  42055. }
  42056. updateTextHolderSize();
  42057. scrollToMakeSureCursorIsVisible();
  42058. undoManager.clearUndoHistory();
  42059. }
  42060. Value& TextEditor::getTextValue()
  42061. {
  42062. if (valueTextNeedsUpdating)
  42063. {
  42064. valueTextNeedsUpdating = false;
  42065. textValue = getText();
  42066. }
  42067. return textValue;
  42068. }
  42069. void TextEditor::textWasChangedByValue()
  42070. {
  42071. if (textValue.getValueSource().getReferenceCount() > 1)
  42072. setText (textValue.getValue());
  42073. }
  42074. void TextEditor::textChanged()
  42075. {
  42076. updateTextHolderSize();
  42077. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42078. if (textValue.getValueSource().getReferenceCount() > 1)
  42079. {
  42080. valueTextNeedsUpdating = false;
  42081. textValue = getText();
  42082. }
  42083. }
  42084. void TextEditor::returnPressed()
  42085. {
  42086. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42087. }
  42088. void TextEditor::escapePressed()
  42089. {
  42090. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42091. }
  42092. void TextEditor::addListener (TextEditorListener* const newListener)
  42093. {
  42094. listeners.add (newListener);
  42095. }
  42096. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42097. {
  42098. listeners.remove (listenerToRemove);
  42099. }
  42100. void TextEditor::timerCallbackInt()
  42101. {
  42102. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42103. if (caretFlashState != newState)
  42104. {
  42105. caretFlashState = newState;
  42106. if (caretFlashState)
  42107. wasFocused = true;
  42108. if (caretVisible
  42109. && hasKeyboardFocus (false)
  42110. && ! isReadOnly())
  42111. {
  42112. repaintCaret();
  42113. }
  42114. }
  42115. const unsigned int now = Time::getApproximateMillisecondCounter();
  42116. if (now > lastTransactionTime + 200)
  42117. newTransaction();
  42118. }
  42119. void TextEditor::repaintCaret()
  42120. {
  42121. if (! findColour (caretColourId).isTransparent())
  42122. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42123. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42124. 4,
  42125. roundToInt (cursorHeight) + 2);
  42126. }
  42127. void TextEditor::repaintText (const Range<int>& range)
  42128. {
  42129. if (! range.isEmpty())
  42130. {
  42131. float x = 0, y = 0, lh = currentFont.getHeight();
  42132. const float wordWrapWidth = getWordWrapWidth();
  42133. if (wordWrapWidth > 0)
  42134. {
  42135. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42136. i.getCharPosition (range.getStart(), x, y, lh);
  42137. const int y1 = (int) y;
  42138. int y2;
  42139. if (range.getEnd() >= getTotalNumChars())
  42140. {
  42141. y2 = textHolder->getHeight();
  42142. }
  42143. else
  42144. {
  42145. i.getCharPosition (range.getEnd(), x, y, lh);
  42146. y2 = (int) (y + lh * 2.0f);
  42147. }
  42148. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42149. }
  42150. }
  42151. }
  42152. void TextEditor::moveCaret (int newCaretPos)
  42153. {
  42154. if (newCaretPos < 0)
  42155. newCaretPos = 0;
  42156. else if (newCaretPos > getTotalNumChars())
  42157. newCaretPos = getTotalNumChars();
  42158. if (newCaretPos != getCaretPosition())
  42159. {
  42160. repaintCaret();
  42161. caretFlashState = true;
  42162. caretPosition = newCaretPos;
  42163. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42164. scrollToMakeSureCursorIsVisible();
  42165. repaintCaret();
  42166. }
  42167. }
  42168. void TextEditor::setCaretPosition (const int newIndex)
  42169. {
  42170. moveCursorTo (newIndex, false);
  42171. }
  42172. int TextEditor::getCaretPosition() const
  42173. {
  42174. return caretPosition;
  42175. }
  42176. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42177. const int desiredCaretY)
  42178. {
  42179. updateCaretPosition();
  42180. int vx = roundToInt (cursorX) - desiredCaretX;
  42181. int vy = roundToInt (cursorY) - desiredCaretY;
  42182. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42183. {
  42184. vx += desiredCaretX - proportionOfWidth (0.2f);
  42185. }
  42186. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42187. {
  42188. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42189. }
  42190. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42191. if (! isMultiLine())
  42192. {
  42193. vy = viewport->getViewPositionY();
  42194. }
  42195. else
  42196. {
  42197. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42198. const int curH = roundToInt (cursorHeight);
  42199. if (desiredCaretY < 0)
  42200. {
  42201. vy = jmax (0, desiredCaretY + vy);
  42202. }
  42203. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42204. {
  42205. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42206. }
  42207. }
  42208. viewport->setViewPosition (vx, vy);
  42209. }
  42210. const Rectangle<int> TextEditor::getCaretRectangle()
  42211. {
  42212. updateCaretPosition();
  42213. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42214. roundToInt (cursorY) - viewport->getY(),
  42215. 1, roundToInt (cursorHeight));
  42216. }
  42217. float TextEditor::getWordWrapWidth() const
  42218. {
  42219. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42220. : 1.0e10f;
  42221. }
  42222. void TextEditor::updateTextHolderSize()
  42223. {
  42224. const float wordWrapWidth = getWordWrapWidth();
  42225. if (wordWrapWidth > 0)
  42226. {
  42227. float maxWidth = 0.0f;
  42228. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42229. while (i.next())
  42230. maxWidth = jmax (maxWidth, i.atomRight);
  42231. const int w = leftIndent + roundToInt (maxWidth);
  42232. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42233. currentFont.getHeight()));
  42234. textHolder->setSize (w + 1, h + 1);
  42235. }
  42236. }
  42237. int TextEditor::getTextWidth() const
  42238. {
  42239. return textHolder->getWidth();
  42240. }
  42241. int TextEditor::getTextHeight() const
  42242. {
  42243. return textHolder->getHeight();
  42244. }
  42245. void TextEditor::setIndents (const int newLeftIndent,
  42246. const int newTopIndent)
  42247. {
  42248. leftIndent = newLeftIndent;
  42249. topIndent = newTopIndent;
  42250. }
  42251. void TextEditor::setBorder (const BorderSize& border)
  42252. {
  42253. borderSize = border;
  42254. resized();
  42255. }
  42256. const BorderSize TextEditor::getBorder() const
  42257. {
  42258. return borderSize;
  42259. }
  42260. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42261. {
  42262. keepCursorOnScreen = shouldScrollToShowCursor;
  42263. }
  42264. void TextEditor::updateCaretPosition()
  42265. {
  42266. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42267. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42268. }
  42269. void TextEditor::scrollToMakeSureCursorIsVisible()
  42270. {
  42271. updateCaretPosition();
  42272. if (keepCursorOnScreen)
  42273. {
  42274. int x = viewport->getViewPositionX();
  42275. int y = viewport->getViewPositionY();
  42276. const int relativeCursorX = roundToInt (cursorX) - x;
  42277. const int relativeCursorY = roundToInt (cursorY) - y;
  42278. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42279. {
  42280. x += relativeCursorX - proportionOfWidth (0.2f);
  42281. }
  42282. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42283. {
  42284. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42285. }
  42286. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42287. if (! isMultiLine())
  42288. {
  42289. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42290. }
  42291. else
  42292. {
  42293. const int curH = roundToInt (cursorHeight);
  42294. if (relativeCursorY < 0)
  42295. {
  42296. y = jmax (0, relativeCursorY + y);
  42297. }
  42298. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42299. {
  42300. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42301. }
  42302. }
  42303. viewport->setViewPosition (x, y);
  42304. }
  42305. }
  42306. void TextEditor::moveCursorTo (const int newPosition,
  42307. const bool isSelecting)
  42308. {
  42309. if (isSelecting)
  42310. {
  42311. moveCaret (newPosition);
  42312. const Range<int> oldSelection (selection);
  42313. if (dragType == notDragging)
  42314. {
  42315. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42316. dragType = draggingSelectionStart;
  42317. else
  42318. dragType = draggingSelectionEnd;
  42319. }
  42320. if (dragType == draggingSelectionStart)
  42321. {
  42322. if (getCaretPosition() >= selection.getEnd())
  42323. dragType = draggingSelectionEnd;
  42324. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42325. }
  42326. else
  42327. {
  42328. if (getCaretPosition() < selection.getStart())
  42329. dragType = draggingSelectionStart;
  42330. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42331. }
  42332. repaintText (selection.getUnionWith (oldSelection));
  42333. }
  42334. else
  42335. {
  42336. dragType = notDragging;
  42337. repaintText (selection);
  42338. moveCaret (newPosition);
  42339. selection = Range<int>::emptyRange (getCaretPosition());
  42340. }
  42341. }
  42342. int TextEditor::getTextIndexAt (const int x,
  42343. const int y)
  42344. {
  42345. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42346. (float) (y + viewport->getViewPositionY() - topIndent));
  42347. }
  42348. void TextEditor::insertTextAtCaret (const String& newText_)
  42349. {
  42350. String newText (newText_);
  42351. if (allowedCharacters.isNotEmpty())
  42352. newText = newText.retainCharacters (allowedCharacters);
  42353. if ((! returnKeyStartsNewLine) && newText == "\n")
  42354. {
  42355. returnPressed();
  42356. return;
  42357. }
  42358. if (! isMultiLine())
  42359. newText = newText.replaceCharacters ("\r\n", " ");
  42360. else
  42361. newText = newText.replace ("\r\n", "\n");
  42362. const int newCaretPos = selection.getStart() + newText.length();
  42363. const int insertIndex = selection.getStart();
  42364. remove (selection, getUndoManager(),
  42365. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42366. if (maxTextLength > 0)
  42367. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42368. if (newText.isNotEmpty())
  42369. insert (newText,
  42370. insertIndex,
  42371. currentFont,
  42372. findColour (textColourId),
  42373. getUndoManager(),
  42374. newCaretPos);
  42375. textChanged();
  42376. }
  42377. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42378. {
  42379. moveCursorTo (newSelection.getStart(), false);
  42380. moveCursorTo (newSelection.getEnd(), true);
  42381. }
  42382. void TextEditor::copy()
  42383. {
  42384. if (passwordCharacter == 0)
  42385. {
  42386. const String selectedText (getHighlightedText());
  42387. if (selectedText.isNotEmpty())
  42388. SystemClipboard::copyTextToClipboard (selectedText);
  42389. }
  42390. }
  42391. void TextEditor::paste()
  42392. {
  42393. if (! isReadOnly())
  42394. {
  42395. const String clip (SystemClipboard::getTextFromClipboard());
  42396. if (clip.isNotEmpty())
  42397. insertTextAtCaret (clip);
  42398. }
  42399. }
  42400. void TextEditor::cut()
  42401. {
  42402. if (! isReadOnly())
  42403. {
  42404. moveCaret (selection.getEnd());
  42405. insertTextAtCaret (String::empty);
  42406. }
  42407. }
  42408. void TextEditor::drawContent (Graphics& g)
  42409. {
  42410. const float wordWrapWidth = getWordWrapWidth();
  42411. if (wordWrapWidth > 0)
  42412. {
  42413. g.setOrigin (leftIndent, topIndent);
  42414. const Rectangle<int> clip (g.getClipBounds());
  42415. Colour selectedTextColour;
  42416. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42417. while (i.lineY + 200.0 < clip.getY() && i.next())
  42418. {}
  42419. if (! selection.isEmpty())
  42420. {
  42421. g.setColour (findColour (highlightColourId)
  42422. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42423. selectedTextColour = findColour (highlightedTextColourId);
  42424. Iterator i2 (i);
  42425. while (i2.next() && i2.lineY < clip.getBottom())
  42426. {
  42427. if (i2.lineY + i2.lineHeight >= clip.getY()
  42428. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42429. {
  42430. i2.drawSelection (g, selection);
  42431. }
  42432. }
  42433. }
  42434. const UniformTextSection* lastSection = 0;
  42435. while (i.next() && i.lineY < clip.getBottom())
  42436. {
  42437. if (i.lineY + i.lineHeight >= clip.getY())
  42438. {
  42439. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42440. {
  42441. i.drawSelectedText (g, selection, selectedTextColour);
  42442. lastSection = 0;
  42443. }
  42444. else
  42445. {
  42446. i.draw (g, lastSection);
  42447. }
  42448. }
  42449. }
  42450. }
  42451. }
  42452. void TextEditor::paint (Graphics& g)
  42453. {
  42454. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42455. }
  42456. void TextEditor::paintOverChildren (Graphics& g)
  42457. {
  42458. if (caretFlashState
  42459. && hasKeyboardFocus (false)
  42460. && caretVisible
  42461. && ! isReadOnly())
  42462. {
  42463. g.setColour (findColour (caretColourId));
  42464. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42465. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42466. 2.0f, cursorHeight);
  42467. }
  42468. if (textToShowWhenEmpty.isNotEmpty()
  42469. && (! hasKeyboardFocus (false))
  42470. && getTotalNumChars() == 0)
  42471. {
  42472. g.setColour (colourForTextWhenEmpty);
  42473. g.setFont (getFont());
  42474. if (isMultiLine())
  42475. {
  42476. g.drawText (textToShowWhenEmpty,
  42477. 0, 0, getWidth(), getHeight(),
  42478. Justification::centred, true);
  42479. }
  42480. else
  42481. {
  42482. g.drawText (textToShowWhenEmpty,
  42483. leftIndent, topIndent,
  42484. viewport->getWidth() - leftIndent,
  42485. viewport->getHeight() - topIndent,
  42486. Justification::centredLeft, true);
  42487. }
  42488. }
  42489. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42490. }
  42491. void TextEditor::mouseDown (const MouseEvent& e)
  42492. {
  42493. beginDragAutoRepeat (100);
  42494. newTransaction();
  42495. if (wasFocused || ! selectAllTextWhenFocused)
  42496. {
  42497. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42498. {
  42499. moveCursorTo (getTextIndexAt (e.x, e.y),
  42500. e.mods.isShiftDown());
  42501. }
  42502. else
  42503. {
  42504. PopupMenu m;
  42505. m.setLookAndFeel (&getLookAndFeel());
  42506. addPopupMenuItems (m, &e);
  42507. menuActive = true;
  42508. const int result = m.show();
  42509. menuActive = false;
  42510. if (result != 0)
  42511. performPopupMenuAction (result);
  42512. }
  42513. }
  42514. }
  42515. void TextEditor::mouseDrag (const MouseEvent& e)
  42516. {
  42517. if (wasFocused || ! selectAllTextWhenFocused)
  42518. {
  42519. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42520. {
  42521. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42522. }
  42523. }
  42524. }
  42525. void TextEditor::mouseUp (const MouseEvent& e)
  42526. {
  42527. newTransaction();
  42528. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42529. if (wasFocused || ! selectAllTextWhenFocused)
  42530. {
  42531. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42532. {
  42533. moveCaret (getTextIndexAt (e.x, e.y));
  42534. }
  42535. }
  42536. wasFocused = true;
  42537. }
  42538. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42539. {
  42540. int tokenEnd = getTextIndexAt (e.x, e.y);
  42541. int tokenStart = tokenEnd;
  42542. if (e.getNumberOfClicks() > 3)
  42543. {
  42544. tokenStart = 0;
  42545. tokenEnd = getTotalNumChars();
  42546. }
  42547. else
  42548. {
  42549. const String t (getText());
  42550. const int totalLength = getTotalNumChars();
  42551. while (tokenEnd < totalLength)
  42552. {
  42553. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  42554. ++tokenEnd;
  42555. else
  42556. break;
  42557. }
  42558. tokenStart = tokenEnd;
  42559. while (tokenStart > 0)
  42560. {
  42561. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  42562. --tokenStart;
  42563. else
  42564. break;
  42565. }
  42566. if (e.getNumberOfClicks() > 2)
  42567. {
  42568. while (tokenEnd < totalLength)
  42569. {
  42570. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42571. ++tokenEnd;
  42572. else
  42573. break;
  42574. }
  42575. while (tokenStart > 0)
  42576. {
  42577. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42578. --tokenStart;
  42579. else
  42580. break;
  42581. }
  42582. }
  42583. }
  42584. moveCursorTo (tokenEnd, false);
  42585. moveCursorTo (tokenStart, true);
  42586. }
  42587. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42588. {
  42589. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42590. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42591. }
  42592. bool TextEditor::keyPressed (const KeyPress& key)
  42593. {
  42594. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42595. return false;
  42596. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42597. if (key.isKeyCode (KeyPress::leftKey)
  42598. || key.isKeyCode (KeyPress::upKey))
  42599. {
  42600. newTransaction();
  42601. int newPos;
  42602. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42603. newPos = indexAtPosition (cursorX, cursorY - 1);
  42604. else if (moveInWholeWordSteps)
  42605. newPos = findWordBreakBefore (getCaretPosition());
  42606. else
  42607. newPos = getCaretPosition() - 1;
  42608. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42609. }
  42610. else if (key.isKeyCode (KeyPress::rightKey)
  42611. || key.isKeyCode (KeyPress::downKey))
  42612. {
  42613. newTransaction();
  42614. int newPos;
  42615. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42616. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42617. else if (moveInWholeWordSteps)
  42618. newPos = findWordBreakAfter (getCaretPosition());
  42619. else
  42620. newPos = getCaretPosition() + 1;
  42621. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42622. }
  42623. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42624. {
  42625. newTransaction();
  42626. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42627. key.getModifiers().isShiftDown());
  42628. }
  42629. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42630. {
  42631. newTransaction();
  42632. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42633. key.getModifiers().isShiftDown());
  42634. }
  42635. else if (key.isKeyCode (KeyPress::homeKey))
  42636. {
  42637. newTransaction();
  42638. if (isMultiLine() && ! moveInWholeWordSteps)
  42639. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42640. key.getModifiers().isShiftDown());
  42641. else
  42642. moveCursorTo (0, key.getModifiers().isShiftDown());
  42643. }
  42644. else if (key.isKeyCode (KeyPress::endKey))
  42645. {
  42646. newTransaction();
  42647. if (isMultiLine() && ! moveInWholeWordSteps)
  42648. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42649. key.getModifiers().isShiftDown());
  42650. else
  42651. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42652. }
  42653. else if (key.isKeyCode (KeyPress::backspaceKey))
  42654. {
  42655. if (moveInWholeWordSteps)
  42656. {
  42657. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42658. }
  42659. else
  42660. {
  42661. if (selection.isEmpty() && selection.getStart() > 0)
  42662. selection.setStart (selection.getEnd() - 1);
  42663. }
  42664. cut();
  42665. }
  42666. else if (key.isKeyCode (KeyPress::deleteKey))
  42667. {
  42668. if (key.getModifiers().isShiftDown())
  42669. copy();
  42670. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42671. selection.setEnd (selection.getStart() + 1);
  42672. cut();
  42673. }
  42674. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42675. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42676. {
  42677. newTransaction();
  42678. copy();
  42679. }
  42680. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42681. {
  42682. newTransaction();
  42683. copy();
  42684. cut();
  42685. }
  42686. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42687. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42688. {
  42689. newTransaction();
  42690. paste();
  42691. }
  42692. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42693. {
  42694. newTransaction();
  42695. doUndoRedo (false);
  42696. }
  42697. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42698. {
  42699. newTransaction();
  42700. doUndoRedo (true);
  42701. }
  42702. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42703. {
  42704. newTransaction();
  42705. moveCursorTo (getTotalNumChars(), false);
  42706. moveCursorTo (0, true);
  42707. }
  42708. else if (key == KeyPress::returnKey)
  42709. {
  42710. newTransaction();
  42711. insertTextAtCaret ("\n");
  42712. }
  42713. else if (key.isKeyCode (KeyPress::escapeKey))
  42714. {
  42715. newTransaction();
  42716. moveCursorTo (getCaretPosition(), false);
  42717. escapePressed();
  42718. }
  42719. else if (key.getTextCharacter() >= ' '
  42720. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42721. {
  42722. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42723. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42724. }
  42725. else
  42726. {
  42727. return false;
  42728. }
  42729. return true;
  42730. }
  42731. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42732. {
  42733. if (! isKeyDown)
  42734. return false;
  42735. #if JUCE_WIN32
  42736. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  42737. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  42738. #endif
  42739. // (overridden to avoid forwarding key events to the parent)
  42740. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  42741. }
  42742. const int baseMenuItemID = 0x7fff0000;
  42743. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  42744. {
  42745. const bool writable = ! isReadOnly();
  42746. if (passwordCharacter == 0)
  42747. {
  42748. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  42749. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  42750. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  42751. }
  42752. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  42753. m.addSeparator();
  42754. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  42755. m.addSeparator();
  42756. if (getUndoManager() != 0)
  42757. {
  42758. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  42759. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  42760. }
  42761. }
  42762. void TextEditor::performPopupMenuAction (const int menuItemID)
  42763. {
  42764. switch (menuItemID)
  42765. {
  42766. case baseMenuItemID + 1:
  42767. copy();
  42768. cut();
  42769. break;
  42770. case baseMenuItemID + 2:
  42771. copy();
  42772. break;
  42773. case baseMenuItemID + 3:
  42774. paste();
  42775. break;
  42776. case baseMenuItemID + 4:
  42777. cut();
  42778. break;
  42779. case baseMenuItemID + 5:
  42780. moveCursorTo (getTotalNumChars(), false);
  42781. moveCursorTo (0, true);
  42782. break;
  42783. case baseMenuItemID + 6:
  42784. doUndoRedo (false);
  42785. break;
  42786. case baseMenuItemID + 7:
  42787. doUndoRedo (true);
  42788. break;
  42789. default:
  42790. break;
  42791. }
  42792. }
  42793. void TextEditor::focusGained (FocusChangeType)
  42794. {
  42795. newTransaction();
  42796. caretFlashState = true;
  42797. if (selectAllTextWhenFocused)
  42798. {
  42799. moveCursorTo (0, false);
  42800. moveCursorTo (getTotalNumChars(), true);
  42801. }
  42802. repaint();
  42803. if (caretVisible)
  42804. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42805. ComponentPeer* const peer = getPeer();
  42806. if (peer != 0 && ! isReadOnly())
  42807. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  42808. }
  42809. void TextEditor::focusLost (FocusChangeType)
  42810. {
  42811. newTransaction();
  42812. wasFocused = false;
  42813. textHolder->stopTimer();
  42814. caretFlashState = false;
  42815. postCommandMessage (TextEditorDefs::focusLossMessageId);
  42816. repaint();
  42817. }
  42818. void TextEditor::resized()
  42819. {
  42820. viewport->setBoundsInset (borderSize);
  42821. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  42822. updateTextHolderSize();
  42823. if (! isMultiLine())
  42824. {
  42825. scrollToMakeSureCursorIsVisible();
  42826. }
  42827. else
  42828. {
  42829. updateCaretPosition();
  42830. }
  42831. }
  42832. void TextEditor::handleCommandMessage (const int commandId)
  42833. {
  42834. Component::BailOutChecker checker (this);
  42835. switch (commandId)
  42836. {
  42837. case TextEditorDefs::textChangeMessageId:
  42838. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  42839. break;
  42840. case TextEditorDefs::returnKeyMessageId:
  42841. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  42842. break;
  42843. case TextEditorDefs::escapeKeyMessageId:
  42844. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  42845. break;
  42846. case TextEditorDefs::focusLossMessageId:
  42847. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  42848. break;
  42849. default:
  42850. jassertfalse
  42851. break;
  42852. }
  42853. }
  42854. void TextEditor::enablementChanged()
  42855. {
  42856. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  42857. : MouseCursor::IBeamCursor);
  42858. repaint();
  42859. }
  42860. UndoManager* TextEditor::getUndoManager() throw()
  42861. {
  42862. return isReadOnly() ? &undoManager : 0;
  42863. }
  42864. void TextEditor::clearInternal (UndoManager* const um)
  42865. {
  42866. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  42867. }
  42868. void TextEditor::insert (const String& text,
  42869. const int insertIndex,
  42870. const Font& font,
  42871. const Colour& colour,
  42872. UndoManager* const um,
  42873. const int caretPositionToMoveTo)
  42874. {
  42875. if (text.isNotEmpty())
  42876. {
  42877. if (um != 0)
  42878. {
  42879. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42880. newTransaction();
  42881. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  42882. caretPosition, caretPositionToMoveTo));
  42883. }
  42884. else
  42885. {
  42886. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  42887. // a line gets moved due to word wrap
  42888. int index = 0;
  42889. int nextIndex = 0;
  42890. for (int i = 0; i < sections.size(); ++i)
  42891. {
  42892. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42893. if (insertIndex == index)
  42894. {
  42895. sections.insert (i, new UniformTextSection (text,
  42896. font, colour,
  42897. passwordCharacter));
  42898. break;
  42899. }
  42900. else if (insertIndex > index && insertIndex < nextIndex)
  42901. {
  42902. splitSection (i, insertIndex - index);
  42903. sections.insert (i + 1, new UniformTextSection (text,
  42904. font, colour,
  42905. passwordCharacter));
  42906. break;
  42907. }
  42908. index = nextIndex;
  42909. }
  42910. if (nextIndex == insertIndex)
  42911. sections.add (new UniformTextSection (text,
  42912. font, colour,
  42913. passwordCharacter));
  42914. coalesceSimilarSections();
  42915. totalNumChars = -1;
  42916. valueTextNeedsUpdating = true;
  42917. moveCursorTo (caretPositionToMoveTo, false);
  42918. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  42919. }
  42920. }
  42921. }
  42922. void TextEditor::reinsert (const int insertIndex,
  42923. const Array <UniformTextSection*>& sectionsToInsert)
  42924. {
  42925. int index = 0;
  42926. int nextIndex = 0;
  42927. for (int i = 0; i < sections.size(); ++i)
  42928. {
  42929. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42930. if (insertIndex == index)
  42931. {
  42932. for (int j = sectionsToInsert.size(); --j >= 0;)
  42933. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42934. break;
  42935. }
  42936. else if (insertIndex > index && insertIndex < nextIndex)
  42937. {
  42938. splitSection (i, insertIndex - index);
  42939. for (int j = sectionsToInsert.size(); --j >= 0;)
  42940. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42941. break;
  42942. }
  42943. index = nextIndex;
  42944. }
  42945. if (nextIndex == insertIndex)
  42946. {
  42947. for (int j = 0; j < sectionsToInsert.size(); ++j)
  42948. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42949. }
  42950. coalesceSimilarSections();
  42951. totalNumChars = -1;
  42952. valueTextNeedsUpdating = true;
  42953. }
  42954. void TextEditor::remove (const Range<int>& range,
  42955. UndoManager* const um,
  42956. const int caretPositionToMoveTo)
  42957. {
  42958. if (! range.isEmpty())
  42959. {
  42960. int index = 0;
  42961. for (int i = 0; i < sections.size(); ++i)
  42962. {
  42963. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  42964. if (range.getStart() > index && range.getStart() < nextIndex)
  42965. {
  42966. splitSection (i, range.getStart() - index);
  42967. --i;
  42968. }
  42969. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  42970. {
  42971. splitSection (i, range.getEnd() - index);
  42972. --i;
  42973. }
  42974. else
  42975. {
  42976. index = nextIndex;
  42977. if (index > range.getEnd())
  42978. break;
  42979. }
  42980. }
  42981. index = 0;
  42982. if (um != 0)
  42983. {
  42984. Array <UniformTextSection*> removedSections;
  42985. for (int i = 0; i < sections.size(); ++i)
  42986. {
  42987. if (range.getEnd() <= range.getStart())
  42988. break;
  42989. UniformTextSection* const section = sections.getUnchecked (i);
  42990. const int nextIndex = index + section->getTotalLength();
  42991. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  42992. removedSections.add (new UniformTextSection (*section));
  42993. index = nextIndex;
  42994. }
  42995. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42996. newTransaction();
  42997. um->perform (new RemoveAction (*this, range, caretPosition,
  42998. caretPositionToMoveTo, removedSections));
  42999. }
  43000. else
  43001. {
  43002. Range<int> remainingRange (range);
  43003. for (int i = 0; i < sections.size(); ++i)
  43004. {
  43005. UniformTextSection* const section = sections.getUnchecked (i);
  43006. const int nextIndex = index + section->getTotalLength();
  43007. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43008. {
  43009. sections.remove(i);
  43010. section->clear();
  43011. delete section;
  43012. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43013. if (remainingRange.isEmpty())
  43014. break;
  43015. --i;
  43016. }
  43017. else
  43018. {
  43019. index = nextIndex;
  43020. }
  43021. }
  43022. coalesceSimilarSections();
  43023. totalNumChars = -1;
  43024. valueTextNeedsUpdating = true;
  43025. moveCursorTo (caretPositionToMoveTo, false);
  43026. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43027. }
  43028. }
  43029. }
  43030. const String TextEditor::getText() const
  43031. {
  43032. String t;
  43033. t.preallocateStorage (getTotalNumChars());
  43034. String::Concatenator concatenator (t);
  43035. for (int i = 0; i < sections.size(); ++i)
  43036. sections.getUnchecked (i)->appendAllText (concatenator);
  43037. return t;
  43038. }
  43039. const String TextEditor::getTextInRange (const Range<int>& range) const
  43040. {
  43041. String t;
  43042. if (! range.isEmpty())
  43043. {
  43044. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43045. String::Concatenator concatenator (t);
  43046. int index = 0;
  43047. for (int i = 0; i < sections.size(); ++i)
  43048. {
  43049. const UniformTextSection* const s = sections.getUnchecked (i);
  43050. const int nextIndex = index + s->getTotalLength();
  43051. if (range.getStart() < nextIndex)
  43052. {
  43053. if (range.getEnd() <= index)
  43054. break;
  43055. s->appendSubstring (concatenator, range - index);
  43056. }
  43057. index = nextIndex;
  43058. }
  43059. }
  43060. return t;
  43061. }
  43062. const String TextEditor::getHighlightedText() const
  43063. {
  43064. return getTextInRange (selection);
  43065. }
  43066. int TextEditor::getTotalNumChars() const
  43067. {
  43068. if (totalNumChars < 0)
  43069. {
  43070. totalNumChars = 0;
  43071. for (int i = sections.size(); --i >= 0;)
  43072. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43073. }
  43074. return totalNumChars;
  43075. }
  43076. bool TextEditor::isEmpty() const
  43077. {
  43078. return getTotalNumChars() == 0;
  43079. }
  43080. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43081. {
  43082. const float wordWrapWidth = getWordWrapWidth();
  43083. if (wordWrapWidth > 0 && sections.size() > 0)
  43084. {
  43085. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43086. i.getCharPosition (index, cx, cy, lineHeight);
  43087. }
  43088. else
  43089. {
  43090. cx = cy = 0;
  43091. lineHeight = currentFont.getHeight();
  43092. }
  43093. }
  43094. int TextEditor::indexAtPosition (const float x, const float y)
  43095. {
  43096. const float wordWrapWidth = getWordWrapWidth();
  43097. if (wordWrapWidth > 0)
  43098. {
  43099. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43100. while (i.next())
  43101. {
  43102. if (i.lineY + i.lineHeight > y)
  43103. {
  43104. if (i.lineY > y)
  43105. return jmax (0, i.indexInText - 1);
  43106. if (i.atomX >= x)
  43107. return i.indexInText;
  43108. if (x < i.atomRight)
  43109. return i.xToIndex (x);
  43110. }
  43111. }
  43112. }
  43113. return getTotalNumChars();
  43114. }
  43115. static int getCharacterCategory (const juce_wchar character)
  43116. {
  43117. return CharacterFunctions::isLetterOrDigit (character)
  43118. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43119. }
  43120. int TextEditor::findWordBreakAfter (const int position) const
  43121. {
  43122. const String t (getTextInRange (Range<int> (position, position + 512)));
  43123. const int totalLength = t.length();
  43124. int i = 0;
  43125. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43126. ++i;
  43127. const int type = getCharacterCategory (t[i]);
  43128. while (i < totalLength && type == getCharacterCategory (t[i]))
  43129. ++i;
  43130. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43131. ++i;
  43132. return position + i;
  43133. }
  43134. int TextEditor::findWordBreakBefore (const int position) const
  43135. {
  43136. if (position <= 0)
  43137. return 0;
  43138. const int startOfBuffer = jmax (0, position - 512);
  43139. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43140. int i = position - startOfBuffer;
  43141. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43142. --i;
  43143. if (i > 0)
  43144. {
  43145. const int type = getCharacterCategory (t [i - 1]);
  43146. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43147. --i;
  43148. }
  43149. jassert (startOfBuffer + i >= 0);
  43150. return startOfBuffer + i;
  43151. }
  43152. void TextEditor::splitSection (const int sectionIndex,
  43153. const int charToSplitAt)
  43154. {
  43155. jassert (sections[sectionIndex] != 0);
  43156. sections.insert (sectionIndex + 1,
  43157. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43158. }
  43159. void TextEditor::coalesceSimilarSections()
  43160. {
  43161. for (int i = 0; i < sections.size() - 1; ++i)
  43162. {
  43163. UniformTextSection* const s1 = sections.getUnchecked (i);
  43164. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43165. if (s1->font == s2->font
  43166. && s1->colour == s2->colour)
  43167. {
  43168. s1->append (*s2, passwordCharacter);
  43169. sections.remove (i + 1);
  43170. delete s2;
  43171. --i;
  43172. }
  43173. }
  43174. }
  43175. END_JUCE_NAMESPACE
  43176. /*** End of inlined file: juce_TextEditor.cpp ***/
  43177. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43178. BEGIN_JUCE_NAMESPACE
  43179. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43180. class ToolbarSpacerComp : public ToolbarItemComponent
  43181. {
  43182. public:
  43183. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43184. : ToolbarItemComponent (itemId_, String::empty, false),
  43185. fixedSize (fixedSize_),
  43186. drawBar (drawBar_)
  43187. {
  43188. }
  43189. ~ToolbarSpacerComp()
  43190. {
  43191. }
  43192. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43193. int& preferredSize, int& minSize, int& maxSize)
  43194. {
  43195. if (fixedSize <= 0)
  43196. {
  43197. preferredSize = toolbarThickness * 2;
  43198. minSize = 4;
  43199. maxSize = 32768;
  43200. }
  43201. else
  43202. {
  43203. maxSize = roundToInt (toolbarThickness * fixedSize);
  43204. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43205. preferredSize = maxSize;
  43206. if (getEditingMode() == editableOnPalette)
  43207. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43208. }
  43209. return true;
  43210. }
  43211. void paintButtonArea (Graphics&, int, int, bool, bool)
  43212. {
  43213. }
  43214. void contentAreaChanged (const Rectangle<int>&)
  43215. {
  43216. }
  43217. int getResizeOrder() const throw()
  43218. {
  43219. return fixedSize <= 0 ? 0 : 1;
  43220. }
  43221. void paint (Graphics& g)
  43222. {
  43223. const int w = getWidth();
  43224. const int h = getHeight();
  43225. if (drawBar)
  43226. {
  43227. g.setColour (findColour (Toolbar::separatorColourId, true));
  43228. const float thickness = 0.2f;
  43229. if (isToolbarVertical())
  43230. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43231. else
  43232. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43233. }
  43234. if (getEditingMode() != normalMode && ! drawBar)
  43235. {
  43236. g.setColour (findColour (Toolbar::separatorColourId, true));
  43237. const int indentX = jmin (2, (w - 3) / 2);
  43238. const int indentY = jmin (2, (h - 3) / 2);
  43239. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43240. if (fixedSize <= 0)
  43241. {
  43242. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43243. if (isToolbarVertical())
  43244. {
  43245. x1 = w * 0.5f;
  43246. y1 = h * 0.4f;
  43247. x2 = x1;
  43248. y2 = indentX * 2.0f;
  43249. x3 = x1;
  43250. y3 = h * 0.6f;
  43251. x4 = x1;
  43252. y4 = h - y2;
  43253. hw = w * 0.15f;
  43254. hl = w * 0.2f;
  43255. }
  43256. else
  43257. {
  43258. x1 = w * 0.4f;
  43259. y1 = h * 0.5f;
  43260. x2 = indentX * 2.0f;
  43261. y2 = y1;
  43262. x3 = w * 0.6f;
  43263. y3 = y1;
  43264. x4 = w - x2;
  43265. y4 = y1;
  43266. hw = h * 0.15f;
  43267. hl = h * 0.2f;
  43268. }
  43269. Path p;
  43270. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  43271. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  43272. g.fillPath (p);
  43273. }
  43274. }
  43275. }
  43276. juce_UseDebuggingNewOperator
  43277. private:
  43278. const float fixedSize;
  43279. const bool drawBar;
  43280. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43281. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43282. };
  43283. class MissingItemsComponent : public PopupMenuCustomComponent
  43284. {
  43285. public:
  43286. MissingItemsComponent (Toolbar& owner_, const int height_)
  43287. : PopupMenuCustomComponent (true),
  43288. owner (owner_),
  43289. height (height_)
  43290. {
  43291. for (int i = owner_.items.size(); --i >= 0;)
  43292. {
  43293. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43294. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43295. {
  43296. oldIndexes.insert (0, i);
  43297. addAndMakeVisible (tc, 0);
  43298. }
  43299. }
  43300. layout (400);
  43301. }
  43302. ~MissingItemsComponent()
  43303. {
  43304. // deleting the toolbar while its menu it open??
  43305. jassert (owner.isValidComponent());
  43306. for (int i = 0; i < getNumChildComponents(); ++i)
  43307. {
  43308. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43309. if (tc != 0)
  43310. {
  43311. tc->setVisible (false);
  43312. const int index = oldIndexes.remove (i);
  43313. owner.addChildComponent (tc, index);
  43314. --i;
  43315. }
  43316. }
  43317. owner.resized();
  43318. }
  43319. void layout (const int preferredWidth)
  43320. {
  43321. const int indent = 8;
  43322. int x = indent;
  43323. int y = indent;
  43324. int maxX = 0;
  43325. for (int i = 0; i < getNumChildComponents(); ++i)
  43326. {
  43327. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43328. if (tc != 0)
  43329. {
  43330. int preferredSize = 1, minSize = 1, maxSize = 1;
  43331. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43332. {
  43333. if (x + preferredSize > preferredWidth && x > indent)
  43334. {
  43335. x = indent;
  43336. y += height;
  43337. }
  43338. tc->setBounds (x, y, preferredSize, height);
  43339. x += preferredSize;
  43340. maxX = jmax (maxX, x);
  43341. }
  43342. }
  43343. }
  43344. setSize (maxX + 8, y + height + 8);
  43345. }
  43346. void getIdealSize (int& idealWidth, int& idealHeight)
  43347. {
  43348. idealWidth = getWidth();
  43349. idealHeight = getHeight();
  43350. }
  43351. juce_UseDebuggingNewOperator
  43352. private:
  43353. Toolbar& owner;
  43354. const int height;
  43355. Array <int> oldIndexes;
  43356. MissingItemsComponent (const MissingItemsComponent&);
  43357. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43358. };
  43359. Toolbar::Toolbar()
  43360. : vertical (false),
  43361. isEditingActive (false),
  43362. toolbarStyle (Toolbar::iconsOnly)
  43363. {
  43364. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43365. missingItemsButton->setAlwaysOnTop (true);
  43366. missingItemsButton->addButtonListener (this);
  43367. }
  43368. Toolbar::~Toolbar()
  43369. {
  43370. animator.cancelAllAnimations (true);
  43371. deleteAllChildren();
  43372. }
  43373. void Toolbar::setVertical (const bool shouldBeVertical)
  43374. {
  43375. if (vertical != shouldBeVertical)
  43376. {
  43377. vertical = shouldBeVertical;
  43378. resized();
  43379. }
  43380. }
  43381. void Toolbar::clear()
  43382. {
  43383. for (int i = items.size(); --i >= 0;)
  43384. {
  43385. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43386. items.remove (i);
  43387. delete tc;
  43388. }
  43389. resized();
  43390. }
  43391. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43392. {
  43393. if (itemId == ToolbarItemFactory::separatorBarId)
  43394. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43395. else if (itemId == ToolbarItemFactory::spacerId)
  43396. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43397. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43398. return new ToolbarSpacerComp (itemId, 0, false);
  43399. return factory.createItem (itemId);
  43400. }
  43401. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43402. const int itemId,
  43403. const int insertIndex)
  43404. {
  43405. // An ID can't be zero - this might indicate a mistake somewhere?
  43406. jassert (itemId != 0);
  43407. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43408. if (tc != 0)
  43409. {
  43410. #if JUCE_DEBUG
  43411. Array <int> allowedIds;
  43412. factory.getAllToolbarItemIds (allowedIds);
  43413. // If your factory can create an item for a given ID, it must also return
  43414. // that ID from its getAllToolbarItemIds() method!
  43415. jassert (allowedIds.contains (itemId));
  43416. #endif
  43417. items.insert (insertIndex, tc);
  43418. addAndMakeVisible (tc, insertIndex);
  43419. }
  43420. }
  43421. void Toolbar::addItem (ToolbarItemFactory& factory,
  43422. const int itemId,
  43423. const int insertIndex)
  43424. {
  43425. addItemInternal (factory, itemId, insertIndex);
  43426. resized();
  43427. }
  43428. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43429. {
  43430. Array <int> ids;
  43431. factoryToUse.getDefaultItemSet (ids);
  43432. clear();
  43433. for (int i = 0; i < ids.size(); ++i)
  43434. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43435. resized();
  43436. }
  43437. void Toolbar::removeToolbarItem (const int itemIndex)
  43438. {
  43439. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43440. if (tc != 0)
  43441. {
  43442. items.removeValue (tc);
  43443. delete tc;
  43444. resized();
  43445. }
  43446. }
  43447. int Toolbar::getNumItems() const throw()
  43448. {
  43449. return items.size();
  43450. }
  43451. int Toolbar::getItemId (const int itemIndex) const throw()
  43452. {
  43453. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43454. return tc != 0 ? tc->getItemId() : 0;
  43455. }
  43456. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43457. {
  43458. return items [itemIndex];
  43459. }
  43460. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43461. {
  43462. for (;;)
  43463. {
  43464. index += delta;
  43465. ToolbarItemComponent* const tc = getItemComponent (index);
  43466. if (tc == 0)
  43467. break;
  43468. if (tc->isActive)
  43469. return tc;
  43470. }
  43471. return 0;
  43472. }
  43473. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43474. {
  43475. if (toolbarStyle != newStyle)
  43476. {
  43477. toolbarStyle = newStyle;
  43478. updateAllItemPositions (false);
  43479. }
  43480. }
  43481. const String Toolbar::toString() const
  43482. {
  43483. String s ("TB:");
  43484. for (int i = 0; i < getNumItems(); ++i)
  43485. s << getItemId(i) << ' ';
  43486. return s.trimEnd();
  43487. }
  43488. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43489. const String& savedVersion)
  43490. {
  43491. if (! savedVersion.startsWith ("TB:"))
  43492. return false;
  43493. StringArray tokens;
  43494. tokens.addTokens (savedVersion.substring (3), false);
  43495. clear();
  43496. for (int i = 0; i < tokens.size(); ++i)
  43497. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43498. resized();
  43499. return true;
  43500. }
  43501. void Toolbar::paint (Graphics& g)
  43502. {
  43503. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43504. }
  43505. int Toolbar::getThickness() const throw()
  43506. {
  43507. return vertical ? getWidth() : getHeight();
  43508. }
  43509. int Toolbar::getLength() const throw()
  43510. {
  43511. return vertical ? getHeight() : getWidth();
  43512. }
  43513. void Toolbar::setEditingActive (const bool active)
  43514. {
  43515. if (isEditingActive != active)
  43516. {
  43517. isEditingActive = active;
  43518. updateAllItemPositions (false);
  43519. }
  43520. }
  43521. void Toolbar::resized()
  43522. {
  43523. updateAllItemPositions (false);
  43524. }
  43525. void Toolbar::updateAllItemPositions (const bool animate)
  43526. {
  43527. if (getWidth() > 0 && getHeight() > 0)
  43528. {
  43529. StretchableObjectResizer resizer;
  43530. int i;
  43531. for (i = 0; i < items.size(); ++i)
  43532. {
  43533. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43534. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43535. : ToolbarItemComponent::normalMode);
  43536. tc->setStyle (toolbarStyle);
  43537. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43538. int preferredSize = 1, minSize = 1, maxSize = 1;
  43539. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43540. preferredSize, minSize, maxSize))
  43541. {
  43542. tc->isActive = true;
  43543. resizer.addItem (preferredSize, minSize, maxSize,
  43544. spacer != 0 ? spacer->getResizeOrder() : 2);
  43545. }
  43546. else
  43547. {
  43548. tc->isActive = false;
  43549. tc->setVisible (false);
  43550. }
  43551. }
  43552. resizer.resizeToFit (getLength());
  43553. int totalLength = 0;
  43554. for (i = 0; i < resizer.getNumItems(); ++i)
  43555. totalLength += (int) resizer.getItemSize (i);
  43556. const bool itemsOffTheEnd = totalLength > getLength();
  43557. const int extrasButtonSize = getThickness() / 2;
  43558. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43559. missingItemsButton->setVisible (itemsOffTheEnd);
  43560. missingItemsButton->setEnabled (! isEditingActive);
  43561. if (vertical)
  43562. missingItemsButton->setCentrePosition (getWidth() / 2,
  43563. getHeight() - 4 - extrasButtonSize / 2);
  43564. else
  43565. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43566. getHeight() / 2);
  43567. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43568. : missingItemsButton->getX()) - 4
  43569. : getLength();
  43570. int pos = 0, activeIndex = 0;
  43571. for (i = 0; i < items.size(); ++i)
  43572. {
  43573. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43574. if (tc->isActive)
  43575. {
  43576. const int size = (int) resizer.getItemSize (activeIndex++);
  43577. Rectangle<int> newBounds;
  43578. if (vertical)
  43579. newBounds.setBounds (0, pos, getWidth(), size);
  43580. else
  43581. newBounds.setBounds (pos, 0, size, getHeight());
  43582. if (animate)
  43583. {
  43584. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43585. }
  43586. else
  43587. {
  43588. animator.cancelAnimation (tc, false);
  43589. tc->setBounds (newBounds);
  43590. }
  43591. pos += size;
  43592. tc->setVisible (pos <= maxLength
  43593. && ((! tc->isBeingDragged)
  43594. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43595. }
  43596. }
  43597. }
  43598. }
  43599. void Toolbar::buttonClicked (Button*)
  43600. {
  43601. jassert (missingItemsButton->isShowing());
  43602. if (missingItemsButton->isShowing())
  43603. {
  43604. PopupMenu m;
  43605. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43606. m.showAt (missingItemsButton);
  43607. }
  43608. }
  43609. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43610. Component* /*sourceComponent*/)
  43611. {
  43612. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43613. }
  43614. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43615. {
  43616. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43617. if (tc != 0)
  43618. {
  43619. if (getNumItems() == 0)
  43620. {
  43621. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43622. {
  43623. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43624. if (palette != 0)
  43625. palette->replaceComponent (tc);
  43626. }
  43627. else
  43628. {
  43629. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43630. }
  43631. items.add (tc);
  43632. addChildComponent (tc);
  43633. updateAllItemPositions (false);
  43634. }
  43635. else
  43636. {
  43637. for (int i = getNumItems(); --i >= 0;)
  43638. {
  43639. int currentIndex = getIndexOfChildComponent (tc);
  43640. if (currentIndex < 0)
  43641. {
  43642. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43643. {
  43644. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43645. if (palette != 0)
  43646. palette->replaceComponent (tc);
  43647. }
  43648. else
  43649. {
  43650. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43651. }
  43652. items.add (tc);
  43653. addChildComponent (tc);
  43654. currentIndex = getIndexOfChildComponent (tc);
  43655. updateAllItemPositions (true);
  43656. }
  43657. int newIndex = currentIndex;
  43658. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43659. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43660. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43661. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43662. if (prev != 0)
  43663. {
  43664. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43665. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43666. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43667. {
  43668. newIndex = getIndexOfChildComponent (prev);
  43669. }
  43670. }
  43671. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43672. if (next != 0)
  43673. {
  43674. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43675. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43676. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43677. {
  43678. newIndex = getIndexOfChildComponent (next) + 1;
  43679. }
  43680. }
  43681. if (newIndex != currentIndex)
  43682. {
  43683. items.removeValue (tc);
  43684. removeChildComponent (tc);
  43685. addChildComponent (tc, newIndex);
  43686. items.insert (newIndex, tc);
  43687. updateAllItemPositions (true);
  43688. }
  43689. else
  43690. {
  43691. break;
  43692. }
  43693. }
  43694. }
  43695. }
  43696. }
  43697. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43698. {
  43699. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43700. if (tc != 0)
  43701. {
  43702. if (isParentOf (tc))
  43703. {
  43704. items.removeValue (tc);
  43705. removeChildComponent (tc);
  43706. updateAllItemPositions (true);
  43707. }
  43708. }
  43709. }
  43710. void Toolbar::itemDropped (const String&, Component*, int, int)
  43711. {
  43712. }
  43713. void Toolbar::mouseDown (const MouseEvent& e)
  43714. {
  43715. if (e.mods.isPopupMenu())
  43716. {
  43717. }
  43718. }
  43719. class ToolbarCustomisationDialog : public DialogWindow
  43720. {
  43721. public:
  43722. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43723. Toolbar* const toolbar_,
  43724. const int optionFlags)
  43725. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43726. toolbar (toolbar_)
  43727. {
  43728. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43729. setResizable (true, true);
  43730. setResizeLimits (400, 300, 1500, 1000);
  43731. positionNearBar();
  43732. }
  43733. ~ToolbarCustomisationDialog()
  43734. {
  43735. setContentComponent (0, true);
  43736. }
  43737. void closeButtonPressed()
  43738. {
  43739. setVisible (false);
  43740. }
  43741. bool canModalEventBeSentToComponent (const Component* comp)
  43742. {
  43743. return toolbar->isParentOf (comp);
  43744. }
  43745. void positionNearBar()
  43746. {
  43747. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  43748. const int tbx = toolbar->getScreenX();
  43749. const int tby = toolbar->getScreenY();
  43750. const int gap = 8;
  43751. int x, y;
  43752. if (toolbar->isVertical())
  43753. {
  43754. y = tby;
  43755. if (tbx > screenSize.getCentreX())
  43756. x = tbx - getWidth() - gap;
  43757. else
  43758. x = tbx + toolbar->getWidth() + gap;
  43759. }
  43760. else
  43761. {
  43762. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  43763. if (tby > screenSize.getCentreY())
  43764. y = tby - getHeight() - gap;
  43765. else
  43766. y = tby + toolbar->getHeight() + gap;
  43767. }
  43768. setTopLeftPosition (x, y);
  43769. }
  43770. private:
  43771. Toolbar* const toolbar;
  43772. class CustomiserPanel : public Component,
  43773. private ComboBoxListener,
  43774. private ButtonListener
  43775. {
  43776. public:
  43777. CustomiserPanel (ToolbarItemFactory& factory_,
  43778. Toolbar* const toolbar_,
  43779. const int optionFlags)
  43780. : factory (factory_),
  43781. toolbar (toolbar_),
  43782. styleBox (0),
  43783. defaultButton (0)
  43784. {
  43785. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  43786. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  43787. | Toolbar::allowIconsWithTextChoice
  43788. | Toolbar::allowTextOnlyChoice)) != 0)
  43789. {
  43790. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  43791. styleBox->setEditableText (false);
  43792. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  43793. styleBox->addItem (TRANS("Show icons only"), 1);
  43794. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  43795. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  43796. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  43797. styleBox->addItem (TRANS("Show descriptions only"), 3);
  43798. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  43799. styleBox->setSelectedId (1);
  43800. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  43801. styleBox->setSelectedId (2);
  43802. else if (toolbar_->getStyle() == Toolbar::textOnly)
  43803. styleBox->setSelectedId (3);
  43804. styleBox->addListener (this);
  43805. }
  43806. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  43807. {
  43808. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  43809. defaultButton->addButtonListener (this);
  43810. }
  43811. addAndMakeVisible (instructions = new Label (String::empty,
  43812. 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.")));
  43813. instructions->setFont (Font (13.0f));
  43814. setSize (500, 300);
  43815. }
  43816. ~CustomiserPanel()
  43817. {
  43818. deleteAllChildren();
  43819. }
  43820. void comboBoxChanged (ComboBox*)
  43821. {
  43822. if (styleBox->getSelectedId() == 1)
  43823. toolbar->setStyle (Toolbar::iconsOnly);
  43824. else if (styleBox->getSelectedId() == 2)
  43825. toolbar->setStyle (Toolbar::iconsWithText);
  43826. else if (styleBox->getSelectedId() == 3)
  43827. toolbar->setStyle (Toolbar::textOnly);
  43828. palette->resized(); // to make it update the styles
  43829. }
  43830. void buttonClicked (Button*)
  43831. {
  43832. toolbar->addDefaultItems (factory);
  43833. }
  43834. void paint (Graphics& g)
  43835. {
  43836. Colour background;
  43837. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  43838. if (dw != 0)
  43839. background = dw->getBackgroundColour();
  43840. g.setColour (background.contrasting().withAlpha (0.3f));
  43841. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  43842. }
  43843. void resized()
  43844. {
  43845. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  43846. if (styleBox != 0)
  43847. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  43848. if (defaultButton != 0)
  43849. {
  43850. defaultButton->changeWidthToFitText (22);
  43851. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  43852. }
  43853. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  43854. }
  43855. private:
  43856. ToolbarItemFactory& factory;
  43857. Toolbar* const toolbar;
  43858. Label* instructions;
  43859. ToolbarItemPalette* palette;
  43860. ComboBox* styleBox;
  43861. TextButton* defaultButton;
  43862. };
  43863. };
  43864. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  43865. {
  43866. setEditingActive (true);
  43867. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  43868. dw.runModalLoop();
  43869. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  43870. setEditingActive (false);
  43871. }
  43872. END_JUCE_NAMESPACE
  43873. /*** End of inlined file: juce_Toolbar.cpp ***/
  43874. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  43875. BEGIN_JUCE_NAMESPACE
  43876. ToolbarItemFactory::ToolbarItemFactory()
  43877. {
  43878. }
  43879. ToolbarItemFactory::~ToolbarItemFactory()
  43880. {
  43881. }
  43882. class ItemDragAndDropOverlayComponent : public Component
  43883. {
  43884. public:
  43885. ItemDragAndDropOverlayComponent()
  43886. : isDragging (false)
  43887. {
  43888. setAlwaysOnTop (true);
  43889. setRepaintsOnMouseActivity (true);
  43890. setMouseCursor (MouseCursor::DraggingHandCursor);
  43891. }
  43892. ~ItemDragAndDropOverlayComponent()
  43893. {
  43894. }
  43895. void paint (Graphics& g)
  43896. {
  43897. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43898. if (isMouseOverOrDragging()
  43899. && tc != 0
  43900. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43901. {
  43902. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  43903. g.drawRect (0, 0, getWidth(), getHeight(),
  43904. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  43905. }
  43906. }
  43907. void mouseDown (const MouseEvent& e)
  43908. {
  43909. isDragging = false;
  43910. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43911. if (tc != 0)
  43912. {
  43913. tc->dragOffsetX = e.x;
  43914. tc->dragOffsetY = e.y;
  43915. }
  43916. }
  43917. void mouseDrag (const MouseEvent& e)
  43918. {
  43919. if (! (isDragging || e.mouseWasClicked()))
  43920. {
  43921. isDragging = true;
  43922. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  43923. if (dnd != 0)
  43924. {
  43925. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  43926. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43927. if (tc != 0)
  43928. {
  43929. tc->isBeingDragged = true;
  43930. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43931. tc->setVisible (false);
  43932. }
  43933. }
  43934. }
  43935. }
  43936. void mouseUp (const MouseEvent&)
  43937. {
  43938. isDragging = false;
  43939. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43940. if (tc != 0)
  43941. {
  43942. tc->isBeingDragged = false;
  43943. Toolbar* const tb = tc->getToolbar();
  43944. if (tb != 0)
  43945. tb->updateAllItemPositions (true);
  43946. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43947. delete tc;
  43948. }
  43949. }
  43950. void parentSizeChanged()
  43951. {
  43952. setBounds (0, 0, getParentWidth(), getParentHeight());
  43953. }
  43954. juce_UseDebuggingNewOperator
  43955. private:
  43956. bool isDragging;
  43957. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  43958. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  43959. };
  43960. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  43961. const String& labelText,
  43962. const bool isBeingUsedAsAButton_)
  43963. : Button (labelText),
  43964. itemId (itemId_),
  43965. mode (normalMode),
  43966. toolbarStyle (Toolbar::iconsOnly),
  43967. dragOffsetX (0),
  43968. dragOffsetY (0),
  43969. isActive (true),
  43970. isBeingDragged (false),
  43971. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  43972. {
  43973. // Your item ID can't be 0!
  43974. jassert (itemId_ != 0);
  43975. }
  43976. ToolbarItemComponent::~ToolbarItemComponent()
  43977. {
  43978. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  43979. overlayComp = 0;
  43980. }
  43981. Toolbar* ToolbarItemComponent::getToolbar() const
  43982. {
  43983. return dynamic_cast <Toolbar*> (getParentComponent());
  43984. }
  43985. bool ToolbarItemComponent::isToolbarVertical() const
  43986. {
  43987. const Toolbar* const t = getToolbar();
  43988. return t != 0 && t->isVertical();
  43989. }
  43990. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  43991. {
  43992. if (toolbarStyle != newStyle)
  43993. {
  43994. toolbarStyle = newStyle;
  43995. repaint();
  43996. resized();
  43997. }
  43998. }
  43999. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44000. {
  44001. if (isBeingUsedAsAButton)
  44002. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44003. over, down, *this);
  44004. if (toolbarStyle != Toolbar::iconsOnly)
  44005. {
  44006. const int indent = contentArea.getX();
  44007. int y = indent;
  44008. int h = getHeight() - indent * 2;
  44009. if (toolbarStyle == Toolbar::iconsWithText)
  44010. {
  44011. y = contentArea.getBottom() + indent / 2;
  44012. h -= contentArea.getHeight();
  44013. }
  44014. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44015. getButtonText(), *this);
  44016. }
  44017. if (! contentArea.isEmpty())
  44018. {
  44019. g.saveState();
  44020. g.setOrigin (contentArea.getX(), contentArea.getY());
  44021. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44022. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44023. g.restoreState();
  44024. }
  44025. }
  44026. void ToolbarItemComponent::resized()
  44027. {
  44028. if (toolbarStyle != Toolbar::textOnly)
  44029. {
  44030. const int indent = jmin (proportionOfWidth (0.08f),
  44031. proportionOfHeight (0.08f));
  44032. contentArea = Rectangle<int> (indent, indent,
  44033. getWidth() - indent * 2,
  44034. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44035. : (getHeight() - indent * 2));
  44036. }
  44037. else
  44038. {
  44039. contentArea = Rectangle<int>();
  44040. }
  44041. contentAreaChanged (contentArea);
  44042. }
  44043. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44044. {
  44045. if (mode != newMode)
  44046. {
  44047. mode = newMode;
  44048. repaint();
  44049. if (mode == normalMode)
  44050. {
  44051. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44052. overlayComp = 0;
  44053. }
  44054. else if (overlayComp == 0)
  44055. {
  44056. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44057. overlayComp->parentSizeChanged();
  44058. }
  44059. resized();
  44060. }
  44061. }
  44062. END_JUCE_NAMESPACE
  44063. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44064. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44065. BEGIN_JUCE_NAMESPACE
  44066. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44067. Toolbar* const toolbar_)
  44068. : factory (factory_),
  44069. toolbar (toolbar_)
  44070. {
  44071. Component* const itemHolder = new Component();
  44072. Array <int> allIds;
  44073. factory_.getAllToolbarItemIds (allIds);
  44074. for (int i = 0; i < allIds.size(); ++i)
  44075. {
  44076. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44077. jassert (tc != 0);
  44078. if (tc != 0)
  44079. {
  44080. itemHolder->addAndMakeVisible (tc);
  44081. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44082. }
  44083. }
  44084. viewport = new Viewport();
  44085. viewport->setViewedComponent (itemHolder);
  44086. addAndMakeVisible (viewport);
  44087. }
  44088. ToolbarItemPalette::~ToolbarItemPalette()
  44089. {
  44090. viewport->getViewedComponent()->deleteAllChildren();
  44091. deleteAllChildren();
  44092. }
  44093. void ToolbarItemPalette::resized()
  44094. {
  44095. viewport->setBoundsInset (BorderSize (1));
  44096. Component* const itemHolder = viewport->getViewedComponent();
  44097. const int indent = 8;
  44098. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44099. const int height = toolbar->getThickness();
  44100. int x = indent;
  44101. int y = indent;
  44102. int maxX = 0;
  44103. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44104. {
  44105. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44106. if (tc != 0)
  44107. {
  44108. tc->setStyle (toolbar->getStyle());
  44109. int preferredSize = 1, minSize = 1, maxSize = 1;
  44110. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44111. {
  44112. if (x + preferredSize > preferredWidth && x > indent)
  44113. {
  44114. x = indent;
  44115. y += height;
  44116. }
  44117. tc->setBounds (x, y, preferredSize, height);
  44118. x += preferredSize + 8;
  44119. maxX = jmax (maxX, x);
  44120. }
  44121. }
  44122. }
  44123. itemHolder->setSize (maxX, y + height + 8);
  44124. }
  44125. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44126. {
  44127. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44128. jassert (tc != 0);
  44129. if (tc != 0)
  44130. {
  44131. tc->setBounds (comp->getBounds());
  44132. tc->setStyle (toolbar->getStyle());
  44133. tc->setEditingMode (comp->getEditingMode());
  44134. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44135. }
  44136. }
  44137. END_JUCE_NAMESPACE
  44138. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44139. /*** Start of inlined file: juce_TreeView.cpp ***/
  44140. BEGIN_JUCE_NAMESPACE
  44141. class TreeViewContentComponent : public Component,
  44142. public TooltipClient
  44143. {
  44144. public:
  44145. TreeViewContentComponent (TreeView& owner_)
  44146. : owner (owner_),
  44147. buttonUnderMouse (0),
  44148. isDragging (false)
  44149. {
  44150. }
  44151. ~TreeViewContentComponent()
  44152. {
  44153. deleteAllChildren();
  44154. }
  44155. void mouseDown (const MouseEvent& e)
  44156. {
  44157. updateButtonUnderMouse (e);
  44158. isDragging = false;
  44159. needSelectionOnMouseUp = false;
  44160. Rectangle<int> pos;
  44161. TreeViewItem* const item = findItemAt (e.y, pos);
  44162. if (item == 0)
  44163. return;
  44164. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44165. // as selection clicks)
  44166. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44167. {
  44168. if (e.x >= pos.getX() - owner.getIndentSize())
  44169. item->setOpen (! item->isOpen());
  44170. // (clicks to the left of an open/close button are ignored)
  44171. }
  44172. else
  44173. {
  44174. // mouse-down inside the body of the item..
  44175. if (! owner.isMultiSelectEnabled())
  44176. item->setSelected (true, true);
  44177. else if (item->isSelected())
  44178. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44179. else
  44180. selectBasedOnModifiers (item, e.mods);
  44181. if (e.x >= pos.getX())
  44182. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44183. }
  44184. }
  44185. void mouseUp (const MouseEvent& e)
  44186. {
  44187. updateButtonUnderMouse (e);
  44188. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44189. {
  44190. Rectangle<int> pos;
  44191. TreeViewItem* const item = findItemAt (e.y, pos);
  44192. if (item != 0)
  44193. selectBasedOnModifiers (item, e.mods);
  44194. }
  44195. }
  44196. void mouseDoubleClick (const MouseEvent& e)
  44197. {
  44198. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44199. {
  44200. Rectangle<int> pos;
  44201. TreeViewItem* const item = findItemAt (e.y, pos);
  44202. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44203. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44204. }
  44205. }
  44206. void mouseDrag (const MouseEvent& e)
  44207. {
  44208. if (isEnabled()
  44209. && ! (isDragging || e.mouseWasClicked()
  44210. || e.getDistanceFromDragStart() < 5
  44211. || e.mods.isPopupMenu()))
  44212. {
  44213. isDragging = true;
  44214. Rectangle<int> pos;
  44215. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44216. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44217. {
  44218. const String dragDescription (item->getDragSourceDescription());
  44219. if (dragDescription.isNotEmpty())
  44220. {
  44221. DragAndDropContainer* const dragContainer
  44222. = DragAndDropContainer::findParentDragContainerFor (this);
  44223. if (dragContainer != 0)
  44224. {
  44225. pos.setSize (pos.getWidth(), item->itemHeight);
  44226. Image* dragImage = Component::createComponentSnapshot (pos, true);
  44227. dragImage->multiplyAllAlphas (0.6f);
  44228. Point<int> imageOffset (pos.getX() - e.x, pos.getY() - e.y);
  44229. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44230. }
  44231. else
  44232. {
  44233. // to be able to do a drag-and-drop operation, the treeview needs to
  44234. // be inside a component which is also a DragAndDropContainer.
  44235. jassertfalse
  44236. }
  44237. }
  44238. }
  44239. }
  44240. }
  44241. void mouseMove (const MouseEvent& e)
  44242. {
  44243. updateButtonUnderMouse (e);
  44244. }
  44245. void mouseExit (const MouseEvent& e)
  44246. {
  44247. updateButtonUnderMouse (e);
  44248. }
  44249. void paint (Graphics& g)
  44250. {
  44251. if (owner.rootItem != 0)
  44252. {
  44253. owner.handleAsyncUpdate();
  44254. if (! owner.rootItemVisible)
  44255. g.setOrigin (0, -owner.rootItem->itemHeight);
  44256. owner.rootItem->paintRecursively (g, getWidth());
  44257. }
  44258. }
  44259. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44260. {
  44261. if (owner.rootItem != 0)
  44262. {
  44263. owner.handleAsyncUpdate();
  44264. if (! owner.rootItemVisible)
  44265. y += owner.rootItem->itemHeight;
  44266. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44267. if (ti != 0)
  44268. itemPosition = ti->getItemPosition (false);
  44269. return ti;
  44270. }
  44271. return 0;
  44272. }
  44273. void updateComponents()
  44274. {
  44275. const int visibleTop = -getY();
  44276. const int visibleBottom = visibleTop + getParentHeight();
  44277. BigInteger itemsToKeep;
  44278. {
  44279. TreeViewItem* item = owner.rootItem;
  44280. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44281. while (item != 0 && y < visibleBottom)
  44282. {
  44283. y += item->itemHeight;
  44284. if (y >= visibleTop)
  44285. {
  44286. const int index = rowComponentIds.indexOf (item->uid);
  44287. if (index < 0)
  44288. {
  44289. Component* const comp = item->createItemComponent();
  44290. if (comp != 0)
  44291. {
  44292. addAndMakeVisible (comp);
  44293. itemsToKeep.setBit (rowComponentItems.size());
  44294. rowComponentItems.add (item);
  44295. rowComponentIds.add (item->uid);
  44296. rowComponents.add (comp);
  44297. }
  44298. }
  44299. else
  44300. {
  44301. itemsToKeep.setBit (index);
  44302. }
  44303. }
  44304. item = item->getNextVisibleItem (true);
  44305. }
  44306. }
  44307. for (int i = rowComponentItems.size(); --i >= 0;)
  44308. {
  44309. Component* const comp = rowComponents.getUnchecked(i);
  44310. bool keep = false;
  44311. if (isParentOf (comp))
  44312. {
  44313. if (itemsToKeep[i])
  44314. {
  44315. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44316. Rectangle<int> pos (item->getItemPosition (false));
  44317. pos.setSize (pos.getWidth(), item->itemHeight);
  44318. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44319. {
  44320. keep = true;
  44321. comp->setBounds (pos);
  44322. }
  44323. }
  44324. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44325. {
  44326. keep = true;
  44327. comp->setSize (0, 0);
  44328. }
  44329. }
  44330. if (! keep)
  44331. {
  44332. delete comp;
  44333. rowComponents.remove (i);
  44334. rowComponentIds.remove (i);
  44335. rowComponentItems.remove (i);
  44336. }
  44337. }
  44338. }
  44339. void updateButtonUnderMouse (const MouseEvent& e)
  44340. {
  44341. TreeViewItem* newItem = 0;
  44342. if (owner.openCloseButtonsVisible)
  44343. {
  44344. Rectangle<int> pos;
  44345. TreeViewItem* item = findItemAt (e.y, pos);
  44346. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44347. {
  44348. newItem = item;
  44349. if (! newItem->mightContainSubItems())
  44350. newItem = 0;
  44351. }
  44352. }
  44353. if (buttonUnderMouse != newItem)
  44354. {
  44355. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44356. {
  44357. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44358. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44359. }
  44360. buttonUnderMouse = newItem;
  44361. if (buttonUnderMouse != 0)
  44362. {
  44363. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44364. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44365. }
  44366. }
  44367. }
  44368. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44369. {
  44370. return item == buttonUnderMouse;
  44371. }
  44372. void resized()
  44373. {
  44374. owner.itemsChanged();
  44375. }
  44376. const String getTooltip()
  44377. {
  44378. Rectangle<int> pos;
  44379. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44380. if (item != 0)
  44381. return item->getTooltip();
  44382. return owner.getTooltip();
  44383. }
  44384. juce_UseDebuggingNewOperator
  44385. private:
  44386. TreeView& owner;
  44387. Array <TreeViewItem*> rowComponentItems;
  44388. Array <int> rowComponentIds;
  44389. Array <Component*> rowComponents;
  44390. TreeViewItem* buttonUnderMouse;
  44391. bool isDragging, needSelectionOnMouseUp;
  44392. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44393. {
  44394. TreeViewItem* firstSelected = 0;
  44395. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44396. {
  44397. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44398. jassert (lastSelected != 0);
  44399. int rowStart = firstSelected->getRowNumberInTree();
  44400. int rowEnd = lastSelected->getRowNumberInTree();
  44401. if (rowStart > rowEnd)
  44402. swapVariables (rowStart, rowEnd);
  44403. int ourRow = item->getRowNumberInTree();
  44404. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44405. if (ourRow > otherEnd)
  44406. swapVariables (ourRow, otherEnd);
  44407. for (int i = ourRow; i <= otherEnd; ++i)
  44408. owner.getItemOnRow (i)->setSelected (true, false);
  44409. }
  44410. else
  44411. {
  44412. const bool cmd = modifiers.isCommandDown();
  44413. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44414. }
  44415. }
  44416. bool containsItem (TreeViewItem* const item) const
  44417. {
  44418. for (int i = rowComponentItems.size(); --i >= 0;)
  44419. if (rowComponentItems.getUnchecked(i) == item)
  44420. return true;
  44421. return false;
  44422. }
  44423. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44424. {
  44425. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44426. {
  44427. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44428. if (source->isDragging())
  44429. {
  44430. Component* const underMouse = source->getComponentUnderMouse();
  44431. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44432. return true;
  44433. }
  44434. }
  44435. return false;
  44436. }
  44437. TreeViewContentComponent (const TreeViewContentComponent&);
  44438. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44439. };
  44440. class TreeView::TreeViewport : public Viewport
  44441. {
  44442. public:
  44443. TreeViewport() throw() : lastX (-1) {}
  44444. ~TreeViewport() throw() {}
  44445. void updateComponents (const bool triggerResize = false)
  44446. {
  44447. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44448. if (tvc != 0)
  44449. {
  44450. if (triggerResize)
  44451. tvc->resized();
  44452. else
  44453. tvc->updateComponents();
  44454. }
  44455. repaint();
  44456. }
  44457. void visibleAreaChanged (int x, int, int, int)
  44458. {
  44459. const bool hasScrolledSideways = (x != lastX);
  44460. lastX = x;
  44461. updateComponents (hasScrolledSideways);
  44462. }
  44463. juce_UseDebuggingNewOperator
  44464. private:
  44465. int lastX;
  44466. TreeViewport (const TreeViewport&);
  44467. TreeViewport& operator= (const TreeViewport&);
  44468. };
  44469. TreeView::TreeView (const String& componentName)
  44470. : Component (componentName),
  44471. rootItem (0),
  44472. dragInsertPointHighlight (0),
  44473. dragTargetGroupHighlight (0),
  44474. indentSize (24),
  44475. defaultOpenness (false),
  44476. needsRecalculating (true),
  44477. rootItemVisible (true),
  44478. multiSelectEnabled (false),
  44479. openCloseButtonsVisible (true)
  44480. {
  44481. addAndMakeVisible (viewport = new TreeViewport());
  44482. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44483. viewport->setWantsKeyboardFocus (false);
  44484. setWantsKeyboardFocus (true);
  44485. }
  44486. TreeView::~TreeView()
  44487. {
  44488. if (rootItem != 0)
  44489. rootItem->setOwnerView (0);
  44490. deleteAllChildren();
  44491. }
  44492. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44493. {
  44494. if (rootItem != newRootItem)
  44495. {
  44496. if (newRootItem != 0)
  44497. {
  44498. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44499. if (newRootItem->ownerView != 0)
  44500. newRootItem->ownerView->setRootItem (0);
  44501. }
  44502. if (rootItem != 0)
  44503. rootItem->setOwnerView (0);
  44504. rootItem = newRootItem;
  44505. if (newRootItem != 0)
  44506. newRootItem->setOwnerView (this);
  44507. needsRecalculating = true;
  44508. handleAsyncUpdate();
  44509. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44510. {
  44511. rootItem->setOpen (false); // force a re-open
  44512. rootItem->setOpen (true);
  44513. }
  44514. }
  44515. }
  44516. void TreeView::deleteRootItem()
  44517. {
  44518. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44519. setRootItem (0);
  44520. }
  44521. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44522. {
  44523. rootItemVisible = shouldBeVisible;
  44524. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44525. {
  44526. rootItem->setOpen (false); // force a re-open
  44527. rootItem->setOpen (true);
  44528. }
  44529. itemsChanged();
  44530. }
  44531. void TreeView::colourChanged()
  44532. {
  44533. setOpaque (findColour (backgroundColourId).isOpaque());
  44534. repaint();
  44535. }
  44536. void TreeView::setIndentSize (const int newIndentSize)
  44537. {
  44538. if (indentSize != newIndentSize)
  44539. {
  44540. indentSize = newIndentSize;
  44541. resized();
  44542. }
  44543. }
  44544. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44545. {
  44546. if (defaultOpenness != isOpenByDefault)
  44547. {
  44548. defaultOpenness = isOpenByDefault;
  44549. itemsChanged();
  44550. }
  44551. }
  44552. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44553. {
  44554. multiSelectEnabled = canMultiSelect;
  44555. }
  44556. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44557. {
  44558. if (openCloseButtonsVisible != shouldBeVisible)
  44559. {
  44560. openCloseButtonsVisible = shouldBeVisible;
  44561. itemsChanged();
  44562. }
  44563. }
  44564. Viewport* TreeView::getViewport() const throw()
  44565. {
  44566. return viewport;
  44567. }
  44568. void TreeView::clearSelectedItems()
  44569. {
  44570. if (rootItem != 0)
  44571. rootItem->deselectAllRecursively();
  44572. }
  44573. int TreeView::getNumSelectedItems() const throw()
  44574. {
  44575. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44576. }
  44577. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44578. {
  44579. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44580. }
  44581. int TreeView::getNumRowsInTree() const
  44582. {
  44583. if (rootItem != 0)
  44584. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44585. return 0;
  44586. }
  44587. TreeViewItem* TreeView::getItemOnRow (int index) const
  44588. {
  44589. if (! rootItemVisible)
  44590. ++index;
  44591. if (rootItem != 0 && index >= 0)
  44592. return rootItem->getItemOnRow (index);
  44593. return 0;
  44594. }
  44595. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44596. {
  44597. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44598. Rectangle<int> pos;
  44599. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44600. }
  44601. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44602. {
  44603. if (rootItem == 0)
  44604. return 0;
  44605. return rootItem->findItemFromIdentifierString (identifierString);
  44606. }
  44607. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44608. {
  44609. XmlElement* e = 0;
  44610. if (rootItem != 0)
  44611. {
  44612. e = rootItem->getOpennessState();
  44613. if (e != 0 && alsoIncludeScrollPosition)
  44614. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44615. }
  44616. return e;
  44617. }
  44618. void TreeView::restoreOpennessState (const XmlElement& newState)
  44619. {
  44620. if (rootItem != 0)
  44621. {
  44622. rootItem->restoreOpennessState (newState);
  44623. if (newState.hasAttribute ("scrollPos"))
  44624. viewport->setViewPosition (viewport->getViewPositionX(),
  44625. newState.getIntAttribute ("scrollPos"));
  44626. }
  44627. }
  44628. void TreeView::paint (Graphics& g)
  44629. {
  44630. g.fillAll (findColour (backgroundColourId));
  44631. }
  44632. void TreeView::resized()
  44633. {
  44634. viewport->setBounds (0, 0, getWidth(), getHeight());
  44635. itemsChanged();
  44636. handleAsyncUpdate();
  44637. }
  44638. void TreeView::enablementChanged()
  44639. {
  44640. repaint();
  44641. }
  44642. void TreeView::moveSelectedRow (int delta)
  44643. {
  44644. if (delta == 0)
  44645. return;
  44646. int rowSelected = 0;
  44647. TreeViewItem* const firstSelected = getSelectedItem (0);
  44648. if (firstSelected != 0)
  44649. rowSelected = firstSelected->getRowNumberInTree();
  44650. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44651. for (;;)
  44652. {
  44653. TreeViewItem* item = getItemOnRow (rowSelected);
  44654. if (item != 0)
  44655. {
  44656. if (! item->canBeSelected())
  44657. {
  44658. // if the row we want to highlight doesn't allow it, try skipping
  44659. // to the next item..
  44660. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44661. rowSelected + (delta < 0 ? -1 : 1));
  44662. if (rowSelected != nextRowToTry)
  44663. {
  44664. rowSelected = nextRowToTry;
  44665. continue;
  44666. }
  44667. else
  44668. {
  44669. break;
  44670. }
  44671. }
  44672. item->setSelected (true, true);
  44673. scrollToKeepItemVisible (item);
  44674. }
  44675. break;
  44676. }
  44677. }
  44678. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44679. {
  44680. if (item != 0 && item->ownerView == this)
  44681. {
  44682. handleAsyncUpdate();
  44683. item = item->getDeepestOpenParentItem();
  44684. int y = item->y;
  44685. int viewTop = viewport->getViewPositionY();
  44686. if (y < viewTop)
  44687. {
  44688. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44689. }
  44690. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44691. {
  44692. viewport->setViewPosition (viewport->getViewPositionX(),
  44693. (y + item->itemHeight) - viewport->getViewHeight());
  44694. }
  44695. }
  44696. }
  44697. bool TreeView::keyPressed (const KeyPress& key)
  44698. {
  44699. if (key.isKeyCode (KeyPress::upKey))
  44700. {
  44701. moveSelectedRow (-1);
  44702. }
  44703. else if (key.isKeyCode (KeyPress::downKey))
  44704. {
  44705. moveSelectedRow (1);
  44706. }
  44707. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44708. {
  44709. if (rootItem != 0)
  44710. {
  44711. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44712. if (key.isKeyCode (KeyPress::pageUpKey))
  44713. rowsOnScreen = -rowsOnScreen;
  44714. moveSelectedRow (rowsOnScreen);
  44715. }
  44716. }
  44717. else if (key.isKeyCode (KeyPress::homeKey))
  44718. {
  44719. moveSelectedRow (-0x3fffffff);
  44720. }
  44721. else if (key.isKeyCode (KeyPress::endKey))
  44722. {
  44723. moveSelectedRow (0x3fffffff);
  44724. }
  44725. else if (key.isKeyCode (KeyPress::returnKey))
  44726. {
  44727. TreeViewItem* const firstSelected = getSelectedItem (0);
  44728. if (firstSelected != 0)
  44729. firstSelected->setOpen (! firstSelected->isOpen());
  44730. }
  44731. else if (key.isKeyCode (KeyPress::leftKey))
  44732. {
  44733. TreeViewItem* const firstSelected = getSelectedItem (0);
  44734. if (firstSelected != 0)
  44735. {
  44736. if (firstSelected->isOpen())
  44737. {
  44738. firstSelected->setOpen (false);
  44739. }
  44740. else
  44741. {
  44742. TreeViewItem* parent = firstSelected->parentItem;
  44743. if ((! rootItemVisible) && parent == rootItem)
  44744. parent = 0;
  44745. if (parent != 0)
  44746. {
  44747. parent->setSelected (true, true);
  44748. scrollToKeepItemVisible (parent);
  44749. }
  44750. }
  44751. }
  44752. }
  44753. else if (key.isKeyCode (KeyPress::rightKey))
  44754. {
  44755. TreeViewItem* const firstSelected = getSelectedItem (0);
  44756. if (firstSelected != 0)
  44757. {
  44758. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  44759. moveSelectedRow (1);
  44760. else
  44761. firstSelected->setOpen (true);
  44762. }
  44763. }
  44764. else
  44765. {
  44766. return false;
  44767. }
  44768. return true;
  44769. }
  44770. void TreeView::itemsChanged() throw()
  44771. {
  44772. needsRecalculating = true;
  44773. repaint();
  44774. triggerAsyncUpdate();
  44775. }
  44776. void TreeView::handleAsyncUpdate()
  44777. {
  44778. if (needsRecalculating)
  44779. {
  44780. needsRecalculating = false;
  44781. const ScopedLock sl (nodeAlterationLock);
  44782. if (rootItem != 0)
  44783. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  44784. viewport->updateComponents();
  44785. if (rootItem != 0)
  44786. {
  44787. viewport->getViewedComponent()
  44788. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  44789. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  44790. }
  44791. else
  44792. {
  44793. viewport->getViewedComponent()->setSize (0, 0);
  44794. }
  44795. }
  44796. }
  44797. class TreeView::InsertPointHighlight : public Component
  44798. {
  44799. public:
  44800. InsertPointHighlight()
  44801. : lastItem (0)
  44802. {
  44803. setSize (100, 12);
  44804. setAlwaysOnTop (true);
  44805. setInterceptsMouseClicks (false, false);
  44806. }
  44807. ~InsertPointHighlight() {}
  44808. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  44809. {
  44810. lastItem = item;
  44811. lastIndex = insertIndex;
  44812. const int offset = getHeight() / 2;
  44813. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  44814. }
  44815. void paint (Graphics& g)
  44816. {
  44817. Path p;
  44818. const float h = (float) getHeight();
  44819. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  44820. p.startNewSubPath (h - 2.0f, h / 2.0f);
  44821. p.lineTo ((float) getWidth(), h / 2.0f);
  44822. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44823. g.strokePath (p, PathStrokeType (2.0f));
  44824. }
  44825. TreeViewItem* lastItem;
  44826. int lastIndex;
  44827. private:
  44828. InsertPointHighlight (const InsertPointHighlight&);
  44829. InsertPointHighlight& operator= (const InsertPointHighlight&);
  44830. };
  44831. class TreeView::TargetGroupHighlight : public Component
  44832. {
  44833. public:
  44834. TargetGroupHighlight()
  44835. {
  44836. setAlwaysOnTop (true);
  44837. setInterceptsMouseClicks (false, false);
  44838. }
  44839. ~TargetGroupHighlight() {}
  44840. void setTargetPosition (TreeViewItem* const item) throw()
  44841. {
  44842. Rectangle<int> r (item->getItemPosition (true));
  44843. r.setHeight (item->getItemHeight());
  44844. setBounds (r);
  44845. }
  44846. void paint (Graphics& g)
  44847. {
  44848. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44849. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  44850. }
  44851. private:
  44852. TargetGroupHighlight (const TargetGroupHighlight&);
  44853. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  44854. };
  44855. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  44856. {
  44857. beginDragAutoRepeat (1000 / 30);
  44858. if (dragInsertPointHighlight == 0)
  44859. {
  44860. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  44861. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  44862. }
  44863. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  44864. dragTargetGroupHighlight->setTargetPosition (item);
  44865. }
  44866. void TreeView::hideDragHighlight() throw()
  44867. {
  44868. deleteAndZero (dragInsertPointHighlight);
  44869. deleteAndZero (dragTargetGroupHighlight);
  44870. }
  44871. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  44872. const StringArray& files, const String& sourceDescription,
  44873. Component* sourceComponent) const throw()
  44874. {
  44875. insertIndex = 0;
  44876. TreeViewItem* item = getItemAt (y);
  44877. if (item == 0)
  44878. return 0;
  44879. Rectangle<int> itemPos (item->getItemPosition (true));
  44880. insertIndex = item->getIndexInParent();
  44881. const int oldY = y;
  44882. y = itemPos.getY();
  44883. if (item->getNumSubItems() == 0 || ! item->isOpen())
  44884. {
  44885. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44886. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44887. {
  44888. // Check if we're trying to drag into an empty group item..
  44889. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  44890. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  44891. {
  44892. insertIndex = 0;
  44893. x = itemPos.getX() + getIndentSize();
  44894. y = itemPos.getBottom();
  44895. return item;
  44896. }
  44897. }
  44898. }
  44899. if (oldY > itemPos.getCentreY())
  44900. {
  44901. y += item->getItemHeight();
  44902. while (item->isLastOfSiblings() && item->parentItem != 0
  44903. && item->parentItem->parentItem != 0)
  44904. {
  44905. if (x > itemPos.getX())
  44906. break;
  44907. item = item->parentItem;
  44908. itemPos = item->getItemPosition (true);
  44909. insertIndex = item->getIndexInParent();
  44910. }
  44911. ++insertIndex;
  44912. }
  44913. x = itemPos.getX();
  44914. return item->parentItem;
  44915. }
  44916. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44917. {
  44918. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  44919. int insertIndex;
  44920. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44921. if (item != 0)
  44922. {
  44923. if (scrolled || dragInsertPointHighlight == 0
  44924. || dragInsertPointHighlight->lastItem != item
  44925. || dragInsertPointHighlight->lastIndex != insertIndex)
  44926. {
  44927. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44928. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44929. showDragHighlight (item, insertIndex, x, y);
  44930. else
  44931. hideDragHighlight();
  44932. }
  44933. }
  44934. else
  44935. {
  44936. hideDragHighlight();
  44937. }
  44938. }
  44939. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44940. {
  44941. hideDragHighlight();
  44942. int insertIndex;
  44943. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44944. if (item != 0)
  44945. {
  44946. if (files.size() > 0)
  44947. {
  44948. if (item->isInterestedInFileDrag (files))
  44949. item->filesDropped (files, insertIndex);
  44950. }
  44951. else
  44952. {
  44953. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44954. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  44955. }
  44956. }
  44957. }
  44958. bool TreeView::isInterestedInFileDrag (const StringArray&)
  44959. {
  44960. return true;
  44961. }
  44962. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  44963. {
  44964. fileDragMove (files, x, y);
  44965. }
  44966. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  44967. {
  44968. handleDrag (files, String::empty, 0, x, y);
  44969. }
  44970. void TreeView::fileDragExit (const StringArray&)
  44971. {
  44972. hideDragHighlight();
  44973. }
  44974. void TreeView::filesDropped (const StringArray& files, int x, int y)
  44975. {
  44976. handleDrop (files, String::empty, 0, x, y);
  44977. }
  44978. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  44979. {
  44980. return true;
  44981. }
  44982. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44983. {
  44984. itemDragMove (sourceDescription, sourceComponent, x, y);
  44985. }
  44986. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44987. {
  44988. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  44989. }
  44990. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  44991. {
  44992. hideDragHighlight();
  44993. }
  44994. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44995. {
  44996. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  44997. }
  44998. enum TreeViewOpenness
  44999. {
  45000. opennessDefault = 0,
  45001. opennessClosed = 1,
  45002. opennessOpen = 2
  45003. };
  45004. TreeViewItem::TreeViewItem()
  45005. : ownerView (0),
  45006. parentItem (0),
  45007. y (0),
  45008. itemHeight (0),
  45009. totalHeight (0),
  45010. selected (false),
  45011. redrawNeeded (true),
  45012. drawLinesInside (true),
  45013. drawsInLeftMargin (false),
  45014. openness (opennessDefault)
  45015. {
  45016. static int nextUID = 0;
  45017. uid = nextUID++;
  45018. }
  45019. TreeViewItem::~TreeViewItem()
  45020. {
  45021. }
  45022. const String TreeViewItem::getUniqueName() const
  45023. {
  45024. return String::empty;
  45025. }
  45026. void TreeViewItem::itemOpennessChanged (bool)
  45027. {
  45028. }
  45029. int TreeViewItem::getNumSubItems() const throw()
  45030. {
  45031. return subItems.size();
  45032. }
  45033. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45034. {
  45035. return subItems [index];
  45036. }
  45037. void TreeViewItem::clearSubItems()
  45038. {
  45039. if (subItems.size() > 0)
  45040. {
  45041. if (ownerView != 0)
  45042. {
  45043. const ScopedLock sl (ownerView->nodeAlterationLock);
  45044. subItems.clear();
  45045. treeHasChanged();
  45046. }
  45047. else
  45048. {
  45049. subItems.clear();
  45050. }
  45051. }
  45052. }
  45053. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45054. {
  45055. if (newItem != 0)
  45056. {
  45057. newItem->parentItem = this;
  45058. newItem->setOwnerView (ownerView);
  45059. newItem->y = 0;
  45060. newItem->itemHeight = newItem->getItemHeight();
  45061. newItem->totalHeight = 0;
  45062. newItem->itemWidth = newItem->getItemWidth();
  45063. newItem->totalWidth = 0;
  45064. if (ownerView != 0)
  45065. {
  45066. const ScopedLock sl (ownerView->nodeAlterationLock);
  45067. subItems.insert (insertPosition, newItem);
  45068. treeHasChanged();
  45069. if (newItem->isOpen())
  45070. newItem->itemOpennessChanged (true);
  45071. }
  45072. else
  45073. {
  45074. subItems.insert (insertPosition, newItem);
  45075. if (newItem->isOpen())
  45076. newItem->itemOpennessChanged (true);
  45077. }
  45078. }
  45079. }
  45080. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45081. {
  45082. if (ownerView != 0)
  45083. {
  45084. const ScopedLock sl (ownerView->nodeAlterationLock);
  45085. if (((unsigned int) index) < (unsigned int) subItems.size())
  45086. {
  45087. subItems.remove (index, deleteItem);
  45088. treeHasChanged();
  45089. }
  45090. }
  45091. else
  45092. {
  45093. subItems.remove (index, deleteItem);
  45094. }
  45095. }
  45096. bool TreeViewItem::isOpen() const throw()
  45097. {
  45098. if (openness == opennessDefault)
  45099. return ownerView != 0 && ownerView->defaultOpenness;
  45100. else
  45101. return openness == opennessOpen;
  45102. }
  45103. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45104. {
  45105. if (isOpen() != shouldBeOpen)
  45106. {
  45107. openness = shouldBeOpen ? opennessOpen
  45108. : opennessClosed;
  45109. treeHasChanged();
  45110. itemOpennessChanged (isOpen());
  45111. }
  45112. }
  45113. bool TreeViewItem::isSelected() const throw()
  45114. {
  45115. return selected;
  45116. }
  45117. void TreeViewItem::deselectAllRecursively()
  45118. {
  45119. setSelected (false, false);
  45120. for (int i = 0; i < subItems.size(); ++i)
  45121. subItems.getUnchecked(i)->deselectAllRecursively();
  45122. }
  45123. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45124. const bool deselectOtherItemsFirst)
  45125. {
  45126. if (shouldBeSelected && ! canBeSelected())
  45127. return;
  45128. if (deselectOtherItemsFirst)
  45129. getTopLevelItem()->deselectAllRecursively();
  45130. if (shouldBeSelected != selected)
  45131. {
  45132. selected = shouldBeSelected;
  45133. if (ownerView != 0)
  45134. ownerView->repaint();
  45135. itemSelectionChanged (shouldBeSelected);
  45136. }
  45137. }
  45138. void TreeViewItem::paintItem (Graphics&, int, int)
  45139. {
  45140. }
  45141. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45142. {
  45143. ownerView->getLookAndFeel()
  45144. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45145. }
  45146. void TreeViewItem::itemClicked (const MouseEvent&)
  45147. {
  45148. }
  45149. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45150. {
  45151. if (mightContainSubItems())
  45152. setOpen (! isOpen());
  45153. }
  45154. void TreeViewItem::itemSelectionChanged (bool)
  45155. {
  45156. }
  45157. const String TreeViewItem::getTooltip()
  45158. {
  45159. return String::empty;
  45160. }
  45161. const String TreeViewItem::getDragSourceDescription()
  45162. {
  45163. return String::empty;
  45164. }
  45165. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45166. {
  45167. return false;
  45168. }
  45169. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45170. {
  45171. }
  45172. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45173. {
  45174. return false;
  45175. }
  45176. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45177. {
  45178. }
  45179. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45180. {
  45181. const int indentX = getIndentX();
  45182. int width = itemWidth;
  45183. if (ownerView != 0 && width < 0)
  45184. width = ownerView->viewport->getViewWidth() - indentX;
  45185. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45186. if (relativeToTreeViewTopLeft)
  45187. r -= ownerView->viewport->getViewPosition();
  45188. return r;
  45189. }
  45190. void TreeViewItem::treeHasChanged() const throw()
  45191. {
  45192. if (ownerView != 0)
  45193. ownerView->itemsChanged();
  45194. }
  45195. void TreeViewItem::repaintItem() const
  45196. {
  45197. if (ownerView != 0 && areAllParentsOpen())
  45198. {
  45199. const Rectangle<int> r (getItemPosition (true));
  45200. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  45201. }
  45202. }
  45203. bool TreeViewItem::areAllParentsOpen() const throw()
  45204. {
  45205. return parentItem == 0
  45206. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45207. }
  45208. void TreeViewItem::updatePositions (int newY)
  45209. {
  45210. y = newY;
  45211. itemHeight = getItemHeight();
  45212. totalHeight = itemHeight;
  45213. itemWidth = getItemWidth();
  45214. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45215. if (isOpen())
  45216. {
  45217. newY += totalHeight;
  45218. for (int i = 0; i < subItems.size(); ++i)
  45219. {
  45220. TreeViewItem* const ti = subItems.getUnchecked(i);
  45221. ti->updatePositions (newY);
  45222. newY += ti->totalHeight;
  45223. totalHeight += ti->totalHeight;
  45224. totalWidth = jmax (totalWidth, ti->totalWidth);
  45225. }
  45226. }
  45227. }
  45228. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45229. {
  45230. TreeViewItem* result = this;
  45231. TreeViewItem* item = this;
  45232. while (item->parentItem != 0)
  45233. {
  45234. item = item->parentItem;
  45235. if (! item->isOpen())
  45236. result = item;
  45237. }
  45238. return result;
  45239. }
  45240. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45241. {
  45242. ownerView = newOwner;
  45243. for (int i = subItems.size(); --i >= 0;)
  45244. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45245. }
  45246. int TreeViewItem::getIndentX() const throw()
  45247. {
  45248. const int indentWidth = ownerView->getIndentSize();
  45249. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45250. if (! ownerView->openCloseButtonsVisible)
  45251. x -= indentWidth;
  45252. TreeViewItem* p = parentItem;
  45253. while (p != 0)
  45254. {
  45255. x += indentWidth;
  45256. p = p->parentItem;
  45257. }
  45258. return x;
  45259. }
  45260. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45261. {
  45262. drawsInLeftMargin = canDrawInLeftMargin;
  45263. }
  45264. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45265. {
  45266. jassert (ownerView != 0);
  45267. if (ownerView == 0)
  45268. return;
  45269. const int indent = getIndentX();
  45270. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45271. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45272. const float halfH = itemHeight * 0.5f;
  45273. int depth = 0;
  45274. TreeViewItem* p = parentItem;
  45275. while (p != 0)
  45276. {
  45277. ++depth;
  45278. p = p->parentItem;
  45279. }
  45280. if (! ownerView->rootItemVisible)
  45281. --depth;
  45282. const int indentWidth = ownerView->getIndentSize();
  45283. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45284. {
  45285. float x = (depth + 0.5f) * indentWidth;
  45286. if (depth >= 0)
  45287. {
  45288. if (parentItem != 0 && parentItem->drawLinesInside)
  45289. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45290. if ((parentItem != 0 && parentItem->drawLinesInside)
  45291. || (parentItem == 0 && drawLinesInside))
  45292. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45293. }
  45294. p = parentItem;
  45295. int d = depth;
  45296. while (p != 0 && --d >= 0)
  45297. {
  45298. x -= (float) indentWidth;
  45299. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45300. && ! p->isLastOfSiblings())
  45301. {
  45302. g.drawLine (x, 0, x, (float) itemHeight);
  45303. }
  45304. p = p->parentItem;
  45305. }
  45306. if (mightContainSubItems())
  45307. {
  45308. g.saveState();
  45309. g.setOrigin (depth * indentWidth, 0);
  45310. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45311. paintOpenCloseButton (g, indentWidth, itemHeight,
  45312. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45313. ->isMouseOverButton (this));
  45314. g.restoreState();
  45315. }
  45316. }
  45317. {
  45318. g.saveState();
  45319. g.setOrigin (indent, 0);
  45320. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45321. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45322. paintItem (g, itemW, itemHeight);
  45323. g.restoreState();
  45324. }
  45325. if (isOpen())
  45326. {
  45327. const Rectangle<int> clip (g.getClipBounds());
  45328. for (int i = 0; i < subItems.size(); ++i)
  45329. {
  45330. TreeViewItem* const ti = subItems.getUnchecked(i);
  45331. const int relY = ti->y - y;
  45332. if (relY >= clip.getBottom())
  45333. break;
  45334. if (relY + ti->totalHeight >= clip.getY())
  45335. {
  45336. g.saveState();
  45337. g.setOrigin (0, relY);
  45338. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45339. ti->paintRecursively (g, width);
  45340. g.restoreState();
  45341. }
  45342. }
  45343. }
  45344. }
  45345. bool TreeViewItem::isLastOfSiblings() const throw()
  45346. {
  45347. return parentItem == 0
  45348. || parentItem->subItems.getLast() == this;
  45349. }
  45350. int TreeViewItem::getIndexInParent() const throw()
  45351. {
  45352. if (parentItem == 0)
  45353. return 0;
  45354. return parentItem->subItems.indexOf (this);
  45355. }
  45356. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45357. {
  45358. return (parentItem == 0) ? this
  45359. : parentItem->getTopLevelItem();
  45360. }
  45361. int TreeViewItem::getNumRows() const throw()
  45362. {
  45363. int num = 1;
  45364. if (isOpen())
  45365. {
  45366. for (int i = subItems.size(); --i >= 0;)
  45367. num += subItems.getUnchecked(i)->getNumRows();
  45368. }
  45369. return num;
  45370. }
  45371. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45372. {
  45373. if (index == 0)
  45374. return this;
  45375. if (index > 0 && isOpen())
  45376. {
  45377. --index;
  45378. for (int i = 0; i < subItems.size(); ++i)
  45379. {
  45380. TreeViewItem* const item = subItems.getUnchecked(i);
  45381. if (index == 0)
  45382. return item;
  45383. const int numRows = item->getNumRows();
  45384. if (numRows > index)
  45385. return item->getItemOnRow (index);
  45386. index -= numRows;
  45387. }
  45388. }
  45389. return 0;
  45390. }
  45391. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45392. {
  45393. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45394. {
  45395. const int h = itemHeight;
  45396. if (targetY < h)
  45397. return this;
  45398. if (isOpen())
  45399. {
  45400. targetY -= h;
  45401. for (int i = 0; i < subItems.size(); ++i)
  45402. {
  45403. TreeViewItem* const ti = subItems.getUnchecked(i);
  45404. if (targetY < ti->totalHeight)
  45405. return ti->findItemRecursively (targetY);
  45406. targetY -= ti->totalHeight;
  45407. }
  45408. }
  45409. }
  45410. return 0;
  45411. }
  45412. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45413. {
  45414. int total = 0;
  45415. if (isSelected())
  45416. ++total;
  45417. for (int i = subItems.size(); --i >= 0;)
  45418. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45419. return total;
  45420. }
  45421. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45422. {
  45423. if (isSelected())
  45424. {
  45425. if (index == 0)
  45426. return this;
  45427. --index;
  45428. }
  45429. if (index >= 0)
  45430. {
  45431. for (int i = 0; i < subItems.size(); ++i)
  45432. {
  45433. TreeViewItem* const item = subItems.getUnchecked(i);
  45434. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45435. if (found != 0)
  45436. return found;
  45437. index -= item->countSelectedItemsRecursively();
  45438. }
  45439. }
  45440. return 0;
  45441. }
  45442. int TreeViewItem::getRowNumberInTree() const throw()
  45443. {
  45444. if (parentItem != 0 && ownerView != 0)
  45445. {
  45446. int n = 1 + parentItem->getRowNumberInTree();
  45447. int ourIndex = parentItem->subItems.indexOf (this);
  45448. jassert (ourIndex >= 0);
  45449. while (--ourIndex >= 0)
  45450. n += parentItem->subItems [ourIndex]->getNumRows();
  45451. if (parentItem->parentItem == 0
  45452. && ! ownerView->rootItemVisible)
  45453. --n;
  45454. return n;
  45455. }
  45456. else
  45457. {
  45458. return 0;
  45459. }
  45460. }
  45461. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45462. {
  45463. drawLinesInside = drawLines;
  45464. }
  45465. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45466. {
  45467. if (recurse && isOpen() && subItems.size() > 0)
  45468. return subItems [0];
  45469. if (parentItem != 0)
  45470. {
  45471. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45472. if (nextIndex >= parentItem->subItems.size())
  45473. return parentItem->getNextVisibleItem (false);
  45474. return parentItem->subItems [nextIndex];
  45475. }
  45476. return 0;
  45477. }
  45478. const String TreeViewItem::getItemIdentifierString() const
  45479. {
  45480. String s;
  45481. if (parentItem != 0)
  45482. s = parentItem->getItemIdentifierString();
  45483. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45484. }
  45485. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45486. {
  45487. const String thisId (getUniqueName());
  45488. if (thisId == identifierString)
  45489. return this;
  45490. if (identifierString.startsWith (thisId + "/"))
  45491. {
  45492. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45493. bool wasOpen = isOpen();
  45494. setOpen (true);
  45495. for (int i = subItems.size(); --i >= 0;)
  45496. {
  45497. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45498. if (item != 0)
  45499. return item;
  45500. }
  45501. setOpen (wasOpen);
  45502. }
  45503. return 0;
  45504. }
  45505. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45506. {
  45507. if (e.hasTagName ("CLOSED"))
  45508. {
  45509. setOpen (false);
  45510. }
  45511. else if (e.hasTagName ("OPEN"))
  45512. {
  45513. setOpen (true);
  45514. forEachXmlChildElement (e, n)
  45515. {
  45516. const String id (n->getStringAttribute ("id"));
  45517. for (int i = 0; i < subItems.size(); ++i)
  45518. {
  45519. TreeViewItem* const ti = subItems.getUnchecked(i);
  45520. if (ti->getUniqueName() == id)
  45521. {
  45522. ti->restoreOpennessState (*n);
  45523. break;
  45524. }
  45525. }
  45526. }
  45527. }
  45528. }
  45529. XmlElement* TreeViewItem::getOpennessState() const throw()
  45530. {
  45531. const String name (getUniqueName());
  45532. if (name.isNotEmpty())
  45533. {
  45534. XmlElement* e;
  45535. if (isOpen())
  45536. {
  45537. e = new XmlElement ("OPEN");
  45538. for (int i = 0; i < subItems.size(); ++i)
  45539. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45540. }
  45541. else
  45542. {
  45543. e = new XmlElement ("CLOSED");
  45544. }
  45545. e->setAttribute ("id", name);
  45546. return e;
  45547. }
  45548. else
  45549. {
  45550. // trying to save the openness for an element that has no name - this won't
  45551. // work because it needs the names to identify what to open.
  45552. jassertfalse
  45553. }
  45554. return 0;
  45555. }
  45556. END_JUCE_NAMESPACE
  45557. /*** End of inlined file: juce_TreeView.cpp ***/
  45558. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45559. BEGIN_JUCE_NAMESPACE
  45560. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45561. : fileList (listToShow)
  45562. {
  45563. }
  45564. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45565. {
  45566. }
  45567. FileBrowserListener::~FileBrowserListener()
  45568. {
  45569. }
  45570. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45571. {
  45572. listeners.add (listener);
  45573. }
  45574. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45575. {
  45576. listeners.remove (listener);
  45577. }
  45578. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45579. {
  45580. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45581. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45582. }
  45583. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45584. {
  45585. if (fileList.getDirectory().exists())
  45586. {
  45587. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45588. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45589. }
  45590. }
  45591. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45592. {
  45593. if (fileList.getDirectory().exists())
  45594. {
  45595. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45596. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45597. }
  45598. }
  45599. END_JUCE_NAMESPACE
  45600. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45601. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45602. BEGIN_JUCE_NAMESPACE
  45603. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45604. TimeSliceThread& thread_)
  45605. : fileFilter (fileFilter_),
  45606. thread (thread_),
  45607. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45608. fileFindHandle (0),
  45609. shouldStop (true)
  45610. {
  45611. }
  45612. DirectoryContentsList::~DirectoryContentsList()
  45613. {
  45614. clear();
  45615. }
  45616. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45617. {
  45618. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45619. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45620. }
  45621. bool DirectoryContentsList::ignoresHiddenFiles() const
  45622. {
  45623. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45624. }
  45625. const File& DirectoryContentsList::getDirectory() const
  45626. {
  45627. return root;
  45628. }
  45629. void DirectoryContentsList::setDirectory (const File& directory,
  45630. const bool includeDirectories,
  45631. const bool includeFiles)
  45632. {
  45633. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45634. if (directory != root)
  45635. {
  45636. clear();
  45637. root = directory;
  45638. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45639. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45640. }
  45641. int newFlags = fileTypeFlags;
  45642. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45643. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45644. setTypeFlags (newFlags);
  45645. }
  45646. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45647. {
  45648. if (fileTypeFlags != newFlags)
  45649. {
  45650. fileTypeFlags = newFlags;
  45651. refresh();
  45652. }
  45653. }
  45654. void DirectoryContentsList::clear()
  45655. {
  45656. shouldStop = true;
  45657. thread.removeTimeSliceClient (this);
  45658. fileFindHandle = 0;
  45659. if (files.size() > 0)
  45660. {
  45661. files.clear();
  45662. changed();
  45663. }
  45664. }
  45665. void DirectoryContentsList::refresh()
  45666. {
  45667. clear();
  45668. if (root.isDirectory())
  45669. {
  45670. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45671. shouldStop = false;
  45672. thread.addTimeSliceClient (this);
  45673. }
  45674. }
  45675. int DirectoryContentsList::getNumFiles() const
  45676. {
  45677. return files.size();
  45678. }
  45679. bool DirectoryContentsList::getFileInfo (const int index,
  45680. FileInfo& result) const
  45681. {
  45682. const ScopedLock sl (fileListLock);
  45683. const FileInfo* const info = files [index];
  45684. if (info != 0)
  45685. {
  45686. result = *info;
  45687. return true;
  45688. }
  45689. return false;
  45690. }
  45691. const File DirectoryContentsList::getFile (const int index) const
  45692. {
  45693. const ScopedLock sl (fileListLock);
  45694. const FileInfo* const info = files [index];
  45695. if (info != 0)
  45696. return root.getChildFile (info->filename);
  45697. return File::nonexistent;
  45698. }
  45699. bool DirectoryContentsList::isStillLoading() const
  45700. {
  45701. return fileFindHandle != 0;
  45702. }
  45703. void DirectoryContentsList::changed()
  45704. {
  45705. sendChangeMessage (this);
  45706. }
  45707. bool DirectoryContentsList::useTimeSlice()
  45708. {
  45709. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45710. bool hasChanged = false;
  45711. for (int i = 100; --i >= 0;)
  45712. {
  45713. if (! checkNextFile (hasChanged))
  45714. {
  45715. if (hasChanged)
  45716. changed();
  45717. return false;
  45718. }
  45719. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45720. break;
  45721. }
  45722. if (hasChanged)
  45723. changed();
  45724. return true;
  45725. }
  45726. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45727. {
  45728. if (fileFindHandle != 0)
  45729. {
  45730. bool fileFoundIsDir, isHidden, isReadOnly;
  45731. int64 fileSize;
  45732. Time modTime, creationTime;
  45733. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45734. &modTime, &creationTime, &isReadOnly))
  45735. {
  45736. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  45737. fileSize, modTime, creationTime, isReadOnly))
  45738. {
  45739. hasChanged = true;
  45740. }
  45741. return true;
  45742. }
  45743. else
  45744. {
  45745. fileFindHandle = 0;
  45746. }
  45747. }
  45748. return false;
  45749. }
  45750. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  45751. const DirectoryContentsList::FileInfo* const second)
  45752. {
  45753. #if JUCE_WINDOWS
  45754. if (first->isDirectory != second->isDirectory)
  45755. return first->isDirectory ? -1 : 1;
  45756. #endif
  45757. return first->filename.compareIgnoreCase (second->filename);
  45758. }
  45759. bool DirectoryContentsList::addFile (const File& file,
  45760. const bool isDir,
  45761. const int64 fileSize,
  45762. const Time& modTime,
  45763. const Time& creationTime,
  45764. const bool isReadOnly)
  45765. {
  45766. if (fileFilter == 0
  45767. || ((! isDir) && fileFilter->isFileSuitable (file))
  45768. || (isDir && fileFilter->isDirectorySuitable (file)))
  45769. {
  45770. ScopedPointer <FileInfo> info (new FileInfo());
  45771. info->filename = file.getFileName();
  45772. info->fileSize = fileSize;
  45773. info->modificationTime = modTime;
  45774. info->creationTime = creationTime;
  45775. info->isDirectory = isDir;
  45776. info->isReadOnly = isReadOnly;
  45777. const ScopedLock sl (fileListLock);
  45778. for (int i = files.size(); --i >= 0;)
  45779. if (files.getUnchecked(i)->filename == info->filename)
  45780. return false;
  45781. files.addSorted (*this, info.release());
  45782. return true;
  45783. }
  45784. return false;
  45785. }
  45786. END_JUCE_NAMESPACE
  45787. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  45788. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  45789. BEGIN_JUCE_NAMESPACE
  45790. FileBrowserComponent::FileBrowserComponent (int flags_,
  45791. const File& initialFileOrDirectory,
  45792. const FileFilter* fileFilter_,
  45793. FilePreviewComponent* previewComp_)
  45794. : FileFilter (String::empty),
  45795. fileFilter (fileFilter_),
  45796. flags (flags_),
  45797. previewComp (previewComp_),
  45798. thread ("Juce FileBrowser")
  45799. {
  45800. // You need to specify one or other of the open/save flags..
  45801. jassert ((flags & (saveMode | openMode)) != 0);
  45802. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  45803. // You need to specify at least one of these flags..
  45804. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  45805. String filename;
  45806. if (initialFileOrDirectory == File::nonexistent)
  45807. {
  45808. currentRoot = File::getCurrentWorkingDirectory();
  45809. }
  45810. else if (initialFileOrDirectory.isDirectory())
  45811. {
  45812. currentRoot = initialFileOrDirectory;
  45813. }
  45814. else
  45815. {
  45816. chosenFiles.add (initialFileOrDirectory);
  45817. currentRoot = initialFileOrDirectory.getParentDirectory();
  45818. filename = initialFileOrDirectory.getFileName();
  45819. }
  45820. fileList = new DirectoryContentsList (this, thread);
  45821. if ((flags & useTreeView) != 0)
  45822. {
  45823. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  45824. if ((flags & canSelectMultipleItems) != 0)
  45825. tree->setMultiSelectEnabled (true);
  45826. addAndMakeVisible (tree);
  45827. fileListComponent = tree;
  45828. }
  45829. else
  45830. {
  45831. FileListComponent* const list = new FileListComponent (*fileList);
  45832. list->setOutlineThickness (1);
  45833. if ((flags & canSelectMultipleItems) != 0)
  45834. list->setMultipleSelectionEnabled (true);
  45835. addAndMakeVisible (list);
  45836. fileListComponent = list;
  45837. }
  45838. fileListComponent->addListener (this);
  45839. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  45840. currentPathBox->setEditableText (true);
  45841. StringArray rootNames, rootPaths;
  45842. const BigInteger separators (getRoots (rootNames, rootPaths));
  45843. for (int i = 0; i < rootNames.size(); ++i)
  45844. {
  45845. if (separators [i])
  45846. currentPathBox->addSeparator();
  45847. currentPathBox->addItem (rootNames[i], i + 1);
  45848. }
  45849. currentPathBox->addSeparator();
  45850. currentPathBox->addListener (this);
  45851. addAndMakeVisible (filenameBox = new TextEditor());
  45852. filenameBox->setMultiLine (false);
  45853. filenameBox->setSelectAllWhenFocused (true);
  45854. filenameBox->setText (filename, false);
  45855. filenameBox->addListener (this);
  45856. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  45857. Label* label = new Label ("f", TRANS("file:"));
  45858. addAndMakeVisible (label);
  45859. label->attachToComponent (filenameBox, true);
  45860. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  45861. goUpButton->addButtonListener (this);
  45862. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  45863. if (previewComp != 0)
  45864. addAndMakeVisible (previewComp);
  45865. setRoot (currentRoot);
  45866. thread.startThread (4);
  45867. }
  45868. FileBrowserComponent::~FileBrowserComponent()
  45869. {
  45870. if (previewComp != 0)
  45871. removeChildComponent (previewComp);
  45872. deleteAllChildren();
  45873. fileList = 0;
  45874. thread.stopThread (10000);
  45875. }
  45876. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  45877. {
  45878. listeners.add (newListener);
  45879. }
  45880. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  45881. {
  45882. listeners.remove (listener);
  45883. }
  45884. bool FileBrowserComponent::isSaveMode() const throw()
  45885. {
  45886. return (flags & saveMode) != 0;
  45887. }
  45888. int FileBrowserComponent::getNumSelectedFiles() const throw()
  45889. {
  45890. if (chosenFiles.size() == 0 && currentFileIsValid())
  45891. return 1;
  45892. return chosenFiles.size();
  45893. }
  45894. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  45895. {
  45896. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  45897. return currentRoot;
  45898. if (! filenameBox->isReadOnly())
  45899. return currentRoot.getChildFile (filenameBox->getText());
  45900. return chosenFiles[index];
  45901. }
  45902. bool FileBrowserComponent::currentFileIsValid() const
  45903. {
  45904. if (isSaveMode())
  45905. return ! getSelectedFile (0).isDirectory();
  45906. else
  45907. return getSelectedFile (0).exists();
  45908. }
  45909. const File FileBrowserComponent::getHighlightedFile() const throw()
  45910. {
  45911. return fileListComponent->getSelectedFile (0);
  45912. }
  45913. void FileBrowserComponent::deselectAllFiles()
  45914. {
  45915. fileListComponent->deselectAllFiles();
  45916. }
  45917. bool FileBrowserComponent::isFileSuitable (const File& file) const
  45918. {
  45919. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  45920. : false;
  45921. }
  45922. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  45923. {
  45924. return true;
  45925. }
  45926. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  45927. {
  45928. if (f.isDirectory())
  45929. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  45930. return (flags & canSelectFiles) != 0 && f.exists()
  45931. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  45932. }
  45933. const File FileBrowserComponent::getRoot() const
  45934. {
  45935. return currentRoot;
  45936. }
  45937. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  45938. {
  45939. if (currentRoot != newRootDirectory)
  45940. {
  45941. fileListComponent->scrollToTop();
  45942. String path (newRootDirectory.getFullPathName());
  45943. if (path.isEmpty())
  45944. path = File::separatorString;
  45945. StringArray rootNames, rootPaths;
  45946. getRoots (rootNames, rootPaths);
  45947. if (! rootPaths.contains (path, true))
  45948. {
  45949. bool alreadyListed = false;
  45950. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  45951. {
  45952. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  45953. {
  45954. alreadyListed = true;
  45955. break;
  45956. }
  45957. }
  45958. if (! alreadyListed)
  45959. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  45960. }
  45961. }
  45962. currentRoot = newRootDirectory;
  45963. fileList->setDirectory (currentRoot, true, true);
  45964. String currentRootName (currentRoot.getFullPathName());
  45965. if (currentRootName.isEmpty())
  45966. currentRootName = File::separatorString;
  45967. currentPathBox->setText (currentRootName, true);
  45968. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  45969. && currentRoot.getParentDirectory() != currentRoot);
  45970. }
  45971. void FileBrowserComponent::goUp()
  45972. {
  45973. setRoot (getRoot().getParentDirectory());
  45974. }
  45975. void FileBrowserComponent::refresh()
  45976. {
  45977. fileList->refresh();
  45978. }
  45979. const String FileBrowserComponent::getActionVerb() const
  45980. {
  45981. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  45982. }
  45983. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  45984. {
  45985. return previewComp;
  45986. }
  45987. void FileBrowserComponent::resized()
  45988. {
  45989. getLookAndFeel()
  45990. .layoutFileBrowserComponent (*this, fileListComponent,
  45991. previewComp, currentPathBox,
  45992. filenameBox, goUpButton);
  45993. }
  45994. void FileBrowserComponent::sendListenerChangeMessage()
  45995. {
  45996. Component::BailOutChecker checker (this);
  45997. if (previewComp != 0)
  45998. previewComp->selectedFileChanged (getSelectedFile (0));
  45999. // You shouldn't delete the browser when the file gets changed!
  46000. jassert (! checker.shouldBailOut());
  46001. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46002. }
  46003. void FileBrowserComponent::selectionChanged()
  46004. {
  46005. StringArray newFilenames;
  46006. bool resetChosenFiles = true;
  46007. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46008. {
  46009. const File f (fileListComponent->getSelectedFile (i));
  46010. if (isFileOrDirSuitable (f))
  46011. {
  46012. if (resetChosenFiles)
  46013. {
  46014. chosenFiles.clear();
  46015. resetChosenFiles = false;
  46016. }
  46017. chosenFiles.add (f);
  46018. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46019. }
  46020. }
  46021. if (newFilenames.size() > 0)
  46022. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46023. sendListenerChangeMessage();
  46024. }
  46025. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46026. {
  46027. Component::BailOutChecker checker (this);
  46028. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46029. }
  46030. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46031. {
  46032. if (f.isDirectory())
  46033. {
  46034. setRoot (f);
  46035. if ((flags & canSelectDirectories) != 0)
  46036. filenameBox->setText (String::empty);
  46037. }
  46038. else
  46039. {
  46040. Component::BailOutChecker checker (this);
  46041. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46042. }
  46043. }
  46044. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46045. {
  46046. (void) key;
  46047. #if JUCE_LINUX || JUCE_WINDOWS
  46048. if (key.getModifiers().isCommandDown()
  46049. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46050. {
  46051. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46052. fileList->refresh();
  46053. return true;
  46054. }
  46055. #endif
  46056. return false;
  46057. }
  46058. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46059. {
  46060. sendListenerChangeMessage();
  46061. }
  46062. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46063. {
  46064. if (filenameBox->getText().containsChar (File::separator))
  46065. {
  46066. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46067. if (f.isDirectory())
  46068. {
  46069. setRoot (f);
  46070. chosenFiles.clear();
  46071. filenameBox->setText (String::empty);
  46072. }
  46073. else
  46074. {
  46075. setRoot (f.getParentDirectory());
  46076. chosenFiles.clear();
  46077. chosenFiles.add (f);
  46078. filenameBox->setText (f.getFileName());
  46079. }
  46080. }
  46081. else
  46082. {
  46083. fileDoubleClicked (getSelectedFile (0));
  46084. }
  46085. }
  46086. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46087. {
  46088. }
  46089. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46090. {
  46091. if (! isSaveMode())
  46092. selectionChanged();
  46093. }
  46094. void FileBrowserComponent::buttonClicked (Button*)
  46095. {
  46096. goUp();
  46097. }
  46098. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46099. {
  46100. const String newText (currentPathBox->getText().trim().unquoted());
  46101. if (newText.isNotEmpty())
  46102. {
  46103. const int index = currentPathBox->getSelectedId() - 1;
  46104. StringArray rootNames, rootPaths;
  46105. getRoots (rootNames, rootPaths);
  46106. if (rootPaths [index].isNotEmpty())
  46107. {
  46108. setRoot (File (rootPaths [index]));
  46109. }
  46110. else
  46111. {
  46112. File f (newText);
  46113. for (;;)
  46114. {
  46115. if (f.isDirectory())
  46116. {
  46117. setRoot (f);
  46118. break;
  46119. }
  46120. if (f.getParentDirectory() == f)
  46121. break;
  46122. f = f.getParentDirectory();
  46123. }
  46124. }
  46125. }
  46126. }
  46127. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46128. {
  46129. BigInteger separators;
  46130. #if JUCE_WINDOWS
  46131. Array<File> roots;
  46132. File::findFileSystemRoots (roots);
  46133. rootPaths.clear();
  46134. for (int i = 0; i < roots.size(); ++i)
  46135. {
  46136. const File& drive = roots.getReference(i);
  46137. String name (drive.getFullPathName());
  46138. rootPaths.add (name);
  46139. if (drive.isOnHardDisk())
  46140. {
  46141. String volume (drive.getVolumeLabel());
  46142. if (volume.isEmpty())
  46143. volume = TRANS("Hard Drive");
  46144. name << " [" << drive.getVolumeLabel() << ']';
  46145. }
  46146. else if (drive.isOnCDRomDrive())
  46147. {
  46148. name << TRANS(" [CD/DVD drive]");
  46149. }
  46150. rootNames.add (name);
  46151. }
  46152. separators.setBit (rootPaths.size());
  46153. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46154. rootNames.add ("Documents");
  46155. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46156. rootNames.add ("Desktop");
  46157. #endif
  46158. #if JUCE_MAC
  46159. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46160. rootNames.add ("Home folder");
  46161. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46162. rootNames.add ("Documents");
  46163. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46164. rootNames.add ("Desktop");
  46165. separators.setBit (rootPaths.size());
  46166. Array <File> volumes;
  46167. File vol ("/Volumes");
  46168. vol.findChildFiles (volumes, File::findDirectories, false);
  46169. for (int i = 0; i < volumes.size(); ++i)
  46170. {
  46171. const File& volume = volumes.getReference(i);
  46172. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46173. {
  46174. rootPaths.add (volume.getFullPathName());
  46175. rootNames.add (volume.getFileName());
  46176. }
  46177. }
  46178. #endif
  46179. #if JUCE_LINUX
  46180. rootPaths.add ("/");
  46181. rootNames.add ("/");
  46182. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46183. rootNames.add ("Home folder");
  46184. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46185. rootNames.add ("Desktop");
  46186. #endif
  46187. return separators;
  46188. }
  46189. END_JUCE_NAMESPACE
  46190. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46191. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46192. BEGIN_JUCE_NAMESPACE
  46193. FileChooser::FileChooser (const String& chooserBoxTitle,
  46194. const File& currentFileOrDirectory,
  46195. const String& fileFilters,
  46196. const bool useNativeDialogBox_)
  46197. : title (chooserBoxTitle),
  46198. filters (fileFilters),
  46199. startingFile (currentFileOrDirectory),
  46200. useNativeDialogBox (useNativeDialogBox_)
  46201. {
  46202. #if JUCE_LINUX
  46203. useNativeDialogBox = false;
  46204. #endif
  46205. if (! fileFilters.containsNonWhitespaceChars())
  46206. filters = "*";
  46207. }
  46208. FileChooser::~FileChooser()
  46209. {
  46210. }
  46211. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46212. {
  46213. return showDialog (false, true, false, false, false, previewComponent);
  46214. }
  46215. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46216. {
  46217. return showDialog (false, true, false, false, true, previewComponent);
  46218. }
  46219. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46220. {
  46221. return showDialog (true, true, false, false, true, previewComponent);
  46222. }
  46223. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46224. {
  46225. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46226. }
  46227. bool FileChooser::browseForDirectory()
  46228. {
  46229. return showDialog (true, false, false, false, false, 0);
  46230. }
  46231. const File FileChooser::getResult() const
  46232. {
  46233. // if you've used a multiple-file select, you should use the getResults() method
  46234. // to retrieve all the files that were chosen.
  46235. jassert (results.size() <= 1);
  46236. return results.getFirst();
  46237. }
  46238. const Array<File>& FileChooser::getResults() const
  46239. {
  46240. return results;
  46241. }
  46242. bool FileChooser::showDialog (const bool selectsDirectories,
  46243. const bool selectsFiles,
  46244. const bool isSave,
  46245. const bool warnAboutOverwritingExistingFiles,
  46246. const bool selectMultipleFiles,
  46247. FilePreviewComponent* const previewComponent)
  46248. {
  46249. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46250. results.clear();
  46251. // the preview component needs to be the right size before you pass it in here..
  46252. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46253. && previewComponent->getHeight() > 10));
  46254. #if JUCE_WINDOWS
  46255. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46256. #elif JUCE_MAC
  46257. if (useNativeDialogBox && (previewComponent == 0))
  46258. #else
  46259. if (false)
  46260. #endif
  46261. {
  46262. showPlatformDialog (results, title, startingFile, filters,
  46263. selectsDirectories, selectsFiles, isSave,
  46264. warnAboutOverwritingExistingFiles,
  46265. selectMultipleFiles,
  46266. previewComponent);
  46267. }
  46268. else
  46269. {
  46270. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46271. selectsDirectories ? "*" : String::empty,
  46272. String::empty);
  46273. int flags = isSave ? FileBrowserComponent::saveMode
  46274. : FileBrowserComponent::openMode;
  46275. if (selectsFiles)
  46276. flags |= FileBrowserComponent::canSelectFiles;
  46277. if (selectsDirectories)
  46278. {
  46279. flags |= FileBrowserComponent::canSelectDirectories;
  46280. if (! isSave)
  46281. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46282. }
  46283. if (selectMultipleFiles)
  46284. flags |= FileBrowserComponent::canSelectMultipleItems;
  46285. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46286. FileChooserDialogBox box (title, String::empty,
  46287. browserComponent,
  46288. warnAboutOverwritingExistingFiles,
  46289. browserComponent.findColour (AlertWindow::backgroundColourId));
  46290. if (box.show())
  46291. {
  46292. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46293. results.add (browserComponent.getSelectedFile (i));
  46294. }
  46295. }
  46296. if (previouslyFocused != 0)
  46297. previouslyFocused->grabKeyboardFocus();
  46298. return results.size() > 0;
  46299. }
  46300. FilePreviewComponent::FilePreviewComponent()
  46301. {
  46302. }
  46303. FilePreviewComponent::~FilePreviewComponent()
  46304. {
  46305. }
  46306. END_JUCE_NAMESPACE
  46307. /*** End of inlined file: juce_FileChooser.cpp ***/
  46308. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46309. BEGIN_JUCE_NAMESPACE
  46310. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46311. const String& instructions,
  46312. FileBrowserComponent& chooserComponent,
  46313. const bool warnAboutOverwritingExistingFiles_,
  46314. const Colour& backgroundColour)
  46315. : ResizableWindow (name, backgroundColour, true),
  46316. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46317. {
  46318. content = new ContentComponent();
  46319. content->setName (name);
  46320. content->instructions = instructions;
  46321. content->chooserComponent = &chooserComponent;
  46322. content->addAndMakeVisible (&chooserComponent);
  46323. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46324. content->addAndMakeVisible (content->okButton);
  46325. content->okButton->addButtonListener (this);
  46326. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46327. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46328. content->cancelButton = new TextButton (TRANS("Cancel"));
  46329. content->addAndMakeVisible (content->cancelButton);
  46330. content->cancelButton->addButtonListener (this);
  46331. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46332. setContentComponent (content);
  46333. setResizable (true, true);
  46334. setResizeLimits (300, 300, 1200, 1000);
  46335. content->chooserComponent->addListener (this);
  46336. }
  46337. FileChooserDialogBox::~FileChooserDialogBox()
  46338. {
  46339. content->chooserComponent->removeListener (this);
  46340. }
  46341. bool FileChooserDialogBox::show (int w, int h)
  46342. {
  46343. if (w <= 0)
  46344. {
  46345. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46346. if (previewComp != 0)
  46347. w = 400 + previewComp->getWidth();
  46348. else
  46349. w = 600;
  46350. }
  46351. if (h <= 0)
  46352. h = 500;
  46353. centreWithSize (w, h);
  46354. const bool ok = (runModalLoop() != 0);
  46355. setVisible (false);
  46356. return ok;
  46357. }
  46358. void FileChooserDialogBox::buttonClicked (Button* button)
  46359. {
  46360. if (button == content->okButton)
  46361. {
  46362. if (warnAboutOverwritingExistingFiles
  46363. && content->chooserComponent->isSaveMode()
  46364. && content->chooserComponent->getSelectedFile(0).exists())
  46365. {
  46366. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46367. TRANS("File already exists"),
  46368. TRANS("There's already a file called:")
  46369. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46370. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46371. TRANS("overwrite"),
  46372. TRANS("cancel")))
  46373. {
  46374. return;
  46375. }
  46376. }
  46377. exitModalState (1);
  46378. }
  46379. else if (button == content->cancelButton)
  46380. closeButtonPressed();
  46381. }
  46382. void FileChooserDialogBox::closeButtonPressed()
  46383. {
  46384. setVisible (false);
  46385. }
  46386. void FileChooserDialogBox::selectionChanged()
  46387. {
  46388. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46389. }
  46390. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46391. {
  46392. }
  46393. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46394. {
  46395. selectionChanged();
  46396. content->okButton->triggerClick();
  46397. }
  46398. FileChooserDialogBox::ContentComponent::ContentComponent()
  46399. {
  46400. setInterceptsMouseClicks (false, true);
  46401. }
  46402. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46403. {
  46404. delete okButton;
  46405. delete cancelButton;
  46406. }
  46407. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46408. {
  46409. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46410. text.draw (g);
  46411. }
  46412. void FileChooserDialogBox::ContentComponent::resized()
  46413. {
  46414. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46415. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46416. const int y = roundToInt (bb.getBottom()) + 10;
  46417. const int buttonHeight = 26;
  46418. const int buttonY = getHeight() - buttonHeight - 8;
  46419. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46420. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46421. proportionOfWidth (0.2f), buttonHeight);
  46422. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46423. proportionOfWidth (0.2f), buttonHeight);
  46424. }
  46425. END_JUCE_NAMESPACE
  46426. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46427. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46428. BEGIN_JUCE_NAMESPACE
  46429. FileFilter::FileFilter (const String& filterDescription)
  46430. : description (filterDescription)
  46431. {
  46432. }
  46433. FileFilter::~FileFilter()
  46434. {
  46435. }
  46436. const String& FileFilter::getDescription() const throw()
  46437. {
  46438. return description;
  46439. }
  46440. END_JUCE_NAMESPACE
  46441. /*** End of inlined file: juce_FileFilter.cpp ***/
  46442. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46443. BEGIN_JUCE_NAMESPACE
  46444. Image* juce_createIconForFile (const File& file);
  46445. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46446. : ListBox (String::empty, 0),
  46447. DirectoryContentsDisplayComponent (listToShow)
  46448. {
  46449. setModel (this);
  46450. fileList.addChangeListener (this);
  46451. }
  46452. FileListComponent::~FileListComponent()
  46453. {
  46454. fileList.removeChangeListener (this);
  46455. deleteAllChildren();
  46456. }
  46457. int FileListComponent::getNumSelectedFiles() const
  46458. {
  46459. return getNumSelectedRows();
  46460. }
  46461. const File FileListComponent::getSelectedFile (int index) const
  46462. {
  46463. return fileList.getFile (getSelectedRow (index));
  46464. }
  46465. void FileListComponent::deselectAllFiles()
  46466. {
  46467. deselectAllRows();
  46468. }
  46469. void FileListComponent::scrollToTop()
  46470. {
  46471. getVerticalScrollBar()->setCurrentRangeStart (0);
  46472. }
  46473. void FileListComponent::changeListenerCallback (void*)
  46474. {
  46475. updateContent();
  46476. if (lastDirectory != fileList.getDirectory())
  46477. {
  46478. lastDirectory = fileList.getDirectory();
  46479. deselectAllRows();
  46480. }
  46481. }
  46482. class FileListItemComponent : public Component,
  46483. public TimeSliceClient,
  46484. public AsyncUpdater
  46485. {
  46486. public:
  46487. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46488. : owner (owner_), thread (thread_),
  46489. highlighted (false), index (0), icon (0)
  46490. {
  46491. }
  46492. ~FileListItemComponent()
  46493. {
  46494. thread.removeTimeSliceClient (this);
  46495. clearIcon();
  46496. }
  46497. void paint (Graphics& g)
  46498. {
  46499. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46500. file.getFileName(),
  46501. icon,
  46502. fileSize, modTime,
  46503. isDirectory, highlighted,
  46504. index);
  46505. }
  46506. void mouseDown (const MouseEvent& e)
  46507. {
  46508. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46509. owner.sendMouseClickMessage (file, e);
  46510. }
  46511. void mouseDoubleClick (const MouseEvent&)
  46512. {
  46513. owner.sendDoubleClickMessage (file);
  46514. }
  46515. void update (const File& root,
  46516. const DirectoryContentsList::FileInfo* const fileInfo,
  46517. const int index_,
  46518. const bool highlighted_)
  46519. {
  46520. thread.removeTimeSliceClient (this);
  46521. if (highlighted_ != highlighted
  46522. || index_ != index)
  46523. {
  46524. index = index_;
  46525. highlighted = highlighted_;
  46526. repaint();
  46527. }
  46528. File newFile;
  46529. String newFileSize;
  46530. String newModTime;
  46531. if (fileInfo != 0)
  46532. {
  46533. newFile = root.getChildFile (fileInfo->filename);
  46534. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46535. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46536. }
  46537. if (newFile != file
  46538. || fileSize != newFileSize
  46539. || modTime != newModTime)
  46540. {
  46541. file = newFile;
  46542. fileSize = newFileSize;
  46543. modTime = newModTime;
  46544. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46545. repaint();
  46546. clearIcon();
  46547. }
  46548. if (file != File::nonexistent
  46549. && icon == 0 && ! isDirectory)
  46550. {
  46551. updateIcon (true);
  46552. if (icon == 0)
  46553. thread.addTimeSliceClient (this);
  46554. }
  46555. }
  46556. bool useTimeSlice()
  46557. {
  46558. updateIcon (false);
  46559. return false;
  46560. }
  46561. void handleAsyncUpdate()
  46562. {
  46563. repaint();
  46564. }
  46565. juce_UseDebuggingNewOperator
  46566. private:
  46567. FileListComponent& owner;
  46568. TimeSliceThread& thread;
  46569. bool highlighted;
  46570. int index;
  46571. File file;
  46572. String fileSize;
  46573. String modTime;
  46574. Image* icon;
  46575. bool isDirectory;
  46576. void clearIcon()
  46577. {
  46578. ImageCache::release (icon);
  46579. icon = 0;
  46580. }
  46581. void updateIcon (const bool onlyUpdateIfCached)
  46582. {
  46583. if (icon == 0)
  46584. {
  46585. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46586. Image* im = ImageCache::getFromHashCode (hashCode);
  46587. if (im == 0 && ! onlyUpdateIfCached)
  46588. {
  46589. im = juce_createIconForFile (file);
  46590. if (im != 0)
  46591. ImageCache::addImageToCache (im, hashCode);
  46592. }
  46593. if (im != 0)
  46594. {
  46595. icon = im;
  46596. triggerAsyncUpdate();
  46597. }
  46598. }
  46599. }
  46600. };
  46601. int FileListComponent::getNumRows()
  46602. {
  46603. return fileList.getNumFiles();
  46604. }
  46605. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46606. {
  46607. }
  46608. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46609. {
  46610. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46611. if (comp == 0)
  46612. {
  46613. delete existingComponentToUpdate;
  46614. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46615. }
  46616. DirectoryContentsList::FileInfo fileInfo;
  46617. if (fileList.getFileInfo (row, fileInfo))
  46618. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46619. else
  46620. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46621. return comp;
  46622. }
  46623. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46624. {
  46625. sendSelectionChangeMessage();
  46626. }
  46627. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46628. {
  46629. }
  46630. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46631. {
  46632. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46633. }
  46634. END_JUCE_NAMESPACE
  46635. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46636. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46637. BEGIN_JUCE_NAMESPACE
  46638. FilenameComponent::FilenameComponent (const String& name,
  46639. const File& currentFile,
  46640. const bool canEditFilename,
  46641. const bool isDirectory,
  46642. const bool isForSaving,
  46643. const String& fileBrowserWildcard,
  46644. const String& enforcedSuffix_,
  46645. const String& textWhenNothingSelected)
  46646. : Component (name),
  46647. maxRecentFiles (30),
  46648. isDir (isDirectory),
  46649. isSaving (isForSaving),
  46650. isFileDragOver (false),
  46651. wildcard (fileBrowserWildcard),
  46652. enforcedSuffix (enforcedSuffix_)
  46653. {
  46654. addAndMakeVisible (filenameBox = new ComboBox ("fn"));
  46655. filenameBox->setEditableText (canEditFilename);
  46656. filenameBox->addListener (this);
  46657. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  46658. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46659. browseButton = 0;
  46660. setBrowseButtonText ("...");
  46661. setCurrentFile (currentFile, true);
  46662. }
  46663. FilenameComponent::~FilenameComponent()
  46664. {
  46665. deleteAllChildren();
  46666. }
  46667. void FilenameComponent::paintOverChildren (Graphics& g)
  46668. {
  46669. if (isFileDragOver)
  46670. {
  46671. g.setColour (Colours::red.withAlpha (0.2f));
  46672. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46673. }
  46674. }
  46675. void FilenameComponent::resized()
  46676. {
  46677. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  46678. }
  46679. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46680. {
  46681. browseButtonText = newBrowseButtonText;
  46682. lookAndFeelChanged();
  46683. }
  46684. void FilenameComponent::lookAndFeelChanged()
  46685. {
  46686. deleteAndZero (browseButton);
  46687. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46688. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46689. resized();
  46690. browseButton->addButtonListener (this);
  46691. }
  46692. void FilenameComponent::setTooltip (const String& newTooltip)
  46693. {
  46694. SettableTooltipClient::setTooltip (newTooltip);
  46695. filenameBox->setTooltip (newTooltip);
  46696. }
  46697. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46698. {
  46699. defaultBrowseFile = newDefaultDirectory;
  46700. }
  46701. void FilenameComponent::buttonClicked (Button*)
  46702. {
  46703. FileChooser fc (TRANS("Choose a new file"),
  46704. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46705. : getCurrentFile(),
  46706. wildcard);
  46707. if (isDir ? fc.browseForDirectory()
  46708. : (isSaving ? fc.browseForFileToSave (false)
  46709. : fc.browseForFileToOpen()))
  46710. {
  46711. setCurrentFile (fc.getResult(), true);
  46712. }
  46713. }
  46714. void FilenameComponent::comboBoxChanged (ComboBox*)
  46715. {
  46716. setCurrentFile (getCurrentFile(), true);
  46717. }
  46718. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46719. {
  46720. return true;
  46721. }
  46722. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46723. {
  46724. isFileDragOver = false;
  46725. repaint();
  46726. const File f (filenames[0]);
  46727. if (f.exists() && (f.isDirectory() == isDir))
  46728. setCurrentFile (f, true);
  46729. }
  46730. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46731. {
  46732. isFileDragOver = true;
  46733. repaint();
  46734. }
  46735. void FilenameComponent::fileDragExit (const StringArray&)
  46736. {
  46737. isFileDragOver = false;
  46738. repaint();
  46739. }
  46740. const File FilenameComponent::getCurrentFile() const
  46741. {
  46742. File f (filenameBox->getText());
  46743. if (enforcedSuffix.isNotEmpty())
  46744. f = f.withFileExtension (enforcedSuffix);
  46745. return f;
  46746. }
  46747. void FilenameComponent::setCurrentFile (File newFile,
  46748. const bool addToRecentlyUsedList,
  46749. const bool sendChangeNotification)
  46750. {
  46751. if (enforcedSuffix.isNotEmpty())
  46752. newFile = newFile.withFileExtension (enforcedSuffix);
  46753. if (newFile.getFullPathName() != lastFilename)
  46754. {
  46755. lastFilename = newFile.getFullPathName();
  46756. if (addToRecentlyUsedList)
  46757. addRecentlyUsedFile (newFile);
  46758. filenameBox->setText (lastFilename, true);
  46759. if (sendChangeNotification)
  46760. triggerAsyncUpdate();
  46761. }
  46762. }
  46763. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  46764. {
  46765. filenameBox->setEditableText (shouldBeEditable);
  46766. }
  46767. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  46768. {
  46769. StringArray names;
  46770. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  46771. names.add (filenameBox->getItemText (i));
  46772. return names;
  46773. }
  46774. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  46775. {
  46776. if (filenames != getRecentlyUsedFilenames())
  46777. {
  46778. filenameBox->clear();
  46779. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  46780. filenameBox->addItem (filenames[i], i + 1);
  46781. }
  46782. }
  46783. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  46784. {
  46785. maxRecentFiles = jmax (1, newMaximum);
  46786. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  46787. }
  46788. void FilenameComponent::addRecentlyUsedFile (const File& file)
  46789. {
  46790. StringArray files (getRecentlyUsedFilenames());
  46791. if (file.getFullPathName().isNotEmpty())
  46792. {
  46793. files.removeString (file.getFullPathName(), true);
  46794. files.insert (0, file.getFullPathName());
  46795. setRecentlyUsedFilenames (files);
  46796. }
  46797. }
  46798. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  46799. {
  46800. listeners.add (listener);
  46801. }
  46802. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  46803. {
  46804. listeners.remove (listener);
  46805. }
  46806. void FilenameComponent::handleAsyncUpdate()
  46807. {
  46808. Component::BailOutChecker checker (this);
  46809. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  46810. }
  46811. END_JUCE_NAMESPACE
  46812. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  46813. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  46814. BEGIN_JUCE_NAMESPACE
  46815. FileSearchPathListComponent::FileSearchPathListComponent()
  46816. {
  46817. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  46818. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  46819. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  46820. listBox->setOutlineThickness (1);
  46821. addAndMakeVisible (addButton = new TextButton ("+"));
  46822. addButton->addButtonListener (this);
  46823. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46824. addAndMakeVisible (removeButton = new TextButton ("-"));
  46825. removeButton->addButtonListener (this);
  46826. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46827. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  46828. changeButton->addButtonListener (this);
  46829. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46830. upButton->addButtonListener (this);
  46831. {
  46832. Path arrowPath;
  46833. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  46834. DrawablePath arrowImage;
  46835. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46836. arrowImage.setPath (arrowPath);
  46837. upButton->setImages (&arrowImage);
  46838. }
  46839. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46840. downButton->addButtonListener (this);
  46841. {
  46842. Path arrowPath;
  46843. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  46844. DrawablePath arrowImage;
  46845. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46846. arrowImage.setPath (arrowPath);
  46847. downButton->setImages (&arrowImage);
  46848. }
  46849. updateButtons();
  46850. }
  46851. FileSearchPathListComponent::~FileSearchPathListComponent()
  46852. {
  46853. deleteAllChildren();
  46854. }
  46855. void FileSearchPathListComponent::updateButtons()
  46856. {
  46857. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  46858. removeButton->setEnabled (anythingSelected);
  46859. changeButton->setEnabled (anythingSelected);
  46860. upButton->setEnabled (anythingSelected);
  46861. downButton->setEnabled (anythingSelected);
  46862. }
  46863. void FileSearchPathListComponent::changed()
  46864. {
  46865. listBox->updateContent();
  46866. listBox->repaint();
  46867. updateButtons();
  46868. }
  46869. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  46870. {
  46871. if (newPath.toString() != path.toString())
  46872. {
  46873. path = newPath;
  46874. changed();
  46875. }
  46876. }
  46877. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46878. {
  46879. defaultBrowseTarget = newDefaultDirectory;
  46880. }
  46881. int FileSearchPathListComponent::getNumRows()
  46882. {
  46883. return path.getNumPaths();
  46884. }
  46885. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  46886. {
  46887. if (rowIsSelected)
  46888. g.fillAll (findColour (TextEditor::highlightColourId));
  46889. g.setColour (findColour (ListBox::textColourId));
  46890. Font f (height * 0.7f);
  46891. f.setHorizontalScale (0.9f);
  46892. g.setFont (f);
  46893. g.drawText (path [rowNumber].getFullPathName(),
  46894. 4, 0, width - 6, height,
  46895. Justification::centredLeft, true);
  46896. }
  46897. void FileSearchPathListComponent::deleteKeyPressed (int row)
  46898. {
  46899. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  46900. {
  46901. path.remove (row);
  46902. changed();
  46903. }
  46904. }
  46905. void FileSearchPathListComponent::returnKeyPressed (int row)
  46906. {
  46907. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  46908. if (chooser.browseForDirectory())
  46909. {
  46910. path.remove (row);
  46911. path.add (chooser.getResult(), row);
  46912. changed();
  46913. }
  46914. }
  46915. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  46916. {
  46917. returnKeyPressed (row);
  46918. }
  46919. void FileSearchPathListComponent::selectedRowsChanged (int)
  46920. {
  46921. updateButtons();
  46922. }
  46923. void FileSearchPathListComponent::paint (Graphics& g)
  46924. {
  46925. g.fillAll (findColour (backgroundColourId));
  46926. }
  46927. void FileSearchPathListComponent::resized()
  46928. {
  46929. const int buttonH = 22;
  46930. const int buttonY = getHeight() - buttonH - 4;
  46931. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  46932. addButton->setBounds (2, buttonY, buttonH, buttonH);
  46933. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  46934. changeButton->changeWidthToFitText (buttonH);
  46935. downButton->setSize (buttonH * 2, buttonH);
  46936. upButton->setSize (buttonH * 2, buttonH);
  46937. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  46938. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  46939. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  46940. }
  46941. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  46942. {
  46943. return true;
  46944. }
  46945. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  46946. {
  46947. for (int i = filenames.size(); --i >= 0;)
  46948. {
  46949. const File f (filenames[i]);
  46950. if (f.isDirectory())
  46951. {
  46952. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  46953. path.add (f, row);
  46954. changed();
  46955. }
  46956. }
  46957. }
  46958. void FileSearchPathListComponent::buttonClicked (Button* button)
  46959. {
  46960. const int currentRow = listBox->getSelectedRow();
  46961. if (button == removeButton)
  46962. {
  46963. deleteKeyPressed (currentRow);
  46964. }
  46965. else if (button == addButton)
  46966. {
  46967. File start (defaultBrowseTarget);
  46968. if (start == File::nonexistent)
  46969. start = path [0];
  46970. if (start == File::nonexistent)
  46971. start = File::getCurrentWorkingDirectory();
  46972. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  46973. if (chooser.browseForDirectory())
  46974. {
  46975. path.add (chooser.getResult(), currentRow);
  46976. }
  46977. }
  46978. else if (button == changeButton)
  46979. {
  46980. returnKeyPressed (currentRow);
  46981. }
  46982. else if (button == upButton)
  46983. {
  46984. if (currentRow > 0 && currentRow < path.getNumPaths())
  46985. {
  46986. const File f (path[currentRow]);
  46987. path.remove (currentRow);
  46988. path.add (f, currentRow - 1);
  46989. listBox->selectRow (currentRow - 1);
  46990. }
  46991. }
  46992. else if (button == downButton)
  46993. {
  46994. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  46995. {
  46996. const File f (path[currentRow]);
  46997. path.remove (currentRow);
  46998. path.add (f, currentRow + 1);
  46999. listBox->selectRow (currentRow + 1);
  47000. }
  47001. }
  47002. changed();
  47003. }
  47004. END_JUCE_NAMESPACE
  47005. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47006. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47007. BEGIN_JUCE_NAMESPACE
  47008. Image* juce_createIconForFile (const File& file);
  47009. class FileListTreeItem : public TreeViewItem,
  47010. public TimeSliceClient,
  47011. public AsyncUpdater,
  47012. public ChangeListener
  47013. {
  47014. public:
  47015. FileListTreeItem (FileTreeComponent& owner_,
  47016. DirectoryContentsList* const parentContentsList_,
  47017. const int indexInContentsList_,
  47018. const File& file_,
  47019. TimeSliceThread& thread_)
  47020. : file (file_),
  47021. owner (owner_),
  47022. parentContentsList (parentContentsList_),
  47023. indexInContentsList (indexInContentsList_),
  47024. subContentsList (0),
  47025. canDeleteSubContentsList (false),
  47026. thread (thread_),
  47027. icon (0)
  47028. {
  47029. DirectoryContentsList::FileInfo fileInfo;
  47030. if (parentContentsList_ != 0
  47031. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47032. {
  47033. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47034. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47035. isDirectory = fileInfo.isDirectory;
  47036. }
  47037. else
  47038. {
  47039. isDirectory = true;
  47040. }
  47041. }
  47042. ~FileListTreeItem()
  47043. {
  47044. thread.removeTimeSliceClient (this);
  47045. clearSubItems();
  47046. ImageCache::release (icon);
  47047. if (canDeleteSubContentsList)
  47048. delete subContentsList;
  47049. }
  47050. bool mightContainSubItems() { return isDirectory; }
  47051. const String getUniqueName() const { return file.getFullPathName(); }
  47052. int getItemHeight() const { return 22; }
  47053. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47054. void itemOpennessChanged (bool isNowOpen)
  47055. {
  47056. if (isNowOpen)
  47057. {
  47058. clearSubItems();
  47059. isDirectory = file.isDirectory();
  47060. if (isDirectory)
  47061. {
  47062. if (subContentsList == 0)
  47063. {
  47064. jassert (parentContentsList != 0);
  47065. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47066. l->setDirectory (file, true, true);
  47067. setSubContentsList (l);
  47068. canDeleteSubContentsList = true;
  47069. }
  47070. changeListenerCallback (0);
  47071. }
  47072. }
  47073. }
  47074. void setSubContentsList (DirectoryContentsList* newList)
  47075. {
  47076. jassert (subContentsList == 0);
  47077. subContentsList = newList;
  47078. newList->addChangeListener (this);
  47079. }
  47080. void changeListenerCallback (void*)
  47081. {
  47082. clearSubItems();
  47083. if (isOpen() && subContentsList != 0)
  47084. {
  47085. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47086. {
  47087. FileListTreeItem* const item
  47088. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47089. addSubItem (item);
  47090. }
  47091. }
  47092. }
  47093. void paintItem (Graphics& g, int width, int height)
  47094. {
  47095. if (file != File::nonexistent)
  47096. {
  47097. updateIcon (true);
  47098. if (icon == 0)
  47099. thread.addTimeSliceClient (this);
  47100. }
  47101. owner.getLookAndFeel()
  47102. .drawFileBrowserRow (g, width, height,
  47103. file.getFileName(),
  47104. icon,
  47105. fileSize, modTime,
  47106. isDirectory, isSelected(),
  47107. indexInContentsList);
  47108. }
  47109. void itemClicked (const MouseEvent& e)
  47110. {
  47111. owner.sendMouseClickMessage (file, e);
  47112. }
  47113. void itemDoubleClicked (const MouseEvent& e)
  47114. {
  47115. TreeViewItem::itemDoubleClicked (e);
  47116. owner.sendDoubleClickMessage (file);
  47117. }
  47118. void itemSelectionChanged (bool)
  47119. {
  47120. owner.sendSelectionChangeMessage();
  47121. }
  47122. bool useTimeSlice()
  47123. {
  47124. updateIcon (false);
  47125. thread.removeTimeSliceClient (this);
  47126. return false;
  47127. }
  47128. void handleAsyncUpdate()
  47129. {
  47130. owner.repaint();
  47131. }
  47132. const File file;
  47133. juce_UseDebuggingNewOperator
  47134. private:
  47135. FileTreeComponent& owner;
  47136. DirectoryContentsList* parentContentsList;
  47137. int indexInContentsList;
  47138. DirectoryContentsList* subContentsList;
  47139. bool isDirectory, canDeleteSubContentsList;
  47140. TimeSliceThread& thread;
  47141. Image* icon;
  47142. String fileSize;
  47143. String modTime;
  47144. void updateIcon (const bool onlyUpdateIfCached)
  47145. {
  47146. if (icon == 0)
  47147. {
  47148. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47149. Image* im = ImageCache::getFromHashCode (hashCode);
  47150. if (im == 0 && ! onlyUpdateIfCached)
  47151. {
  47152. im = juce_createIconForFile (file);
  47153. if (im != 0)
  47154. ImageCache::addImageToCache (im, hashCode);
  47155. }
  47156. if (im != 0)
  47157. {
  47158. icon = im;
  47159. triggerAsyncUpdate();
  47160. }
  47161. }
  47162. }
  47163. };
  47164. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47165. : DirectoryContentsDisplayComponent (listToShow)
  47166. {
  47167. FileListTreeItem* const root
  47168. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47169. listToShow.getTimeSliceThread());
  47170. root->setSubContentsList (&listToShow);
  47171. setRootItemVisible (false);
  47172. setRootItem (root);
  47173. }
  47174. FileTreeComponent::~FileTreeComponent()
  47175. {
  47176. deleteRootItem();
  47177. }
  47178. const File FileTreeComponent::getSelectedFile (const int index) const
  47179. {
  47180. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47181. return item != 0 ? item->file
  47182. : File::nonexistent;
  47183. }
  47184. void FileTreeComponent::deselectAllFiles()
  47185. {
  47186. clearSelectedItems();
  47187. }
  47188. void FileTreeComponent::scrollToTop()
  47189. {
  47190. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47191. }
  47192. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47193. {
  47194. dragAndDropDescription = description;
  47195. }
  47196. END_JUCE_NAMESPACE
  47197. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47198. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47199. BEGIN_JUCE_NAMESPACE
  47200. ImagePreviewComponent::ImagePreviewComponent()
  47201. {
  47202. }
  47203. ImagePreviewComponent::~ImagePreviewComponent()
  47204. {
  47205. }
  47206. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47207. {
  47208. const int availableW = proportionOfWidth (0.97f);
  47209. const int availableH = getHeight() - 13 * 4;
  47210. const double scale = jmin (1.0,
  47211. availableW / (double) w,
  47212. availableH / (double) h);
  47213. w = roundToInt (scale * w);
  47214. h = roundToInt (scale * h);
  47215. }
  47216. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47217. {
  47218. if (fileToLoad != file)
  47219. {
  47220. fileToLoad = file;
  47221. startTimer (100);
  47222. }
  47223. }
  47224. void ImagePreviewComponent::timerCallback()
  47225. {
  47226. stopTimer();
  47227. currentThumbnail = 0;
  47228. currentDetails = String::empty;
  47229. repaint();
  47230. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47231. if (in != 0)
  47232. {
  47233. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47234. if (format != 0)
  47235. {
  47236. currentThumbnail = format->decodeImage (*in);
  47237. if (currentThumbnail != 0)
  47238. {
  47239. int w = currentThumbnail->getWidth();
  47240. int h = currentThumbnail->getHeight();
  47241. currentDetails
  47242. << fileToLoad.getFileName() << "\n"
  47243. << format->getFormatName() << "\n"
  47244. << w << " x " << h << " pixels\n"
  47245. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47246. getThumbSize (w, h);
  47247. currentThumbnail = currentThumbnail->createCopy (w, h);
  47248. }
  47249. }
  47250. }
  47251. }
  47252. void ImagePreviewComponent::paint (Graphics& g)
  47253. {
  47254. if (currentThumbnail != 0)
  47255. {
  47256. g.setFont (13.0f);
  47257. int w = currentThumbnail->getWidth();
  47258. int h = currentThumbnail->getHeight();
  47259. getThumbSize (w, h);
  47260. const int numLines = 4;
  47261. const int totalH = 13 * numLines + h + 4;
  47262. const int y = (getHeight() - totalH) / 2;
  47263. g.drawImageWithin (currentThumbnail,
  47264. (getWidth() - w) / 2, y, w, h,
  47265. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47266. false);
  47267. g.drawFittedText (currentDetails,
  47268. 0, y + h + 4, getWidth(), 100,
  47269. Justification::centredTop, numLines);
  47270. }
  47271. }
  47272. END_JUCE_NAMESPACE
  47273. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47274. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47275. BEGIN_JUCE_NAMESPACE
  47276. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47277. const String& directoryWildcardPatterns,
  47278. const String& description_)
  47279. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47280. : (description_ + " (" + fileWildcardPatterns + ")"))
  47281. {
  47282. parse (fileWildcardPatterns, fileWildcards);
  47283. parse (directoryWildcardPatterns, directoryWildcards);
  47284. }
  47285. WildcardFileFilter::~WildcardFileFilter()
  47286. {
  47287. }
  47288. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47289. {
  47290. return match (file, fileWildcards);
  47291. }
  47292. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47293. {
  47294. return match (file, directoryWildcards);
  47295. }
  47296. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47297. {
  47298. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47299. result.trim();
  47300. result.removeEmptyStrings();
  47301. // special case for *.*, because people use it to mean "any file", but it
  47302. // would actually ignore files with no extension.
  47303. for (int i = result.size(); --i >= 0;)
  47304. if (result[i] == "*.*")
  47305. result.set (i, "*");
  47306. }
  47307. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47308. {
  47309. const String filename (file.getFileName());
  47310. for (int i = wildcards.size(); --i >= 0;)
  47311. if (filename.matchesWildcard (wildcards[i], true))
  47312. return true;
  47313. return false;
  47314. }
  47315. END_JUCE_NAMESPACE
  47316. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47317. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47318. BEGIN_JUCE_NAMESPACE
  47319. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47320. {
  47321. }
  47322. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47323. {
  47324. }
  47325. namespace KeyboardFocusHelpers
  47326. {
  47327. // This will sort a set of components, so that they are ordered in terms of
  47328. // left-to-right and then top-to-bottom.
  47329. class ScreenPositionComparator
  47330. {
  47331. public:
  47332. ScreenPositionComparator() {}
  47333. static int compareElements (const Component* const first, const Component* const second)
  47334. {
  47335. int explicitOrder1 = first->getExplicitFocusOrder();
  47336. if (explicitOrder1 <= 0)
  47337. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47338. int explicitOrder2 = second->getExplicitFocusOrder();
  47339. if (explicitOrder2 <= 0)
  47340. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47341. if (explicitOrder1 != explicitOrder2)
  47342. return explicitOrder1 - explicitOrder2;
  47343. const int diff = first->getY() - second->getY();
  47344. return (diff == 0) ? first->getX() - second->getX()
  47345. : diff;
  47346. }
  47347. };
  47348. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47349. {
  47350. if (parent->getNumChildComponents() > 0)
  47351. {
  47352. Array <Component*> localComps;
  47353. ScreenPositionComparator comparator;
  47354. int i;
  47355. for (i = parent->getNumChildComponents(); --i >= 0;)
  47356. {
  47357. Component* const c = parent->getChildComponent (i);
  47358. if (c->isVisible() && c->isEnabled())
  47359. localComps.addSorted (comparator, c);
  47360. }
  47361. for (i = 0; i < localComps.size(); ++i)
  47362. {
  47363. Component* const c = localComps.getUnchecked (i);
  47364. if (c->getWantsKeyboardFocus())
  47365. comps.add (c);
  47366. if (! c->isFocusContainer())
  47367. findAllFocusableComponents (c, comps);
  47368. }
  47369. }
  47370. }
  47371. }
  47372. static Component* getIncrementedComponent (Component* const current, const int delta)
  47373. {
  47374. Component* focusContainer = current->getParentComponent();
  47375. if (focusContainer != 0)
  47376. {
  47377. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47378. focusContainer = focusContainer->getParentComponent();
  47379. if (focusContainer != 0)
  47380. {
  47381. Array <Component*> comps;
  47382. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47383. if (comps.size() > 0)
  47384. {
  47385. const int index = comps.indexOf (current);
  47386. return comps [(index + comps.size() + delta) % comps.size()];
  47387. }
  47388. }
  47389. }
  47390. return 0;
  47391. }
  47392. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47393. {
  47394. return getIncrementedComponent (current, 1);
  47395. }
  47396. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47397. {
  47398. return getIncrementedComponent (current, -1);
  47399. }
  47400. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47401. {
  47402. Array <Component*> comps;
  47403. if (parentComponent != 0)
  47404. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47405. return comps.getFirst();
  47406. }
  47407. END_JUCE_NAMESPACE
  47408. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47409. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47410. BEGIN_JUCE_NAMESPACE
  47411. bool KeyListener::keyStateChanged (const bool, Component*)
  47412. {
  47413. return false;
  47414. }
  47415. END_JUCE_NAMESPACE
  47416. /*** End of inlined file: juce_KeyListener.cpp ***/
  47417. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47418. BEGIN_JUCE_NAMESPACE
  47419. // N.B. these two includes are put here deliberately to avoid problems with
  47420. // old GCCs failing on long include paths
  47421. const int maxKeys = 3;
  47422. class KeyMappingChangeButton : public Button
  47423. {
  47424. public:
  47425. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47426. const CommandID commandID_,
  47427. const String& keyName,
  47428. const int keyNum_)
  47429. : Button (keyName),
  47430. owner (owner_),
  47431. commandID (commandID_),
  47432. keyNum (keyNum_)
  47433. {
  47434. setWantsKeyboardFocus (false);
  47435. setTriggeredOnMouseDown (keyNum >= 0);
  47436. if (keyNum_ < 0)
  47437. setTooltip (TRANS("adds a new key-mapping"));
  47438. else
  47439. setTooltip (TRANS("click to change this key-mapping"));
  47440. }
  47441. ~KeyMappingChangeButton()
  47442. {
  47443. }
  47444. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47445. {
  47446. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47447. keyNum >= 0 ? getName() : String::empty);
  47448. }
  47449. void clicked()
  47450. {
  47451. if (keyNum >= 0)
  47452. {
  47453. // existing key clicked..
  47454. PopupMenu m;
  47455. m.addItem (1, TRANS("change this key-mapping"));
  47456. m.addSeparator();
  47457. m.addItem (2, TRANS("remove this key-mapping"));
  47458. const int res = m.show();
  47459. if (res == 1)
  47460. {
  47461. owner->assignNewKey (commandID, keyNum);
  47462. }
  47463. else if (res == 2)
  47464. {
  47465. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47466. }
  47467. }
  47468. else
  47469. {
  47470. // + button pressed..
  47471. owner->assignNewKey (commandID, -1);
  47472. }
  47473. }
  47474. void fitToContent (const int h) throw()
  47475. {
  47476. if (keyNum < 0)
  47477. {
  47478. setSize (h, h);
  47479. }
  47480. else
  47481. {
  47482. Font f (h * 0.6f);
  47483. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47484. }
  47485. }
  47486. juce_UseDebuggingNewOperator
  47487. private:
  47488. KeyMappingEditorComponent* const owner;
  47489. const CommandID commandID;
  47490. const int keyNum;
  47491. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47492. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47493. };
  47494. class KeyMappingItemComponent : public Component
  47495. {
  47496. public:
  47497. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47498. const CommandID commandID_)
  47499. : owner (owner_),
  47500. commandID (commandID_)
  47501. {
  47502. setInterceptsMouseClicks (false, true);
  47503. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47504. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47505. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47506. {
  47507. KeyMappingChangeButton* const kb
  47508. = new KeyMappingChangeButton (owner_, commandID,
  47509. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47510. kb->setEnabled (! isReadOnly);
  47511. addAndMakeVisible (kb);
  47512. }
  47513. KeyMappingChangeButton* const kb
  47514. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47515. addChildComponent (kb);
  47516. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47517. }
  47518. ~KeyMappingItemComponent()
  47519. {
  47520. deleteAllChildren();
  47521. }
  47522. void paint (Graphics& g)
  47523. {
  47524. g.setFont (getHeight() * 0.7f);
  47525. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47526. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47527. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47528. Justification::centredLeft, true);
  47529. }
  47530. void resized()
  47531. {
  47532. int x = getWidth() - 4;
  47533. for (int i = getNumChildComponents(); --i >= 0;)
  47534. {
  47535. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47536. kb->fitToContent (getHeight() - 2);
  47537. kb->setTopRightPosition (x, 1);
  47538. x -= kb->getWidth() + 5;
  47539. }
  47540. }
  47541. juce_UseDebuggingNewOperator
  47542. private:
  47543. KeyMappingEditorComponent* const owner;
  47544. const CommandID commandID;
  47545. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47546. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47547. };
  47548. class KeyMappingTreeViewItem : public TreeViewItem
  47549. {
  47550. public:
  47551. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47552. const CommandID commandID_)
  47553. : owner (owner_),
  47554. commandID (commandID_)
  47555. {
  47556. }
  47557. ~KeyMappingTreeViewItem()
  47558. {
  47559. }
  47560. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47561. bool mightContainSubItems() { return false; }
  47562. int getItemHeight() const { return 20; }
  47563. Component* createItemComponent()
  47564. {
  47565. return new KeyMappingItemComponent (owner, commandID);
  47566. }
  47567. juce_UseDebuggingNewOperator
  47568. private:
  47569. KeyMappingEditorComponent* const owner;
  47570. const CommandID commandID;
  47571. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47572. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47573. };
  47574. class KeyCategoryTreeViewItem : public TreeViewItem
  47575. {
  47576. public:
  47577. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47578. const String& name)
  47579. : owner (owner_),
  47580. categoryName (name)
  47581. {
  47582. }
  47583. ~KeyCategoryTreeViewItem()
  47584. {
  47585. }
  47586. const String getUniqueName() const { return categoryName + "_cat"; }
  47587. bool mightContainSubItems() { return true; }
  47588. int getItemHeight() const { return 28; }
  47589. void paintItem (Graphics& g, int width, int height)
  47590. {
  47591. g.setFont (height * 0.6f, Font::bold);
  47592. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47593. g.drawText (categoryName,
  47594. 2, 0, width - 2, height,
  47595. Justification::centredLeft, true);
  47596. }
  47597. void itemOpennessChanged (bool isNowOpen)
  47598. {
  47599. if (isNowOpen)
  47600. {
  47601. if (getNumSubItems() == 0)
  47602. {
  47603. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47604. for (int i = 0; i < commands.size(); ++i)
  47605. {
  47606. if (owner->shouldCommandBeIncluded (commands[i]))
  47607. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47608. }
  47609. }
  47610. }
  47611. else
  47612. {
  47613. clearSubItems();
  47614. }
  47615. }
  47616. juce_UseDebuggingNewOperator
  47617. private:
  47618. KeyMappingEditorComponent* owner;
  47619. String categoryName;
  47620. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47621. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47622. };
  47623. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47624. const bool showResetToDefaultButton)
  47625. : mappings (mappingManager)
  47626. {
  47627. jassert (mappingManager != 0); // can't be null!
  47628. mappingManager->addChangeListener (this);
  47629. setLinesDrawnForSubItems (false);
  47630. resetButton = 0;
  47631. if (showResetToDefaultButton)
  47632. {
  47633. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47634. resetButton->addButtonListener (this);
  47635. }
  47636. addAndMakeVisible (tree = new TreeView());
  47637. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47638. tree->setRootItemVisible (false);
  47639. tree->setDefaultOpenness (true);
  47640. tree->setRootItem (this);
  47641. }
  47642. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47643. {
  47644. mappings->removeChangeListener (this);
  47645. deleteAllChildren();
  47646. }
  47647. bool KeyMappingEditorComponent::mightContainSubItems()
  47648. {
  47649. return true;
  47650. }
  47651. const String KeyMappingEditorComponent::getUniqueName() const
  47652. {
  47653. return "keys";
  47654. }
  47655. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47656. const Colour& textColour)
  47657. {
  47658. setColour (backgroundColourId, mainBackground);
  47659. setColour (textColourId, textColour);
  47660. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47661. }
  47662. void KeyMappingEditorComponent::parentHierarchyChanged()
  47663. {
  47664. changeListenerCallback (0);
  47665. }
  47666. void KeyMappingEditorComponent::resized()
  47667. {
  47668. int h = getHeight();
  47669. if (resetButton != 0)
  47670. {
  47671. const int buttonHeight = 20;
  47672. h -= buttonHeight + 8;
  47673. int x = getWidth() - 8;
  47674. resetButton->changeWidthToFitText (buttonHeight);
  47675. resetButton->setTopRightPosition (x, h + 6);
  47676. }
  47677. tree->setBounds (0, 0, getWidth(), h);
  47678. }
  47679. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47680. {
  47681. if (button == resetButton)
  47682. {
  47683. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47684. TRANS("Reset to defaults"),
  47685. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47686. TRANS("Reset")))
  47687. {
  47688. mappings->resetToDefaultMappings();
  47689. }
  47690. }
  47691. }
  47692. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47693. {
  47694. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47695. clearSubItems();
  47696. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47697. for (int i = 0; i < categories.size(); ++i)
  47698. {
  47699. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47700. int count = 0;
  47701. for (int j = 0; j < commands.size(); ++j)
  47702. if (shouldCommandBeIncluded (commands[j]))
  47703. ++count;
  47704. if (count > 0)
  47705. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47706. }
  47707. if (oldOpenness != 0)
  47708. tree->restoreOpennessState (*oldOpenness);
  47709. }
  47710. class KeyEntryWindow : public AlertWindow
  47711. {
  47712. public:
  47713. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47714. : AlertWindow (TRANS("New key-mapping"),
  47715. TRANS("Please press a key combination now..."),
  47716. AlertWindow::NoIcon),
  47717. owner (owner_)
  47718. {
  47719. addButton (TRANS("ok"), 1);
  47720. addButton (TRANS("cancel"), 0);
  47721. // (avoid return + escape keys getting processed by the buttons..)
  47722. for (int i = getNumChildComponents(); --i >= 0;)
  47723. getChildComponent (i)->setWantsKeyboardFocus (false);
  47724. setWantsKeyboardFocus (true);
  47725. grabKeyboardFocus();
  47726. }
  47727. ~KeyEntryWindow()
  47728. {
  47729. }
  47730. bool keyPressed (const KeyPress& key)
  47731. {
  47732. lastPress = key;
  47733. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47734. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  47735. if (previousCommand != 0)
  47736. {
  47737. message << "\n\n"
  47738. << TRANS("(Currently assigned to \"")
  47739. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  47740. << "\")";
  47741. }
  47742. setMessage (message);
  47743. return true;
  47744. }
  47745. bool keyStateChanged (bool)
  47746. {
  47747. return true;
  47748. }
  47749. KeyPress lastPress;
  47750. juce_UseDebuggingNewOperator
  47751. private:
  47752. KeyMappingEditorComponent* owner;
  47753. KeyEntryWindow (const KeyEntryWindow&);
  47754. KeyEntryWindow& operator= (const KeyEntryWindow&);
  47755. };
  47756. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  47757. {
  47758. KeyEntryWindow entryWindow (this);
  47759. if (entryWindow.runModalLoop() != 0)
  47760. {
  47761. entryWindow.setVisible (false);
  47762. if (entryWindow.lastPress.isValid())
  47763. {
  47764. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  47765. if (previousCommand != 0)
  47766. {
  47767. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47768. TRANS("Change key-mapping"),
  47769. TRANS("This key is already assigned to the command \"")
  47770. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  47771. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  47772. TRANS("re-assign"),
  47773. TRANS("cancel")))
  47774. {
  47775. return;
  47776. }
  47777. }
  47778. mappings->removeKeyPress (entryWindow.lastPress);
  47779. if (index >= 0)
  47780. mappings->removeKeyPress (commandID, index);
  47781. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  47782. }
  47783. }
  47784. }
  47785. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  47786. {
  47787. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47788. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  47789. }
  47790. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  47791. {
  47792. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47793. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  47794. }
  47795. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  47796. {
  47797. return key.getTextDescription();
  47798. }
  47799. END_JUCE_NAMESPACE
  47800. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47801. /*** Start of inlined file: juce_KeyPress.cpp ***/
  47802. BEGIN_JUCE_NAMESPACE
  47803. KeyPress::KeyPress() throw()
  47804. : keyCode (0),
  47805. mods (0),
  47806. textCharacter (0)
  47807. {
  47808. }
  47809. KeyPress::KeyPress (const int keyCode_,
  47810. const ModifierKeys& mods_,
  47811. const juce_wchar textCharacter_) throw()
  47812. : keyCode (keyCode_),
  47813. mods (mods_),
  47814. textCharacter (textCharacter_)
  47815. {
  47816. }
  47817. KeyPress::KeyPress (const int keyCode_) throw()
  47818. : keyCode (keyCode_),
  47819. textCharacter (0)
  47820. {
  47821. }
  47822. KeyPress::KeyPress (const KeyPress& other) throw()
  47823. : keyCode (other.keyCode),
  47824. mods (other.mods),
  47825. textCharacter (other.textCharacter)
  47826. {
  47827. }
  47828. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  47829. {
  47830. keyCode = other.keyCode;
  47831. mods = other.mods;
  47832. textCharacter = other.textCharacter;
  47833. return *this;
  47834. }
  47835. bool KeyPress::operator== (const KeyPress& other) const throw()
  47836. {
  47837. return mods.getRawFlags() == other.mods.getRawFlags()
  47838. && (textCharacter == other.textCharacter
  47839. || textCharacter == 0
  47840. || other.textCharacter == 0)
  47841. && (keyCode == other.keyCode
  47842. || (keyCode < 256
  47843. && other.keyCode < 256
  47844. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  47845. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  47846. }
  47847. bool KeyPress::operator!= (const KeyPress& other) const throw()
  47848. {
  47849. return ! operator== (other);
  47850. }
  47851. bool KeyPress::isCurrentlyDown() const
  47852. {
  47853. return isKeyCurrentlyDown (keyCode)
  47854. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  47855. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  47856. }
  47857. namespace KeyPressHelpers
  47858. {
  47859. struct KeyNameAndCode
  47860. {
  47861. const char* name;
  47862. int code;
  47863. };
  47864. static const KeyNameAndCode translations[] =
  47865. {
  47866. { "spacebar", KeyPress::spaceKey },
  47867. { "return", KeyPress::returnKey },
  47868. { "escape", KeyPress::escapeKey },
  47869. { "backspace", KeyPress::backspaceKey },
  47870. { "cursor left", KeyPress::leftKey },
  47871. { "cursor right", KeyPress::rightKey },
  47872. { "cursor up", KeyPress::upKey },
  47873. { "cursor down", KeyPress::downKey },
  47874. { "page up", KeyPress::pageUpKey },
  47875. { "page down", KeyPress::pageDownKey },
  47876. { "home", KeyPress::homeKey },
  47877. { "end", KeyPress::endKey },
  47878. { "delete", KeyPress::deleteKey },
  47879. { "insert", KeyPress::insertKey },
  47880. { "tab", KeyPress::tabKey },
  47881. { "play", KeyPress::playKey },
  47882. { "stop", KeyPress::stopKey },
  47883. { "fast forward", KeyPress::fastForwardKey },
  47884. { "rewind", KeyPress::rewindKey }
  47885. };
  47886. static const String numberPadPrefix() { return "numpad "; }
  47887. }
  47888. const KeyPress KeyPress::createFromDescription (const String& desc)
  47889. {
  47890. int modifiers = 0;
  47891. if (desc.containsWholeWordIgnoreCase ("ctrl")
  47892. || desc.containsWholeWordIgnoreCase ("control")
  47893. || desc.containsWholeWordIgnoreCase ("ctl"))
  47894. modifiers |= ModifierKeys::ctrlModifier;
  47895. if (desc.containsWholeWordIgnoreCase ("shift")
  47896. || desc.containsWholeWordIgnoreCase ("shft"))
  47897. modifiers |= ModifierKeys::shiftModifier;
  47898. if (desc.containsWholeWordIgnoreCase ("alt")
  47899. || desc.containsWholeWordIgnoreCase ("option"))
  47900. modifiers |= ModifierKeys::altModifier;
  47901. if (desc.containsWholeWordIgnoreCase ("command")
  47902. || desc.containsWholeWordIgnoreCase ("cmd"))
  47903. modifiers |= ModifierKeys::commandModifier;
  47904. int key = 0;
  47905. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47906. {
  47907. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  47908. {
  47909. key = KeyPressHelpers::translations[i].code;
  47910. break;
  47911. }
  47912. }
  47913. if (key == 0)
  47914. {
  47915. // see if it's a numpad key..
  47916. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  47917. {
  47918. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  47919. if (lastChar >= '0' && lastChar <= '9')
  47920. key = numberPad0 + lastChar - '0';
  47921. else if (lastChar == '+')
  47922. key = numberPadAdd;
  47923. else if (lastChar == '-')
  47924. key = numberPadSubtract;
  47925. else if (lastChar == '*')
  47926. key = numberPadMultiply;
  47927. else if (lastChar == '/')
  47928. key = numberPadDivide;
  47929. else if (lastChar == '.')
  47930. key = numberPadDecimalPoint;
  47931. else if (lastChar == '=')
  47932. key = numberPadEquals;
  47933. else if (desc.endsWith ("separator"))
  47934. key = numberPadSeparator;
  47935. else if (desc.endsWith ("delete"))
  47936. key = numberPadDelete;
  47937. }
  47938. if (key == 0)
  47939. {
  47940. // see if it's a function key..
  47941. for (int i = 1; i <= 12; ++i)
  47942. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  47943. key = F1Key + i - 1;
  47944. if (key == 0)
  47945. {
  47946. // give up and use the hex code..
  47947. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  47948. .toLowerCase()
  47949. .retainCharacters ("0123456789abcdef")
  47950. .getHexValue32();
  47951. if (hexCode > 0)
  47952. key = hexCode;
  47953. else
  47954. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  47955. }
  47956. }
  47957. }
  47958. return KeyPress (key, ModifierKeys (modifiers), 0);
  47959. }
  47960. const String KeyPress::getTextDescription() const
  47961. {
  47962. String desc;
  47963. if (keyCode > 0)
  47964. {
  47965. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  47966. // want to store it as being a slash, not shift+whatever.
  47967. if (textCharacter == '/')
  47968. return "/";
  47969. if (mods.isCtrlDown())
  47970. desc << "ctrl + ";
  47971. if (mods.isShiftDown())
  47972. desc << "shift + ";
  47973. #if JUCE_MAC
  47974. // only do this on the mac, because on Windows ctrl and command are the same,
  47975. // and this would get confusing
  47976. if (mods.isCommandDown())
  47977. desc << "command + ";
  47978. if (mods.isAltDown())
  47979. desc << "option + ";
  47980. #else
  47981. if (mods.isAltDown())
  47982. desc << "alt + ";
  47983. #endif
  47984. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47985. if (keyCode == KeyPressHelpers::translations[i].code)
  47986. return desc + KeyPressHelpers::translations[i].name;
  47987. if (keyCode >= F1Key && keyCode <= F16Key)
  47988. desc << 'F' << (1 + keyCode - F1Key);
  47989. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  47990. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  47991. else if (keyCode >= 33 && keyCode < 176)
  47992. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  47993. else if (keyCode == numberPadAdd)
  47994. desc << KeyPressHelpers::numberPadPrefix() << '+';
  47995. else if (keyCode == numberPadSubtract)
  47996. desc << KeyPressHelpers::numberPadPrefix() << '-';
  47997. else if (keyCode == numberPadMultiply)
  47998. desc << KeyPressHelpers::numberPadPrefix() << '*';
  47999. else if (keyCode == numberPadDivide)
  48000. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48001. else if (keyCode == numberPadSeparator)
  48002. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48003. else if (keyCode == numberPadDecimalPoint)
  48004. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48005. else if (keyCode == numberPadDelete)
  48006. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48007. else
  48008. desc << '#' << String::toHexString (keyCode);
  48009. }
  48010. return desc;
  48011. }
  48012. END_JUCE_NAMESPACE
  48013. /*** End of inlined file: juce_KeyPress.cpp ***/
  48014. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48015. BEGIN_JUCE_NAMESPACE
  48016. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48017. : commandManager (commandManager_)
  48018. {
  48019. // A manager is needed to get the descriptions of commands, and will be called when
  48020. // a command is invoked. So you can't leave this null..
  48021. jassert (commandManager_ != 0);
  48022. Desktop::getInstance().addFocusChangeListener (this);
  48023. }
  48024. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48025. : commandManager (other.commandManager)
  48026. {
  48027. Desktop::getInstance().addFocusChangeListener (this);
  48028. }
  48029. KeyPressMappingSet::~KeyPressMappingSet()
  48030. {
  48031. Desktop::getInstance().removeFocusChangeListener (this);
  48032. }
  48033. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48034. {
  48035. for (int i = 0; i < mappings.size(); ++i)
  48036. if (mappings.getUnchecked(i)->commandID == commandID)
  48037. return mappings.getUnchecked (i)->keypresses;
  48038. return Array <KeyPress> ();
  48039. }
  48040. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48041. const KeyPress& newKeyPress,
  48042. int insertIndex)
  48043. {
  48044. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48045. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48046. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48047. && ! newKeyPress.getModifiers().isShiftDown()));
  48048. if (findCommandForKeyPress (newKeyPress) != commandID)
  48049. {
  48050. removeKeyPress (newKeyPress);
  48051. if (newKeyPress.isValid())
  48052. {
  48053. for (int i = mappings.size(); --i >= 0;)
  48054. {
  48055. if (mappings.getUnchecked(i)->commandID == commandID)
  48056. {
  48057. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48058. sendChangeMessage (this);
  48059. return;
  48060. }
  48061. }
  48062. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48063. if (ci != 0)
  48064. {
  48065. CommandMapping* const cm = new CommandMapping();
  48066. cm->commandID = commandID;
  48067. cm->keypresses.add (newKeyPress);
  48068. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48069. mappings.add (cm);
  48070. sendChangeMessage (this);
  48071. }
  48072. }
  48073. }
  48074. }
  48075. void KeyPressMappingSet::resetToDefaultMappings()
  48076. {
  48077. mappings.clear();
  48078. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48079. {
  48080. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48081. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48082. {
  48083. addKeyPress (ci->commandID,
  48084. ci->defaultKeypresses.getReference (j));
  48085. }
  48086. }
  48087. sendChangeMessage (this);
  48088. }
  48089. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48090. {
  48091. clearAllKeyPresses (commandID);
  48092. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48093. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48094. {
  48095. addKeyPress (ci->commandID,
  48096. ci->defaultKeypresses.getReference (j));
  48097. }
  48098. }
  48099. void KeyPressMappingSet::clearAllKeyPresses()
  48100. {
  48101. if (mappings.size() > 0)
  48102. {
  48103. sendChangeMessage (this);
  48104. mappings.clear();
  48105. }
  48106. }
  48107. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48108. {
  48109. for (int i = mappings.size(); --i >= 0;)
  48110. {
  48111. if (mappings.getUnchecked(i)->commandID == commandID)
  48112. {
  48113. mappings.remove (i);
  48114. sendChangeMessage (this);
  48115. }
  48116. }
  48117. }
  48118. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48119. {
  48120. if (keypress.isValid())
  48121. {
  48122. for (int i = mappings.size(); --i >= 0;)
  48123. {
  48124. CommandMapping* const cm = mappings.getUnchecked(i);
  48125. for (int j = cm->keypresses.size(); --j >= 0;)
  48126. {
  48127. if (keypress == cm->keypresses [j])
  48128. {
  48129. cm->keypresses.remove (j);
  48130. sendChangeMessage (this);
  48131. }
  48132. }
  48133. }
  48134. }
  48135. }
  48136. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48137. {
  48138. for (int i = mappings.size(); --i >= 0;)
  48139. {
  48140. if (mappings.getUnchecked(i)->commandID == commandID)
  48141. {
  48142. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48143. sendChangeMessage (this);
  48144. break;
  48145. }
  48146. }
  48147. }
  48148. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48149. {
  48150. for (int i = 0; i < mappings.size(); ++i)
  48151. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48152. return mappings.getUnchecked(i)->commandID;
  48153. return 0;
  48154. }
  48155. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48156. {
  48157. for (int i = mappings.size(); --i >= 0;)
  48158. if (mappings.getUnchecked(i)->commandID == commandID)
  48159. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48160. return false;
  48161. }
  48162. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48163. const KeyPress& key,
  48164. const bool isKeyDown,
  48165. const int millisecsSinceKeyPressed,
  48166. Component* const originatingComponent) const
  48167. {
  48168. ApplicationCommandTarget::InvocationInfo info (commandID);
  48169. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48170. info.isKeyDown = isKeyDown;
  48171. info.keyPress = key;
  48172. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48173. info.originatingComponent = originatingComponent;
  48174. commandManager->invoke (info, false);
  48175. }
  48176. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48177. {
  48178. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48179. {
  48180. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48181. {
  48182. // if the XML was created as a set of differences from the default mappings,
  48183. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48184. resetToDefaultMappings();
  48185. }
  48186. else
  48187. {
  48188. // if the XML was created calling createXml (false), then we need to clear all
  48189. // the keys and treat the xml as describing the entire set of mappings.
  48190. clearAllKeyPresses();
  48191. }
  48192. forEachXmlChildElement (xmlVersion, map)
  48193. {
  48194. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48195. if (commandId != 0)
  48196. {
  48197. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48198. if (map->hasTagName ("MAPPING"))
  48199. {
  48200. addKeyPress (commandId, key);
  48201. }
  48202. else if (map->hasTagName ("UNMAPPING"))
  48203. {
  48204. if (containsMapping (commandId, key))
  48205. removeKeyPress (key);
  48206. }
  48207. }
  48208. }
  48209. return true;
  48210. }
  48211. return false;
  48212. }
  48213. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48214. {
  48215. ScopedPointer <KeyPressMappingSet> defaultSet;
  48216. if (saveDifferencesFromDefaultSet)
  48217. {
  48218. defaultSet = new KeyPressMappingSet (commandManager);
  48219. defaultSet->resetToDefaultMappings();
  48220. }
  48221. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48222. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48223. int i;
  48224. for (i = 0; i < mappings.size(); ++i)
  48225. {
  48226. const CommandMapping* const cm = mappings.getUnchecked(i);
  48227. for (int j = 0; j < cm->keypresses.size(); ++j)
  48228. {
  48229. if (defaultSet == 0
  48230. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48231. {
  48232. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48233. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48234. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48235. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48236. }
  48237. }
  48238. }
  48239. if (defaultSet != 0)
  48240. {
  48241. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48242. {
  48243. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48244. for (int j = 0; j < cm->keypresses.size(); ++j)
  48245. {
  48246. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48247. {
  48248. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48249. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48250. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48251. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48252. }
  48253. }
  48254. }
  48255. }
  48256. return doc;
  48257. }
  48258. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48259. Component* originatingComponent)
  48260. {
  48261. bool used = false;
  48262. const CommandID commandID = findCommandForKeyPress (key);
  48263. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48264. if (ci != 0
  48265. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48266. {
  48267. ApplicationCommandInfo info (0);
  48268. if (commandManager->getTargetForCommand (commandID, info) != 0
  48269. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48270. {
  48271. invokeCommand (commandID, key, true, 0, originatingComponent);
  48272. used = true;
  48273. }
  48274. else
  48275. {
  48276. if (originatingComponent != 0)
  48277. originatingComponent->getLookAndFeel().playAlertSound();
  48278. }
  48279. }
  48280. return used;
  48281. }
  48282. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48283. {
  48284. bool used = false;
  48285. const uint32 now = Time::getMillisecondCounter();
  48286. for (int i = mappings.size(); --i >= 0;)
  48287. {
  48288. CommandMapping* const cm = mappings.getUnchecked(i);
  48289. if (cm->wantsKeyUpDownCallbacks)
  48290. {
  48291. for (int j = cm->keypresses.size(); --j >= 0;)
  48292. {
  48293. const KeyPress key (cm->keypresses.getReference (j));
  48294. const bool isDown = key.isCurrentlyDown();
  48295. int keyPressEntryIndex = 0;
  48296. bool wasDown = false;
  48297. for (int k = keysDown.size(); --k >= 0;)
  48298. {
  48299. if (key == keysDown.getUnchecked(k)->key)
  48300. {
  48301. keyPressEntryIndex = k;
  48302. wasDown = true;
  48303. used = true;
  48304. break;
  48305. }
  48306. }
  48307. if (isDown != wasDown)
  48308. {
  48309. int millisecs = 0;
  48310. if (isDown)
  48311. {
  48312. KeyPressTime* const k = new KeyPressTime();
  48313. k->key = key;
  48314. k->timeWhenPressed = now;
  48315. keysDown.add (k);
  48316. }
  48317. else
  48318. {
  48319. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48320. if (now > pressTime)
  48321. millisecs = now - pressTime;
  48322. keysDown.remove (keyPressEntryIndex);
  48323. }
  48324. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48325. used = true;
  48326. }
  48327. }
  48328. }
  48329. }
  48330. return used;
  48331. }
  48332. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48333. {
  48334. if (focusedComponent != 0)
  48335. focusedComponent->keyStateChanged (false);
  48336. }
  48337. END_JUCE_NAMESPACE
  48338. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48339. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48340. BEGIN_JUCE_NAMESPACE
  48341. ModifierKeys::ModifierKeys (const int flags_) throw()
  48342. : flags (flags_)
  48343. {
  48344. }
  48345. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48346. : flags (other.flags)
  48347. {
  48348. }
  48349. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48350. {
  48351. flags = other.flags;
  48352. return *this;
  48353. }
  48354. ModifierKeys ModifierKeys::currentModifiers;
  48355. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48356. {
  48357. return currentModifiers;
  48358. }
  48359. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48360. {
  48361. int num = 0;
  48362. if (isLeftButtonDown()) ++num;
  48363. if (isRightButtonDown()) ++num;
  48364. if (isMiddleButtonDown()) ++num;
  48365. return num;
  48366. }
  48367. END_JUCE_NAMESPACE
  48368. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48369. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48370. BEGIN_JUCE_NAMESPACE
  48371. class ComponentAnimator::AnimationTask
  48372. {
  48373. public:
  48374. AnimationTask (Component* const comp)
  48375. : component (comp)
  48376. {
  48377. }
  48378. Component::SafePointer<Component> component;
  48379. Rectangle<int> destination;
  48380. int msElapsed, msTotal;
  48381. double startSpeed, midSpeed, endSpeed, lastProgress;
  48382. double left, top, right, bottom;
  48383. bool useTimeslice (const int elapsed)
  48384. {
  48385. if (component == 0)
  48386. return false;
  48387. msElapsed += elapsed;
  48388. double newProgress = msElapsed / (double) msTotal;
  48389. if (newProgress >= 0 && newProgress < 1.0)
  48390. {
  48391. newProgress = timeToDistance (newProgress);
  48392. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48393. jassert (newProgress >= lastProgress);
  48394. lastProgress = newProgress;
  48395. left += (destination.getX() - left) * delta;
  48396. top += (destination.getY() - top) * delta;
  48397. right += (destination.getRight() - right) * delta;
  48398. bottom += (destination.getBottom() - bottom) * delta;
  48399. if (delta < 1.0)
  48400. {
  48401. const Rectangle<int> newBounds (roundToInt (left),
  48402. roundToInt (top),
  48403. roundToInt (right - left),
  48404. roundToInt (bottom - top));
  48405. if (newBounds != destination)
  48406. {
  48407. component->setBounds (newBounds);
  48408. return true;
  48409. }
  48410. }
  48411. }
  48412. component->setBounds (destination);
  48413. return false;
  48414. }
  48415. void moveToFinalDestination()
  48416. {
  48417. if (component != 0)
  48418. component->setBounds (destination);
  48419. }
  48420. private:
  48421. inline double timeToDistance (const double time) const
  48422. {
  48423. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48424. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48425. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48426. }
  48427. };
  48428. ComponentAnimator::ComponentAnimator()
  48429. : lastTime (0)
  48430. {
  48431. }
  48432. ComponentAnimator::~ComponentAnimator()
  48433. {
  48434. cancelAllAnimations (false);
  48435. jassert (tasks.size() == 0);
  48436. }
  48437. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48438. {
  48439. for (int i = tasks.size(); --i >= 0;)
  48440. if (component == tasks.getUnchecked(i)->component.getComponent())
  48441. return tasks.getUnchecked(i);
  48442. return 0;
  48443. }
  48444. void ComponentAnimator::animateComponent (Component* const component,
  48445. const Rectangle<int>& finalPosition,
  48446. const int millisecondsToSpendMoving,
  48447. const double startSpeed,
  48448. const double endSpeed)
  48449. {
  48450. if (component != 0)
  48451. {
  48452. AnimationTask* at = findTaskFor (component);
  48453. if (at == 0)
  48454. {
  48455. at = new AnimationTask (component);
  48456. tasks.add (at);
  48457. sendChangeMessage (this);
  48458. }
  48459. at->msElapsed = 0;
  48460. at->lastProgress = 0;
  48461. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48462. at->destination = finalPosition;
  48463. // the speeds must be 0 or greater!
  48464. jassert (startSpeed >= 0 && endSpeed >= 0)
  48465. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48466. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48467. at->midSpeed = invTotalDistance;
  48468. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48469. at->left = component->getX();
  48470. at->top = component->getY();
  48471. at->right = component->getRight();
  48472. at->bottom = component->getBottom();
  48473. if (! isTimerRunning())
  48474. {
  48475. lastTime = Time::getMillisecondCounter();
  48476. startTimer (1000 / 50);
  48477. }
  48478. }
  48479. }
  48480. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48481. {
  48482. for (int i = tasks.size(); --i >= 0;)
  48483. {
  48484. AnimationTask* const at = tasks.getUnchecked(i);
  48485. if (moveComponentsToTheirFinalPositions)
  48486. at->moveToFinalDestination();
  48487. delete at;
  48488. tasks.remove (i);
  48489. sendChangeMessage (this);
  48490. }
  48491. }
  48492. void ComponentAnimator::cancelAnimation (Component* const component,
  48493. const bool moveComponentToItsFinalPosition)
  48494. {
  48495. AnimationTask* const at = findTaskFor (component);
  48496. if (at != 0)
  48497. {
  48498. if (moveComponentToItsFinalPosition)
  48499. at->moveToFinalDestination();
  48500. tasks.removeValue (at);
  48501. delete at;
  48502. sendChangeMessage (this);
  48503. }
  48504. }
  48505. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48506. {
  48507. AnimationTask* const at = findTaskFor (component);
  48508. if (at != 0)
  48509. return at->destination;
  48510. else if (component != 0)
  48511. return component->getBounds();
  48512. return Rectangle<int>();
  48513. }
  48514. bool ComponentAnimator::isAnimating (Component* component) const
  48515. {
  48516. return findTaskFor (component) != 0;
  48517. }
  48518. void ComponentAnimator::timerCallback()
  48519. {
  48520. const uint32 timeNow = Time::getMillisecondCounter();
  48521. if (lastTime == 0 || lastTime == timeNow)
  48522. lastTime = timeNow;
  48523. const int elapsed = timeNow - lastTime;
  48524. for (int i = tasks.size(); --i >= 0;)
  48525. {
  48526. AnimationTask* const at = tasks.getUnchecked(i);
  48527. if (! at->useTimeslice (elapsed))
  48528. {
  48529. tasks.remove (i);
  48530. delete at;
  48531. sendChangeMessage (this);
  48532. }
  48533. }
  48534. lastTime = timeNow;
  48535. if (tasks.size() == 0)
  48536. stopTimer();
  48537. }
  48538. END_JUCE_NAMESPACE
  48539. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48540. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48541. BEGIN_JUCE_NAMESPACE
  48542. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48543. : minW (0),
  48544. maxW (0x3fffffff),
  48545. minH (0),
  48546. maxH (0x3fffffff),
  48547. minOffTop (0),
  48548. minOffLeft (0),
  48549. minOffBottom (0),
  48550. minOffRight (0),
  48551. aspectRatio (0.0)
  48552. {
  48553. }
  48554. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48555. {
  48556. }
  48557. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48558. {
  48559. minW = minimumWidth;
  48560. }
  48561. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48562. {
  48563. maxW = maximumWidth;
  48564. }
  48565. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48566. {
  48567. minH = minimumHeight;
  48568. }
  48569. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48570. {
  48571. maxH = maximumHeight;
  48572. }
  48573. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48574. {
  48575. jassert (maxW >= minimumWidth);
  48576. jassert (maxH >= minimumHeight);
  48577. jassert (minimumWidth > 0 && minimumHeight > 0);
  48578. minW = minimumWidth;
  48579. minH = minimumHeight;
  48580. if (minW > maxW)
  48581. maxW = minW;
  48582. if (minH > maxH)
  48583. maxH = minH;
  48584. }
  48585. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48586. {
  48587. jassert (maximumWidth >= minW);
  48588. jassert (maximumHeight >= minH);
  48589. jassert (maximumWidth > 0 && maximumHeight > 0);
  48590. maxW = jmax (minW, maximumWidth);
  48591. maxH = jmax (minH, maximumHeight);
  48592. }
  48593. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48594. const int minimumHeight,
  48595. const int maximumWidth,
  48596. const int maximumHeight) throw()
  48597. {
  48598. jassert (maximumWidth >= minimumWidth);
  48599. jassert (maximumHeight >= minimumHeight);
  48600. jassert (maximumWidth > 0 && maximumHeight > 0);
  48601. jassert (minimumWidth > 0 && minimumHeight > 0);
  48602. minW = jmax (0, minimumWidth);
  48603. minH = jmax (0, minimumHeight);
  48604. maxW = jmax (minW, maximumWidth);
  48605. maxH = jmax (minH, maximumHeight);
  48606. }
  48607. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48608. const int minimumWhenOffTheLeft,
  48609. const int minimumWhenOffTheBottom,
  48610. const int minimumWhenOffTheRight) throw()
  48611. {
  48612. minOffTop = minimumWhenOffTheTop;
  48613. minOffLeft = minimumWhenOffTheLeft;
  48614. minOffBottom = minimumWhenOffTheBottom;
  48615. minOffRight = minimumWhenOffTheRight;
  48616. }
  48617. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48618. {
  48619. aspectRatio = jmax (0.0, widthOverHeight);
  48620. }
  48621. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48622. {
  48623. return aspectRatio;
  48624. }
  48625. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48626. const Rectangle<int>& targetBounds,
  48627. const bool isStretchingTop,
  48628. const bool isStretchingLeft,
  48629. const bool isStretchingBottom,
  48630. const bool isStretchingRight)
  48631. {
  48632. jassert (component != 0);
  48633. Rectangle<int> limits, bounds (targetBounds);
  48634. BorderSize border;
  48635. Component* const parent = component->getParentComponent();
  48636. if (parent == 0)
  48637. {
  48638. ComponentPeer* peer = component->getPeer();
  48639. if (peer != 0)
  48640. border = peer->getFrameSize();
  48641. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48642. }
  48643. else
  48644. {
  48645. limits.setSize (parent->getWidth(), parent->getHeight());
  48646. }
  48647. border.addTo (bounds);
  48648. checkBounds (bounds,
  48649. border.addedTo (component->getBounds()), limits,
  48650. isStretchingTop, isStretchingLeft,
  48651. isStretchingBottom, isStretchingRight);
  48652. border.subtractFrom (bounds);
  48653. applyBoundsToComponent (component, bounds);
  48654. }
  48655. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48656. {
  48657. setBoundsForComponent (component, component->getBounds(),
  48658. false, false, false, false);
  48659. }
  48660. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48661. const Rectangle<int>& bounds)
  48662. {
  48663. component->setBounds (bounds);
  48664. }
  48665. void ComponentBoundsConstrainer::resizeStart()
  48666. {
  48667. }
  48668. void ComponentBoundsConstrainer::resizeEnd()
  48669. {
  48670. }
  48671. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48672. const Rectangle<int>& old,
  48673. const Rectangle<int>& limits,
  48674. const bool isStretchingTop,
  48675. const bool isStretchingLeft,
  48676. const bool isStretchingBottom,
  48677. const bool isStretchingRight)
  48678. {
  48679. int x = bounds.getX();
  48680. int y = bounds.getY();
  48681. int w = bounds.getWidth();
  48682. int h = bounds.getHeight();
  48683. // constrain the size if it's being stretched..
  48684. if (isStretchingLeft)
  48685. {
  48686. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48687. w = old.getRight() - x;
  48688. }
  48689. if (isStretchingRight)
  48690. {
  48691. w = jlimit (minW, maxW, w);
  48692. }
  48693. if (isStretchingTop)
  48694. {
  48695. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48696. h = old.getBottom() - y;
  48697. }
  48698. if (isStretchingBottom)
  48699. {
  48700. h = jlimit (minH, maxH, h);
  48701. }
  48702. // constrain the aspect ratio if one has been specified..
  48703. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48704. {
  48705. bool adjustWidth;
  48706. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48707. {
  48708. adjustWidth = true;
  48709. }
  48710. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48711. {
  48712. adjustWidth = false;
  48713. }
  48714. else
  48715. {
  48716. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48717. const double newRatio = fabs (w / (double) h);
  48718. adjustWidth = (oldRatio > newRatio);
  48719. }
  48720. if (adjustWidth)
  48721. {
  48722. w = roundToInt (h * aspectRatio);
  48723. if (w > maxW || w < minW)
  48724. {
  48725. w = jlimit (minW, maxW, w);
  48726. h = roundToInt (w / aspectRatio);
  48727. }
  48728. }
  48729. else
  48730. {
  48731. h = roundToInt (w / aspectRatio);
  48732. if (h > maxH || h < minH)
  48733. {
  48734. h = jlimit (minH, maxH, h);
  48735. w = roundToInt (h * aspectRatio);
  48736. }
  48737. }
  48738. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48739. {
  48740. x = old.getX() + (old.getWidth() - w) / 2;
  48741. }
  48742. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48743. {
  48744. y = old.getY() + (old.getHeight() - h) / 2;
  48745. }
  48746. else
  48747. {
  48748. if (isStretchingLeft)
  48749. x = old.getRight() - w;
  48750. if (isStretchingTop)
  48751. y = old.getBottom() - h;
  48752. }
  48753. }
  48754. // ...and constrain the position if limits have been set for that.
  48755. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  48756. {
  48757. if (minOffTop > 0)
  48758. {
  48759. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  48760. if (y < limit)
  48761. {
  48762. if (isStretchingTop)
  48763. h -= (limit - y);
  48764. y = limit;
  48765. }
  48766. }
  48767. if (minOffLeft > 0)
  48768. {
  48769. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  48770. if (x < limit)
  48771. {
  48772. if (isStretchingLeft)
  48773. w -= (limit - x);
  48774. x = limit;
  48775. }
  48776. }
  48777. if (minOffBottom > 0)
  48778. {
  48779. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  48780. if (y > limit)
  48781. {
  48782. if (isStretchingBottom)
  48783. h += (limit - y);
  48784. else
  48785. y = limit;
  48786. }
  48787. }
  48788. if (minOffRight > 0)
  48789. {
  48790. const int limit = limits.getRight() - jmin (minOffRight, w);
  48791. if (x > limit)
  48792. {
  48793. if (isStretchingRight)
  48794. w += (limit - x);
  48795. else
  48796. x = limit;
  48797. }
  48798. }
  48799. }
  48800. jassert (w >= 0 && h >= 0);
  48801. bounds = Rectangle<int> (x, y, w, h);
  48802. }
  48803. END_JUCE_NAMESPACE
  48804. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48805. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48806. BEGIN_JUCE_NAMESPACE
  48807. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  48808. : component (component_),
  48809. lastPeer (0),
  48810. reentrant (false)
  48811. {
  48812. jassert (component != 0); // can't use this with a null pointer..
  48813. component->addComponentListener (this);
  48814. registerWithParentComps();
  48815. }
  48816. ComponentMovementWatcher::~ComponentMovementWatcher()
  48817. {
  48818. component->removeComponentListener (this);
  48819. unregister();
  48820. }
  48821. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  48822. {
  48823. // agh! don't delete the target component without deleting this object first!
  48824. jassert (component != 0);
  48825. if (! reentrant)
  48826. {
  48827. reentrant = true;
  48828. ComponentPeer* const peer = component->getPeer();
  48829. if (peer != lastPeer)
  48830. {
  48831. componentPeerChanged();
  48832. if (component == 0)
  48833. return;
  48834. lastPeer = peer;
  48835. }
  48836. unregister();
  48837. registerWithParentComps();
  48838. reentrant = false;
  48839. componentMovedOrResized (*component, true, true);
  48840. }
  48841. }
  48842. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  48843. {
  48844. // agh! don't delete the target component without deleting this object first!
  48845. jassert (component != 0);
  48846. if (wasMoved)
  48847. {
  48848. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  48849. wasMoved = lastBounds.getPosition() != pos;
  48850. lastBounds.setPosition (pos);
  48851. }
  48852. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  48853. lastBounds.setSize (component->getWidth(), component->getHeight());
  48854. if (wasMoved || wasResized)
  48855. componentMovedOrResized (wasMoved, wasResized);
  48856. }
  48857. void ComponentMovementWatcher::registerWithParentComps() throw()
  48858. {
  48859. Component* p = component->getParentComponent();
  48860. while (p != 0)
  48861. {
  48862. p->addComponentListener (this);
  48863. registeredParentComps.add (p);
  48864. p = p->getParentComponent();
  48865. }
  48866. }
  48867. void ComponentMovementWatcher::unregister() throw()
  48868. {
  48869. for (int i = registeredParentComps.size(); --i >= 0;)
  48870. static_cast <Component*> (registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  48871. registeredParentComps.clear();
  48872. }
  48873. END_JUCE_NAMESPACE
  48874. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48875. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  48876. BEGIN_JUCE_NAMESPACE
  48877. GroupComponent::GroupComponent (const String& componentName,
  48878. const String& labelText)
  48879. : Component (componentName),
  48880. text (labelText),
  48881. justification (Justification::left)
  48882. {
  48883. setInterceptsMouseClicks (false, true);
  48884. }
  48885. GroupComponent::~GroupComponent()
  48886. {
  48887. }
  48888. void GroupComponent::setText (const String& newText)
  48889. {
  48890. if (text != newText)
  48891. {
  48892. text = newText;
  48893. repaint();
  48894. }
  48895. }
  48896. const String GroupComponent::getText() const
  48897. {
  48898. return text;
  48899. }
  48900. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  48901. {
  48902. if (justification.getFlags() != newJustification.getFlags())
  48903. {
  48904. justification = newJustification;
  48905. repaint();
  48906. }
  48907. }
  48908. void GroupComponent::paint (Graphics& g)
  48909. {
  48910. getLookAndFeel()
  48911. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  48912. text, justification,
  48913. *this);
  48914. }
  48915. void GroupComponent::enablementChanged()
  48916. {
  48917. repaint();
  48918. }
  48919. void GroupComponent::colourChanged()
  48920. {
  48921. repaint();
  48922. }
  48923. END_JUCE_NAMESPACE
  48924. /*** End of inlined file: juce_GroupComponent.cpp ***/
  48925. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  48926. BEGIN_JUCE_NAMESPACE
  48927. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  48928. : DocumentWindow (String::empty, backgroundColour,
  48929. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  48930. {
  48931. }
  48932. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  48933. {
  48934. }
  48935. void MultiDocumentPanelWindow::maximiseButtonPressed()
  48936. {
  48937. MultiDocumentPanel* const owner = getOwner();
  48938. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48939. if (owner != 0)
  48940. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  48941. }
  48942. void MultiDocumentPanelWindow::closeButtonPressed()
  48943. {
  48944. MultiDocumentPanel* const owner = getOwner();
  48945. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48946. if (owner != 0)
  48947. owner->closeDocument (getContentComponent(), true);
  48948. }
  48949. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  48950. {
  48951. DocumentWindow::activeWindowStatusChanged();
  48952. updateOrder();
  48953. }
  48954. void MultiDocumentPanelWindow::broughtToFront()
  48955. {
  48956. DocumentWindow::broughtToFront();
  48957. updateOrder();
  48958. }
  48959. void MultiDocumentPanelWindow::updateOrder()
  48960. {
  48961. MultiDocumentPanel* const owner = getOwner();
  48962. if (owner != 0)
  48963. owner->updateOrder();
  48964. }
  48965. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  48966. {
  48967. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  48968. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  48969. }
  48970. class MDITabbedComponentInternal : public TabbedComponent
  48971. {
  48972. public:
  48973. MDITabbedComponentInternal()
  48974. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  48975. {
  48976. }
  48977. ~MDITabbedComponentInternal()
  48978. {
  48979. }
  48980. void currentTabChanged (int, const String&)
  48981. {
  48982. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  48983. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  48984. if (owner != 0)
  48985. owner->updateOrder();
  48986. }
  48987. };
  48988. MultiDocumentPanel::MultiDocumentPanel()
  48989. : mode (MaximisedWindowsWithTabs),
  48990. tabComponent (0),
  48991. backgroundColour (Colours::lightblue),
  48992. maximumNumDocuments (0),
  48993. numDocsBeforeTabsUsed (0)
  48994. {
  48995. setOpaque (true);
  48996. }
  48997. MultiDocumentPanel::~MultiDocumentPanel()
  48998. {
  48999. closeAllDocuments (false);
  49000. }
  49001. static bool shouldDeleteComp (Component* const c)
  49002. {
  49003. return c->getProperties() ["mdiDocumentDelete_"];
  49004. }
  49005. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49006. {
  49007. while (components.size() > 0)
  49008. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49009. return false;
  49010. return true;
  49011. }
  49012. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49013. {
  49014. return new MultiDocumentPanelWindow (backgroundColour);
  49015. }
  49016. void MultiDocumentPanel::addWindow (Component* component)
  49017. {
  49018. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49019. dw->setResizable (true, false);
  49020. dw->setContentComponent (component, false, true);
  49021. dw->setName (component->getName());
  49022. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49023. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49024. int x = 4;
  49025. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49026. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49027. x += 16;
  49028. dw->setTopLeftPosition (x, x);
  49029. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49030. if (pos.toString().isNotEmpty())
  49031. dw->restoreWindowStateFromString (pos.toString());
  49032. addAndMakeVisible (dw);
  49033. dw->toFront (true);
  49034. }
  49035. bool MultiDocumentPanel::addDocument (Component* const component,
  49036. const Colour& docColour,
  49037. const bool deleteWhenRemoved)
  49038. {
  49039. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49040. // with a frame-within-a-frame! Just pass in the bare content component.
  49041. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49042. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49043. return false;
  49044. components.add (component);
  49045. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49046. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49047. component->addComponentListener (this);
  49048. if (mode == FloatingWindows)
  49049. {
  49050. if (isFullscreenWhenOneDocument())
  49051. {
  49052. if (components.size() == 1)
  49053. {
  49054. addAndMakeVisible (component);
  49055. }
  49056. else
  49057. {
  49058. if (components.size() == 2)
  49059. addWindow (components.getFirst());
  49060. addWindow (component);
  49061. }
  49062. }
  49063. else
  49064. {
  49065. addWindow (component);
  49066. }
  49067. }
  49068. else
  49069. {
  49070. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49071. {
  49072. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49073. Array <Component*> temp (components);
  49074. for (int i = 0; i < temp.size(); ++i)
  49075. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49076. resized();
  49077. }
  49078. else
  49079. {
  49080. if (tabComponent != 0)
  49081. tabComponent->addTab (component->getName(), docColour, component, false);
  49082. else
  49083. addAndMakeVisible (component);
  49084. }
  49085. setActiveDocument (component);
  49086. }
  49087. resized();
  49088. activeDocumentChanged();
  49089. return true;
  49090. }
  49091. bool MultiDocumentPanel::closeDocument (Component* component,
  49092. const bool checkItsOkToCloseFirst)
  49093. {
  49094. if (components.contains (component))
  49095. {
  49096. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49097. return false;
  49098. component->removeComponentListener (this);
  49099. const bool shouldDelete = shouldDeleteComp (component);
  49100. component->getProperties().remove ("mdiDocumentDelete_");
  49101. component->getProperties().remove ("mdiDocumentBkg_");
  49102. if (mode == FloatingWindows)
  49103. {
  49104. for (int i = getNumChildComponents(); --i >= 0;)
  49105. {
  49106. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49107. if (dw != 0 && dw->getContentComponent() == component)
  49108. {
  49109. dw->setContentComponent (0, false);
  49110. delete dw;
  49111. break;
  49112. }
  49113. }
  49114. if (shouldDelete)
  49115. delete component;
  49116. components.removeValue (component);
  49117. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49118. {
  49119. for (int i = getNumChildComponents(); --i >= 0;)
  49120. {
  49121. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49122. if (dw != 0)
  49123. {
  49124. dw->setContentComponent (0, false);
  49125. delete dw;
  49126. }
  49127. }
  49128. addAndMakeVisible (components.getFirst());
  49129. }
  49130. }
  49131. else
  49132. {
  49133. jassert (components.indexOf (component) >= 0);
  49134. if (tabComponent != 0)
  49135. {
  49136. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49137. if (tabComponent->getTabContentComponent (i) == component)
  49138. tabComponent->removeTab (i);
  49139. }
  49140. else
  49141. {
  49142. removeChildComponent (component);
  49143. }
  49144. if (shouldDelete)
  49145. delete component;
  49146. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49147. deleteAndZero (tabComponent);
  49148. components.removeValue (component);
  49149. if (components.size() > 0 && tabComponent == 0)
  49150. addAndMakeVisible (components.getFirst());
  49151. }
  49152. resized();
  49153. activeDocumentChanged();
  49154. }
  49155. else
  49156. {
  49157. jassertfalse
  49158. }
  49159. return true;
  49160. }
  49161. int MultiDocumentPanel::getNumDocuments() const throw()
  49162. {
  49163. return components.size();
  49164. }
  49165. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49166. {
  49167. return components [index];
  49168. }
  49169. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49170. {
  49171. if (mode == FloatingWindows)
  49172. {
  49173. for (int i = getNumChildComponents(); --i >= 0;)
  49174. {
  49175. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49176. if (dw != 0 && dw->isActiveWindow())
  49177. return dw->getContentComponent();
  49178. }
  49179. }
  49180. return components.getLast();
  49181. }
  49182. void MultiDocumentPanel::setActiveDocument (Component* component)
  49183. {
  49184. if (mode == FloatingWindows)
  49185. {
  49186. component = getContainerComp (component);
  49187. if (component != 0)
  49188. component->toFront (true);
  49189. }
  49190. else if (tabComponent != 0)
  49191. {
  49192. jassert (components.indexOf (component) >= 0);
  49193. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49194. {
  49195. if (tabComponent->getTabContentComponent (i) == component)
  49196. {
  49197. tabComponent->setCurrentTabIndex (i);
  49198. break;
  49199. }
  49200. }
  49201. }
  49202. else
  49203. {
  49204. component->grabKeyboardFocus();
  49205. }
  49206. }
  49207. void MultiDocumentPanel::activeDocumentChanged()
  49208. {
  49209. }
  49210. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49211. {
  49212. maximumNumDocuments = newNumber;
  49213. }
  49214. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49215. {
  49216. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49217. }
  49218. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49219. {
  49220. return numDocsBeforeTabsUsed != 0;
  49221. }
  49222. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49223. {
  49224. if (mode != newLayoutMode)
  49225. {
  49226. mode = newLayoutMode;
  49227. if (mode == FloatingWindows)
  49228. {
  49229. deleteAndZero (tabComponent);
  49230. }
  49231. else
  49232. {
  49233. for (int i = getNumChildComponents(); --i >= 0;)
  49234. {
  49235. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49236. if (dw != 0)
  49237. {
  49238. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49239. dw->setContentComponent (0, false);
  49240. delete dw;
  49241. }
  49242. }
  49243. }
  49244. resized();
  49245. const Array <Component*> tempComps (components);
  49246. components.clear();
  49247. for (int i = 0; i < tempComps.size(); ++i)
  49248. {
  49249. Component* const c = tempComps.getUnchecked(i);
  49250. addDocument (c,
  49251. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49252. shouldDeleteComp (c));
  49253. }
  49254. }
  49255. }
  49256. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49257. {
  49258. if (backgroundColour != newBackgroundColour)
  49259. {
  49260. backgroundColour = newBackgroundColour;
  49261. setOpaque (newBackgroundColour.isOpaque());
  49262. repaint();
  49263. }
  49264. }
  49265. void MultiDocumentPanel::paint (Graphics& g)
  49266. {
  49267. g.fillAll (backgroundColour);
  49268. }
  49269. void MultiDocumentPanel::resized()
  49270. {
  49271. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49272. {
  49273. for (int i = getNumChildComponents(); --i >= 0;)
  49274. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  49275. }
  49276. setWantsKeyboardFocus (components.size() == 0);
  49277. }
  49278. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49279. {
  49280. if (mode == FloatingWindows)
  49281. {
  49282. for (int i = 0; i < getNumChildComponents(); ++i)
  49283. {
  49284. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49285. if (dw != 0 && dw->getContentComponent() == c)
  49286. {
  49287. c = dw;
  49288. break;
  49289. }
  49290. }
  49291. }
  49292. return c;
  49293. }
  49294. void MultiDocumentPanel::componentNameChanged (Component&)
  49295. {
  49296. if (mode == FloatingWindows)
  49297. {
  49298. for (int i = 0; i < getNumChildComponents(); ++i)
  49299. {
  49300. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49301. if (dw != 0)
  49302. dw->setName (dw->getContentComponent()->getName());
  49303. }
  49304. }
  49305. else if (tabComponent != 0)
  49306. {
  49307. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49308. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49309. }
  49310. }
  49311. void MultiDocumentPanel::updateOrder()
  49312. {
  49313. const Array <Component*> oldList (components);
  49314. if (mode == FloatingWindows)
  49315. {
  49316. components.clear();
  49317. for (int i = 0; i < getNumChildComponents(); ++i)
  49318. {
  49319. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49320. if (dw != 0)
  49321. components.add (dw->getContentComponent());
  49322. }
  49323. }
  49324. else
  49325. {
  49326. if (tabComponent != 0)
  49327. {
  49328. Component* const current = tabComponent->getCurrentContentComponent();
  49329. if (current != 0)
  49330. {
  49331. components.removeValue (current);
  49332. components.add (current);
  49333. }
  49334. }
  49335. }
  49336. if (components != oldList)
  49337. activeDocumentChanged();
  49338. }
  49339. END_JUCE_NAMESPACE
  49340. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49341. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49342. BEGIN_JUCE_NAMESPACE
  49343. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49344. : zone (zoneFlags)
  49345. {
  49346. }
  49347. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49348. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49349. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49350. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49351. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49352. const BorderSize& border,
  49353. const Point<int>& position)
  49354. {
  49355. int z = 0;
  49356. if (totalSize.contains (position)
  49357. && ! border.subtractedFrom (totalSize).contains (position))
  49358. {
  49359. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49360. if (position.getX() < jmax (border.getLeft(), minW))
  49361. z |= left;
  49362. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49363. z |= right;
  49364. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49365. if (position.getY() < jmax (border.getTop(), minH))
  49366. z |= top;
  49367. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49368. z |= bottom;
  49369. }
  49370. return Zone (z);
  49371. }
  49372. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49373. {
  49374. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49375. switch (zone)
  49376. {
  49377. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49378. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49379. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49380. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49381. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49382. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49383. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49384. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49385. default: break;
  49386. }
  49387. return mc;
  49388. }
  49389. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49390. {
  49391. if (isDraggingWholeObject())
  49392. return b + offset;
  49393. if (isDraggingLeftEdge())
  49394. b.setLeft (b.getX() + offset.getX());
  49395. if (isDraggingRightEdge())
  49396. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49397. if (isDraggingTopEdge())
  49398. b.setTop (b.getY() + offset.getY());
  49399. if (isDraggingBottomEdge())
  49400. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49401. return b;
  49402. }
  49403. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49404. {
  49405. if (isDraggingWholeObject())
  49406. return b + offset;
  49407. if (isDraggingLeftEdge())
  49408. b.setLeft (b.getX() + offset.getX());
  49409. if (isDraggingRightEdge())
  49410. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49411. if (isDraggingTopEdge())
  49412. b.setTop (b.getY() + offset.getY());
  49413. if (isDraggingBottomEdge())
  49414. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49415. return b;
  49416. }
  49417. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49418. ComponentBoundsConstrainer* const constrainer_)
  49419. : component (componentToResize),
  49420. constrainer (constrainer_),
  49421. borderSize (5),
  49422. mouseZone (0)
  49423. {
  49424. }
  49425. ResizableBorderComponent::~ResizableBorderComponent()
  49426. {
  49427. }
  49428. void ResizableBorderComponent::paint (Graphics& g)
  49429. {
  49430. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49431. }
  49432. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49433. {
  49434. updateMouseZone (e);
  49435. }
  49436. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49437. {
  49438. updateMouseZone (e);
  49439. }
  49440. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49441. {
  49442. if (component == 0)
  49443. {
  49444. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49445. return;
  49446. }
  49447. updateMouseZone (e);
  49448. originalBounds = component->getBounds();
  49449. if (constrainer != 0)
  49450. constrainer->resizeStart();
  49451. }
  49452. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49453. {
  49454. if (component == 0)
  49455. {
  49456. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49457. return;
  49458. }
  49459. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49460. if (constrainer != 0)
  49461. constrainer->setBoundsForComponent (component, bounds,
  49462. mouseZone.isDraggingTopEdge(),
  49463. mouseZone.isDraggingLeftEdge(),
  49464. mouseZone.isDraggingBottomEdge(),
  49465. mouseZone.isDraggingRightEdge());
  49466. else
  49467. component->setBounds (bounds);
  49468. }
  49469. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49470. {
  49471. if (constrainer != 0)
  49472. constrainer->resizeEnd();
  49473. }
  49474. bool ResizableBorderComponent::hitTest (int x, int y)
  49475. {
  49476. return x < borderSize.getLeft()
  49477. || x >= getWidth() - borderSize.getRight()
  49478. || y < borderSize.getTop()
  49479. || y >= getHeight() - borderSize.getBottom();
  49480. }
  49481. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49482. {
  49483. if (borderSize != newBorderSize)
  49484. {
  49485. borderSize = newBorderSize;
  49486. repaint();
  49487. }
  49488. }
  49489. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49490. {
  49491. return borderSize;
  49492. }
  49493. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49494. {
  49495. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49496. if (mouseZone != newZone)
  49497. {
  49498. mouseZone = newZone;
  49499. setMouseCursor (newZone.getMouseCursor());
  49500. }
  49501. }
  49502. END_JUCE_NAMESPACE
  49503. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49504. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49505. BEGIN_JUCE_NAMESPACE
  49506. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49507. ComponentBoundsConstrainer* const constrainer_)
  49508. : component (componentToResize),
  49509. constrainer (constrainer_)
  49510. {
  49511. setRepaintsOnMouseActivity (true);
  49512. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49513. }
  49514. ResizableCornerComponent::~ResizableCornerComponent()
  49515. {
  49516. }
  49517. void ResizableCornerComponent::paint (Graphics& g)
  49518. {
  49519. getLookAndFeel()
  49520. .drawCornerResizer (g, getWidth(), getHeight(),
  49521. isMouseOverOrDragging(),
  49522. isMouseButtonDown());
  49523. }
  49524. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49525. {
  49526. if (component == 0)
  49527. {
  49528. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49529. return;
  49530. }
  49531. originalBounds = component->getBounds();
  49532. if (constrainer != 0)
  49533. constrainer->resizeStart();
  49534. }
  49535. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49536. {
  49537. if (component == 0)
  49538. {
  49539. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49540. return;
  49541. }
  49542. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49543. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49544. if (constrainer != 0)
  49545. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49546. else
  49547. component->setBounds (r);
  49548. }
  49549. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49550. {
  49551. if (constrainer != 0)
  49552. constrainer->resizeStart();
  49553. }
  49554. bool ResizableCornerComponent::hitTest (int x, int y)
  49555. {
  49556. if (getWidth() <= 0)
  49557. return false;
  49558. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49559. return y >= yAtX - getHeight() / 4;
  49560. }
  49561. END_JUCE_NAMESPACE
  49562. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49563. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49564. BEGIN_JUCE_NAMESPACE
  49565. class ScrollBar::ScrollbarButton : public Button
  49566. {
  49567. public:
  49568. int direction;
  49569. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49570. : Button (String::empty),
  49571. direction (direction_),
  49572. owner (owner_)
  49573. {
  49574. setWantsKeyboardFocus (false);
  49575. }
  49576. ~ScrollbarButton()
  49577. {
  49578. }
  49579. void paintButton (Graphics& g, bool over, bool down)
  49580. {
  49581. getLookAndFeel()
  49582. .drawScrollbarButton (g, owner,
  49583. getWidth(), getHeight(),
  49584. direction,
  49585. owner.isVertical(),
  49586. over, down);
  49587. }
  49588. void clicked()
  49589. {
  49590. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49591. }
  49592. juce_UseDebuggingNewOperator
  49593. private:
  49594. ScrollBar& owner;
  49595. ScrollbarButton (const ScrollbarButton&);
  49596. ScrollbarButton& operator= (const ScrollbarButton&);
  49597. };
  49598. ScrollBar::ScrollBar (const bool vertical_,
  49599. const bool buttonsAreVisible)
  49600. : totalRange (0.0, 1.0),
  49601. visibleRange (0.0, 0.1),
  49602. singleStepSize (0.1),
  49603. thumbAreaStart (0),
  49604. thumbAreaSize (0),
  49605. thumbStart (0),
  49606. thumbSize (0),
  49607. initialDelayInMillisecs (100),
  49608. repeatDelayInMillisecs (50),
  49609. minimumDelayInMillisecs (10),
  49610. vertical (vertical_),
  49611. isDraggingThumb (false),
  49612. autohides (true),
  49613. upButton (0),
  49614. downButton (0)
  49615. {
  49616. setButtonVisibility (buttonsAreVisible);
  49617. setRepaintsOnMouseActivity (true);
  49618. setFocusContainer (true);
  49619. }
  49620. ScrollBar::~ScrollBar()
  49621. {
  49622. deleteAllChildren();
  49623. }
  49624. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49625. {
  49626. if (totalRange != newRangeLimit)
  49627. {
  49628. totalRange = newRangeLimit;
  49629. setCurrentRange (visibleRange);
  49630. updateThumbPosition();
  49631. }
  49632. }
  49633. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49634. {
  49635. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49636. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49637. }
  49638. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49639. {
  49640. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49641. if (visibleRange != constrainedRange)
  49642. {
  49643. visibleRange = constrainedRange;
  49644. updateThumbPosition();
  49645. triggerAsyncUpdate();
  49646. }
  49647. }
  49648. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49649. {
  49650. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49651. }
  49652. void ScrollBar::setCurrentRangeStart (const double newStart)
  49653. {
  49654. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49655. }
  49656. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49657. {
  49658. singleStepSize = newSingleStepSize;
  49659. }
  49660. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49661. {
  49662. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49663. }
  49664. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49665. {
  49666. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49667. }
  49668. void ScrollBar::scrollToTop()
  49669. {
  49670. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49671. }
  49672. void ScrollBar::scrollToBottom()
  49673. {
  49674. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49675. }
  49676. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49677. const int repeatDelayInMillisecs_,
  49678. const int minimumDelayInMillisecs_)
  49679. {
  49680. initialDelayInMillisecs = initialDelayInMillisecs_;
  49681. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49682. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49683. if (upButton != 0)
  49684. {
  49685. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49686. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49687. }
  49688. }
  49689. void ScrollBar::addListener (ScrollBarListener* const listener)
  49690. {
  49691. listeners.add (listener);
  49692. }
  49693. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49694. {
  49695. listeners.remove (listener);
  49696. }
  49697. void ScrollBar::handleAsyncUpdate()
  49698. {
  49699. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49700. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49701. }
  49702. void ScrollBar::updateThumbPosition()
  49703. {
  49704. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49705. : thumbAreaSize);
  49706. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49707. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49708. if (newThumbSize > thumbAreaSize)
  49709. newThumbSize = thumbAreaSize;
  49710. int newThumbStart = thumbAreaStart;
  49711. if (totalRange.getLength() > visibleRange.getLength())
  49712. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49713. / (totalRange.getLength() - visibleRange.getLength()));
  49714. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49715. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49716. {
  49717. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49718. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49719. if (vertical)
  49720. repaint (0, repaintStart, getWidth(), repaintSize);
  49721. else
  49722. repaint (repaintStart, 0, repaintSize, getHeight());
  49723. thumbStart = newThumbStart;
  49724. thumbSize = newThumbSize;
  49725. }
  49726. }
  49727. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49728. {
  49729. if (vertical != shouldBeVertical)
  49730. {
  49731. vertical = shouldBeVertical;
  49732. if (upButton != 0)
  49733. {
  49734. upButton->direction = vertical ? 0 : 3;
  49735. downButton->direction = vertical ? 2 : 1;
  49736. }
  49737. updateThumbPosition();
  49738. }
  49739. }
  49740. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  49741. {
  49742. delete upButton;
  49743. upButton = 0;
  49744. delete downButton;
  49745. downButton = 0;
  49746. if (buttonsAreVisible)
  49747. {
  49748. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  49749. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  49750. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49751. }
  49752. updateThumbPosition();
  49753. }
  49754. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  49755. {
  49756. autohides = shouldHideWhenFullRange;
  49757. updateThumbPosition();
  49758. }
  49759. bool ScrollBar::autoHides() const throw()
  49760. {
  49761. return autohides;
  49762. }
  49763. void ScrollBar::paint (Graphics& g)
  49764. {
  49765. if (thumbAreaSize > 0)
  49766. {
  49767. LookAndFeel& lf = getLookAndFeel();
  49768. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  49769. ? thumbSize : 0;
  49770. if (vertical)
  49771. {
  49772. lf.drawScrollbar (g, *this,
  49773. 0, thumbAreaStart,
  49774. getWidth(), thumbAreaSize,
  49775. vertical,
  49776. thumbStart, thumb,
  49777. isMouseOver(), isMouseButtonDown());
  49778. }
  49779. else
  49780. {
  49781. lf.drawScrollbar (g, *this,
  49782. thumbAreaStart, 0,
  49783. thumbAreaSize, getHeight(),
  49784. vertical,
  49785. thumbStart, thumb,
  49786. isMouseOver(), isMouseButtonDown());
  49787. }
  49788. }
  49789. }
  49790. void ScrollBar::lookAndFeelChanged()
  49791. {
  49792. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  49793. }
  49794. void ScrollBar::resized()
  49795. {
  49796. const int length = ((vertical) ? getHeight() : getWidth());
  49797. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  49798. : 0;
  49799. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49800. {
  49801. thumbAreaStart = length >> 1;
  49802. thumbAreaSize = 0;
  49803. }
  49804. else
  49805. {
  49806. thumbAreaStart = buttonSize;
  49807. thumbAreaSize = length - (buttonSize << 1);
  49808. }
  49809. if (upButton != 0)
  49810. {
  49811. if (vertical)
  49812. {
  49813. upButton->setBounds (0, 0, getWidth(), buttonSize);
  49814. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  49815. }
  49816. else
  49817. {
  49818. upButton->setBounds (0, 0, buttonSize, getHeight());
  49819. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  49820. }
  49821. }
  49822. updateThumbPosition();
  49823. }
  49824. void ScrollBar::mouseDown (const MouseEvent& e)
  49825. {
  49826. isDraggingThumb = false;
  49827. lastMousePos = vertical ? e.y : e.x;
  49828. dragStartMousePos = lastMousePos;
  49829. dragStartRange = visibleRange.getStart();
  49830. if (dragStartMousePos < thumbStart)
  49831. {
  49832. moveScrollbarInPages (-1);
  49833. startTimer (400);
  49834. }
  49835. else if (dragStartMousePos >= thumbStart + thumbSize)
  49836. {
  49837. moveScrollbarInPages (1);
  49838. startTimer (400);
  49839. }
  49840. else
  49841. {
  49842. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49843. && (thumbAreaSize > thumbSize);
  49844. }
  49845. }
  49846. void ScrollBar::mouseDrag (const MouseEvent& e)
  49847. {
  49848. if (isDraggingThumb)
  49849. {
  49850. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  49851. setCurrentRangeStart (dragStartRange
  49852. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  49853. / (thumbAreaSize - thumbSize));
  49854. }
  49855. else
  49856. {
  49857. lastMousePos = (vertical) ? e.y : e.x;
  49858. }
  49859. }
  49860. void ScrollBar::mouseUp (const MouseEvent&)
  49861. {
  49862. isDraggingThumb = false;
  49863. stopTimer();
  49864. repaint();
  49865. }
  49866. void ScrollBar::mouseWheelMove (const MouseEvent&,
  49867. float wheelIncrementX,
  49868. float wheelIncrementY)
  49869. {
  49870. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  49871. if (increment < 0)
  49872. increment = jmin (increment * 10.0f, -1.0f);
  49873. else if (increment > 0)
  49874. increment = jmax (increment * 10.0f, 1.0f);
  49875. setCurrentRange (visibleRange - singleStepSize * increment);
  49876. }
  49877. void ScrollBar::timerCallback()
  49878. {
  49879. if (isMouseButtonDown())
  49880. {
  49881. startTimer (40);
  49882. if (lastMousePos < thumbStart)
  49883. setCurrentRange (visibleRange - visibleRange.getLength());
  49884. else if (lastMousePos > thumbStart + thumbSize)
  49885. setCurrentRangeStart (visibleRange.getEnd());
  49886. }
  49887. else
  49888. {
  49889. stopTimer();
  49890. }
  49891. }
  49892. bool ScrollBar::keyPressed (const KeyPress& key)
  49893. {
  49894. if (! isVisible())
  49895. return false;
  49896. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  49897. moveScrollbarInSteps (-1);
  49898. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  49899. moveScrollbarInSteps (1);
  49900. else if (key.isKeyCode (KeyPress::pageUpKey))
  49901. moveScrollbarInPages (-1);
  49902. else if (key.isKeyCode (KeyPress::pageDownKey))
  49903. moveScrollbarInPages (1);
  49904. else if (key.isKeyCode (KeyPress::homeKey))
  49905. scrollToTop();
  49906. else if (key.isKeyCode (KeyPress::endKey))
  49907. scrollToBottom();
  49908. else
  49909. return false;
  49910. return true;
  49911. }
  49912. END_JUCE_NAMESPACE
  49913. /*** End of inlined file: juce_ScrollBar.cpp ***/
  49914. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  49915. BEGIN_JUCE_NAMESPACE
  49916. StretchableLayoutManager::StretchableLayoutManager()
  49917. : totalSize (0)
  49918. {
  49919. }
  49920. StretchableLayoutManager::~StretchableLayoutManager()
  49921. {
  49922. }
  49923. void StretchableLayoutManager::clearAllItems()
  49924. {
  49925. items.clear();
  49926. totalSize = 0;
  49927. }
  49928. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  49929. const double minimumSize,
  49930. const double maximumSize,
  49931. const double preferredSize)
  49932. {
  49933. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  49934. if (layout == 0)
  49935. {
  49936. layout = new ItemLayoutProperties();
  49937. layout->itemIndex = itemIndex;
  49938. int i;
  49939. for (i = 0; i < items.size(); ++i)
  49940. if (items.getUnchecked (i)->itemIndex > itemIndex)
  49941. break;
  49942. items.insert (i, layout);
  49943. }
  49944. layout->minSize = minimumSize;
  49945. layout->maxSize = maximumSize;
  49946. layout->preferredSize = preferredSize;
  49947. layout->currentSize = 0;
  49948. }
  49949. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  49950. double& minimumSize,
  49951. double& maximumSize,
  49952. double& preferredSize) const
  49953. {
  49954. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49955. if (layout != 0)
  49956. {
  49957. minimumSize = layout->minSize;
  49958. maximumSize = layout->maxSize;
  49959. preferredSize = layout->preferredSize;
  49960. return true;
  49961. }
  49962. return false;
  49963. }
  49964. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  49965. {
  49966. totalSize = newTotalSize;
  49967. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  49968. }
  49969. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  49970. {
  49971. int pos = 0;
  49972. for (int i = 0; i < itemIndex; ++i)
  49973. {
  49974. const ItemLayoutProperties* const layout = getInfoFor (i);
  49975. if (layout != 0)
  49976. pos += layout->currentSize;
  49977. }
  49978. return pos;
  49979. }
  49980. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  49981. {
  49982. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49983. if (layout != 0)
  49984. return layout->currentSize;
  49985. return 0;
  49986. }
  49987. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  49988. {
  49989. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49990. if (layout != 0)
  49991. return -layout->currentSize / (double) totalSize;
  49992. return 0;
  49993. }
  49994. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  49995. int newPosition)
  49996. {
  49997. for (int i = items.size(); --i >= 0;)
  49998. {
  49999. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50000. if (layout->itemIndex == itemIndex)
  50001. {
  50002. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50003. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50004. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50005. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50006. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50007. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50008. endPos += layout->currentSize;
  50009. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50010. updatePrefSizesToMatchCurrentPositions();
  50011. break;
  50012. }
  50013. }
  50014. }
  50015. void StretchableLayoutManager::layOutComponents (Component** const components,
  50016. int numComponents,
  50017. int x, int y, int w, int h,
  50018. const bool vertically,
  50019. const bool resizeOtherDimension)
  50020. {
  50021. setTotalSize (vertically ? h : w);
  50022. int pos = vertically ? y : x;
  50023. for (int i = 0; i < numComponents; ++i)
  50024. {
  50025. const ItemLayoutProperties* const layout = getInfoFor (i);
  50026. if (layout != 0)
  50027. {
  50028. Component* const c = components[i];
  50029. if (c != 0)
  50030. {
  50031. if (i == numComponents - 1)
  50032. {
  50033. // if it's the last item, crop it to exactly fit the available space..
  50034. if (resizeOtherDimension)
  50035. {
  50036. if (vertically)
  50037. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50038. else
  50039. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50040. }
  50041. else
  50042. {
  50043. if (vertically)
  50044. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50045. else
  50046. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50047. }
  50048. }
  50049. else
  50050. {
  50051. if (resizeOtherDimension)
  50052. {
  50053. if (vertically)
  50054. c->setBounds (x, pos, w, layout->currentSize);
  50055. else
  50056. c->setBounds (pos, y, layout->currentSize, h);
  50057. }
  50058. else
  50059. {
  50060. if (vertically)
  50061. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50062. else
  50063. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50064. }
  50065. }
  50066. }
  50067. pos += layout->currentSize;
  50068. }
  50069. }
  50070. }
  50071. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50072. {
  50073. for (int i = items.size(); --i >= 0;)
  50074. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50075. return items.getUnchecked(i);
  50076. return 0;
  50077. }
  50078. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50079. const int endIndex,
  50080. const int availableSpace,
  50081. int startPos)
  50082. {
  50083. // calculate the total sizes
  50084. int i;
  50085. double totalIdealSize = 0.0;
  50086. int totalMinimums = 0;
  50087. for (i = startIndex; i < endIndex; ++i)
  50088. {
  50089. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50090. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50091. totalMinimums += layout->currentSize;
  50092. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50093. }
  50094. if (totalIdealSize <= 0)
  50095. totalIdealSize = 1.0;
  50096. // now calc the best sizes..
  50097. int extraSpace = availableSpace - totalMinimums;
  50098. while (extraSpace > 0)
  50099. {
  50100. int numWantingMoreSpace = 0;
  50101. int numHavingTakenExtraSpace = 0;
  50102. // first figure out how many comps want a slice of the extra space..
  50103. for (i = startIndex; i < endIndex; ++i)
  50104. {
  50105. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50106. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50107. const int bestSize = jlimit (layout->currentSize,
  50108. jmax (layout->currentSize,
  50109. sizeToRealSize (layout->maxSize, totalSize)),
  50110. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50111. if (bestSize > layout->currentSize)
  50112. ++numWantingMoreSpace;
  50113. }
  50114. // ..share out the extra space..
  50115. for (i = startIndex; i < endIndex; ++i)
  50116. {
  50117. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50118. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50119. int bestSize = jlimit (layout->currentSize,
  50120. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50121. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50122. const int extraWanted = bestSize - layout->currentSize;
  50123. if (extraWanted > 0)
  50124. {
  50125. const int extraAllowed = jmin (extraWanted,
  50126. extraSpace / jmax (1, numWantingMoreSpace));
  50127. if (extraAllowed > 0)
  50128. {
  50129. ++numHavingTakenExtraSpace;
  50130. --numWantingMoreSpace;
  50131. layout->currentSize += extraAllowed;
  50132. extraSpace -= extraAllowed;
  50133. }
  50134. }
  50135. }
  50136. if (numHavingTakenExtraSpace <= 0)
  50137. break;
  50138. }
  50139. // ..and calculate the end position
  50140. for (i = startIndex; i < endIndex; ++i)
  50141. {
  50142. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50143. startPos += layout->currentSize;
  50144. }
  50145. return startPos;
  50146. }
  50147. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50148. const int endIndex) const
  50149. {
  50150. int totalMinimums = 0;
  50151. for (int i = startIndex; i < endIndex; ++i)
  50152. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50153. return totalMinimums;
  50154. }
  50155. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50156. {
  50157. int totalMaximums = 0;
  50158. for (int i = startIndex; i < endIndex; ++i)
  50159. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50160. return totalMaximums;
  50161. }
  50162. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50163. {
  50164. for (int i = 0; i < items.size(); ++i)
  50165. {
  50166. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50167. layout->preferredSize
  50168. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50169. : getItemCurrentAbsoluteSize (i);
  50170. }
  50171. }
  50172. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50173. {
  50174. if (size < 0)
  50175. size *= -totalSpace;
  50176. return roundToInt (size);
  50177. }
  50178. END_JUCE_NAMESPACE
  50179. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50180. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50181. BEGIN_JUCE_NAMESPACE
  50182. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50183. const int itemIndex_,
  50184. const bool isVertical_)
  50185. : layout (layout_),
  50186. itemIndex (itemIndex_),
  50187. isVertical (isVertical_)
  50188. {
  50189. setRepaintsOnMouseActivity (true);
  50190. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50191. : MouseCursor::UpDownResizeCursor));
  50192. }
  50193. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50194. {
  50195. }
  50196. void StretchableLayoutResizerBar::paint (Graphics& g)
  50197. {
  50198. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50199. getWidth(), getHeight(),
  50200. isVertical,
  50201. isMouseOver(),
  50202. isMouseButtonDown());
  50203. }
  50204. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50205. {
  50206. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50207. }
  50208. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50209. {
  50210. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50211. : e.getDistanceFromDragStartY());
  50212. layout->setItemPosition (itemIndex, desiredPos);
  50213. hasBeenMoved();
  50214. }
  50215. void StretchableLayoutResizerBar::hasBeenMoved()
  50216. {
  50217. if (getParentComponent() != 0)
  50218. getParentComponent()->resized();
  50219. }
  50220. END_JUCE_NAMESPACE
  50221. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50222. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50223. BEGIN_JUCE_NAMESPACE
  50224. StretchableObjectResizer::StretchableObjectResizer()
  50225. {
  50226. }
  50227. StretchableObjectResizer::~StretchableObjectResizer()
  50228. {
  50229. }
  50230. void StretchableObjectResizer::addItem (const double size,
  50231. const double minSize, const double maxSize,
  50232. const int order)
  50233. {
  50234. // the order must be >= 0 but less than the maximum integer value.
  50235. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50236. Item* const item = new Item();
  50237. item->size = size;
  50238. item->minSize = minSize;
  50239. item->maxSize = maxSize;
  50240. item->order = order;
  50241. items.add (item);
  50242. }
  50243. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50244. {
  50245. const Item* const it = items [index];
  50246. return it != 0 ? it->size : 0;
  50247. }
  50248. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50249. {
  50250. int order = 0;
  50251. for (;;)
  50252. {
  50253. double currentSize = 0;
  50254. double minSize = 0;
  50255. double maxSize = 0;
  50256. int nextHighestOrder = std::numeric_limits<int>::max();
  50257. for (int i = 0; i < items.size(); ++i)
  50258. {
  50259. const Item* const it = items.getUnchecked(i);
  50260. currentSize += it->size;
  50261. if (it->order <= order)
  50262. {
  50263. minSize += it->minSize;
  50264. maxSize += it->maxSize;
  50265. }
  50266. else
  50267. {
  50268. minSize += it->size;
  50269. maxSize += it->size;
  50270. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50271. }
  50272. }
  50273. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50274. if (thisIterationTarget >= currentSize)
  50275. {
  50276. const double availableExtraSpace = maxSize - currentSize;
  50277. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50278. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50279. for (int i = 0; i < items.size(); ++i)
  50280. {
  50281. Item* const it = items.getUnchecked(i);
  50282. if (it->order <= order)
  50283. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50284. }
  50285. }
  50286. else
  50287. {
  50288. const double amountOfSlack = currentSize - minSize;
  50289. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50290. const double scale = targetAmountOfSlack / amountOfSlack;
  50291. for (int i = 0; i < items.size(); ++i)
  50292. {
  50293. Item* const it = items.getUnchecked(i);
  50294. if (it->order <= order)
  50295. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50296. }
  50297. }
  50298. if (nextHighestOrder < std::numeric_limits<int>::max())
  50299. order = nextHighestOrder;
  50300. else
  50301. break;
  50302. }
  50303. }
  50304. END_JUCE_NAMESPACE
  50305. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50306. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50307. BEGIN_JUCE_NAMESPACE
  50308. TabBarButton::TabBarButton (const String& name,
  50309. TabbedButtonBar* const owner_,
  50310. const int index)
  50311. : Button (name),
  50312. owner (owner_),
  50313. tabIndex (index),
  50314. overlapPixels (0)
  50315. {
  50316. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50317. setComponentEffect (&shadow);
  50318. setWantsKeyboardFocus (false);
  50319. }
  50320. TabBarButton::~TabBarButton()
  50321. {
  50322. }
  50323. void TabBarButton::paintButton (Graphics& g,
  50324. bool isMouseOverButton,
  50325. bool isButtonDown)
  50326. {
  50327. int x, y, w, h;
  50328. getActiveArea (x, y, w, h);
  50329. g.setOrigin (x, y);
  50330. getLookAndFeel()
  50331. .drawTabButton (g, w, h,
  50332. owner->getTabBackgroundColour (tabIndex),
  50333. tabIndex, getButtonText(), *this,
  50334. owner->getOrientation(),
  50335. isMouseOverButton, isButtonDown,
  50336. getToggleState());
  50337. }
  50338. void TabBarButton::clicked (const ModifierKeys& mods)
  50339. {
  50340. if (mods.isPopupMenu())
  50341. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50342. else
  50343. owner->setCurrentTabIndex (tabIndex);
  50344. }
  50345. bool TabBarButton::hitTest (int mx, int my)
  50346. {
  50347. int x, y, w, h;
  50348. getActiveArea (x, y, w, h);
  50349. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50350. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50351. {
  50352. if (((unsigned int) mx) < (unsigned int) getWidth()
  50353. && my >= y + overlapPixels
  50354. && my < y + h - overlapPixels)
  50355. return true;
  50356. }
  50357. else
  50358. {
  50359. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50360. && ((unsigned int) my) < (unsigned int) getHeight())
  50361. return true;
  50362. }
  50363. Path p;
  50364. getLookAndFeel()
  50365. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50366. owner->getOrientation(),
  50367. false, false, getToggleState());
  50368. return p.contains ((float) (mx - x),
  50369. (float) (my - y));
  50370. }
  50371. int TabBarButton::getBestTabLength (const int depth)
  50372. {
  50373. return jlimit (depth * 2,
  50374. depth * 7,
  50375. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50376. }
  50377. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50378. {
  50379. x = 0;
  50380. y = 0;
  50381. int r = getWidth();
  50382. int b = getHeight();
  50383. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50384. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50385. r -= spaceAroundImage;
  50386. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50387. x += spaceAroundImage;
  50388. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50389. y += spaceAroundImage;
  50390. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50391. b -= spaceAroundImage;
  50392. w = r - x;
  50393. h = b - y;
  50394. }
  50395. class TabAreaBehindFrontButtonComponent : public Component
  50396. {
  50397. public:
  50398. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50399. : owner (owner_)
  50400. {
  50401. setInterceptsMouseClicks (false, false);
  50402. }
  50403. ~TabAreaBehindFrontButtonComponent()
  50404. {
  50405. }
  50406. void paint (Graphics& g)
  50407. {
  50408. getLookAndFeel()
  50409. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50410. *owner, owner->getOrientation());
  50411. }
  50412. void enablementChanged()
  50413. {
  50414. repaint();
  50415. }
  50416. private:
  50417. TabbedButtonBar* const owner;
  50418. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50419. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50420. };
  50421. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50422. : orientation (orientation_),
  50423. currentTabIndex (-1),
  50424. extraTabsButton (0)
  50425. {
  50426. setInterceptsMouseClicks (false, true);
  50427. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50428. setFocusContainer (true);
  50429. }
  50430. TabbedButtonBar::~TabbedButtonBar()
  50431. {
  50432. deleteAllChildren();
  50433. }
  50434. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50435. {
  50436. orientation = newOrientation;
  50437. for (int i = getNumChildComponents(); --i >= 0;)
  50438. getChildComponent (i)->resized();
  50439. resized();
  50440. }
  50441. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50442. {
  50443. return new TabBarButton (name, this, index);
  50444. }
  50445. void TabbedButtonBar::clearTabs()
  50446. {
  50447. tabs.clear();
  50448. tabColours.clear();
  50449. currentTabIndex = -1;
  50450. deleteAndZero (extraTabsButton);
  50451. removeChildComponent (behindFrontTab);
  50452. deleteAllChildren();
  50453. addChildComponent (behindFrontTab);
  50454. setCurrentTabIndex (-1);
  50455. }
  50456. void TabbedButtonBar::addTab (const String& tabName,
  50457. const Colour& tabBackgroundColour,
  50458. int insertIndex)
  50459. {
  50460. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50461. if (tabName.isNotEmpty())
  50462. {
  50463. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50464. insertIndex = tabs.size();
  50465. for (int i = tabs.size(); --i >= insertIndex;)
  50466. {
  50467. TabBarButton* const tb = getTabButton (i);
  50468. if (tb != 0)
  50469. tb->tabIndex++;
  50470. }
  50471. tabs.insert (insertIndex, tabName);
  50472. tabColours.insert (insertIndex, tabBackgroundColour);
  50473. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50474. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50475. addAndMakeVisible (tb, insertIndex);
  50476. resized();
  50477. if (currentTabIndex < 0)
  50478. setCurrentTabIndex (0);
  50479. }
  50480. }
  50481. void TabbedButtonBar::setTabName (const int tabIndex,
  50482. const String& newName)
  50483. {
  50484. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50485. && tabs[tabIndex] != newName)
  50486. {
  50487. tabs.set (tabIndex, newName);
  50488. TabBarButton* const tb = getTabButton (tabIndex);
  50489. if (tb != 0)
  50490. tb->setButtonText (newName);
  50491. resized();
  50492. }
  50493. }
  50494. void TabbedButtonBar::removeTab (const int tabIndex)
  50495. {
  50496. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50497. {
  50498. const int oldTabIndex = currentTabIndex;
  50499. if (currentTabIndex == tabIndex)
  50500. currentTabIndex = -1;
  50501. tabs.remove (tabIndex);
  50502. tabColours.remove (tabIndex);
  50503. delete getTabButton (tabIndex);
  50504. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50505. {
  50506. TabBarButton* const tb = getTabButton (i);
  50507. if (tb != 0)
  50508. tb->tabIndex--;
  50509. }
  50510. resized();
  50511. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50512. }
  50513. }
  50514. void TabbedButtonBar::moveTab (const int currentIndex,
  50515. const int newIndex)
  50516. {
  50517. tabs.move (currentIndex, newIndex);
  50518. tabColours.move (currentIndex, newIndex);
  50519. resized();
  50520. }
  50521. int TabbedButtonBar::getNumTabs() const
  50522. {
  50523. return tabs.size();
  50524. }
  50525. const StringArray TabbedButtonBar::getTabNames() const
  50526. {
  50527. return tabs;
  50528. }
  50529. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50530. {
  50531. if (currentTabIndex != newIndex)
  50532. {
  50533. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50534. newIndex = -1;
  50535. currentTabIndex = newIndex;
  50536. for (int i = 0; i < getNumChildComponents(); ++i)
  50537. {
  50538. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50539. if (tb != 0)
  50540. tb->setToggleState (tb->tabIndex == newIndex, false);
  50541. }
  50542. resized();
  50543. if (sendChangeMessage_)
  50544. sendChangeMessage (this);
  50545. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50546. }
  50547. }
  50548. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50549. {
  50550. for (int i = getNumChildComponents(); --i >= 0;)
  50551. {
  50552. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50553. if (tb != 0 && tb->tabIndex == index)
  50554. return tb;
  50555. }
  50556. return 0;
  50557. }
  50558. void TabbedButtonBar::lookAndFeelChanged()
  50559. {
  50560. deleteAndZero (extraTabsButton);
  50561. resized();
  50562. }
  50563. void TabbedButtonBar::resized()
  50564. {
  50565. const double minimumScale = 0.7;
  50566. int depth = getWidth();
  50567. int length = getHeight();
  50568. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50569. swapVariables (depth, length);
  50570. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50571. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50572. int i, totalLength = overlap;
  50573. int numVisibleButtons = tabs.size();
  50574. for (i = 0; i < getNumChildComponents(); ++i)
  50575. {
  50576. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50577. if (tb != 0)
  50578. {
  50579. totalLength += tb->getBestTabLength (depth) - overlap;
  50580. tb->overlapPixels = overlap / 2;
  50581. }
  50582. }
  50583. double scale = 1.0;
  50584. if (totalLength > length)
  50585. scale = jmax (minimumScale, length / (double) totalLength);
  50586. const bool isTooBig = totalLength * scale > length;
  50587. int tabsButtonPos = 0;
  50588. if (isTooBig)
  50589. {
  50590. if (extraTabsButton == 0)
  50591. {
  50592. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50593. extraTabsButton->addButtonListener (this);
  50594. extraTabsButton->setAlwaysOnTop (true);
  50595. extraTabsButton->setTriggeredOnMouseDown (true);
  50596. }
  50597. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50598. extraTabsButton->setSize (buttonSize, buttonSize);
  50599. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50600. {
  50601. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50602. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50603. }
  50604. else
  50605. {
  50606. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50607. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50608. }
  50609. totalLength = 0;
  50610. for (i = 0; i < tabs.size(); ++i)
  50611. {
  50612. TabBarButton* const tb = getTabButton (i);
  50613. if (tb != 0)
  50614. {
  50615. const int newLength = totalLength + tb->getBestTabLength (depth);
  50616. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50617. {
  50618. totalLength += overlap;
  50619. break;
  50620. }
  50621. numVisibleButtons = i + 1;
  50622. totalLength = newLength - overlap;
  50623. }
  50624. }
  50625. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50626. }
  50627. else
  50628. {
  50629. deleteAndZero (extraTabsButton);
  50630. }
  50631. int pos = 0;
  50632. TabBarButton* frontTab = 0;
  50633. for (i = 0; i < tabs.size(); ++i)
  50634. {
  50635. TabBarButton* const tb = getTabButton (i);
  50636. if (tb != 0)
  50637. {
  50638. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50639. if (i < numVisibleButtons)
  50640. {
  50641. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50642. tb->setBounds (pos, 0, bestLength, getHeight());
  50643. else
  50644. tb->setBounds (0, pos, getWidth(), bestLength);
  50645. tb->toBack();
  50646. if (tb->tabIndex == currentTabIndex)
  50647. frontTab = tb;
  50648. tb->setVisible (true);
  50649. }
  50650. else
  50651. {
  50652. tb->setVisible (false);
  50653. }
  50654. pos += bestLength - overlap;
  50655. }
  50656. }
  50657. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  50658. if (frontTab != 0)
  50659. {
  50660. frontTab->toFront (false);
  50661. behindFrontTab->toBehind (frontTab);
  50662. }
  50663. }
  50664. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50665. {
  50666. return tabColours [tabIndex];
  50667. }
  50668. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50669. {
  50670. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50671. && tabColours [tabIndex] != newColour)
  50672. {
  50673. tabColours.set (tabIndex, newColour);
  50674. repaint();
  50675. }
  50676. }
  50677. void TabbedButtonBar::buttonClicked (Button* button)
  50678. {
  50679. if (extraTabsButton == button)
  50680. {
  50681. PopupMenu m;
  50682. for (int i = 0; i < tabs.size(); ++i)
  50683. {
  50684. TabBarButton* const tb = getTabButton (i);
  50685. if (tb != 0 && ! tb->isVisible())
  50686. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50687. }
  50688. const int res = m.showAt (extraTabsButton);
  50689. if (res != 0)
  50690. setCurrentTabIndex (res - 1);
  50691. }
  50692. }
  50693. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50694. {
  50695. }
  50696. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50697. {
  50698. }
  50699. END_JUCE_NAMESPACE
  50700. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50701. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50702. BEGIN_JUCE_NAMESPACE
  50703. class TabCompButtonBar : public TabbedButtonBar
  50704. {
  50705. public:
  50706. TabCompButtonBar (TabbedComponent* const owner_,
  50707. const TabbedButtonBar::Orientation orientation_)
  50708. : TabbedButtonBar (orientation_),
  50709. owner (owner_)
  50710. {
  50711. }
  50712. ~TabCompButtonBar()
  50713. {
  50714. }
  50715. void currentTabChanged (int newCurrentTabIndex,
  50716. const String& newTabName)
  50717. {
  50718. owner->changeCallback (newCurrentTabIndex, newTabName);
  50719. }
  50720. void popupMenuClickOnTab (int tabIndex,
  50721. const String& tabName)
  50722. {
  50723. owner->popupMenuClickOnTab (tabIndex, tabName);
  50724. }
  50725. const Colour getTabBackgroundColour (const int tabIndex)
  50726. {
  50727. return owner->tabs->getTabBackgroundColour (tabIndex);
  50728. }
  50729. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50730. {
  50731. return owner->createTabButton (tabName, tabIndex);
  50732. }
  50733. juce_UseDebuggingNewOperator
  50734. private:
  50735. TabbedComponent* const owner;
  50736. TabCompButtonBar (const TabCompButtonBar&);
  50737. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50738. };
  50739. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  50740. : panelComponent (0),
  50741. tabDepth (30),
  50742. outlineThickness (1),
  50743. edgeIndent (0)
  50744. {
  50745. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  50746. }
  50747. TabbedComponent::~TabbedComponent()
  50748. {
  50749. clearTabs();
  50750. delete tabs;
  50751. }
  50752. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  50753. {
  50754. tabs->setOrientation (orientation);
  50755. resized();
  50756. }
  50757. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  50758. {
  50759. return tabs->getOrientation();
  50760. }
  50761. void TabbedComponent::setTabBarDepth (const int newDepth)
  50762. {
  50763. if (tabDepth != newDepth)
  50764. {
  50765. tabDepth = newDepth;
  50766. resized();
  50767. }
  50768. }
  50769. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  50770. {
  50771. return new TabBarButton (tabName, tabs, tabIndex);
  50772. }
  50773. void TabbedComponent::clearTabs()
  50774. {
  50775. if (panelComponent != 0)
  50776. {
  50777. panelComponent->setVisible (false);
  50778. removeChildComponent (panelComponent);
  50779. panelComponent = 0;
  50780. }
  50781. tabs->clearTabs();
  50782. for (int i = contentComponents.size(); --i >= 0;)
  50783. {
  50784. Component* const c = contentComponents.getUnchecked(i);
  50785. // be careful not to delete these components until they've been removed from the tab component
  50786. jassert (c == 0 || c->isValidComponent());
  50787. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50788. delete c;
  50789. }
  50790. contentComponents.clear();
  50791. }
  50792. void TabbedComponent::addTab (const String& tabName,
  50793. const Colour& tabBackgroundColour,
  50794. Component* const contentComponent,
  50795. const bool deleteComponentWhenNotNeeded,
  50796. const int insertIndex)
  50797. {
  50798. contentComponents.insert (insertIndex, contentComponent);
  50799. if (contentComponent != 0)
  50800. contentComponent->getProperties().set ("deleteByTabComp_", deleteComponentWhenNotNeeded);
  50801. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  50802. }
  50803. void TabbedComponent::setTabName (const int tabIndex,
  50804. const String& newName)
  50805. {
  50806. tabs->setTabName (tabIndex, newName);
  50807. }
  50808. void TabbedComponent::removeTab (const int tabIndex)
  50809. {
  50810. Component* const c = contentComponents [tabIndex];
  50811. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50812. {
  50813. if (c == panelComponent)
  50814. panelComponent = 0;
  50815. delete c;
  50816. }
  50817. contentComponents.remove (tabIndex);
  50818. tabs->removeTab (tabIndex);
  50819. }
  50820. int TabbedComponent::getNumTabs() const
  50821. {
  50822. return tabs->getNumTabs();
  50823. }
  50824. const StringArray TabbedComponent::getTabNames() const
  50825. {
  50826. return tabs->getTabNames();
  50827. }
  50828. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  50829. {
  50830. return contentComponents [tabIndex];
  50831. }
  50832. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  50833. {
  50834. return tabs->getTabBackgroundColour (tabIndex);
  50835. }
  50836. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50837. {
  50838. tabs->setTabBackgroundColour (tabIndex, newColour);
  50839. if (getCurrentTabIndex() == tabIndex)
  50840. repaint();
  50841. }
  50842. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  50843. {
  50844. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  50845. }
  50846. int TabbedComponent::getCurrentTabIndex() const
  50847. {
  50848. return tabs->getCurrentTabIndex();
  50849. }
  50850. const String& TabbedComponent::getCurrentTabName() const
  50851. {
  50852. return tabs->getCurrentTabName();
  50853. }
  50854. void TabbedComponent::setOutline (int thickness)
  50855. {
  50856. outlineThickness = thickness;
  50857. repaint();
  50858. }
  50859. void TabbedComponent::setIndent (const int indentThickness)
  50860. {
  50861. edgeIndent = indentThickness;
  50862. }
  50863. void TabbedComponent::paint (Graphics& g)
  50864. {
  50865. g.fillAll (findColour (backgroundColourId));
  50866. const TabbedButtonBar::Orientation o = getOrientation();
  50867. int x = 0;
  50868. int y = 0;
  50869. int r = getWidth();
  50870. int b = getHeight();
  50871. if (o == TabbedButtonBar::TabsAtTop)
  50872. y += tabDepth;
  50873. else if (o == TabbedButtonBar::TabsAtBottom)
  50874. b -= tabDepth;
  50875. else if (o == TabbedButtonBar::TabsAtLeft)
  50876. x += tabDepth;
  50877. else if (o == TabbedButtonBar::TabsAtRight)
  50878. r -= tabDepth;
  50879. g.reduceClipRegion (x, y, r - x, b - y);
  50880. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  50881. if (outlineThickness > 0)
  50882. {
  50883. if (o == TabbedButtonBar::TabsAtTop)
  50884. --y;
  50885. else if (o == TabbedButtonBar::TabsAtBottom)
  50886. ++b;
  50887. else if (o == TabbedButtonBar::TabsAtLeft)
  50888. --x;
  50889. else if (o == TabbedButtonBar::TabsAtRight)
  50890. ++r;
  50891. g.setColour (findColour (outlineColourId));
  50892. g.drawRect (x, y, r - x, b - y, outlineThickness);
  50893. }
  50894. }
  50895. void TabbedComponent::resized()
  50896. {
  50897. const TabbedButtonBar::Orientation o = getOrientation();
  50898. const int indent = edgeIndent + outlineThickness;
  50899. BorderSize indents (indent);
  50900. if (o == TabbedButtonBar::TabsAtTop)
  50901. {
  50902. tabs->setBounds (0, 0, getWidth(), tabDepth);
  50903. indents.setTop (tabDepth + edgeIndent);
  50904. }
  50905. else if (o == TabbedButtonBar::TabsAtBottom)
  50906. {
  50907. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  50908. indents.setBottom (tabDepth + edgeIndent);
  50909. }
  50910. else if (o == TabbedButtonBar::TabsAtLeft)
  50911. {
  50912. tabs->setBounds (0, 0, tabDepth, getHeight());
  50913. indents.setLeft (tabDepth + edgeIndent);
  50914. }
  50915. else if (o == TabbedButtonBar::TabsAtRight)
  50916. {
  50917. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  50918. indents.setRight (tabDepth + edgeIndent);
  50919. }
  50920. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  50921. for (int i = contentComponents.size(); --i >= 0;)
  50922. if (contentComponents.getUnchecked (i) != 0)
  50923. contentComponents.getUnchecked (i)->setBounds (bounds);
  50924. }
  50925. void TabbedComponent::lookAndFeelChanged()
  50926. {
  50927. for (int i = contentComponents.size(); --i >= 0;)
  50928. if (contentComponents.getUnchecked (i) != 0)
  50929. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  50930. }
  50931. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  50932. const String& newTabName)
  50933. {
  50934. if (panelComponent != 0)
  50935. {
  50936. panelComponent->setVisible (false);
  50937. removeChildComponent (panelComponent);
  50938. panelComponent = 0;
  50939. }
  50940. if (getCurrentTabIndex() >= 0)
  50941. {
  50942. panelComponent = contentComponents [getCurrentTabIndex()];
  50943. if (panelComponent != 0)
  50944. {
  50945. // do these ops as two stages instead of addAndMakeVisible() so that the
  50946. // component has always got a parent when it gets the visibilityChanged() callback
  50947. addChildComponent (panelComponent);
  50948. panelComponent->setVisible (true);
  50949. panelComponent->toFront (true);
  50950. }
  50951. repaint();
  50952. }
  50953. resized();
  50954. currentTabChanged (newCurrentTabIndex, newTabName);
  50955. }
  50956. void TabbedComponent::currentTabChanged (const int, const String&)
  50957. {
  50958. }
  50959. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  50960. {
  50961. }
  50962. END_JUCE_NAMESPACE
  50963. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  50964. /*** Start of inlined file: juce_Viewport.cpp ***/
  50965. BEGIN_JUCE_NAMESPACE
  50966. Viewport::Viewport (const String& componentName)
  50967. : Component (componentName),
  50968. contentComp (0),
  50969. scrollBarThickness (0),
  50970. singleStepX (16),
  50971. singleStepY (16),
  50972. showHScrollbar (true),
  50973. showVScrollbar (true)
  50974. {
  50975. // content holder is used to clip the contents so they don't overlap the scrollbars
  50976. addAndMakeVisible (contentHolder = new Component());
  50977. contentHolder->setInterceptsMouseClicks (false, true);
  50978. verticalScrollBar = new ScrollBar (true);
  50979. horizontalScrollBar = new ScrollBar (false);
  50980. addChildComponent (verticalScrollBar);
  50981. addChildComponent (horizontalScrollBar);
  50982. verticalScrollBar->addListener (this);
  50983. horizontalScrollBar->addListener (this);
  50984. setInterceptsMouseClicks (false, true);
  50985. setWantsKeyboardFocus (true);
  50986. }
  50987. Viewport::~Viewport()
  50988. {
  50989. contentHolder->deleteAllChildren();
  50990. deleteAllChildren();
  50991. }
  50992. void Viewport::visibleAreaChanged (int, int, int, int)
  50993. {
  50994. }
  50995. void Viewport::setViewedComponent (Component* const newViewedComponent)
  50996. {
  50997. if (contentComp.getComponent() != newViewedComponent)
  50998. {
  50999. {
  51000. ScopedPointer<Component> oldCompDeleter (contentComp);
  51001. contentComp = 0;
  51002. }
  51003. contentComp = newViewedComponent;
  51004. if (contentComp != 0)
  51005. {
  51006. contentComp->setTopLeftPosition (0, 0);
  51007. contentHolder->addAndMakeVisible (contentComp);
  51008. contentComp->addComponentListener (this);
  51009. }
  51010. updateVisibleRegion();
  51011. }
  51012. }
  51013. int Viewport::getMaximumVisibleWidth() const throw()
  51014. {
  51015. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51016. }
  51017. int Viewport::getMaximumVisibleHeight() const throw()
  51018. {
  51019. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51020. }
  51021. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51022. {
  51023. if (contentComp != 0)
  51024. contentComp->setTopLeftPosition (-xPixelsOffset,
  51025. -yPixelsOffset);
  51026. }
  51027. void Viewport::setViewPositionProportionately (const double x, const double y)
  51028. {
  51029. if (contentComp != 0)
  51030. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51031. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51032. }
  51033. bool Viewport::autoScroll (int mouseX, int mouseY, int activeBorderThickness, int maximumSpeed)
  51034. {
  51035. if (contentComp != 0)
  51036. {
  51037. int dx = 0, dy = 0;
  51038. if (horizontalScrollBar->isVisible())
  51039. {
  51040. if (mouseX < activeBorderThickness)
  51041. dx = activeBorderThickness - mouseX;
  51042. else if (mouseX >= contentHolder->getWidth() - activeBorderThickness)
  51043. dx = (contentHolder->getWidth() - activeBorderThickness) - mouseX;
  51044. if (dx < 0)
  51045. dx = jmax (dx, -maximumSpeed, contentHolder->getWidth() - contentComp->getRight());
  51046. else
  51047. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51048. }
  51049. if (verticalScrollBar->isVisible())
  51050. {
  51051. if (mouseY < activeBorderThickness)
  51052. dy = activeBorderThickness - mouseY;
  51053. else if (mouseY >= contentHolder->getHeight() - activeBorderThickness)
  51054. dy = (contentHolder->getHeight() - activeBorderThickness) - mouseY;
  51055. if (dy < 0)
  51056. dy = jmax (dy, -maximumSpeed, contentHolder->getHeight() - contentComp->getBottom());
  51057. else
  51058. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51059. }
  51060. if (dx != 0 || dy != 0)
  51061. {
  51062. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51063. contentComp->getY() + dy);
  51064. return true;
  51065. }
  51066. }
  51067. return false;
  51068. }
  51069. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51070. {
  51071. updateVisibleRegion();
  51072. }
  51073. void Viewport::resized()
  51074. {
  51075. updateVisibleRegion();
  51076. }
  51077. void Viewport::updateVisibleRegion()
  51078. {
  51079. if (contentComp != 0)
  51080. {
  51081. Rectangle<int> newViewPos;
  51082. newViewPos.setPosition (-contentComp->getPosition());
  51083. if (newViewPos.getX() == 0 && newViewPos.getY() == 0
  51084. && contentComp->getWidth() <= getWidth()
  51085. && contentComp->getHeight() <= getHeight())
  51086. {
  51087. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51088. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51089. }
  51090. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  51091. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51092. horizontalScrollBar->setSingleStepSize (singleStepX);
  51093. if (! (contentComp->getWidth() > 0 && showHScrollbar && getHeight() > getScrollBarThickness()))
  51094. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51095. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  51096. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51097. verticalScrollBar->setSingleStepSize (singleStepY);
  51098. if (! (contentComp->getHeight() > 0 && showVScrollbar && getWidth() > getScrollBarThickness()))
  51099. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51100. if (verticalScrollBar->isVisible())
  51101. {
  51102. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51103. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51104. verticalScrollBar
  51105. ->setBounds (getMaximumVisibleWidth(), 0,
  51106. getScrollBarThickness(), getMaximumVisibleHeight());
  51107. }
  51108. if (horizontalScrollBar->isVisible())
  51109. {
  51110. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51111. horizontalScrollBar
  51112. ->setBounds (0, getMaximumVisibleHeight(),
  51113. getMaximumVisibleWidth(), getScrollBarThickness());
  51114. }
  51115. contentHolder->setSize (getMaximumVisibleWidth(),
  51116. getMaximumVisibleHeight());
  51117. newViewPos.setSize (jmin (contentComp->getRight(), getMaximumVisibleWidth()),
  51118. jmin (contentComp->getBottom(), getMaximumVisibleHeight()));
  51119. if (lastViewPos != newViewPos)
  51120. {
  51121. lastViewPos = newViewPos;
  51122. visibleAreaChanged (newViewPos.getX(), newViewPos.getY(), newViewPos.getWidth(), newViewPos.getHeight());
  51123. }
  51124. horizontalScrollBar->handleUpdateNowIfNeeded();
  51125. verticalScrollBar->handleUpdateNowIfNeeded();
  51126. }
  51127. else
  51128. {
  51129. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51130. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51131. }
  51132. }
  51133. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51134. {
  51135. singleStepX = stepX;
  51136. singleStepY = stepY;
  51137. updateVisibleRegion();
  51138. }
  51139. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51140. const bool showHorizontalScrollbarIfNeeded)
  51141. {
  51142. showVScrollbar = showVerticalScrollbarIfNeeded;
  51143. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51144. updateVisibleRegion();
  51145. }
  51146. void Viewport::setScrollBarThickness (const int thickness)
  51147. {
  51148. scrollBarThickness = thickness;
  51149. updateVisibleRegion();
  51150. }
  51151. int Viewport::getScrollBarThickness() const throw()
  51152. {
  51153. return (scrollBarThickness > 0) ? scrollBarThickness
  51154. : getLookAndFeel().getDefaultScrollbarWidth();
  51155. }
  51156. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51157. {
  51158. verticalScrollBar->setButtonVisibility (buttonsVisible);
  51159. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  51160. }
  51161. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51162. {
  51163. if (scrollBarThatHasMoved == horizontalScrollBar)
  51164. {
  51165. setViewPosition (roundToInt (newRangeStart), getViewPositionY());
  51166. }
  51167. else if (scrollBarThatHasMoved == verticalScrollBar)
  51168. {
  51169. setViewPosition (getViewPositionX(), roundToInt (newRangeStart));
  51170. }
  51171. }
  51172. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51173. {
  51174. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51175. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51176. }
  51177. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51178. {
  51179. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51180. {
  51181. const bool hasVertBar = verticalScrollBar->isVisible();
  51182. const bool hasHorzBar = horizontalScrollBar->isVisible();
  51183. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51184. {
  51185. if (wheelIncrementX == 0 && ! hasVertBar)
  51186. wheelIncrementX = wheelIncrementY;
  51187. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  51188. wheelIncrementX, wheelIncrementY);
  51189. return true;
  51190. }
  51191. else if (hasVertBar && wheelIncrementY != 0)
  51192. {
  51193. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  51194. wheelIncrementX, wheelIncrementY);
  51195. return true;
  51196. }
  51197. }
  51198. return false;
  51199. }
  51200. bool Viewport::keyPressed (const KeyPress& key)
  51201. {
  51202. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51203. || key.isKeyCode (KeyPress::downKey)
  51204. || key.isKeyCode (KeyPress::pageUpKey)
  51205. || key.isKeyCode (KeyPress::pageDownKey)
  51206. || key.isKeyCode (KeyPress::homeKey)
  51207. || key.isKeyCode (KeyPress::endKey);
  51208. if (verticalScrollBar->isVisible() && isUpDownKey)
  51209. return verticalScrollBar->keyPressed (key);
  51210. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51211. || key.isKeyCode (KeyPress::rightKey);
  51212. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  51213. return horizontalScrollBar->keyPressed (key);
  51214. return false;
  51215. }
  51216. END_JUCE_NAMESPACE
  51217. /*** End of inlined file: juce_Viewport.cpp ***/
  51218. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51219. BEGIN_JUCE_NAMESPACE
  51220. static const Colour createBaseColour (const Colour& buttonColour,
  51221. const bool hasKeyboardFocus,
  51222. const bool isMouseOverButton,
  51223. const bool isButtonDown) throw()
  51224. {
  51225. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51226. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51227. if (isButtonDown)
  51228. return baseColour.contrasting (0.2f);
  51229. else if (isMouseOverButton)
  51230. return baseColour.contrasting (0.1f);
  51231. return baseColour;
  51232. }
  51233. LookAndFeel::LookAndFeel()
  51234. {
  51235. /* if this fails it means you're trying to create a LookAndFeel object before
  51236. the static Colours have been initialised. That ain't gonna work. It probably
  51237. means that you're using a static LookAndFeel object and that your compiler has
  51238. decided to intialise it before the Colours class.
  51239. */
  51240. jassert (Colours::white == Colour (0xffffffff));
  51241. // set up the standard set of colours..
  51242. const int textButtonColour = 0xffbbbbff;
  51243. const int textHighlightColour = 0x401111ee;
  51244. const int standardOutlineColour = 0xb2808080;
  51245. static const int standardColours[] =
  51246. {
  51247. TextButton::buttonColourId, textButtonColour,
  51248. TextButton::buttonOnColourId, 0xff4444ff,
  51249. TextButton::textColourOnId, 0xff000000,
  51250. TextButton::textColourOffId, 0xff000000,
  51251. ComboBox::buttonColourId, 0xffbbbbff,
  51252. ComboBox::outlineColourId, standardOutlineColour,
  51253. ToggleButton::textColourId, 0xff000000,
  51254. TextEditor::backgroundColourId, 0xffffffff,
  51255. TextEditor::textColourId, 0xff000000,
  51256. TextEditor::highlightColourId, textHighlightColour,
  51257. TextEditor::highlightedTextColourId, 0xff000000,
  51258. TextEditor::caretColourId, 0xff000000,
  51259. TextEditor::outlineColourId, 0x00000000,
  51260. TextEditor::focusedOutlineColourId, textButtonColour,
  51261. TextEditor::shadowColourId, 0x38000000,
  51262. Label::backgroundColourId, 0x00000000,
  51263. Label::textColourId, 0xff000000,
  51264. Label::outlineColourId, 0x00000000,
  51265. ScrollBar::backgroundColourId, 0x00000000,
  51266. ScrollBar::thumbColourId, 0xffffffff,
  51267. ScrollBar::trackColourId, 0xffffffff,
  51268. TreeView::linesColourId, 0x4c000000,
  51269. TreeView::backgroundColourId, 0x00000000,
  51270. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51271. PopupMenu::backgroundColourId, 0xffffffff,
  51272. PopupMenu::textColourId, 0xff000000,
  51273. PopupMenu::headerTextColourId, 0xff000000,
  51274. PopupMenu::highlightedTextColourId, 0xffffffff,
  51275. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51276. ComboBox::textColourId, 0xff000000,
  51277. ComboBox::backgroundColourId, 0xffffffff,
  51278. ComboBox::arrowColourId, 0x99000000,
  51279. ListBox::backgroundColourId, 0xffffffff,
  51280. ListBox::outlineColourId, standardOutlineColour,
  51281. ListBox::textColourId, 0xff000000,
  51282. Slider::backgroundColourId, 0x00000000,
  51283. Slider::thumbColourId, textButtonColour,
  51284. Slider::trackColourId, 0x7fffffff,
  51285. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51286. Slider::rotarySliderOutlineColourId, 0x66000000,
  51287. Slider::textBoxTextColourId, 0xff000000,
  51288. Slider::textBoxBackgroundColourId, 0xffffffff,
  51289. Slider::textBoxHighlightColourId, textHighlightColour,
  51290. Slider::textBoxOutlineColourId, standardOutlineColour,
  51291. ResizableWindow::backgroundColourId, 0xff777777,
  51292. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51293. AlertWindow::backgroundColourId, 0xffededed,
  51294. AlertWindow::textColourId, 0xff000000,
  51295. AlertWindow::outlineColourId, 0xff666666,
  51296. ProgressBar::backgroundColourId, 0xffeeeeee,
  51297. ProgressBar::foregroundColourId, 0xffaaaaee,
  51298. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51299. TooltipWindow::textColourId, 0xff000000,
  51300. TooltipWindow::outlineColourId, 0x4c000000,
  51301. TabbedComponent::backgroundColourId, 0x00000000,
  51302. TabbedComponent::outlineColourId, 0xff777777,
  51303. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51304. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51305. Toolbar::backgroundColourId, 0xfff6f8f9,
  51306. Toolbar::separatorColourId, 0x4c000000,
  51307. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51308. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51309. Toolbar::labelTextColourId, 0xff000000,
  51310. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51311. HyperlinkButton::textColourId, 0xcc1111ee,
  51312. GroupComponent::outlineColourId, 0x66000000,
  51313. GroupComponent::textColourId, 0xff000000,
  51314. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51315. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51316. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51317. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51318. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51319. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51320. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51321. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51322. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51323. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51324. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51325. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51326. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51327. CodeEditorComponent::caretColourId, 0xff000000,
  51328. CodeEditorComponent::highlightColourId, textHighlightColour,
  51329. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51330. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51331. ColourSelector::labelTextColourId, 0xff000000,
  51332. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51333. KeyMappingEditorComponent::textColourId, 0xff000000,
  51334. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51335. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51336. };
  51337. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51338. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51339. static String defaultSansName, defaultSerifName, defaultFixedName;
  51340. if (defaultSansName.isEmpty())
  51341. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51342. defaultSans = defaultSansName;
  51343. defaultSerif = defaultSerifName;
  51344. defaultFixed = defaultFixedName;
  51345. }
  51346. LookAndFeel::~LookAndFeel()
  51347. {
  51348. }
  51349. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51350. {
  51351. const int index = colourIds.indexOf (colourId);
  51352. if (index >= 0)
  51353. return colours [index];
  51354. jassertfalse
  51355. return Colours::black;
  51356. }
  51357. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51358. {
  51359. const int index = colourIds.indexOf (colourId);
  51360. if (index >= 0)
  51361. colours.set (index, colour);
  51362. colourIds.add (colourId);
  51363. colours.add (colour);
  51364. }
  51365. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51366. {
  51367. return colourIds.contains (colourId);
  51368. }
  51369. static LookAndFeel* defaultLF = 0;
  51370. static LookAndFeel* currentDefaultLF = 0;
  51371. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51372. {
  51373. // if this happens, your app hasn't initialised itself properly.. if you're
  51374. // trying to hack your own main() function, have a look at
  51375. // JUCEApplication::initialiseForGUI()
  51376. jassert (currentDefaultLF != 0);
  51377. return *currentDefaultLF;
  51378. }
  51379. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51380. {
  51381. if (newDefaultLookAndFeel == 0)
  51382. {
  51383. if (defaultLF == 0)
  51384. defaultLF = new LookAndFeel();
  51385. newDefaultLookAndFeel = defaultLF;
  51386. }
  51387. currentDefaultLF = newDefaultLookAndFeel;
  51388. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51389. {
  51390. Component* const c = Desktop::getInstance().getComponent (i);
  51391. if (c != 0)
  51392. c->sendLookAndFeelChange();
  51393. }
  51394. }
  51395. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51396. {
  51397. if (currentDefaultLF == defaultLF)
  51398. currentDefaultLF = 0;
  51399. deleteAndZero (defaultLF);
  51400. }
  51401. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51402. {
  51403. String faceName (font.getTypefaceName());
  51404. if (faceName == Font::getDefaultSansSerifFontName())
  51405. faceName = defaultSans;
  51406. else if (faceName == Font::getDefaultSerifFontName())
  51407. faceName = defaultSerif;
  51408. else if (faceName == Font::getDefaultMonospacedFontName())
  51409. faceName = defaultFixed;
  51410. Font f (font);
  51411. f.setTypefaceName (faceName);
  51412. return Typeface::createSystemTypefaceFor (f);
  51413. }
  51414. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51415. {
  51416. defaultSans = newName;
  51417. }
  51418. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51419. {
  51420. return component.getMouseCursor();
  51421. }
  51422. void LookAndFeel::drawButtonBackground (Graphics& g,
  51423. Button& button,
  51424. const Colour& backgroundColour,
  51425. bool isMouseOverButton,
  51426. bool isButtonDown)
  51427. {
  51428. const int width = button.getWidth();
  51429. const int height = button.getHeight();
  51430. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51431. const float halfThickness = outlineThickness * 0.5f;
  51432. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51433. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51434. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51435. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51436. const Colour baseColour (createBaseColour (backgroundColour,
  51437. button.hasKeyboardFocus (true),
  51438. isMouseOverButton, isButtonDown)
  51439. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51440. drawGlassLozenge (g,
  51441. indentL,
  51442. indentT,
  51443. width - indentL - indentR,
  51444. height - indentT - indentB,
  51445. baseColour, outlineThickness, -1.0f,
  51446. button.isConnectedOnLeft(),
  51447. button.isConnectedOnRight(),
  51448. button.isConnectedOnTop(),
  51449. button.isConnectedOnBottom());
  51450. }
  51451. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51452. {
  51453. return button.getFont();
  51454. }
  51455. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51456. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51457. {
  51458. Font font (getFontForTextButton (button));
  51459. g.setFont (font);
  51460. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51461. : TextButton::textColourOffId)
  51462. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51463. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51464. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51465. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51466. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51467. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51468. g.drawFittedText (button.getButtonText(),
  51469. leftIndent,
  51470. yIndent,
  51471. button.getWidth() - leftIndent - rightIndent,
  51472. button.getHeight() - yIndent * 2,
  51473. Justification::centred, 2);
  51474. }
  51475. void LookAndFeel::drawTickBox (Graphics& g,
  51476. Component& component,
  51477. float x, float y, float w, float h,
  51478. const bool ticked,
  51479. const bool isEnabled,
  51480. const bool isMouseOverButton,
  51481. const bool isButtonDown)
  51482. {
  51483. const float boxSize = w * 0.7f;
  51484. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51485. createBaseColour (component.findColour (TextButton::buttonColourId)
  51486. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51487. true,
  51488. isMouseOverButton,
  51489. isButtonDown),
  51490. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51491. if (ticked)
  51492. {
  51493. Path tick;
  51494. tick.startNewSubPath (1.5f, 3.0f);
  51495. tick.lineTo (3.0f, 6.0f);
  51496. tick.lineTo (6.0f, 0.0f);
  51497. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51498. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51499. .translated (x, y));
  51500. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51501. }
  51502. }
  51503. void LookAndFeel::drawToggleButton (Graphics& g,
  51504. ToggleButton& button,
  51505. bool isMouseOverButton,
  51506. bool isButtonDown)
  51507. {
  51508. if (button.hasKeyboardFocus (true))
  51509. {
  51510. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51511. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51512. }
  51513. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51514. const float tickWidth = fontSize * 1.1f;
  51515. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51516. tickWidth, tickWidth,
  51517. button.getToggleState(),
  51518. button.isEnabled(),
  51519. isMouseOverButton,
  51520. isButtonDown);
  51521. g.setColour (button.findColour (ToggleButton::textColourId));
  51522. g.setFont (fontSize);
  51523. if (! button.isEnabled())
  51524. g.setOpacity (0.5f);
  51525. const int textX = (int) tickWidth + 5;
  51526. g.drawFittedText (button.getButtonText(),
  51527. textX, 0,
  51528. button.getWidth() - textX - 2, button.getHeight(),
  51529. Justification::centredLeft, 10);
  51530. }
  51531. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51532. {
  51533. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51534. const int tickWidth = jmin (24, button.getHeight());
  51535. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51536. button.getHeight());
  51537. }
  51538. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51539. const String& message,
  51540. const String& button1,
  51541. const String& button2,
  51542. const String& button3,
  51543. AlertWindow::AlertIconType iconType,
  51544. int numButtons,
  51545. Component* associatedComponent)
  51546. {
  51547. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51548. if (numButtons == 1)
  51549. {
  51550. aw->addButton (button1, 0,
  51551. KeyPress (KeyPress::escapeKey, 0, 0),
  51552. KeyPress (KeyPress::returnKey, 0, 0));
  51553. }
  51554. else
  51555. {
  51556. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51557. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51558. if (button1ShortCut == button2ShortCut)
  51559. button2ShortCut = KeyPress();
  51560. if (numButtons == 2)
  51561. {
  51562. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51563. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51564. }
  51565. else if (numButtons == 3)
  51566. {
  51567. aw->addButton (button1, 1, button1ShortCut);
  51568. aw->addButton (button2, 2, button2ShortCut);
  51569. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51570. }
  51571. }
  51572. return aw;
  51573. }
  51574. void LookAndFeel::drawAlertBox (Graphics& g,
  51575. AlertWindow& alert,
  51576. const Rectangle<int>& textArea,
  51577. TextLayout& textLayout)
  51578. {
  51579. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51580. int iconSpaceUsed = 0;
  51581. Justification alignment (Justification::horizontallyCentred);
  51582. const int iconWidth = 80;
  51583. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51584. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51585. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51586. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51587. iconSize, iconSize);
  51588. if (alert.getAlertType() != AlertWindow::NoIcon)
  51589. {
  51590. Path icon;
  51591. uint32 colour;
  51592. char character;
  51593. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51594. {
  51595. colour = 0x55ff5555;
  51596. character = '!';
  51597. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51598. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51599. (float) iconRect.getX(), (float) iconRect.getBottom());
  51600. icon = icon.createPathWithRoundedCorners (5.0f);
  51601. }
  51602. else
  51603. {
  51604. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51605. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51606. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51607. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51608. }
  51609. GlyphArrangement ga;
  51610. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51611. String::charToString (character),
  51612. (float) iconRect.getX(), (float) iconRect.getY(),
  51613. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51614. Justification::centred, false);
  51615. ga.createPath (icon);
  51616. icon.setUsingNonZeroWinding (false);
  51617. g.setColour (Colour (colour));
  51618. g.fillPath (icon);
  51619. iconSpaceUsed = iconWidth;
  51620. alignment = Justification::left;
  51621. }
  51622. g.setColour (alert.findColour (AlertWindow::textColourId));
  51623. textLayout.drawWithin (g,
  51624. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51625. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51626. alignment.getFlags() | Justification::top);
  51627. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51628. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51629. }
  51630. int LookAndFeel::getAlertBoxWindowFlags()
  51631. {
  51632. return ComponentPeer::windowAppearsOnTaskbar
  51633. | ComponentPeer::windowHasDropShadow;
  51634. }
  51635. int LookAndFeel::getAlertWindowButtonHeight()
  51636. {
  51637. return 28;
  51638. }
  51639. const Font LookAndFeel::getAlertWindowFont()
  51640. {
  51641. return Font (12.0f);
  51642. }
  51643. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51644. int width, int height,
  51645. double progress, const String& textToShow)
  51646. {
  51647. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51648. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51649. g.fillAll (background);
  51650. if (progress >= 0.0f && progress < 1.0f)
  51651. {
  51652. drawGlassLozenge (g, 1.0f, 1.0f,
  51653. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51654. (float) (height - 2),
  51655. foreground,
  51656. 0.5f, 0.0f,
  51657. true, true, true, true);
  51658. }
  51659. else
  51660. {
  51661. // spinning bar..
  51662. g.setColour (foreground);
  51663. const int stripeWidth = height * 2;
  51664. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51665. Path p;
  51666. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51667. p.addQuadrilateral (x, 0.0f,
  51668. x + stripeWidth * 0.5f, 0.0f,
  51669. x, (float) height,
  51670. x - stripeWidth * 0.5f, (float) height);
  51671. Image im (Image::ARGB, width, height, true);
  51672. {
  51673. Graphics g2 (im);
  51674. drawGlassLozenge (g2, 1.0f, 1.0f,
  51675. (float) (width - 2),
  51676. (float) (height - 2),
  51677. foreground,
  51678. 0.5f, 0.0f,
  51679. true, true, true, true);
  51680. }
  51681. g.setTiledImageFill (im, 0, 0, 0.85f);
  51682. g.fillPath (p);
  51683. }
  51684. if (textToShow.isNotEmpty())
  51685. {
  51686. g.setColour (Colour::contrasting (background, foreground));
  51687. g.setFont (height * 0.6f);
  51688. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51689. }
  51690. }
  51691. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51692. {
  51693. const float radius = jmin (w, h) * 0.4f;
  51694. const float thickness = radius * 0.15f;
  51695. Path p;
  51696. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  51697. radius * 0.6f, thickness,
  51698. thickness * 0.5f);
  51699. const float cx = x + w * 0.5f;
  51700. const float cy = y + h * 0.5f;
  51701. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  51702. for (int i = 0; i < 12; ++i)
  51703. {
  51704. const int n = (i + 12 - animationIndex) % 12;
  51705. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  51706. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  51707. .translated (cx, cy));
  51708. }
  51709. }
  51710. void LookAndFeel::drawScrollbarButton (Graphics& g,
  51711. ScrollBar& scrollbar,
  51712. int width, int height,
  51713. int buttonDirection,
  51714. bool /*isScrollbarVertical*/,
  51715. bool /*isMouseOverButton*/,
  51716. bool isButtonDown)
  51717. {
  51718. Path p;
  51719. if (buttonDirection == 0)
  51720. p.addTriangle (width * 0.5f, height * 0.2f,
  51721. width * 0.1f, height * 0.7f,
  51722. width * 0.9f, height * 0.7f);
  51723. else if (buttonDirection == 1)
  51724. p.addTriangle (width * 0.8f, height * 0.5f,
  51725. width * 0.3f, height * 0.1f,
  51726. width * 0.3f, height * 0.9f);
  51727. else if (buttonDirection == 2)
  51728. p.addTriangle (width * 0.5f, height * 0.8f,
  51729. width * 0.1f, height * 0.3f,
  51730. width * 0.9f, height * 0.3f);
  51731. else if (buttonDirection == 3)
  51732. p.addTriangle (width * 0.2f, height * 0.5f,
  51733. width * 0.7f, height * 0.1f,
  51734. width * 0.7f, height * 0.9f);
  51735. if (isButtonDown)
  51736. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  51737. else
  51738. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51739. g.fillPath (p);
  51740. g.setColour (Colour (0x80000000));
  51741. g.strokePath (p, PathStrokeType (0.5f));
  51742. }
  51743. void LookAndFeel::drawScrollbar (Graphics& g,
  51744. ScrollBar& scrollbar,
  51745. int x, int y,
  51746. int width, int height,
  51747. bool isScrollbarVertical,
  51748. int thumbStartPosition,
  51749. int thumbSize,
  51750. bool /*isMouseOver*/,
  51751. bool /*isMouseDown*/)
  51752. {
  51753. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  51754. Path slotPath, thumbPath;
  51755. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  51756. const float slotIndentx2 = slotIndent * 2.0f;
  51757. const float thumbIndent = slotIndent + 1.0f;
  51758. const float thumbIndentx2 = thumbIndent * 2.0f;
  51759. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  51760. if (isScrollbarVertical)
  51761. {
  51762. slotPath.addRoundedRectangle (x + slotIndent,
  51763. y + slotIndent,
  51764. width - slotIndentx2,
  51765. height - slotIndentx2,
  51766. (width - slotIndentx2) * 0.5f);
  51767. if (thumbSize > 0)
  51768. thumbPath.addRoundedRectangle (x + thumbIndent,
  51769. thumbStartPosition + thumbIndent,
  51770. width - thumbIndentx2,
  51771. thumbSize - thumbIndentx2,
  51772. (width - thumbIndentx2) * 0.5f);
  51773. gx1 = (float) x;
  51774. gx2 = x + width * 0.7f;
  51775. }
  51776. else
  51777. {
  51778. slotPath.addRoundedRectangle (x + slotIndent,
  51779. y + slotIndent,
  51780. width - slotIndentx2,
  51781. height - slotIndentx2,
  51782. (height - slotIndentx2) * 0.5f);
  51783. if (thumbSize > 0)
  51784. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  51785. y + thumbIndent,
  51786. thumbSize - thumbIndentx2,
  51787. height - thumbIndentx2,
  51788. (height - thumbIndentx2) * 0.5f);
  51789. gy1 = (float) y;
  51790. gy2 = y + height * 0.7f;
  51791. }
  51792. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51793. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  51794. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  51795. g.fillPath (slotPath);
  51796. if (isScrollbarVertical)
  51797. {
  51798. gx1 = x + width * 0.6f;
  51799. gx2 = (float) x + width;
  51800. }
  51801. else
  51802. {
  51803. gy1 = y + height * 0.6f;
  51804. gy2 = (float) y + height;
  51805. }
  51806. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  51807. Colour (0x19000000), gx2, gy2, false));
  51808. g.fillPath (slotPath);
  51809. g.setColour (thumbColour);
  51810. g.fillPath (thumbPath);
  51811. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  51812. Colours::transparentBlack, gx2, gy2, false));
  51813. g.saveState();
  51814. if (isScrollbarVertical)
  51815. g.reduceClipRegion (x + width / 2, y, width, height);
  51816. else
  51817. g.reduceClipRegion (x, y + height / 2, width, height);
  51818. g.fillPath (thumbPath);
  51819. g.restoreState();
  51820. g.setColour (Colour (0x4c000000));
  51821. g.strokePath (thumbPath, PathStrokeType (0.4f));
  51822. }
  51823. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  51824. {
  51825. return 0;
  51826. }
  51827. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  51828. {
  51829. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  51830. }
  51831. int LookAndFeel::getDefaultScrollbarWidth()
  51832. {
  51833. return 18;
  51834. }
  51835. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  51836. {
  51837. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  51838. : scrollbar.getHeight());
  51839. }
  51840. const Path LookAndFeel::getTickShape (const float height)
  51841. {
  51842. static const unsigned char tickShapeData[] =
  51843. {
  51844. 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,
  51845. 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,
  51846. 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,
  51847. 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,
  51848. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  51849. };
  51850. Path p;
  51851. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  51852. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51853. return p;
  51854. }
  51855. const Path LookAndFeel::getCrossShape (const float height)
  51856. {
  51857. static const unsigned char crossShapeData[] =
  51858. {
  51859. 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,
  51860. 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,
  51861. 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,
  51862. 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,
  51863. 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,
  51864. 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,
  51865. 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
  51866. };
  51867. Path p;
  51868. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  51869. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51870. return p;
  51871. }
  51872. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  51873. {
  51874. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  51875. x += (w - boxSize) >> 1;
  51876. y += (h - boxSize) >> 1;
  51877. w = boxSize;
  51878. h = boxSize;
  51879. g.setColour (Colour (0xe5ffffff));
  51880. g.fillRect (x, y, w, h);
  51881. g.setColour (Colour (0x80000000));
  51882. g.drawRect (x, y, w, h);
  51883. const float size = boxSize / 2 + 1.0f;
  51884. const float centre = (float) (boxSize / 2);
  51885. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  51886. if (isPlus)
  51887. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  51888. }
  51889. void LookAndFeel::drawBubble (Graphics& g,
  51890. float tipX, float tipY,
  51891. float boxX, float boxY,
  51892. float boxW, float boxH)
  51893. {
  51894. int side = 0;
  51895. if (tipX < boxX)
  51896. side = 1;
  51897. else if (tipX > boxX + boxW)
  51898. side = 3;
  51899. else if (tipY > boxY + boxH)
  51900. side = 2;
  51901. const float indent = 2.0f;
  51902. Path p;
  51903. p.addBubble (boxX + indent,
  51904. boxY + indent,
  51905. boxW - indent * 2.0f,
  51906. boxH - indent * 2.0f,
  51907. 5.0f,
  51908. tipX, tipY,
  51909. side,
  51910. 0.5f,
  51911. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  51912. //xxx need to take comp as param for colour
  51913. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  51914. g.fillPath (p);
  51915. //xxx as above
  51916. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  51917. g.strokePath (p, PathStrokeType (1.33f));
  51918. }
  51919. const Font LookAndFeel::getPopupMenuFont()
  51920. {
  51921. return Font (17.0f);
  51922. }
  51923. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  51924. const bool isSeparator,
  51925. int standardMenuItemHeight,
  51926. int& idealWidth,
  51927. int& idealHeight)
  51928. {
  51929. if (isSeparator)
  51930. {
  51931. idealWidth = 50;
  51932. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  51933. }
  51934. else
  51935. {
  51936. Font font (getPopupMenuFont());
  51937. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  51938. font.setHeight (standardMenuItemHeight / 1.3f);
  51939. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  51940. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  51941. }
  51942. }
  51943. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51944. {
  51945. const Colour background (findColour (PopupMenu::backgroundColourId));
  51946. g.fillAll (background);
  51947. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  51948. for (int i = 0; i < height; i += 3)
  51949. g.fillRect (0, i, width, 1);
  51950. #if ! JUCE_MAC
  51951. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  51952. g.drawRect (0, 0, width, height);
  51953. #endif
  51954. }
  51955. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  51956. int width, int height,
  51957. bool isScrollUpArrow)
  51958. {
  51959. const Colour background (findColour (PopupMenu::backgroundColourId));
  51960. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  51961. background.withAlpha (0.0f),
  51962. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  51963. false));
  51964. g.fillRect (1, 1, width - 2, height - 2);
  51965. const float hw = width * 0.5f;
  51966. const float arrowW = height * 0.3f;
  51967. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  51968. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  51969. Path p;
  51970. p.addTriangle (hw - arrowW, y1,
  51971. hw + arrowW, y1,
  51972. hw, y2);
  51973. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  51974. g.fillPath (p);
  51975. }
  51976. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  51977. int width, int height,
  51978. const bool isSeparator,
  51979. const bool isActive,
  51980. const bool isHighlighted,
  51981. const bool isTicked,
  51982. const bool hasSubMenu,
  51983. const String& text,
  51984. const String& shortcutKeyText,
  51985. Image* image,
  51986. const Colour* const textColourToUse)
  51987. {
  51988. const float halfH = height * 0.5f;
  51989. if (isSeparator)
  51990. {
  51991. const float separatorIndent = 5.5f;
  51992. g.setColour (Colour (0x33000000));
  51993. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  51994. g.setColour (Colour (0x66ffffff));
  51995. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  51996. }
  51997. else
  51998. {
  51999. Colour textColour (findColour (PopupMenu::textColourId));
  52000. if (textColourToUse != 0)
  52001. textColour = *textColourToUse;
  52002. if (isHighlighted)
  52003. {
  52004. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52005. g.fillRect (1, 1, width - 2, height - 2);
  52006. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52007. }
  52008. else
  52009. {
  52010. g.setColour (textColour);
  52011. }
  52012. if (! isActive)
  52013. g.setOpacity (0.3f);
  52014. Font font (getPopupMenuFont());
  52015. if (font.getHeight() > height / 1.3f)
  52016. font.setHeight (height / 1.3f);
  52017. g.setFont (font);
  52018. const int leftBorder = (height * 5) / 4;
  52019. const int rightBorder = 4;
  52020. if (image != 0)
  52021. {
  52022. g.drawImageWithin (image,
  52023. 2, 1, leftBorder - 4, height - 2,
  52024. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52025. }
  52026. else if (isTicked)
  52027. {
  52028. const Path tick (getTickShape (1.0f));
  52029. const float th = font.getAscent();
  52030. const float ty = halfH - th * 0.5f;
  52031. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52032. th, true));
  52033. }
  52034. g.drawFittedText (text,
  52035. leftBorder, 0,
  52036. width - (leftBorder + rightBorder), height,
  52037. Justification::centredLeft, 1);
  52038. if (shortcutKeyText.isNotEmpty())
  52039. {
  52040. Font f2 (font);
  52041. f2.setHeight (f2.getHeight() * 0.75f);
  52042. f2.setHorizontalScale (0.95f);
  52043. g.setFont (f2);
  52044. g.drawText (shortcutKeyText,
  52045. leftBorder,
  52046. 0,
  52047. width - (leftBorder + rightBorder + 4),
  52048. height,
  52049. Justification::centredRight,
  52050. true);
  52051. }
  52052. if (hasSubMenu)
  52053. {
  52054. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52055. const float x = width - height * 0.6f;
  52056. Path p;
  52057. p.addTriangle (x, halfH - arrowH * 0.5f,
  52058. x, halfH + arrowH * 0.5f,
  52059. x + arrowH * 0.6f, halfH);
  52060. g.fillPath (p);
  52061. }
  52062. }
  52063. }
  52064. int LookAndFeel::getMenuWindowFlags()
  52065. {
  52066. return ComponentPeer::windowHasDropShadow;
  52067. }
  52068. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52069. bool, MenuBarComponent& menuBar)
  52070. {
  52071. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52072. if (menuBar.isEnabled())
  52073. {
  52074. drawShinyButtonShape (g,
  52075. -4.0f, 0.0f,
  52076. width + 8.0f, (float) height,
  52077. 0.0f,
  52078. baseColour,
  52079. 0.4f,
  52080. true, true, true, true);
  52081. }
  52082. else
  52083. {
  52084. g.fillAll (baseColour);
  52085. }
  52086. }
  52087. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52088. {
  52089. return Font (menuBar.getHeight() * 0.7f);
  52090. }
  52091. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52092. {
  52093. return getMenuBarFont (menuBar, itemIndex, itemText)
  52094. .getStringWidth (itemText) + menuBar.getHeight();
  52095. }
  52096. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52097. int width, int height,
  52098. int itemIndex,
  52099. const String& itemText,
  52100. bool isMouseOverItem,
  52101. bool isMenuOpen,
  52102. bool /*isMouseOverBar*/,
  52103. MenuBarComponent& menuBar)
  52104. {
  52105. if (! menuBar.isEnabled())
  52106. {
  52107. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52108. .withMultipliedAlpha (0.5f));
  52109. }
  52110. else if (isMenuOpen || isMouseOverItem)
  52111. {
  52112. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52113. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52114. }
  52115. else
  52116. {
  52117. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52118. }
  52119. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52120. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52121. }
  52122. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52123. TextEditor& textEditor)
  52124. {
  52125. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52126. }
  52127. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52128. {
  52129. if (textEditor.isEnabled())
  52130. {
  52131. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52132. {
  52133. const int border = 2;
  52134. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52135. g.drawRect (0, 0, width, height, border);
  52136. g.setOpacity (1.0f);
  52137. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52138. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52139. }
  52140. else
  52141. {
  52142. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52143. g.drawRect (0, 0, width, height);
  52144. g.setOpacity (1.0f);
  52145. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52146. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52147. }
  52148. }
  52149. }
  52150. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52151. const bool isButtonDown,
  52152. int buttonX, int buttonY,
  52153. int buttonW, int buttonH,
  52154. ComboBox& box)
  52155. {
  52156. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52157. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52158. {
  52159. g.setColour (box.findColour (TextButton::buttonColourId));
  52160. g.drawRect (0, 0, width, height, 2);
  52161. }
  52162. else
  52163. {
  52164. g.setColour (box.findColour (ComboBox::outlineColourId));
  52165. g.drawRect (0, 0, width, height);
  52166. }
  52167. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52168. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52169. box.hasKeyboardFocus (true),
  52170. false, isButtonDown)
  52171. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52172. drawGlassLozenge (g,
  52173. buttonX + outlineThickness, buttonY + outlineThickness,
  52174. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52175. baseColour, outlineThickness, -1.0f,
  52176. true, true, true, true);
  52177. if (box.isEnabled())
  52178. {
  52179. const float arrowX = 0.3f;
  52180. const float arrowH = 0.2f;
  52181. Path p;
  52182. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52183. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52184. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52185. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52186. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52187. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52188. g.setColour (box.findColour (ComboBox::arrowColourId));
  52189. g.fillPath (p);
  52190. }
  52191. }
  52192. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52193. {
  52194. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52195. }
  52196. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52197. {
  52198. return new Label (String::empty, String::empty);
  52199. }
  52200. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52201. {
  52202. label.setBounds (1, 1,
  52203. box.getWidth() + 3 - box.getHeight(),
  52204. box.getHeight() - 2);
  52205. label.setFont (getComboBoxFont (box));
  52206. }
  52207. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52208. {
  52209. g.fillAll (label.findColour (Label::backgroundColourId));
  52210. if (! label.isBeingEdited())
  52211. {
  52212. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52213. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52214. g.setFont (label.getFont());
  52215. g.drawFittedText (label.getText(),
  52216. label.getHorizontalBorderSize(),
  52217. label.getVerticalBorderSize(),
  52218. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52219. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52220. label.getJustificationType(),
  52221. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52222. label.getMinimumHorizontalScale());
  52223. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52224. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52225. }
  52226. else if (label.isEnabled())
  52227. {
  52228. g.setColour (label.findColour (Label::outlineColourId));
  52229. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52230. }
  52231. }
  52232. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52233. int x, int y,
  52234. int width, int height,
  52235. float /*sliderPos*/,
  52236. float /*minSliderPos*/,
  52237. float /*maxSliderPos*/,
  52238. const Slider::SliderStyle /*style*/,
  52239. Slider& slider)
  52240. {
  52241. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52242. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52243. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52244. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52245. Path indent;
  52246. if (slider.isHorizontal())
  52247. {
  52248. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52249. const float ih = sliderRadius;
  52250. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52251. gradCol2, 0.0f, iy + ih, false));
  52252. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52253. width + sliderRadius, ih,
  52254. 5.0f);
  52255. g.fillPath (indent);
  52256. }
  52257. else
  52258. {
  52259. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52260. const float iw = sliderRadius;
  52261. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52262. gradCol2, ix + iw, 0.0f, false));
  52263. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52264. iw, height + sliderRadius,
  52265. 5.0f);
  52266. g.fillPath (indent);
  52267. }
  52268. g.setColour (Colour (0x4c000000));
  52269. g.strokePath (indent, PathStrokeType (0.5f));
  52270. }
  52271. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52272. int x, int y,
  52273. int width, int height,
  52274. float sliderPos,
  52275. float minSliderPos,
  52276. float maxSliderPos,
  52277. const Slider::SliderStyle style,
  52278. Slider& slider)
  52279. {
  52280. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52281. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52282. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52283. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52284. slider.isMouseButtonDown() && slider.isEnabled()));
  52285. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52286. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52287. {
  52288. float kx, ky;
  52289. if (style == Slider::LinearVertical)
  52290. {
  52291. kx = x + width * 0.5f;
  52292. ky = sliderPos;
  52293. }
  52294. else
  52295. {
  52296. kx = sliderPos;
  52297. ky = y + height * 0.5f;
  52298. }
  52299. drawGlassSphere (g,
  52300. kx - sliderRadius,
  52301. ky - sliderRadius,
  52302. sliderRadius * 2.0f,
  52303. knobColour, outlineThickness);
  52304. }
  52305. else
  52306. {
  52307. if (style == Slider::ThreeValueVertical)
  52308. {
  52309. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52310. sliderPos - sliderRadius,
  52311. sliderRadius * 2.0f,
  52312. knobColour, outlineThickness);
  52313. }
  52314. else if (style == Slider::ThreeValueHorizontal)
  52315. {
  52316. drawGlassSphere (g,sliderPos - sliderRadius,
  52317. y + height * 0.5f - sliderRadius,
  52318. sliderRadius * 2.0f,
  52319. knobColour, outlineThickness);
  52320. }
  52321. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52322. {
  52323. const float sr = jmin (sliderRadius, width * 0.4f);
  52324. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52325. minSliderPos - sliderRadius,
  52326. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52327. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52328. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52329. }
  52330. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52331. {
  52332. const float sr = jmin (sliderRadius, height * 0.4f);
  52333. drawGlassPointer (g, minSliderPos - sr,
  52334. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52335. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52336. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52337. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52338. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52339. }
  52340. }
  52341. }
  52342. void LookAndFeel::drawLinearSlider (Graphics& g,
  52343. int x, int y,
  52344. int width, int height,
  52345. float sliderPos,
  52346. float minSliderPos,
  52347. float maxSliderPos,
  52348. const Slider::SliderStyle style,
  52349. Slider& slider)
  52350. {
  52351. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52352. if (style == Slider::LinearBar)
  52353. {
  52354. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52355. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52356. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52357. false,
  52358. isMouseOver,
  52359. isMouseOver || slider.isMouseButtonDown()));
  52360. drawShinyButtonShape (g,
  52361. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52362. baseColour,
  52363. slider.isEnabled() ? 0.9f : 0.3f,
  52364. true, true, true, true);
  52365. }
  52366. else
  52367. {
  52368. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52369. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52370. }
  52371. }
  52372. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52373. {
  52374. return jmin (7,
  52375. slider.getHeight() / 2,
  52376. slider.getWidth() / 2) + 2;
  52377. }
  52378. void LookAndFeel::drawRotarySlider (Graphics& g,
  52379. int x, int y,
  52380. int width, int height,
  52381. float sliderPos,
  52382. const float rotaryStartAngle,
  52383. const float rotaryEndAngle,
  52384. Slider& slider)
  52385. {
  52386. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52387. const float centreX = x + width * 0.5f;
  52388. const float centreY = y + height * 0.5f;
  52389. const float rx = centreX - radius;
  52390. const float ry = centreY - radius;
  52391. const float rw = radius * 2.0f;
  52392. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52393. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52394. if (radius > 12.0f)
  52395. {
  52396. if (slider.isEnabled())
  52397. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52398. else
  52399. g.setColour (Colour (0x80808080));
  52400. const float thickness = 0.7f;
  52401. {
  52402. Path filledArc;
  52403. filledArc.addPieSegment (rx, ry, rw, rw,
  52404. rotaryStartAngle,
  52405. angle,
  52406. thickness);
  52407. g.fillPath (filledArc);
  52408. }
  52409. if (thickness > 0)
  52410. {
  52411. const float innerRadius = radius * 0.2f;
  52412. Path p;
  52413. p.addTriangle (-innerRadius, 0.0f,
  52414. 0.0f, -radius * thickness * 1.1f,
  52415. innerRadius, 0.0f);
  52416. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52417. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52418. }
  52419. if (slider.isEnabled())
  52420. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52421. else
  52422. g.setColour (Colour (0x80808080));
  52423. Path outlineArc;
  52424. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52425. outlineArc.closeSubPath();
  52426. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52427. }
  52428. else
  52429. {
  52430. if (slider.isEnabled())
  52431. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52432. else
  52433. g.setColour (Colour (0x80808080));
  52434. Path p;
  52435. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52436. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52437. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  52438. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52439. }
  52440. }
  52441. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52442. {
  52443. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52444. }
  52445. class SliderLabelComp : public Label
  52446. {
  52447. public:
  52448. SliderLabelComp() : Label (String::empty, String::empty) {}
  52449. ~SliderLabelComp() {}
  52450. void mouseWheelMove (const MouseEvent&, float, float) {}
  52451. };
  52452. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52453. {
  52454. Label* const l = new SliderLabelComp();
  52455. l->setJustificationType (Justification::centred);
  52456. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52457. l->setColour (Label::backgroundColourId,
  52458. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52459. : slider.findColour (Slider::textBoxBackgroundColourId));
  52460. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52461. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52462. l->setColour (TextEditor::backgroundColourId,
  52463. slider.findColour (Slider::textBoxBackgroundColourId)
  52464. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52465. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52466. return l;
  52467. }
  52468. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52469. {
  52470. return 0;
  52471. }
  52472. static const TextLayout layoutTooltipText (const String& text) throw()
  52473. {
  52474. const float tooltipFontSize = 12.0f;
  52475. const int maxToolTipWidth = 400;
  52476. const Font f (tooltipFontSize, Font::bold);
  52477. TextLayout tl (text, f);
  52478. tl.layout (maxToolTipWidth, Justification::left, true);
  52479. return tl;
  52480. }
  52481. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52482. {
  52483. const TextLayout tl (layoutTooltipText (tipText));
  52484. width = tl.getWidth() + 14;
  52485. height = tl.getHeight() + 6;
  52486. }
  52487. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52488. {
  52489. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52490. const Colour textCol (findColour (TooltipWindow::textColourId));
  52491. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52492. g.setColour (findColour (TooltipWindow::outlineColourId));
  52493. g.drawRect (0, 0, width, height, 1);
  52494. #endif
  52495. const TextLayout tl (layoutTooltipText (text));
  52496. g.setColour (findColour (TooltipWindow::textColourId));
  52497. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52498. }
  52499. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52500. {
  52501. return new TextButton (text, TRANS("click to browse for a different file"));
  52502. }
  52503. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52504. ComboBox* filenameBox,
  52505. Button* browseButton)
  52506. {
  52507. browseButton->setSize (80, filenameComp.getHeight());
  52508. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52509. if (tb != 0)
  52510. tb->changeWidthToFitText();
  52511. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52512. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52513. }
  52514. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52515. int imageX, int imageY, int imageW, int imageH,
  52516. const Colour& overlayColour,
  52517. float imageOpacity,
  52518. ImageButton& button)
  52519. {
  52520. if (! button.isEnabled())
  52521. imageOpacity *= 0.3f;
  52522. if (! overlayColour.isOpaque())
  52523. {
  52524. g.setOpacity (imageOpacity);
  52525. g.drawImage (image, imageX, imageY, imageW, imageH,
  52526. 0, 0, image->getWidth(), image->getHeight(), false);
  52527. }
  52528. if (! overlayColour.isTransparent())
  52529. {
  52530. g.setColour (overlayColour);
  52531. g.drawImage (image, imageX, imageY, imageW, imageH,
  52532. 0, 0, image->getWidth(), image->getHeight(), true);
  52533. }
  52534. }
  52535. void LookAndFeel::drawCornerResizer (Graphics& g,
  52536. int w, int h,
  52537. bool /*isMouseOver*/,
  52538. bool /*isMouseDragging*/)
  52539. {
  52540. const float lineThickness = jmin (w, h) * 0.075f;
  52541. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52542. {
  52543. g.setColour (Colours::lightgrey);
  52544. g.drawLine (w * i,
  52545. h + 1.0f,
  52546. w + 1.0f,
  52547. h * i,
  52548. lineThickness);
  52549. g.setColour (Colours::darkgrey);
  52550. g.drawLine (w * i + lineThickness,
  52551. h + 1.0f,
  52552. w + 1.0f,
  52553. h * i + lineThickness,
  52554. lineThickness);
  52555. }
  52556. }
  52557. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52558. const BorderSize& /*borders*/)
  52559. {
  52560. }
  52561. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52562. const BorderSize& /*border*/, ResizableWindow& window)
  52563. {
  52564. g.fillAll (window.getBackgroundColour());
  52565. }
  52566. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52567. const BorderSize& border, ResizableWindow&)
  52568. {
  52569. g.setColour (Colour (0x80000000));
  52570. g.drawRect (0, 0, w, h);
  52571. g.setColour (Colour (0x19000000));
  52572. g.drawRect (border.getLeft() - 1,
  52573. border.getTop() - 1,
  52574. w + 2 - border.getLeftAndRight(),
  52575. h + 2 - border.getTopAndBottom());
  52576. }
  52577. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52578. Graphics& g, int w, int h,
  52579. int titleSpaceX, int titleSpaceW,
  52580. const Image* icon,
  52581. bool drawTitleTextOnLeft)
  52582. {
  52583. const bool isActive = window.isActiveWindow();
  52584. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52585. 0.0f, 0.0f,
  52586. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52587. 0.0f, (float) h, false));
  52588. g.fillAll();
  52589. Font font (h * 0.65f, Font::bold);
  52590. g.setFont (font);
  52591. int textW = font.getStringWidth (window.getName());
  52592. int iconW = 0;
  52593. int iconH = 0;
  52594. if (icon != 0)
  52595. {
  52596. iconH = (int) font.getHeight();
  52597. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52598. }
  52599. textW = jmin (titleSpaceW, textW + iconW);
  52600. int textX = drawTitleTextOnLeft ? titleSpaceX
  52601. : jmax (titleSpaceX, (w - textW) / 2);
  52602. if (textX + textW > titleSpaceX + titleSpaceW)
  52603. textX = titleSpaceX + titleSpaceW - textW;
  52604. if (icon != 0)
  52605. {
  52606. g.setOpacity (isActive ? 1.0f : 0.6f);
  52607. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  52608. RectanglePlacement::centred, false);
  52609. textX += iconW;
  52610. textW -= iconW;
  52611. }
  52612. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52613. g.setColour (findColour (DocumentWindow::textColourId));
  52614. else
  52615. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52616. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52617. }
  52618. class GlassWindowButton : public Button
  52619. {
  52620. public:
  52621. GlassWindowButton (const String& name, const Colour& col,
  52622. const Path& normalShape_,
  52623. const Path& toggledShape_) throw()
  52624. : Button (name),
  52625. colour (col),
  52626. normalShape (normalShape_),
  52627. toggledShape (toggledShape_)
  52628. {
  52629. }
  52630. ~GlassWindowButton()
  52631. {
  52632. }
  52633. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52634. {
  52635. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52636. if (! isEnabled())
  52637. alpha *= 0.5f;
  52638. float x = 0, y = 0, diam;
  52639. if (getWidth() < getHeight())
  52640. {
  52641. diam = (float) getWidth();
  52642. y = (getHeight() - getWidth()) * 0.5f;
  52643. }
  52644. else
  52645. {
  52646. diam = (float) getHeight();
  52647. y = (getWidth() - getHeight()) * 0.5f;
  52648. }
  52649. x += diam * 0.05f;
  52650. y += diam * 0.05f;
  52651. diam *= 0.9f;
  52652. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52653. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52654. g.fillEllipse (x, y, diam, diam);
  52655. x += 2.0f;
  52656. y += 2.0f;
  52657. diam -= 4.0f;
  52658. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52659. Path& p = getToggleState() ? toggledShape : normalShape;
  52660. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52661. diam * 0.4f, diam * 0.4f, true));
  52662. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52663. g.fillPath (p, t);
  52664. }
  52665. juce_UseDebuggingNewOperator
  52666. private:
  52667. Colour colour;
  52668. Path normalShape, toggledShape;
  52669. GlassWindowButton (const GlassWindowButton&);
  52670. GlassWindowButton& operator= (const GlassWindowButton&);
  52671. };
  52672. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52673. {
  52674. Path shape;
  52675. const float crossThickness = 0.25f;
  52676. if (buttonType == DocumentWindow::closeButton)
  52677. {
  52678. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  52679. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  52680. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52681. }
  52682. else if (buttonType == DocumentWindow::minimiseButton)
  52683. {
  52684. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52685. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52686. }
  52687. else if (buttonType == DocumentWindow::maximiseButton)
  52688. {
  52689. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  52690. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52691. Path fullscreenShape;
  52692. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52693. fullscreenShape.lineTo (0.0f, 100.0f);
  52694. fullscreenShape.lineTo (0.0f, 0.0f);
  52695. fullscreenShape.lineTo (100.0f, 0.0f);
  52696. fullscreenShape.lineTo (100.0f, 45.0f);
  52697. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  52698. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  52699. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  52700. }
  52701. jassertfalse
  52702. return 0;
  52703. }
  52704. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  52705. int titleBarX,
  52706. int titleBarY,
  52707. int titleBarW,
  52708. int titleBarH,
  52709. Button* minimiseButton,
  52710. Button* maximiseButton,
  52711. Button* closeButton,
  52712. bool positionTitleBarButtonsOnLeft)
  52713. {
  52714. const int buttonW = titleBarH - titleBarH / 8;
  52715. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  52716. : titleBarX + titleBarW - buttonW - buttonW / 4;
  52717. if (closeButton != 0)
  52718. {
  52719. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52720. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  52721. }
  52722. if (positionTitleBarButtonsOnLeft)
  52723. swapVariables (minimiseButton, maximiseButton);
  52724. if (maximiseButton != 0)
  52725. {
  52726. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52727. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  52728. }
  52729. if (minimiseButton != 0)
  52730. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52731. }
  52732. int LookAndFeel::getDefaultMenuBarHeight()
  52733. {
  52734. return 24;
  52735. }
  52736. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  52737. {
  52738. return new DropShadower (0.4f, 1, 5, 10);
  52739. }
  52740. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  52741. int w, int h,
  52742. bool /*isVerticalBar*/,
  52743. bool isMouseOver,
  52744. bool isMouseDragging)
  52745. {
  52746. float alpha = 0.5f;
  52747. if (isMouseOver || isMouseDragging)
  52748. {
  52749. g.fillAll (Colour (0x190000ff));
  52750. alpha = 1.0f;
  52751. }
  52752. const float cx = w * 0.5f;
  52753. const float cy = h * 0.5f;
  52754. const float cr = jmin (w, h) * 0.4f;
  52755. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  52756. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  52757. true));
  52758. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  52759. }
  52760. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  52761. const String& text,
  52762. const Justification& position,
  52763. GroupComponent& group)
  52764. {
  52765. const float textH = 15.0f;
  52766. const float indent = 3.0f;
  52767. const float textEdgeGap = 4.0f;
  52768. float cs = 5.0f;
  52769. Font f (textH);
  52770. Path p;
  52771. float x = indent;
  52772. float y = f.getAscent() - 3.0f;
  52773. float w = jmax (0.0f, width - x * 2.0f);
  52774. float h = jmax (0.0f, height - y - indent);
  52775. cs = jmin (cs, w * 0.5f, h * 0.5f);
  52776. const float cs2 = 2.0f * cs;
  52777. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  52778. float textX = cs + textEdgeGap;
  52779. if (position.testFlags (Justification::horizontallyCentred))
  52780. textX = cs + (w - cs2 - textW) * 0.5f;
  52781. else if (position.testFlags (Justification::right))
  52782. textX = w - cs - textW - textEdgeGap;
  52783. p.startNewSubPath (x + textX + textW, y);
  52784. p.lineTo (x + w - cs, y);
  52785. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  52786. p.lineTo (x + w, y + h - cs);
  52787. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52788. p.lineTo (x + cs, y + h);
  52789. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52790. p.lineTo (x, y + cs);
  52791. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52792. p.lineTo (x + textX, y);
  52793. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  52794. g.setColour (group.findColour (GroupComponent::outlineColourId)
  52795. .withMultipliedAlpha (alpha));
  52796. g.strokePath (p, PathStrokeType (2.0f));
  52797. g.setColour (group.findColour (GroupComponent::textColourId)
  52798. .withMultipliedAlpha (alpha));
  52799. g.setFont (f);
  52800. g.drawText (text,
  52801. roundToInt (x + textX), 0,
  52802. roundToInt (textW),
  52803. roundToInt (textH),
  52804. Justification::centred, true);
  52805. }
  52806. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  52807. {
  52808. return 1 + tabDepth / 3;
  52809. }
  52810. int LookAndFeel::getTabButtonSpaceAroundImage()
  52811. {
  52812. return 4;
  52813. }
  52814. void LookAndFeel::createTabButtonShape (Path& p,
  52815. int width, int height,
  52816. int /*tabIndex*/,
  52817. const String& /*text*/,
  52818. Button& /*button*/,
  52819. TabbedButtonBar::Orientation orientation,
  52820. const bool /*isMouseOver*/,
  52821. const bool /*isMouseDown*/,
  52822. const bool /*isFrontTab*/)
  52823. {
  52824. const float w = (float) width;
  52825. const float h = (float) height;
  52826. float length = w;
  52827. float depth = h;
  52828. if (orientation == TabbedButtonBar::TabsAtLeft
  52829. || orientation == TabbedButtonBar::TabsAtRight)
  52830. {
  52831. swapVariables (length, depth);
  52832. }
  52833. const float indent = (float) getTabButtonOverlap ((int) depth);
  52834. const float overhang = 4.0f;
  52835. if (orientation == TabbedButtonBar::TabsAtLeft)
  52836. {
  52837. p.startNewSubPath (w, 0.0f);
  52838. p.lineTo (0.0f, indent);
  52839. p.lineTo (0.0f, h - indent);
  52840. p.lineTo (w, h);
  52841. p.lineTo (w + overhang, h + overhang);
  52842. p.lineTo (w + overhang, -overhang);
  52843. }
  52844. else if (orientation == TabbedButtonBar::TabsAtRight)
  52845. {
  52846. p.startNewSubPath (0.0f, 0.0f);
  52847. p.lineTo (w, indent);
  52848. p.lineTo (w, h - indent);
  52849. p.lineTo (0.0f, h);
  52850. p.lineTo (-overhang, h + overhang);
  52851. p.lineTo (-overhang, -overhang);
  52852. }
  52853. else if (orientation == TabbedButtonBar::TabsAtBottom)
  52854. {
  52855. p.startNewSubPath (0.0f, 0.0f);
  52856. p.lineTo (indent, h);
  52857. p.lineTo (w - indent, h);
  52858. p.lineTo (w, 0.0f);
  52859. p.lineTo (w + overhang, -overhang);
  52860. p.lineTo (-overhang, -overhang);
  52861. }
  52862. else
  52863. {
  52864. p.startNewSubPath (0.0f, h);
  52865. p.lineTo (indent, 0.0f);
  52866. p.lineTo (w - indent, 0.0f);
  52867. p.lineTo (w, h);
  52868. p.lineTo (w + overhang, h + overhang);
  52869. p.lineTo (-overhang, h + overhang);
  52870. }
  52871. p.closeSubPath();
  52872. p = p.createPathWithRoundedCorners (3.0f);
  52873. }
  52874. void LookAndFeel::fillTabButtonShape (Graphics& g,
  52875. const Path& path,
  52876. const Colour& preferredColour,
  52877. int /*tabIndex*/,
  52878. const String& /*text*/,
  52879. Button& button,
  52880. TabbedButtonBar::Orientation /*orientation*/,
  52881. const bool /*isMouseOver*/,
  52882. const bool /*isMouseDown*/,
  52883. const bool isFrontTab)
  52884. {
  52885. g.setColour (isFrontTab ? preferredColour
  52886. : preferredColour.withMultipliedAlpha (0.9f));
  52887. g.fillPath (path);
  52888. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  52889. : TabbedButtonBar::tabOutlineColourId, false)
  52890. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52891. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  52892. }
  52893. void LookAndFeel::drawTabButtonText (Graphics& g,
  52894. int x, int y, int w, int h,
  52895. const Colour& preferredBackgroundColour,
  52896. int /*tabIndex*/,
  52897. const String& text,
  52898. Button& button,
  52899. TabbedButtonBar::Orientation orientation,
  52900. const bool isMouseOver,
  52901. const bool isMouseDown,
  52902. const bool isFrontTab)
  52903. {
  52904. int length = w;
  52905. int depth = h;
  52906. if (orientation == TabbedButtonBar::TabsAtLeft
  52907. || orientation == TabbedButtonBar::TabsAtRight)
  52908. {
  52909. swapVariables (length, depth);
  52910. }
  52911. Font font (depth * 0.6f);
  52912. font.setUnderline (button.hasKeyboardFocus (false));
  52913. GlyphArrangement textLayout;
  52914. textLayout.addFittedText (font, text.trim(),
  52915. 0.0f, 0.0f, (float) length, (float) depth,
  52916. Justification::centred,
  52917. jmax (1, depth / 12));
  52918. AffineTransform transform;
  52919. if (orientation == TabbedButtonBar::TabsAtLeft)
  52920. {
  52921. transform = transform.rotated (float_Pi * -0.5f)
  52922. .translated ((float) x, (float) (y + h));
  52923. }
  52924. else if (orientation == TabbedButtonBar::TabsAtRight)
  52925. {
  52926. transform = transform.rotated (float_Pi * 0.5f)
  52927. .translated ((float) (x + w), (float) y);
  52928. }
  52929. else
  52930. {
  52931. transform = transform.translated ((float) x, (float) y);
  52932. }
  52933. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  52934. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  52935. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  52936. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  52937. else
  52938. g.setColour (preferredBackgroundColour.contrasting());
  52939. if (! (isMouseOver || isMouseDown))
  52940. g.setOpacity (0.8f);
  52941. if (! button.isEnabled())
  52942. g.setOpacity (0.3f);
  52943. textLayout.draw (g, transform);
  52944. }
  52945. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  52946. const String& text,
  52947. int tabDepth,
  52948. Button&)
  52949. {
  52950. Font f (tabDepth * 0.6f);
  52951. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  52952. }
  52953. void LookAndFeel::drawTabButton (Graphics& g,
  52954. int w, int h,
  52955. const Colour& preferredColour,
  52956. int tabIndex,
  52957. const String& text,
  52958. Button& button,
  52959. TabbedButtonBar::Orientation orientation,
  52960. const bool isMouseOver,
  52961. const bool isMouseDown,
  52962. const bool isFrontTab)
  52963. {
  52964. int length = w;
  52965. int depth = h;
  52966. if (orientation == TabbedButtonBar::TabsAtLeft
  52967. || orientation == TabbedButtonBar::TabsAtRight)
  52968. {
  52969. swapVariables (length, depth);
  52970. }
  52971. Path tabShape;
  52972. createTabButtonShape (tabShape, w, h,
  52973. tabIndex, text, button, orientation,
  52974. isMouseOver, isMouseDown, isFrontTab);
  52975. fillTabButtonShape (g, tabShape, preferredColour,
  52976. tabIndex, text, button, orientation,
  52977. isMouseOver, isMouseDown, isFrontTab);
  52978. const int indent = getTabButtonOverlap (depth);
  52979. int x = 0, y = 0;
  52980. if (orientation == TabbedButtonBar::TabsAtLeft
  52981. || orientation == TabbedButtonBar::TabsAtRight)
  52982. {
  52983. y += indent;
  52984. h -= indent * 2;
  52985. }
  52986. else
  52987. {
  52988. x += indent;
  52989. w -= indent * 2;
  52990. }
  52991. drawTabButtonText (g, x, y, w, h, preferredColour,
  52992. tabIndex, text, button, orientation,
  52993. isMouseOver, isMouseDown, isFrontTab);
  52994. }
  52995. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  52996. int w, int h,
  52997. TabbedButtonBar& tabBar,
  52998. TabbedButtonBar::Orientation orientation)
  52999. {
  53000. const float shadowSize = 0.2f;
  53001. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53002. Rectangle<int> shadowRect;
  53003. if (orientation == TabbedButtonBar::TabsAtLeft)
  53004. {
  53005. x1 = (float) w;
  53006. x2 = w * (1.0f - shadowSize);
  53007. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53008. }
  53009. else if (orientation == TabbedButtonBar::TabsAtRight)
  53010. {
  53011. x2 = w * shadowSize;
  53012. shadowRect.setBounds (0, 0, (int) x2, h);
  53013. }
  53014. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53015. {
  53016. y2 = h * shadowSize;
  53017. shadowRect.setBounds (0, 0, w, (int) y2);
  53018. }
  53019. else
  53020. {
  53021. y1 = (float) h;
  53022. y2 = h * (1.0f - shadowSize);
  53023. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53024. }
  53025. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53026. Colours::transparentBlack, x2, y2, false));
  53027. shadowRect.expand (2, 2);
  53028. g.fillRect (shadowRect);
  53029. g.setColour (Colour (0x80000000));
  53030. if (orientation == TabbedButtonBar::TabsAtLeft)
  53031. {
  53032. g.fillRect (w - 1, 0, 1, h);
  53033. }
  53034. else if (orientation == TabbedButtonBar::TabsAtRight)
  53035. {
  53036. g.fillRect (0, 0, 1, h);
  53037. }
  53038. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53039. {
  53040. g.fillRect (0, 0, w, 1);
  53041. }
  53042. else
  53043. {
  53044. g.fillRect (0, h - 1, w, 1);
  53045. }
  53046. }
  53047. Button* LookAndFeel::createTabBarExtrasButton()
  53048. {
  53049. const float thickness = 7.0f;
  53050. const float indent = 22.0f;
  53051. Path p;
  53052. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53053. DrawablePath ellipse;
  53054. ellipse.setPath (p);
  53055. ellipse.setFill (Colour (0x99ffffff));
  53056. p.clear();
  53057. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53058. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53059. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53060. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53061. p.setUsingNonZeroWinding (false);
  53062. DrawablePath dp;
  53063. dp.setPath (p);
  53064. dp.setFill (Colour (0x59000000));
  53065. DrawableComposite normalImage;
  53066. normalImage.insertDrawable (ellipse);
  53067. normalImage.insertDrawable (dp);
  53068. dp.setFill (Colour (0xcc000000));
  53069. DrawableComposite overImage;
  53070. overImage.insertDrawable (ellipse);
  53071. overImage.insertDrawable (dp);
  53072. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53073. db->setImages (&normalImage, &overImage, 0);
  53074. return db;
  53075. }
  53076. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53077. {
  53078. g.fillAll (Colours::white);
  53079. const int w = header.getWidth();
  53080. const int h = header.getHeight();
  53081. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53082. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53083. false));
  53084. g.fillRect (0, h / 2, w, h);
  53085. g.setColour (Colour (0x33000000));
  53086. g.fillRect (0, h - 1, w, 1);
  53087. for (int i = header.getNumColumns (true); --i >= 0;)
  53088. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53089. }
  53090. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53091. int width, int height,
  53092. bool isMouseOver, bool isMouseDown,
  53093. int columnFlags)
  53094. {
  53095. if (isMouseDown)
  53096. g.fillAll (Colour (0x8899aadd));
  53097. else if (isMouseOver)
  53098. g.fillAll (Colour (0x5599aadd));
  53099. int rightOfText = width - 4;
  53100. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53101. {
  53102. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53103. const float bottom = height - top;
  53104. const float w = height * 0.5f;
  53105. const float x = rightOfText - (w * 1.25f);
  53106. rightOfText = (int) x;
  53107. Path sortArrow;
  53108. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53109. g.setColour (Colour (0x99000000));
  53110. g.fillPath (sortArrow);
  53111. }
  53112. g.setColour (Colours::black);
  53113. g.setFont (height * 0.5f, Font::bold);
  53114. const int textX = 4;
  53115. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53116. }
  53117. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53118. {
  53119. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53120. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53121. background.darker (0.1f),
  53122. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53123. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53124. false));
  53125. g.fillAll();
  53126. }
  53127. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53128. {
  53129. return createTabBarExtrasButton();
  53130. }
  53131. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53132. bool isMouseOver, bool isMouseDown,
  53133. ToolbarItemComponent& component)
  53134. {
  53135. if (isMouseDown)
  53136. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53137. else if (isMouseOver)
  53138. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53139. }
  53140. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53141. const String& text, ToolbarItemComponent& component)
  53142. {
  53143. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53144. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53145. const float fontHeight = jmin (14.0f, height * 0.85f);
  53146. g.setFont (fontHeight);
  53147. g.drawFittedText (text,
  53148. x, y, width, height,
  53149. Justification::centred,
  53150. jmax (1, height / (int) fontHeight));
  53151. }
  53152. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53153. bool isOpen, int width, int height)
  53154. {
  53155. const int buttonSize = (height * 3) / 4;
  53156. const int buttonIndent = (height - buttonSize) / 2;
  53157. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53158. const int textX = buttonIndent * 2 + buttonSize + 2;
  53159. g.setColour (Colours::black);
  53160. g.setFont (height * 0.7f, Font::bold);
  53161. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53162. }
  53163. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53164. PropertyComponent&)
  53165. {
  53166. g.setColour (Colour (0x66ffffff));
  53167. g.fillRect (0, 0, width, height - 1);
  53168. }
  53169. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53170. PropertyComponent& component)
  53171. {
  53172. g.setColour (Colours::black);
  53173. if (! component.isEnabled())
  53174. g.setOpacity (0.6f);
  53175. g.setFont (jmin (height, 24) * 0.65f);
  53176. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53177. g.drawFittedText (component.getName(),
  53178. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53179. Justification::centredLeft, 2);
  53180. }
  53181. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53182. {
  53183. return Rectangle<int> (component.getWidth() / 3, 1,
  53184. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53185. }
  53186. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53187. const String& instructions,
  53188. GlyphArrangement& text,
  53189. int width)
  53190. {
  53191. text.clear();
  53192. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53193. 8.0f, 22.0f, width - 16.0f,
  53194. Justification::centred);
  53195. text.addJustifiedText (Font (14.0f), instructions,
  53196. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53197. Justification::centred);
  53198. }
  53199. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53200. const String& filename, Image* icon,
  53201. const String& fileSizeDescription,
  53202. const String& fileTimeDescription,
  53203. const bool isDirectory,
  53204. const bool isItemSelected,
  53205. const int /*itemIndex*/)
  53206. {
  53207. if (isItemSelected)
  53208. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53209. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53210. g.setFont (height * 0.7f);
  53211. Image* im = icon;
  53212. Image* toRelease = 0;
  53213. if (im == 0)
  53214. {
  53215. toRelease = im = (isDirectory ? getDefaultFolderImage()
  53216. : getDefaultDocumentFileImage());
  53217. }
  53218. const int x = 32;
  53219. if (im != 0)
  53220. {
  53221. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53222. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53223. false);
  53224. ImageCache::release (toRelease);
  53225. }
  53226. if (width > 450 && ! isDirectory)
  53227. {
  53228. const int sizeX = roundToInt (width * 0.7f);
  53229. const int dateX = roundToInt (width * 0.8f);
  53230. g.drawFittedText (filename,
  53231. x, 0, sizeX - x, height,
  53232. Justification::centredLeft, 1);
  53233. g.setFont (height * 0.5f);
  53234. g.setColour (Colours::darkgrey);
  53235. if (! isDirectory)
  53236. {
  53237. g.drawFittedText (fileSizeDescription,
  53238. sizeX, 0, dateX - sizeX - 8, height,
  53239. Justification::centredRight, 1);
  53240. g.drawFittedText (fileTimeDescription,
  53241. dateX, 0, width - 8 - dateX, height,
  53242. Justification::centredRight, 1);
  53243. }
  53244. }
  53245. else
  53246. {
  53247. g.drawFittedText (filename,
  53248. x, 0, width - x, height,
  53249. Justification::centredLeft, 1);
  53250. }
  53251. }
  53252. Button* LookAndFeel::createFileBrowserGoUpButton()
  53253. {
  53254. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53255. Path arrowPath;
  53256. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  53257. DrawablePath arrowImage;
  53258. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53259. arrowImage.setPath (arrowPath);
  53260. goUpButton->setImages (&arrowImage);
  53261. return goUpButton;
  53262. }
  53263. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53264. DirectoryContentsDisplayComponent* fileListComponent,
  53265. FilePreviewComponent* previewComp,
  53266. ComboBox* currentPathBox,
  53267. TextEditor* filenameBox,
  53268. Button* goUpButton)
  53269. {
  53270. const int x = 8;
  53271. int w = browserComp.getWidth() - x - x;
  53272. if (previewComp != 0)
  53273. {
  53274. const int previewWidth = w / 3;
  53275. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53276. w -= previewWidth + 4;
  53277. }
  53278. int y = 4;
  53279. const int controlsHeight = 22;
  53280. const int bottomSectionHeight = controlsHeight + 8;
  53281. const int upButtonWidth = 50;
  53282. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53283. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53284. y += controlsHeight + 4;
  53285. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53286. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53287. y = listAsComp->getBottom() + 4;
  53288. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53289. }
  53290. Image* LookAndFeel::getDefaultFolderImage()
  53291. {
  53292. 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,
  53293. 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,
  53294. 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,
  53295. 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,
  53296. 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,
  53297. 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,
  53298. 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,
  53299. 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,
  53300. 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,
  53301. 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,
  53302. 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,
  53303. 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,
  53304. 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,
  53305. 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,
  53306. 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,
  53307. 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,
  53308. 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,
  53309. 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,
  53310. 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,
  53311. 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,
  53312. 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,
  53313. 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,
  53314. 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,
  53315. 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,
  53316. 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,
  53317. 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,
  53318. 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,
  53319. 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,
  53320. 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,
  53321. 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,
  53322. 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,
  53323. 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,
  53324. 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,
  53325. 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,
  53326. 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,
  53327. 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,
  53328. 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,
  53329. 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,
  53330. 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,
  53331. 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,
  53332. 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,
  53333. 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,
  53334. 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,
  53335. 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};
  53336. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53337. }
  53338. Image* LookAndFeel::getDefaultDocumentFileImage()
  53339. {
  53340. 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,
  53341. 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,
  53342. 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,
  53343. 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,
  53344. 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,
  53345. 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,
  53346. 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,
  53347. 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,
  53348. 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,
  53349. 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,
  53350. 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,
  53351. 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,
  53352. 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,
  53353. 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,
  53354. 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,
  53355. 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,
  53356. 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,
  53357. 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,
  53358. 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,
  53359. 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,
  53360. 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,
  53361. 174,66,96,130,0,0};
  53362. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53363. }
  53364. void LookAndFeel::playAlertSound()
  53365. {
  53366. PlatformUtilities::beep();
  53367. }
  53368. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53369. {
  53370. g.setColour (Colours::white.withAlpha (0.7f));
  53371. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53372. g.setColour (Colours::black.withAlpha (0.2f));
  53373. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53374. const int totalBlocks = 7;
  53375. const int numBlocks = roundToInt (totalBlocks * level);
  53376. const float w = (width - 6.0f) / (float) totalBlocks;
  53377. for (int i = 0; i < totalBlocks; ++i)
  53378. {
  53379. if (i >= numBlocks)
  53380. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53381. else
  53382. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53383. : Colours::red);
  53384. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53385. }
  53386. }
  53387. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53388. {
  53389. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53390. if (keyDescription.isNotEmpty())
  53391. {
  53392. if (button.isEnabled())
  53393. {
  53394. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53395. g.fillAll (textColour.withAlpha (alpha));
  53396. g.setOpacity (0.3f);
  53397. g.drawBevel (0, 0, width, height, 2);
  53398. }
  53399. g.setColour (textColour);
  53400. g.setFont (height * 0.6f);
  53401. g.drawFittedText (keyDescription,
  53402. 3, 0, width - 6, height,
  53403. Justification::centred, 1);
  53404. }
  53405. else
  53406. {
  53407. const float thickness = 7.0f;
  53408. const float indent = 22.0f;
  53409. Path p;
  53410. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53411. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53412. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53413. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53414. p.setUsingNonZeroWinding (false);
  53415. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53416. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53417. }
  53418. if (button.hasKeyboardFocus (false))
  53419. {
  53420. g.setColour (textColour.withAlpha (0.4f));
  53421. g.drawRect (0, 0, width, height);
  53422. }
  53423. }
  53424. static void createRoundedPath (Path& p,
  53425. const float x, const float y,
  53426. const float w, const float h,
  53427. const float cs,
  53428. const bool curveTopLeft, const bool curveTopRight,
  53429. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53430. {
  53431. const float cs2 = 2.0f * cs;
  53432. if (curveTopLeft)
  53433. {
  53434. p.startNewSubPath (x, y + cs);
  53435. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53436. }
  53437. else
  53438. {
  53439. p.startNewSubPath (x, y);
  53440. }
  53441. if (curveTopRight)
  53442. {
  53443. p.lineTo (x + w - cs, y);
  53444. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53445. }
  53446. else
  53447. {
  53448. p.lineTo (x + w, y);
  53449. }
  53450. if (curveBottomRight)
  53451. {
  53452. p.lineTo (x + w, y + h - cs);
  53453. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53454. }
  53455. else
  53456. {
  53457. p.lineTo (x + w, y + h);
  53458. }
  53459. if (curveBottomLeft)
  53460. {
  53461. p.lineTo (x + cs, y + h);
  53462. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53463. }
  53464. else
  53465. {
  53466. p.lineTo (x, y + h);
  53467. }
  53468. p.closeSubPath();
  53469. }
  53470. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53471. float x, float y, float w, float h,
  53472. float maxCornerSize,
  53473. const Colour& baseColour,
  53474. const float strokeWidth,
  53475. const bool flatOnLeft,
  53476. const bool flatOnRight,
  53477. const bool flatOnTop,
  53478. const bool flatOnBottom) throw()
  53479. {
  53480. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53481. return;
  53482. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53483. Path outline;
  53484. createRoundedPath (outline, x, y, w, h, cs,
  53485. ! (flatOnLeft || flatOnTop),
  53486. ! (flatOnRight || flatOnTop),
  53487. ! (flatOnLeft || flatOnBottom),
  53488. ! (flatOnRight || flatOnBottom));
  53489. ColourGradient cg (baseColour, 0.0f, y,
  53490. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53491. false);
  53492. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53493. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53494. g.setGradientFill (cg);
  53495. g.fillPath (outline);
  53496. g.setColour (Colour (0x80000000));
  53497. g.strokePath (outline, PathStrokeType (strokeWidth));
  53498. }
  53499. void LookAndFeel::drawGlassSphere (Graphics& g,
  53500. const float x, const float y,
  53501. const float diameter,
  53502. const Colour& colour,
  53503. const float outlineThickness) throw()
  53504. {
  53505. if (diameter <= outlineThickness)
  53506. return;
  53507. Path p;
  53508. p.addEllipse (x, y, diameter, diameter);
  53509. {
  53510. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53511. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53512. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53513. g.setGradientFill (cg);
  53514. g.fillPath (p);
  53515. }
  53516. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53517. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53518. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53519. ColourGradient cg (Colours::transparentBlack,
  53520. x + diameter * 0.5f, y + diameter * 0.5f,
  53521. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53522. x, y + diameter * 0.5f, true);
  53523. cg.addColour (0.7, Colours::transparentBlack);
  53524. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53525. g.setGradientFill (cg);
  53526. g.fillPath (p);
  53527. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53528. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53529. }
  53530. void LookAndFeel::drawGlassPointer (Graphics& g,
  53531. const float x, const float y,
  53532. const float diameter,
  53533. const Colour& colour, const float outlineThickness,
  53534. const int direction) throw()
  53535. {
  53536. if (diameter <= outlineThickness)
  53537. return;
  53538. Path p;
  53539. p.startNewSubPath (x + diameter * 0.5f, y);
  53540. p.lineTo (x + diameter, y + diameter * 0.6f);
  53541. p.lineTo (x + diameter, y + diameter);
  53542. p.lineTo (x, y + diameter);
  53543. p.lineTo (x, y + diameter * 0.6f);
  53544. p.closeSubPath();
  53545. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53546. {
  53547. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53548. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53549. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53550. g.setGradientFill (cg);
  53551. g.fillPath (p);
  53552. }
  53553. ColourGradient cg (Colours::transparentBlack,
  53554. x + diameter * 0.5f, y + diameter * 0.5f,
  53555. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53556. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53557. cg.addColour (0.5, Colours::transparentBlack);
  53558. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53559. g.setGradientFill (cg);
  53560. g.fillPath (p);
  53561. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53562. g.strokePath (p, PathStrokeType (outlineThickness));
  53563. }
  53564. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53565. const float x, const float y,
  53566. const float width, const float height,
  53567. const Colour& colour,
  53568. const float outlineThickness,
  53569. const float cornerSize,
  53570. const bool flatOnLeft,
  53571. const bool flatOnRight,
  53572. const bool flatOnTop,
  53573. const bool flatOnBottom) throw()
  53574. {
  53575. if (width <= outlineThickness || height <= outlineThickness)
  53576. return;
  53577. const int intX = (int) x;
  53578. const int intY = (int) y;
  53579. const int intW = (int) width;
  53580. const int intH = (int) height;
  53581. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53582. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53583. const int intEdge = (int) edgeBlurRadius;
  53584. Path outline;
  53585. createRoundedPath (outline, x, y, width, height, cs,
  53586. ! (flatOnLeft || flatOnTop),
  53587. ! (flatOnRight || flatOnTop),
  53588. ! (flatOnLeft || flatOnBottom),
  53589. ! (flatOnRight || flatOnBottom));
  53590. {
  53591. ColourGradient cg (colour.darker (0.2f), 0, y,
  53592. colour.darker (0.2f), 0, y + height, false);
  53593. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53594. cg.addColour (0.4, colour);
  53595. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53596. g.setGradientFill (cg);
  53597. g.fillPath (outline);
  53598. }
  53599. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53600. colour.darker (0.2f), x, y + height * 0.5f, true);
  53601. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53602. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53603. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53604. {
  53605. g.saveState();
  53606. g.setGradientFill (cg);
  53607. g.reduceClipRegion (intX, intY, intEdge, intH);
  53608. g.fillPath (outline);
  53609. g.restoreState();
  53610. }
  53611. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53612. {
  53613. cg.x1 = x + width - edgeBlurRadius;
  53614. cg.x2 = x + width;
  53615. g.saveState();
  53616. g.setGradientFill (cg);
  53617. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53618. g.fillPath (outline);
  53619. g.restoreState();
  53620. }
  53621. {
  53622. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53623. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53624. Path highlight;
  53625. createRoundedPath (highlight,
  53626. x + leftIndent,
  53627. y + cs * 0.1f,
  53628. width - (leftIndent + rightIndent),
  53629. height * 0.4f, cs * 0.4f,
  53630. ! (flatOnLeft || flatOnTop),
  53631. ! (flatOnRight || flatOnTop),
  53632. ! (flatOnLeft || flatOnBottom),
  53633. ! (flatOnRight || flatOnBottom));
  53634. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53635. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53636. g.fillPath (highlight);
  53637. }
  53638. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53639. g.strokePath (outline, PathStrokeType (outlineThickness));
  53640. }
  53641. END_JUCE_NAMESPACE
  53642. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53643. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53644. BEGIN_JUCE_NAMESPACE
  53645. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53646. {
  53647. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53648. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53649. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53650. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53651. setColour (Slider::thumbColourId, Colours::white);
  53652. setColour (Slider::trackColourId, Colour (0x7f000000));
  53653. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53654. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53655. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53656. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53657. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53658. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53659. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53660. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53661. }
  53662. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53663. {
  53664. }
  53665. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53666. Button& button,
  53667. const Colour& backgroundColour,
  53668. bool isMouseOverButton,
  53669. bool isButtonDown)
  53670. {
  53671. const int width = button.getWidth();
  53672. const int height = button.getHeight();
  53673. const float indent = 2.0f;
  53674. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53675. roundToInt (height * 0.4f));
  53676. Path p;
  53677. p.addRoundedRectangle (indent, indent,
  53678. width - indent * 2.0f,
  53679. height - indent * 2.0f,
  53680. (float) cornerSize);
  53681. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  53682. if (isMouseOverButton)
  53683. {
  53684. if (isButtonDown)
  53685. bc = bc.brighter();
  53686. else if (bc.getBrightness() > 0.5f)
  53687. bc = bc.darker (0.1f);
  53688. else
  53689. bc = bc.brighter (0.1f);
  53690. }
  53691. g.setColour (bc);
  53692. g.fillPath (p);
  53693. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  53694. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  53695. }
  53696. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  53697. Component& /*component*/,
  53698. float x, float y, float w, float h,
  53699. const bool ticked,
  53700. const bool isEnabled,
  53701. const bool /*isMouseOverButton*/,
  53702. const bool isButtonDown)
  53703. {
  53704. Path box;
  53705. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  53706. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  53707. : Colours::lightgrey.withAlpha (0.1f));
  53708. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  53709. g.fillPath (box, trans);
  53710. g.setColour (Colours::black.withAlpha (0.6f));
  53711. g.strokePath (box, PathStrokeType (0.9f), trans);
  53712. if (ticked)
  53713. {
  53714. Path tick;
  53715. tick.startNewSubPath (1.5f, 3.0f);
  53716. tick.lineTo (3.0f, 6.0f);
  53717. tick.lineTo (6.0f, 0.0f);
  53718. g.setColour (isEnabled ? Colours::black : Colours::grey);
  53719. g.strokePath (tick, PathStrokeType (2.5f), trans);
  53720. }
  53721. }
  53722. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  53723. ToggleButton& button,
  53724. bool isMouseOverButton,
  53725. bool isButtonDown)
  53726. {
  53727. if (button.hasKeyboardFocus (true))
  53728. {
  53729. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  53730. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  53731. }
  53732. const int tickWidth = jmin (20, button.getHeight() - 4);
  53733. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  53734. (float) tickWidth, (float) tickWidth,
  53735. button.getToggleState(),
  53736. button.isEnabled(),
  53737. isMouseOverButton,
  53738. isButtonDown);
  53739. g.setColour (button.findColour (ToggleButton::textColourId));
  53740. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  53741. if (! button.isEnabled())
  53742. g.setOpacity (0.5f);
  53743. const int textX = tickWidth + 5;
  53744. g.drawFittedText (button.getButtonText(),
  53745. textX, 4,
  53746. button.getWidth() - textX - 2, button.getHeight() - 8,
  53747. Justification::centredLeft, 10);
  53748. }
  53749. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53750. int width, int height,
  53751. double progress, const String& textToShow)
  53752. {
  53753. if (progress < 0 || progress >= 1.0)
  53754. {
  53755. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  53756. }
  53757. else
  53758. {
  53759. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53760. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53761. g.fillAll (background);
  53762. g.setColour (foreground);
  53763. g.fillRect (1, 1,
  53764. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  53765. height - 2);
  53766. if (textToShow.isNotEmpty())
  53767. {
  53768. g.setColour (Colour::contrasting (background, foreground));
  53769. g.setFont (height * 0.6f);
  53770. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53771. }
  53772. }
  53773. }
  53774. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  53775. ScrollBar& bar,
  53776. int width, int height,
  53777. int buttonDirection,
  53778. bool isScrollbarVertical,
  53779. bool isMouseOverButton,
  53780. bool isButtonDown)
  53781. {
  53782. if (isScrollbarVertical)
  53783. width -= 2;
  53784. else
  53785. height -= 2;
  53786. Path p;
  53787. if (buttonDirection == 0)
  53788. p.addTriangle (width * 0.5f, height * 0.2f,
  53789. width * 0.1f, height * 0.7f,
  53790. width * 0.9f, height * 0.7f);
  53791. else if (buttonDirection == 1)
  53792. p.addTriangle (width * 0.8f, height * 0.5f,
  53793. width * 0.3f, height * 0.1f,
  53794. width * 0.3f, height * 0.9f);
  53795. else if (buttonDirection == 2)
  53796. p.addTriangle (width * 0.5f, height * 0.8f,
  53797. width * 0.1f, height * 0.3f,
  53798. width * 0.9f, height * 0.3f);
  53799. else if (buttonDirection == 3)
  53800. p.addTriangle (width * 0.2f, height * 0.5f,
  53801. width * 0.7f, height * 0.1f,
  53802. width * 0.7f, height * 0.9f);
  53803. if (isButtonDown)
  53804. g.setColour (Colours::white);
  53805. else if (isMouseOverButton)
  53806. g.setColour (Colours::white.withAlpha (0.7f));
  53807. else
  53808. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  53809. g.fillPath (p);
  53810. g.setColour (Colours::black.withAlpha (0.5f));
  53811. g.strokePath (p, PathStrokeType (0.5f));
  53812. }
  53813. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  53814. ScrollBar& bar,
  53815. int x, int y,
  53816. int width, int height,
  53817. bool isScrollbarVertical,
  53818. int thumbStartPosition,
  53819. int thumbSize,
  53820. bool isMouseOver,
  53821. bool isMouseDown)
  53822. {
  53823. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  53824. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53825. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  53826. if (thumbSize > 0.0f)
  53827. {
  53828. Rectangle<int> thumb;
  53829. if (isScrollbarVertical)
  53830. {
  53831. width -= 2;
  53832. g.fillRect (x + roundToInt (width * 0.35f), y,
  53833. roundToInt (width * 0.3f), height);
  53834. thumb.setBounds (x + 1, thumbStartPosition,
  53835. width - 2, thumbSize);
  53836. }
  53837. else
  53838. {
  53839. height -= 2;
  53840. g.fillRect (x, y + roundToInt (height * 0.35f),
  53841. width, roundToInt (height * 0.3f));
  53842. thumb.setBounds (thumbStartPosition, y + 1,
  53843. thumbSize, height - 2);
  53844. }
  53845. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53846. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  53847. g.fillRect (thumb);
  53848. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  53849. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  53850. if (thumbSize > 16)
  53851. {
  53852. for (int i = 3; --i >= 0;)
  53853. {
  53854. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  53855. g.setColour (Colours::black.withAlpha (0.15f));
  53856. if (isScrollbarVertical)
  53857. {
  53858. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  53859. g.setColour (Colours::white.withAlpha (0.15f));
  53860. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  53861. }
  53862. else
  53863. {
  53864. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  53865. g.setColour (Colours::white.withAlpha (0.15f));
  53866. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  53867. }
  53868. }
  53869. }
  53870. }
  53871. }
  53872. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  53873. {
  53874. return &scrollbarShadow;
  53875. }
  53876. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53877. {
  53878. g.fillAll (findColour (PopupMenu::backgroundColourId));
  53879. g.setColour (Colours::black.withAlpha (0.6f));
  53880. g.drawRect (0, 0, width, height);
  53881. }
  53882. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  53883. bool, MenuBarComponent& menuBar)
  53884. {
  53885. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  53886. }
  53887. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53888. {
  53889. if (textEditor.isEnabled())
  53890. {
  53891. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53892. g.drawRect (0, 0, width, height);
  53893. }
  53894. }
  53895. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53896. const bool isButtonDown,
  53897. int buttonX, int buttonY,
  53898. int buttonW, int buttonH,
  53899. ComboBox& box)
  53900. {
  53901. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53902. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  53903. : ComboBox::backgroundColourId));
  53904. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  53905. g.setColour (box.findColour (ComboBox::outlineColourId));
  53906. g.drawRect (0, 0, width, height);
  53907. const float arrowX = 0.2f;
  53908. const float arrowH = 0.3f;
  53909. if (box.isEnabled())
  53910. {
  53911. Path p;
  53912. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53913. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53914. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53915. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53916. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53917. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53918. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  53919. : ComboBox::buttonColourId));
  53920. g.fillPath (p);
  53921. }
  53922. }
  53923. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  53924. {
  53925. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  53926. f.setHorizontalScale (0.9f);
  53927. return f;
  53928. }
  53929. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  53930. {
  53931. Path p;
  53932. p.addTriangle (x1, y1, x2, y2, x3, y3);
  53933. g.setColour (fill);
  53934. g.fillPath (p);
  53935. g.setColour (outline);
  53936. g.strokePath (p, PathStrokeType (0.3f));
  53937. }
  53938. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  53939. int x, int y,
  53940. int w, int h,
  53941. float sliderPos,
  53942. float minSliderPos,
  53943. float maxSliderPos,
  53944. const Slider::SliderStyle style,
  53945. Slider& slider)
  53946. {
  53947. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53948. if (style == Slider::LinearBar)
  53949. {
  53950. g.setColour (slider.findColour (Slider::thumbColourId));
  53951. g.fillRect (x, y, (int) sliderPos - x, h);
  53952. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  53953. g.drawRect (x, y, (int) sliderPos - x, h);
  53954. }
  53955. else
  53956. {
  53957. g.setColour (slider.findColour (Slider::trackColourId)
  53958. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  53959. if (slider.isHorizontal())
  53960. {
  53961. g.fillRect (x, y + roundToInt (h * 0.6f),
  53962. w, roundToInt (h * 0.2f));
  53963. }
  53964. else
  53965. {
  53966. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  53967. jmin (4, roundToInt (w * 0.2f)), h);
  53968. }
  53969. float alpha = 0.35f;
  53970. if (slider.isEnabled())
  53971. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  53972. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  53973. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  53974. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53975. {
  53976. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  53977. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  53978. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  53979. fill, outline);
  53980. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  53981. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  53982. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  53983. fill, outline);
  53984. }
  53985. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53986. {
  53987. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  53988. minSliderPos - 7.0f, y + h * 0.9f ,
  53989. minSliderPos, y + h * 0.9f,
  53990. fill, outline);
  53991. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  53992. maxSliderPos, y + h * 0.9f,
  53993. maxSliderPos + 7.0f, y + h * 0.9f,
  53994. fill, outline);
  53995. }
  53996. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  53997. {
  53998. drawTriangle (g, sliderPos, y + h * 0.9f,
  53999. sliderPos - 7.0f, y + h * 0.2f,
  54000. sliderPos + 7.0f, y + h * 0.2f,
  54001. fill, outline);
  54002. }
  54003. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54004. {
  54005. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54006. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54007. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54008. fill, outline);
  54009. }
  54010. }
  54011. }
  54012. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54013. {
  54014. if (isIncrement)
  54015. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54016. else
  54017. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54018. }
  54019. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54020. {
  54021. return &scrollbarShadow;
  54022. }
  54023. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54024. {
  54025. return 8;
  54026. }
  54027. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54028. int w, int h,
  54029. bool isMouseOver,
  54030. bool isMouseDragging)
  54031. {
  54032. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54033. : Colours::darkgrey);
  54034. const float lineThickness = jmin (w, h) * 0.1f;
  54035. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54036. {
  54037. g.drawLine (w * i,
  54038. h + 1.0f,
  54039. w + 1.0f,
  54040. h * i,
  54041. lineThickness);
  54042. }
  54043. }
  54044. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54045. {
  54046. Path shape;
  54047. if (buttonType == DocumentWindow::closeButton)
  54048. {
  54049. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  54050. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  54051. ShapeButton* const b = new ShapeButton ("close",
  54052. Colour (0x7fff3333),
  54053. Colour (0xd7ff3333),
  54054. Colour (0xf7ff3333));
  54055. b->setShape (shape, true, true, true);
  54056. return b;
  54057. }
  54058. else if (buttonType == DocumentWindow::minimiseButton)
  54059. {
  54060. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54061. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54062. DrawablePath dp;
  54063. dp.setPath (shape);
  54064. dp.setFill (Colours::black.withAlpha (0.3f));
  54065. b->setImages (&dp);
  54066. return b;
  54067. }
  54068. else if (buttonType == DocumentWindow::maximiseButton)
  54069. {
  54070. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  54071. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54072. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54073. DrawablePath dp;
  54074. dp.setPath (shape);
  54075. dp.setFill (Colours::black.withAlpha (0.3f));
  54076. b->setImages (&dp);
  54077. return b;
  54078. }
  54079. jassertfalse
  54080. return 0;
  54081. }
  54082. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54083. int titleBarX,
  54084. int titleBarY,
  54085. int titleBarW,
  54086. int titleBarH,
  54087. Button* minimiseButton,
  54088. Button* maximiseButton,
  54089. Button* closeButton,
  54090. bool positionTitleBarButtonsOnLeft)
  54091. {
  54092. titleBarY += titleBarH / 8;
  54093. titleBarH -= titleBarH / 4;
  54094. const int buttonW = titleBarH;
  54095. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54096. : titleBarX + titleBarW - buttonW - 4;
  54097. if (closeButton != 0)
  54098. {
  54099. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54100. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54101. : -(buttonW + buttonW / 5);
  54102. }
  54103. if (positionTitleBarButtonsOnLeft)
  54104. swapVariables (minimiseButton, maximiseButton);
  54105. if (maximiseButton != 0)
  54106. {
  54107. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54108. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54109. }
  54110. if (minimiseButton != 0)
  54111. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54112. }
  54113. END_JUCE_NAMESPACE
  54114. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54115. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54116. BEGIN_JUCE_NAMESPACE
  54117. class DummyMenuComponent : public Component
  54118. {
  54119. DummyMenuComponent (const DummyMenuComponent&);
  54120. DummyMenuComponent& operator= (const DummyMenuComponent&);
  54121. public:
  54122. DummyMenuComponent() {}
  54123. ~DummyMenuComponent() {}
  54124. void inputAttemptWhenModal()
  54125. {
  54126. exitModalState (0);
  54127. }
  54128. };
  54129. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54130. : model (0),
  54131. itemUnderMouse (-1),
  54132. currentPopupIndex (-1),
  54133. indexToShowAgain (-1),
  54134. lastMouseX (0),
  54135. lastMouseY (0),
  54136. inModalState (false)
  54137. {
  54138. setRepaintsOnMouseActivity (true);
  54139. setWantsKeyboardFocus (false);
  54140. setMouseClickGrabsKeyboardFocus (false);
  54141. setModel (model_);
  54142. }
  54143. MenuBarComponent::~MenuBarComponent()
  54144. {
  54145. setModel (0);
  54146. Desktop::getInstance().removeGlobalMouseListener (this);
  54147. currentPopup = 0;
  54148. }
  54149. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54150. {
  54151. if (model != newModel)
  54152. {
  54153. if (model != 0)
  54154. model->removeListener (this);
  54155. model = newModel;
  54156. if (model != 0)
  54157. model->addListener (this);
  54158. repaint();
  54159. menuBarItemsChanged (0);
  54160. }
  54161. }
  54162. void MenuBarComponent::paint (Graphics& g)
  54163. {
  54164. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54165. getLookAndFeel().drawMenuBarBackground (g,
  54166. getWidth(),
  54167. getHeight(),
  54168. isMouseOverBar,
  54169. *this);
  54170. if (model != 0)
  54171. {
  54172. for (int i = 0; i < menuNames.size(); ++i)
  54173. {
  54174. g.saveState();
  54175. g.setOrigin (xPositions [i], 0);
  54176. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54177. getLookAndFeel().drawMenuBarItem (g,
  54178. xPositions[i + 1] - xPositions[i],
  54179. getHeight(),
  54180. i,
  54181. menuNames[i],
  54182. i == itemUnderMouse,
  54183. i == currentPopupIndex,
  54184. isMouseOverBar,
  54185. *this);
  54186. g.restoreState();
  54187. }
  54188. }
  54189. }
  54190. void MenuBarComponent::resized()
  54191. {
  54192. xPositions.clear();
  54193. int x = 2;
  54194. xPositions.add (x);
  54195. for (int i = 0; i < menuNames.size(); ++i)
  54196. {
  54197. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54198. xPositions.add (x);
  54199. }
  54200. }
  54201. int MenuBarComponent::getItemAt (const int x, const int y)
  54202. {
  54203. for (int i = 0; i < xPositions.size(); ++i)
  54204. if (x >= xPositions[i] && x < xPositions[i + 1])
  54205. return reallyContains (x, y, true) ? i : -1;
  54206. return -1;
  54207. }
  54208. void MenuBarComponent::repaintMenuItem (int index)
  54209. {
  54210. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54211. {
  54212. const int x1 = xPositions [index];
  54213. const int x2 = xPositions [index + 1];
  54214. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54215. }
  54216. }
  54217. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54218. {
  54219. const int newItem = getItemAt (x, y);
  54220. if (itemUnderMouse != newItem)
  54221. {
  54222. repaintMenuItem (itemUnderMouse);
  54223. itemUnderMouse = newItem;
  54224. repaintMenuItem (itemUnderMouse);
  54225. }
  54226. }
  54227. void MenuBarComponent::hideCurrentMenu()
  54228. {
  54229. currentPopup = 0;
  54230. repaint();
  54231. }
  54232. void MenuBarComponent::showMenu (int index)
  54233. {
  54234. if (index != currentPopupIndex)
  54235. {
  54236. if (inModalState)
  54237. {
  54238. hideCurrentMenu();
  54239. indexToShowAgain = index;
  54240. return;
  54241. }
  54242. indexToShowAgain = -1;
  54243. currentPopupIndex = -1;
  54244. itemUnderMouse = index;
  54245. currentPopup = 0;
  54246. menuBarItemsChanged (0);
  54247. Component::SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  54248. Component::SafePointer<Component> deletionChecker (this);
  54249. enterModalState (false);
  54250. inModalState = true;
  54251. int result = 0;
  54252. ApplicationCommandManager* managerOfChosenCommand = 0;
  54253. Desktop::getInstance().addGlobalMouseListener (this);
  54254. for (;;)
  54255. {
  54256. const int x = getScreenX() + xPositions [itemUnderMouse];
  54257. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  54258. currentPopupIndex = itemUnderMouse;
  54259. indexToShowAgain = -1;
  54260. repaint();
  54261. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  54262. {
  54263. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54264. menuNames [itemUnderMouse]));
  54265. if (m.lookAndFeel == 0)
  54266. m.setLookAndFeel (&getLookAndFeel());
  54267. currentPopup = m.createMenuComponent (x, getScreenY(),
  54268. w, getHeight(),
  54269. 0, w, 0, 0,
  54270. true, this,
  54271. &managerOfChosenCommand,
  54272. this);
  54273. }
  54274. if (currentPopup == 0)
  54275. {
  54276. currentPopup = new DummyMenuComponent();
  54277. addAndMakeVisible (currentPopup);
  54278. }
  54279. currentPopup->enterModalState (false);
  54280. currentPopup->toFront (false); // need to do this after making it modal, or it could
  54281. // be stuck behind other comps that are already modal..
  54282. result = currentPopup->runModalLoop();
  54283. if (deletionChecker == 0)
  54284. return;
  54285. const int lastPopupIndex = currentPopupIndex;
  54286. currentPopup = 0;
  54287. currentPopupIndex = -1;
  54288. if (result != 0)
  54289. {
  54290. topLevelIndexClicked = lastPopupIndex;
  54291. break;
  54292. }
  54293. else if (indexToShowAgain >= 0)
  54294. {
  54295. menuBarItemsChanged (0);
  54296. repaint();
  54297. itemUnderMouse = indexToShowAgain;
  54298. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  54299. break;
  54300. }
  54301. else
  54302. {
  54303. break;
  54304. }
  54305. }
  54306. Desktop::getInstance().removeGlobalMouseListener (this);
  54307. inModalState = false;
  54308. exitModalState (0);
  54309. if (prevFocused != 0)
  54310. prevFocused->grabKeyboardFocus();
  54311. const Point<int> mousePos (getMouseXYRelative());
  54312. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54313. repaint();
  54314. if (result != 0)
  54315. {
  54316. if (managerOfChosenCommand != 0)
  54317. {
  54318. ApplicationCommandTarget::InvocationInfo info (result);
  54319. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  54320. managerOfChosenCommand->invoke (info, true);
  54321. }
  54322. postCommandMessage (result);
  54323. }
  54324. }
  54325. }
  54326. void MenuBarComponent::handleCommandMessage (int commandId)
  54327. {
  54328. if (model != 0)
  54329. model->menuItemSelected (commandId, topLevelIndexClicked);
  54330. }
  54331. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54332. {
  54333. if (e.eventComponent == this)
  54334. updateItemUnderMouse (e.x, e.y);
  54335. }
  54336. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54337. {
  54338. if (e.eventComponent == this)
  54339. updateItemUnderMouse (e.x, e.y);
  54340. }
  54341. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54342. {
  54343. if (currentPopupIndex < 0)
  54344. {
  54345. const MouseEvent e2 (e.getEventRelativeTo (this));
  54346. updateItemUnderMouse (e2.x, e2.y);
  54347. currentPopupIndex = -2;
  54348. showMenu (itemUnderMouse);
  54349. }
  54350. }
  54351. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54352. {
  54353. const MouseEvent e2 (e.getEventRelativeTo (this));
  54354. const int item = getItemAt (e2.x, e2.y);
  54355. if (item >= 0)
  54356. showMenu (item);
  54357. }
  54358. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54359. {
  54360. const MouseEvent e2 (e.getEventRelativeTo (this));
  54361. updateItemUnderMouse (e2.x, e2.y);
  54362. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (static_cast <Component*> (currentPopup)) != 0)
  54363. hideCurrentMenu();
  54364. }
  54365. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54366. {
  54367. const MouseEvent e2 (e.getEventRelativeTo (this));
  54368. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54369. {
  54370. if (currentPopupIndex >= 0)
  54371. {
  54372. const int item = getItemAt (e2.x, e2.y);
  54373. if (item >= 0)
  54374. showMenu (item);
  54375. }
  54376. else
  54377. {
  54378. updateItemUnderMouse (e2.x, e2.y);
  54379. }
  54380. lastMouseX = e2.x;
  54381. lastMouseY = e2.y;
  54382. }
  54383. }
  54384. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54385. {
  54386. bool used = false;
  54387. const int numMenus = menuNames.size();
  54388. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54389. if (key.isKeyCode (KeyPress::leftKey))
  54390. {
  54391. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54392. used = true;
  54393. }
  54394. else if (key.isKeyCode (KeyPress::rightKey))
  54395. {
  54396. showMenu ((currentIndex + 1) % numMenus);
  54397. used = true;
  54398. }
  54399. return used;
  54400. }
  54401. void MenuBarComponent::inputAttemptWhenModal()
  54402. {
  54403. hideCurrentMenu();
  54404. }
  54405. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54406. {
  54407. StringArray newNames;
  54408. if (model != 0)
  54409. newNames = model->getMenuBarNames();
  54410. if (newNames != menuNames)
  54411. {
  54412. menuNames = newNames;
  54413. repaint();
  54414. resized();
  54415. }
  54416. }
  54417. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54418. const ApplicationCommandTarget::InvocationInfo& info)
  54419. {
  54420. if (model == 0
  54421. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54422. return;
  54423. for (int i = 0; i < menuNames.size(); ++i)
  54424. {
  54425. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54426. if (menu.containsCommandItem (info.commandID))
  54427. {
  54428. itemUnderMouse = i;
  54429. repaintMenuItem (i);
  54430. startTimer (200);
  54431. break;
  54432. }
  54433. }
  54434. }
  54435. void MenuBarComponent::timerCallback()
  54436. {
  54437. stopTimer();
  54438. const Point<int> mousePos (getMouseXYRelative());
  54439. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54440. }
  54441. END_JUCE_NAMESPACE
  54442. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54443. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54444. BEGIN_JUCE_NAMESPACE
  54445. MenuBarModel::MenuBarModel() throw()
  54446. : manager (0)
  54447. {
  54448. }
  54449. MenuBarModel::~MenuBarModel()
  54450. {
  54451. setApplicationCommandManagerToWatch (0);
  54452. }
  54453. void MenuBarModel::menuItemsChanged()
  54454. {
  54455. triggerAsyncUpdate();
  54456. }
  54457. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54458. {
  54459. if (manager != newManager)
  54460. {
  54461. if (manager != 0)
  54462. manager->removeListener (this);
  54463. manager = newManager;
  54464. if (manager != 0)
  54465. manager->addListener (this);
  54466. }
  54467. }
  54468. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54469. {
  54470. listeners.add (newListener);
  54471. }
  54472. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54473. {
  54474. // Trying to remove a listener that isn't on the list!
  54475. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54476. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54477. jassert (listeners.contains (listenerToRemove));
  54478. listeners.remove (listenerToRemove);
  54479. }
  54480. void MenuBarModel::handleAsyncUpdate()
  54481. {
  54482. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54483. }
  54484. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54485. {
  54486. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54487. }
  54488. void MenuBarModel::applicationCommandListChanged()
  54489. {
  54490. menuItemsChanged();
  54491. }
  54492. END_JUCE_NAMESPACE
  54493. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54494. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54495. BEGIN_JUCE_NAMESPACE
  54496. class PopupMenu::Item
  54497. {
  54498. public:
  54499. Item()
  54500. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54501. usesColour (false), customComp (0), commandManager (0)
  54502. {
  54503. }
  54504. Item (const int itemId_,
  54505. const String& text_,
  54506. const bool active_,
  54507. const bool isTicked_,
  54508. const Image* im,
  54509. const Colour& textColour_,
  54510. const bool usesColour_,
  54511. PopupMenuCustomComponent* const customComp_,
  54512. const PopupMenu* const subMenu_,
  54513. ApplicationCommandManager* const commandManager_)
  54514. : itemId (itemId_), text (text_), textColour (textColour_),
  54515. active (active_), isSeparator (false), isTicked (isTicked_),
  54516. usesColour (usesColour_), customComp (customComp_),
  54517. commandManager (commandManager_)
  54518. {
  54519. if (subMenu_ != 0)
  54520. subMenu = new PopupMenu (*subMenu_);
  54521. if (im != 0)
  54522. image = im->createCopy();
  54523. if (commandManager_ != 0 && itemId_ != 0)
  54524. {
  54525. String shortcutKey;
  54526. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54527. ->getKeyPressesAssignedToCommand (itemId_));
  54528. for (int i = 0; i < keyPresses.size(); ++i)
  54529. {
  54530. const String key (keyPresses.getReference(i).getTextDescription());
  54531. if (shortcutKey.isNotEmpty())
  54532. shortcutKey << ", ";
  54533. if (key.length() == 1)
  54534. shortcutKey << "shortcut: '" << key << '\'';
  54535. else
  54536. shortcutKey << key;
  54537. }
  54538. shortcutKey = shortcutKey.trim();
  54539. if (shortcutKey.isNotEmpty())
  54540. text << "<end>" << shortcutKey;
  54541. }
  54542. }
  54543. Item (const Item& other)
  54544. : itemId (other.itemId),
  54545. text (other.text),
  54546. textColour (other.textColour),
  54547. active (other.active),
  54548. isSeparator (other.isSeparator),
  54549. isTicked (other.isTicked),
  54550. usesColour (other.usesColour),
  54551. customComp (other.customComp),
  54552. commandManager (other.commandManager)
  54553. {
  54554. if (other.subMenu != 0)
  54555. subMenu = new PopupMenu (*(other.subMenu));
  54556. if (other.image != 0)
  54557. image = other.image->createCopy();
  54558. }
  54559. ~Item()
  54560. {
  54561. customComp = 0;
  54562. }
  54563. bool canBeTriggered() const throw()
  54564. {
  54565. return active && ! (isSeparator || (subMenu != 0));
  54566. }
  54567. bool hasActiveSubMenu() const throw()
  54568. {
  54569. return active && (subMenu != 0);
  54570. }
  54571. const int itemId;
  54572. String text;
  54573. const Colour textColour;
  54574. const bool active, isSeparator, isTicked, usesColour;
  54575. ScopedPointer <Image> image;
  54576. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54577. ScopedPointer <PopupMenu> subMenu;
  54578. ApplicationCommandManager* const commandManager;
  54579. juce_UseDebuggingNewOperator
  54580. private:
  54581. Item& operator= (const Item&);
  54582. };
  54583. class PopupMenu::ItemComponent : public Component
  54584. {
  54585. public:
  54586. ItemComponent (const PopupMenu::Item& itemInfo_)
  54587. : itemInfo (itemInfo_),
  54588. isHighlighted (false)
  54589. {
  54590. if (itemInfo.customComp != 0)
  54591. addAndMakeVisible (itemInfo.customComp);
  54592. }
  54593. ~ItemComponent()
  54594. {
  54595. if (itemInfo.customComp != 0)
  54596. removeChildComponent (itemInfo.customComp);
  54597. }
  54598. void getIdealSize (int& idealWidth,
  54599. int& idealHeight,
  54600. const int standardItemHeight)
  54601. {
  54602. if (itemInfo.customComp != 0)
  54603. {
  54604. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54605. }
  54606. else
  54607. {
  54608. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54609. itemInfo.isSeparator,
  54610. standardItemHeight,
  54611. idealWidth,
  54612. idealHeight);
  54613. }
  54614. }
  54615. void paint (Graphics& g)
  54616. {
  54617. if (itemInfo.customComp == 0)
  54618. {
  54619. String mainText (itemInfo.text);
  54620. String endText;
  54621. const int endIndex = mainText.indexOf ("<end>");
  54622. if (endIndex >= 0)
  54623. {
  54624. endText = mainText.substring (endIndex + 5).trim();
  54625. mainText = mainText.substring (0, endIndex);
  54626. }
  54627. getLookAndFeel()
  54628. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54629. itemInfo.isSeparator,
  54630. itemInfo.active,
  54631. isHighlighted,
  54632. itemInfo.isTicked,
  54633. itemInfo.subMenu != 0,
  54634. mainText, endText,
  54635. itemInfo.image,
  54636. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54637. }
  54638. }
  54639. void resized()
  54640. {
  54641. if (getNumChildComponents() > 0)
  54642. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54643. }
  54644. void setHighlighted (bool shouldBeHighlighted)
  54645. {
  54646. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54647. if (isHighlighted != shouldBeHighlighted)
  54648. {
  54649. isHighlighted = shouldBeHighlighted;
  54650. if (itemInfo.customComp != 0)
  54651. {
  54652. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54653. itemInfo.customComp->repaint();
  54654. }
  54655. repaint();
  54656. }
  54657. }
  54658. PopupMenu::Item itemInfo;
  54659. juce_UseDebuggingNewOperator
  54660. private:
  54661. bool isHighlighted;
  54662. ItemComponent (const ItemComponent&);
  54663. ItemComponent& operator= (const ItemComponent&);
  54664. };
  54665. namespace PopupMenuSettings
  54666. {
  54667. static const int scrollZone = 24;
  54668. static const int borderSize = 2;
  54669. static const int timerInterval = 50;
  54670. static const int dismissCommandId = 0x6287345f;
  54671. }
  54672. class PopupMenu::Window : public Component,
  54673. private Timer
  54674. {
  54675. public:
  54676. Window()
  54677. : Component ("menu"),
  54678. owner (0),
  54679. currentChild (0),
  54680. activeSubMenu (0),
  54681. menuBarComponent (0),
  54682. managerOfChosenCommand (0),
  54683. minimumWidth (0),
  54684. maximumNumColumns (7),
  54685. standardItemHeight (0),
  54686. isOver (false),
  54687. hasBeenOver (false),
  54688. isDown (false),
  54689. needsToScroll (false),
  54690. hideOnExit (false),
  54691. disableMouseMoves (false),
  54692. hasAnyJuceCompHadFocus (false),
  54693. numColumns (0),
  54694. contentHeight (0),
  54695. childYOffset (0),
  54696. timeEnteredCurrentChildComp (0),
  54697. scrollAcceleration (1.0)
  54698. {
  54699. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54700. setWantsKeyboardFocus (true);
  54701. setMouseClickGrabsKeyboardFocus (false);
  54702. setOpaque (true);
  54703. setAlwaysOnTop (true);
  54704. Desktop::getInstance().addGlobalMouseListener (this);
  54705. getActiveWindows().add (this);
  54706. }
  54707. ~Window()
  54708. {
  54709. getActiveWindows().removeValue (this);
  54710. Desktop::getInstance().removeGlobalMouseListener (this);
  54711. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54712. activeSubMenu = 0;
  54713. deleteAllChildren();
  54714. }
  54715. static Window* create (const PopupMenu& menu,
  54716. const bool dismissOnMouseUp,
  54717. Window* const owner_,
  54718. const int minX, const int maxX,
  54719. const int minY, const int maxY,
  54720. const int minimumWidth,
  54721. const int maximumNumColumns,
  54722. const int standardItemHeight,
  54723. const bool alignToRectangle,
  54724. const int itemIdThatMustBeVisible,
  54725. Component* const menuBarComponent,
  54726. ApplicationCommandManager** managerOfChosenCommand,
  54727. Component* const componentAttachedTo)
  54728. {
  54729. if (menu.items.size() > 0)
  54730. {
  54731. int totalItems = 0;
  54732. ScopedPointer <Window> mw (new Window());
  54733. mw->setLookAndFeel (menu.lookAndFeel);
  54734. mw->setWantsKeyboardFocus (false);
  54735. mw->minimumWidth = minimumWidth;
  54736. mw->maximumNumColumns = maximumNumColumns;
  54737. mw->standardItemHeight = standardItemHeight;
  54738. mw->dismissOnMouseUp = dismissOnMouseUp;
  54739. for (int i = 0; i < menu.items.size(); ++i)
  54740. {
  54741. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  54742. mw->addItem (*item);
  54743. ++totalItems;
  54744. }
  54745. if (totalItems > 0)
  54746. {
  54747. mw->owner = owner_;
  54748. mw->menuBarComponent = menuBarComponent;
  54749. mw->managerOfChosenCommand = managerOfChosenCommand;
  54750. mw->componentAttachedTo = componentAttachedTo;
  54751. mw->componentAttachedToOriginal = componentAttachedTo;
  54752. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  54753. mw->setTopLeftPosition (mw->windowPos.getX(),
  54754. mw->windowPos.getY());
  54755. mw->updateYPositions();
  54756. if (itemIdThatMustBeVisible != 0)
  54757. {
  54758. const int y = minY - mw->windowPos.getY();
  54759. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  54760. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  54761. }
  54762. mw->resizeToBestWindowPos();
  54763. mw->addToDesktop (ComponentPeer::windowIsTemporary
  54764. | mw->getLookAndFeel().getMenuWindowFlags());
  54765. return mw.release();
  54766. }
  54767. }
  54768. return 0;
  54769. }
  54770. void paint (Graphics& g)
  54771. {
  54772. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  54773. }
  54774. void paintOverChildren (Graphics& g)
  54775. {
  54776. if (isScrolling())
  54777. {
  54778. LookAndFeel& lf = getLookAndFeel();
  54779. if (isScrollZoneActive (false))
  54780. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  54781. if (isScrollZoneActive (true))
  54782. {
  54783. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  54784. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  54785. }
  54786. }
  54787. }
  54788. bool isScrollZoneActive (bool bottomOne) const
  54789. {
  54790. return isScrolling()
  54791. && (bottomOne
  54792. ? childYOffset < contentHeight - windowPos.getHeight()
  54793. : childYOffset > 0);
  54794. }
  54795. void addItem (const PopupMenu::Item& item)
  54796. {
  54797. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  54798. addAndMakeVisible (mic);
  54799. int itemW = 80;
  54800. int itemH = 16;
  54801. mic->getIdealSize (itemW, itemH, standardItemHeight);
  54802. mic->setSize (itemW, jlimit (2, 600, itemH));
  54803. mic->addMouseListener (this, false);
  54804. }
  54805. // hide this and all sub-comps
  54806. void hide (const PopupMenu::Item* const item)
  54807. {
  54808. if (isVisible())
  54809. {
  54810. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54811. activeSubMenu = 0;
  54812. currentChild = 0;
  54813. exitModalState (item != 0 ? item->itemId : 0);
  54814. setVisible (false);
  54815. if (item != 0
  54816. && item->commandManager != 0
  54817. && item->itemId != 0)
  54818. {
  54819. *managerOfChosenCommand = item->commandManager;
  54820. }
  54821. }
  54822. }
  54823. void dismissMenu (const PopupMenu::Item* const item)
  54824. {
  54825. if (owner != 0)
  54826. {
  54827. owner->dismissMenu (item);
  54828. }
  54829. else
  54830. {
  54831. if (item != 0)
  54832. {
  54833. // need a copy of this on the stack as the one passed in will get deleted during this call
  54834. const PopupMenu::Item mi (*item);
  54835. hide (&mi);
  54836. }
  54837. else
  54838. {
  54839. hide (0);
  54840. }
  54841. }
  54842. }
  54843. void mouseMove (const MouseEvent&)
  54844. {
  54845. timerCallback();
  54846. }
  54847. void mouseDown (const MouseEvent&)
  54848. {
  54849. timerCallback();
  54850. }
  54851. void mouseDrag (const MouseEvent&)
  54852. {
  54853. timerCallback();
  54854. }
  54855. void mouseUp (const MouseEvent&)
  54856. {
  54857. timerCallback();
  54858. }
  54859. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  54860. {
  54861. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  54862. lastMouse = Point<int> (-1, -1);
  54863. }
  54864. bool keyPressed (const KeyPress& key)
  54865. {
  54866. if (key.isKeyCode (KeyPress::downKey))
  54867. {
  54868. selectNextItem (1);
  54869. }
  54870. else if (key.isKeyCode (KeyPress::upKey))
  54871. {
  54872. selectNextItem (-1);
  54873. }
  54874. else if (key.isKeyCode (KeyPress::leftKey))
  54875. {
  54876. if (owner != 0)
  54877. {
  54878. Component::SafePointer<Window> parentWindow (owner);
  54879. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  54880. hide (0);
  54881. if (parentWindow != 0)
  54882. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  54883. disableTimerUntilMouseMoves();
  54884. }
  54885. else if (menuBarComponent != 0)
  54886. {
  54887. menuBarComponent->keyPressed (key);
  54888. }
  54889. }
  54890. else if (key.isKeyCode (KeyPress::rightKey))
  54891. {
  54892. disableTimerUntilMouseMoves();
  54893. if (showSubMenuFor (currentChild))
  54894. {
  54895. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54896. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  54897. activeSubMenu->selectNextItem (1);
  54898. }
  54899. else if (menuBarComponent != 0)
  54900. {
  54901. menuBarComponent->keyPressed (key);
  54902. }
  54903. }
  54904. else if (key.isKeyCode (KeyPress::returnKey))
  54905. {
  54906. triggerCurrentlyHighlightedItem();
  54907. }
  54908. else if (key.isKeyCode (KeyPress::escapeKey))
  54909. {
  54910. dismissMenu (0);
  54911. }
  54912. else
  54913. {
  54914. return false;
  54915. }
  54916. return true;
  54917. }
  54918. void inputAttemptWhenModal()
  54919. {
  54920. timerCallback();
  54921. if (! isOverAnyMenu())
  54922. {
  54923. if (componentAttachedTo != 0)
  54924. {
  54925. // we want to dismiss the menu, but if we do it synchronously, then
  54926. // the mouse-click will be allowed to pass through. That's good, except
  54927. // when the user clicks on the button that orginally popped the menu up,
  54928. // as they'll expect the menu to go away, and in fact it'll just
  54929. // come back. So only dismiss synchronously if they're not on the original
  54930. // comp that we're attached to.
  54931. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  54932. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  54933. {
  54934. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  54935. return;
  54936. }
  54937. }
  54938. dismissMenu (0);
  54939. }
  54940. }
  54941. void handleCommandMessage (int commandId)
  54942. {
  54943. Component::handleCommandMessage (commandId);
  54944. if (commandId == PopupMenuSettings::dismissCommandId)
  54945. dismissMenu (0);
  54946. }
  54947. void timerCallback()
  54948. {
  54949. if (! isVisible())
  54950. return;
  54951. if (componentAttachedTo != componentAttachedToOriginal)
  54952. {
  54953. dismissMenu (0);
  54954. return;
  54955. }
  54956. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  54957. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  54958. return;
  54959. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  54960. // move rather than a real timer callback
  54961. const Point<int> globalMousePos (Desktop::getMousePosition());
  54962. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  54963. const uint32 now = Time::getMillisecondCounter();
  54964. if (now > timeEnteredCurrentChildComp + 100
  54965. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  54966. && currentChild->isValidComponent()
  54967. && (! disableMouseMoves)
  54968. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  54969. {
  54970. showSubMenuFor (currentChild);
  54971. }
  54972. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  54973. {
  54974. highlightItemUnderMouse (globalMousePos, localMousePos);
  54975. }
  54976. bool overScrollArea = false;
  54977. if (isScrolling()
  54978. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  54979. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  54980. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  54981. {
  54982. if (now > lastScroll + 20)
  54983. {
  54984. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  54985. int amount = 0;
  54986. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  54987. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  54988. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  54989. lastScroll = now;
  54990. }
  54991. overScrollArea = true;
  54992. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  54993. }
  54994. else
  54995. {
  54996. scrollAcceleration = 1.0;
  54997. }
  54998. const bool wasDown = isDown;
  54999. bool isOverAny = isOverAnyMenu();
  55000. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55001. {
  55002. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55003. isOverAny = isOverAnyMenu();
  55004. }
  55005. if (hideOnExit && hasBeenOver && ! isOverAny)
  55006. {
  55007. hide (0);
  55008. }
  55009. else
  55010. {
  55011. isDown = hasBeenOver
  55012. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55013. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55014. bool anyFocused = Process::isForegroundProcess();
  55015. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55016. {
  55017. // because no component at all may have focus, our test here will
  55018. // only be triggered when something has focus and then loses it.
  55019. anyFocused = ! hasAnyJuceCompHadFocus;
  55020. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55021. {
  55022. if (ComponentPeer::getPeer (i)->isFocused())
  55023. {
  55024. anyFocused = true;
  55025. hasAnyJuceCompHadFocus = true;
  55026. break;
  55027. }
  55028. }
  55029. }
  55030. if (! anyFocused)
  55031. {
  55032. if (now > lastFocused + 10)
  55033. {
  55034. wasHiddenBecauseOfAppChange() = true;
  55035. dismissMenu (0);
  55036. return; // may have been deleted by the previous call..
  55037. }
  55038. }
  55039. else if (wasDown && now > menuCreationTime + 250
  55040. && ! (isDown || overScrollArea))
  55041. {
  55042. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55043. if (isOver)
  55044. {
  55045. triggerCurrentlyHighlightedItem();
  55046. }
  55047. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55048. {
  55049. dismissMenu (0);
  55050. }
  55051. return; // may have been deleted by the previous calls..
  55052. }
  55053. else
  55054. {
  55055. lastFocused = now;
  55056. }
  55057. }
  55058. }
  55059. static Array<Window*>& getActiveWindows()
  55060. {
  55061. static Array<Window*> activeMenuWindows;
  55062. return activeMenuWindows;
  55063. }
  55064. static bool& wasHiddenBecauseOfAppChange() throw()
  55065. {
  55066. static bool b = false;
  55067. return b;
  55068. }
  55069. juce_UseDebuggingNewOperator
  55070. private:
  55071. Window* owner;
  55072. PopupMenu::ItemComponent* currentChild;
  55073. ScopedPointer <Window> activeSubMenu;
  55074. Component* menuBarComponent;
  55075. ApplicationCommandManager** managerOfChosenCommand;
  55076. Component::SafePointer<Component> componentAttachedTo;
  55077. Component* componentAttachedToOriginal;
  55078. Rectangle<int> windowPos;
  55079. Point<int> lastMouse;
  55080. int minimumWidth, maximumNumColumns, standardItemHeight;
  55081. bool isOver, hasBeenOver, isDown, needsToScroll;
  55082. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55083. int numColumns, contentHeight, childYOffset;
  55084. Array <int> columnWidths;
  55085. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55086. double scrollAcceleration;
  55087. bool overlaps (const Rectangle<int>& r) const
  55088. {
  55089. return r.intersects (getBounds())
  55090. || (owner != 0 && owner->overlaps (r));
  55091. }
  55092. bool isOverAnyMenu() const
  55093. {
  55094. return (owner != 0) ? owner->isOverAnyMenu()
  55095. : isOverChildren();
  55096. }
  55097. bool isOverChildren() const
  55098. {
  55099. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55100. return isVisible()
  55101. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55102. }
  55103. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55104. {
  55105. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55106. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55107. if (activeSubMenu != 0)
  55108. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55109. }
  55110. bool treeContains (const Window* const window) const throw()
  55111. {
  55112. const Window* mw = this;
  55113. while (mw->owner != 0)
  55114. mw = mw->owner;
  55115. while (mw != 0)
  55116. {
  55117. if (mw == window)
  55118. return true;
  55119. mw = mw->activeSubMenu;
  55120. }
  55121. return false;
  55122. }
  55123. void calculateWindowPos (const int minX, const int maxX,
  55124. const int minY, const int maxY,
  55125. const bool alignToRectangle)
  55126. {
  55127. const Rectangle<int> mon (Desktop::getInstance()
  55128. .getMonitorAreaContaining (Point<int> ((minX + maxX) / 2,
  55129. (minY + maxY) / 2),
  55130. #if JUCE_MAC
  55131. true));
  55132. #else
  55133. false)); // on windows, don't stop the menu overlapping the taskbar
  55134. #endif
  55135. int x, y, widthToUse, heightToUse;
  55136. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55137. if (alignToRectangle)
  55138. {
  55139. x = minX;
  55140. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  55141. const int spaceOver = minY - mon.getY();
  55142. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55143. y = maxY;
  55144. else
  55145. y = minY - heightToUse;
  55146. }
  55147. else
  55148. {
  55149. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  55150. if (owner != 0)
  55151. {
  55152. if (owner->owner != 0)
  55153. {
  55154. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55155. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55156. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  55157. tendTowardsRight = true;
  55158. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  55159. tendTowardsRight = false;
  55160. }
  55161. else if (maxX + widthToUse < mon.getRight() - 32)
  55162. {
  55163. tendTowardsRight = true;
  55164. }
  55165. }
  55166. const int biggestSpace = jmax (mon.getRight() - maxX,
  55167. minX - mon.getX()) - 32;
  55168. if (biggestSpace < widthToUse)
  55169. {
  55170. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  55171. if (numColumns > 1)
  55172. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55173. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  55174. }
  55175. if (tendTowardsRight)
  55176. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  55177. else
  55178. x = jmax (mon.getX() + 4, minX - widthToUse);
  55179. y = minY;
  55180. if ((minY + maxY) / 2 > mon.getCentreY())
  55181. y = jmax (mon.getY(), maxY - heightToUse);
  55182. }
  55183. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55184. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55185. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55186. // sets this flag if it's big enough to obscure any of its parent menus
  55187. hideOnExit = (owner != 0)
  55188. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55189. }
  55190. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55191. {
  55192. numColumns = 0;
  55193. contentHeight = 0;
  55194. const int maxMenuH = getParentHeight() - 24;
  55195. int totalW;
  55196. do
  55197. {
  55198. ++numColumns;
  55199. totalW = workOutBestSize (maxMenuW);
  55200. if (totalW > maxMenuW)
  55201. {
  55202. numColumns = jmax (1, numColumns - 1);
  55203. totalW = workOutBestSize (maxMenuW); // to update col widths
  55204. break;
  55205. }
  55206. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55207. {
  55208. break;
  55209. }
  55210. } while (numColumns < maximumNumColumns);
  55211. const int actualH = jmin (contentHeight, maxMenuH);
  55212. needsToScroll = contentHeight > actualH;
  55213. width = updateYPositions();
  55214. height = actualH + PopupMenuSettings::borderSize * 2;
  55215. }
  55216. int workOutBestSize (const int maxMenuW)
  55217. {
  55218. int totalW = 0;
  55219. contentHeight = 0;
  55220. int childNum = 0;
  55221. for (int col = 0; col < numColumns; ++col)
  55222. {
  55223. int i, colW = 50, colH = 0;
  55224. const int numChildren = jmin (getNumChildComponents() - childNum,
  55225. (getNumChildComponents() + numColumns - 1) / numColumns);
  55226. for (i = numChildren; --i >= 0;)
  55227. {
  55228. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55229. colH += getChildComponent (childNum + i)->getHeight();
  55230. }
  55231. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55232. columnWidths.set (col, colW);
  55233. totalW += colW;
  55234. contentHeight = jmax (contentHeight, colH);
  55235. childNum += numChildren;
  55236. }
  55237. if (totalW < minimumWidth)
  55238. {
  55239. totalW = minimumWidth;
  55240. for (int col = 0; col < numColumns; ++col)
  55241. columnWidths.set (0, totalW / numColumns);
  55242. }
  55243. return totalW;
  55244. }
  55245. void ensureItemIsVisible (const int itemId, int wantedY)
  55246. {
  55247. jassert (itemId != 0)
  55248. for (int i = getNumChildComponents(); --i >= 0;)
  55249. {
  55250. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55251. if (m != 0
  55252. && m->itemInfo.itemId == itemId
  55253. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55254. {
  55255. const int currentY = m->getY();
  55256. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55257. {
  55258. if (wantedY < 0)
  55259. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55260. jmax (PopupMenuSettings::scrollZone,
  55261. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55262. currentY);
  55263. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55264. int deltaY = wantedY - currentY;
  55265. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55266. jmin (windowPos.getHeight(), mon.getHeight()));
  55267. const int newY = jlimit (mon.getY(),
  55268. mon.getBottom() - windowPos.getHeight(),
  55269. windowPos.getY() + deltaY);
  55270. deltaY -= newY - windowPos.getY();
  55271. childYOffset -= deltaY;
  55272. windowPos.setPosition (windowPos.getX(), newY);
  55273. updateYPositions();
  55274. }
  55275. break;
  55276. }
  55277. }
  55278. }
  55279. void resizeToBestWindowPos()
  55280. {
  55281. Rectangle<int> r (windowPos);
  55282. if (childYOffset < 0)
  55283. {
  55284. r.setBounds (r.getX(), r.getY() - childYOffset,
  55285. r.getWidth(), r.getHeight() + childYOffset);
  55286. }
  55287. else if (childYOffset > 0)
  55288. {
  55289. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55290. if (spaceAtBottom > 0)
  55291. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55292. }
  55293. setBounds (r);
  55294. updateYPositions();
  55295. }
  55296. void alterChildYPos (const int delta)
  55297. {
  55298. if (isScrolling())
  55299. {
  55300. childYOffset += delta;
  55301. if (delta < 0)
  55302. {
  55303. childYOffset = jmax (childYOffset, 0);
  55304. }
  55305. else if (delta > 0)
  55306. {
  55307. childYOffset = jmin (childYOffset,
  55308. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55309. }
  55310. updateYPositions();
  55311. }
  55312. else
  55313. {
  55314. childYOffset = 0;
  55315. }
  55316. resizeToBestWindowPos();
  55317. repaint();
  55318. }
  55319. int updateYPositions()
  55320. {
  55321. int x = 0;
  55322. int childNum = 0;
  55323. for (int col = 0; col < numColumns; ++col)
  55324. {
  55325. const int numChildren = jmin (getNumChildComponents() - childNum,
  55326. (getNumChildComponents() + numColumns - 1) / numColumns);
  55327. const int colW = columnWidths [col];
  55328. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55329. for (int i = 0; i < numChildren; ++i)
  55330. {
  55331. Component* const c = getChildComponent (childNum + i);
  55332. c->setBounds (x, y, colW, c->getHeight());
  55333. y += c->getHeight();
  55334. }
  55335. x += colW;
  55336. childNum += numChildren;
  55337. }
  55338. return x;
  55339. }
  55340. bool isScrolling() const throw()
  55341. {
  55342. return childYOffset != 0 || needsToScroll;
  55343. }
  55344. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55345. {
  55346. if (currentChild->isValidComponent())
  55347. currentChild->setHighlighted (false);
  55348. currentChild = child;
  55349. if (currentChild != 0)
  55350. {
  55351. currentChild->setHighlighted (true);
  55352. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55353. }
  55354. }
  55355. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55356. {
  55357. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55358. activeSubMenu = 0;
  55359. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55360. {
  55361. const Point<int> topLeft (childComp->relativePositionToGlobal (Point<int>()));
  55362. const Point<int> bottomRight (childComp->relativePositionToGlobal (Point<int> (childComp->getWidth(), childComp->getHeight())));
  55363. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55364. dismissOnMouseUp,
  55365. this,
  55366. topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(),
  55367. 0, maximumNumColumns,
  55368. standardItemHeight,
  55369. false, 0, menuBarComponent,
  55370. managerOfChosenCommand,
  55371. componentAttachedTo);
  55372. if (activeSubMenu != 0)
  55373. {
  55374. activeSubMenu->setVisible (true);
  55375. activeSubMenu->enterModalState (false);
  55376. activeSubMenu->toFront (false);
  55377. return true;
  55378. }
  55379. }
  55380. return false;
  55381. }
  55382. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55383. {
  55384. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55385. if (isOver)
  55386. hasBeenOver = true;
  55387. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55388. {
  55389. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55390. if (disableMouseMoves && isOver)
  55391. disableMouseMoves = false;
  55392. }
  55393. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55394. return;
  55395. bool isMovingTowardsMenu = false;
  55396. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55397. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55398. {
  55399. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55400. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55401. // extends from the last mouse pos to the submenu's rectangle..
  55402. float subX = (float) activeSubMenu->getScreenX();
  55403. if (activeSubMenu->getX() > getX())
  55404. {
  55405. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55406. }
  55407. else
  55408. {
  55409. lastMouse += Point<int> (2, 0);
  55410. subX += activeSubMenu->getWidth();
  55411. }
  55412. Path areaTowardsSubMenu;
  55413. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55414. (float) lastMouse.getY(),
  55415. subX,
  55416. (float) activeSubMenu->getScreenY(),
  55417. subX,
  55418. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55419. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55420. }
  55421. lastMouse = globalMousePos;
  55422. if (! isMovingTowardsMenu)
  55423. {
  55424. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55425. if (c == this)
  55426. c = 0;
  55427. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55428. if (mic == 0 && c != 0)
  55429. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55430. if (mic != currentChild
  55431. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55432. {
  55433. if (isOver && (c != 0) && (activeSubMenu != 0))
  55434. {
  55435. activeSubMenu->hide (0);
  55436. }
  55437. if (! isOver)
  55438. mic = 0;
  55439. setCurrentlyHighlightedChild (mic);
  55440. }
  55441. }
  55442. }
  55443. void triggerCurrentlyHighlightedItem()
  55444. {
  55445. if (currentChild->isValidComponent()
  55446. && currentChild->itemInfo.canBeTriggered()
  55447. && (currentChild->itemInfo.customComp == 0
  55448. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55449. {
  55450. dismissMenu (&currentChild->itemInfo);
  55451. }
  55452. }
  55453. void selectNextItem (const int delta)
  55454. {
  55455. disableTimerUntilMouseMoves();
  55456. PopupMenu::ItemComponent* mic = 0;
  55457. bool wasLastOne = (currentChild == 0);
  55458. const int numItems = getNumChildComponents();
  55459. for (int i = 0; i < numItems + 1; ++i)
  55460. {
  55461. int index = (delta > 0) ? i : (numItems - 1 - i);
  55462. index = (index + numItems) % numItems;
  55463. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55464. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55465. && wasLastOne)
  55466. break;
  55467. if (mic == currentChild)
  55468. wasLastOne = true;
  55469. }
  55470. setCurrentlyHighlightedChild (mic);
  55471. }
  55472. void disableTimerUntilMouseMoves()
  55473. {
  55474. disableMouseMoves = true;
  55475. if (owner != 0)
  55476. owner->disableTimerUntilMouseMoves();
  55477. }
  55478. Window (const Window&);
  55479. Window& operator= (const Window&);
  55480. };
  55481. PopupMenu::PopupMenu()
  55482. : lookAndFeel (0),
  55483. separatorPending (false)
  55484. {
  55485. }
  55486. PopupMenu::PopupMenu (const PopupMenu& other)
  55487. : lookAndFeel (other.lookAndFeel),
  55488. separatorPending (false)
  55489. {
  55490. items.ensureStorageAllocated (other.items.size());
  55491. for (int i = 0; i < other.items.size(); ++i)
  55492. items.add (new Item (*other.items.getUnchecked(i)));
  55493. }
  55494. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55495. {
  55496. if (this != &other)
  55497. {
  55498. lookAndFeel = other.lookAndFeel;
  55499. clear();
  55500. items.ensureStorageAllocated (other.items.size());
  55501. for (int i = 0; i < other.items.size(); ++i)
  55502. items.add (new Item (*other.items.getUnchecked(i)));
  55503. }
  55504. return *this;
  55505. }
  55506. PopupMenu::~PopupMenu()
  55507. {
  55508. clear();
  55509. }
  55510. void PopupMenu::clear()
  55511. {
  55512. items.clear();
  55513. separatorPending = false;
  55514. }
  55515. void PopupMenu::addSeparatorIfPending()
  55516. {
  55517. if (separatorPending)
  55518. {
  55519. separatorPending = false;
  55520. if (items.size() > 0)
  55521. items.add (new Item());
  55522. }
  55523. }
  55524. void PopupMenu::addItem (const int itemResultId,
  55525. const String& itemText,
  55526. const bool isActive,
  55527. const bool isTicked,
  55528. const Image* const iconToUse)
  55529. {
  55530. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55531. // didn't pick anything, so you shouldn't use it as the id
  55532. // for an item..
  55533. addSeparatorIfPending();
  55534. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55535. iconToUse, Colours::black, false, 0, 0, 0));
  55536. }
  55537. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55538. const int commandID,
  55539. const String& displayName)
  55540. {
  55541. jassert (commandManager != 0 && commandID != 0);
  55542. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55543. if (registeredInfo != 0)
  55544. {
  55545. ApplicationCommandInfo info (*registeredInfo);
  55546. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55547. addSeparatorIfPending();
  55548. items.add (new Item (commandID,
  55549. displayName.isNotEmpty() ? displayName
  55550. : info.shortName,
  55551. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55552. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55553. 0,
  55554. Colours::black,
  55555. false,
  55556. 0, 0,
  55557. commandManager));
  55558. }
  55559. }
  55560. void PopupMenu::addColouredItem (const int itemResultId,
  55561. const String& itemText,
  55562. const Colour& itemTextColour,
  55563. const bool isActive,
  55564. const bool isTicked,
  55565. const Image* const iconToUse)
  55566. {
  55567. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55568. // didn't pick anything, so you shouldn't use it as the id
  55569. // for an item..
  55570. addSeparatorIfPending();
  55571. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55572. iconToUse, itemTextColour, true, 0, 0, 0));
  55573. }
  55574. void PopupMenu::addCustomItem (const int itemResultId,
  55575. PopupMenuCustomComponent* const customComponent)
  55576. {
  55577. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55578. // didn't pick anything, so you shouldn't use it as the id
  55579. // for an item..
  55580. addSeparatorIfPending();
  55581. items.add (new Item (itemResultId, String::empty, true, false, 0,
  55582. Colours::black, false, customComponent, 0, 0));
  55583. }
  55584. class NormalComponentWrapper : public PopupMenuCustomComponent
  55585. {
  55586. public:
  55587. NormalComponentWrapper (Component* const comp,
  55588. const int w, const int h,
  55589. const bool triggerMenuItemAutomaticallyWhenClicked)
  55590. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55591. width (w),
  55592. height (h)
  55593. {
  55594. addAndMakeVisible (comp);
  55595. }
  55596. ~NormalComponentWrapper() {}
  55597. void getIdealSize (int& idealWidth, int& idealHeight)
  55598. {
  55599. idealWidth = width;
  55600. idealHeight = height;
  55601. }
  55602. void resized()
  55603. {
  55604. if (getChildComponent(0) != 0)
  55605. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  55606. }
  55607. juce_UseDebuggingNewOperator
  55608. private:
  55609. const int width, height;
  55610. NormalComponentWrapper (const NormalComponentWrapper&);
  55611. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55612. };
  55613. void PopupMenu::addCustomItem (const int itemResultId,
  55614. Component* customComponent,
  55615. int idealWidth, int idealHeight,
  55616. const bool triggerMenuItemAutomaticallyWhenClicked)
  55617. {
  55618. addCustomItem (itemResultId,
  55619. new NormalComponentWrapper (customComponent,
  55620. idealWidth, idealHeight,
  55621. triggerMenuItemAutomaticallyWhenClicked));
  55622. }
  55623. void PopupMenu::addSubMenu (const String& subMenuName,
  55624. const PopupMenu& subMenu,
  55625. const bool isActive,
  55626. Image* const iconToUse,
  55627. const bool isTicked)
  55628. {
  55629. addSeparatorIfPending();
  55630. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55631. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55632. }
  55633. void PopupMenu::addSeparator()
  55634. {
  55635. separatorPending = true;
  55636. }
  55637. class HeaderItemComponent : public PopupMenuCustomComponent
  55638. {
  55639. public:
  55640. HeaderItemComponent (const String& name)
  55641. : PopupMenuCustomComponent (false)
  55642. {
  55643. setName (name);
  55644. }
  55645. ~HeaderItemComponent()
  55646. {
  55647. }
  55648. void paint (Graphics& g)
  55649. {
  55650. Font f (getLookAndFeel().getPopupMenuFont());
  55651. f.setBold (true);
  55652. g.setFont (f);
  55653. g.setColour (findColour (PopupMenu::headerTextColourId));
  55654. g.drawFittedText (getName(),
  55655. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55656. Justification::bottomLeft, 1);
  55657. }
  55658. void getIdealSize (int& idealWidth,
  55659. int& idealHeight)
  55660. {
  55661. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55662. idealHeight += idealHeight / 2;
  55663. idealWidth += idealWidth / 4;
  55664. }
  55665. juce_UseDebuggingNewOperator
  55666. };
  55667. void PopupMenu::addSectionHeader (const String& title)
  55668. {
  55669. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55670. }
  55671. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  55672. const int itemIdThatMustBeVisible,
  55673. const int minimumWidth,
  55674. const int maximumNumColumns,
  55675. const int standardItemHeight,
  55676. const bool alignToRectangle,
  55677. Component* menuBarComponent,
  55678. ApplicationCommandManager** managerOfChosenCommand,
  55679. Component* const componentAttachedTo)
  55680. {
  55681. Window* const pw
  55682. = Window::create (*this,
  55683. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55684. 0,
  55685. x, x + w,
  55686. y, y + h,
  55687. minimumWidth,
  55688. maximumNumColumns,
  55689. standardItemHeight,
  55690. alignToRectangle,
  55691. itemIdThatMustBeVisible,
  55692. menuBarComponent,
  55693. managerOfChosenCommand,
  55694. componentAttachedTo);
  55695. if (pw != 0)
  55696. pw->setVisible (true);
  55697. return pw;
  55698. }
  55699. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  55700. const int itemIdThatMustBeVisible,
  55701. const int minimumWidth,
  55702. const int maximumNumColumns,
  55703. const int standardItemHeight,
  55704. const bool alignToRectangle,
  55705. Component* const componentAttachedTo)
  55706. {
  55707. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55708. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55709. Window::wasHiddenBecauseOfAppChange() = false;
  55710. int result = 0;
  55711. ApplicationCommandManager* managerOfChosenCommand = 0;
  55712. ScopedPointer <Component> popupComp (createMenuComponent (x, y, w, h,
  55713. itemIdThatMustBeVisible,
  55714. minimumWidth,
  55715. maximumNumColumns > 0 ? maximumNumColumns : 7,
  55716. standardItemHeight,
  55717. alignToRectangle, 0,
  55718. &managerOfChosenCommand,
  55719. componentAttachedTo));
  55720. if (popupComp != 0)
  55721. {
  55722. popupComp->enterModalState (false);
  55723. popupComp->toFront (false); // need to do this after making it modal, or it could
  55724. // be stuck behind other comps that are already modal..
  55725. result = popupComp->runModalLoop();
  55726. popupComp = 0;
  55727. if (! Window::wasHiddenBecauseOfAppChange())
  55728. {
  55729. if (prevTopLevel != 0)
  55730. prevTopLevel->toFront (true);
  55731. if (prevFocused != 0)
  55732. prevFocused->grabKeyboardFocus();
  55733. }
  55734. }
  55735. if (managerOfChosenCommand != 0 && result != 0)
  55736. {
  55737. ApplicationCommandTarget::InvocationInfo info (result);
  55738. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55739. managerOfChosenCommand->invoke (info, true);
  55740. }
  55741. return result;
  55742. }
  55743. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55744. const int minimumWidth,
  55745. const int maximumNumColumns,
  55746. const int standardItemHeight)
  55747. {
  55748. const Point<int> mousePos (Desktop::getMousePosition());
  55749. return showAt (mousePos.getX(), mousePos.getY(),
  55750. itemIdThatMustBeVisible,
  55751. minimumWidth,
  55752. maximumNumColumns,
  55753. standardItemHeight);
  55754. }
  55755. int PopupMenu::showAt (const int screenX,
  55756. const int screenY,
  55757. const int itemIdThatMustBeVisible,
  55758. const int minimumWidth,
  55759. const int maximumNumColumns,
  55760. const int standardItemHeight)
  55761. {
  55762. return showMenu (screenX, screenY, 1, 1,
  55763. itemIdThatMustBeVisible,
  55764. minimumWidth, maximumNumColumns,
  55765. standardItemHeight,
  55766. false, 0);
  55767. }
  55768. int PopupMenu::showAt (Component* componentToAttachTo,
  55769. const int itemIdThatMustBeVisible,
  55770. const int minimumWidth,
  55771. const int maximumNumColumns,
  55772. const int standardItemHeight)
  55773. {
  55774. if (componentToAttachTo != 0)
  55775. {
  55776. return showMenu (componentToAttachTo->getScreenX(),
  55777. componentToAttachTo->getScreenY(),
  55778. componentToAttachTo->getWidth(),
  55779. componentToAttachTo->getHeight(),
  55780. itemIdThatMustBeVisible,
  55781. minimumWidth,
  55782. maximumNumColumns,
  55783. standardItemHeight,
  55784. true, componentToAttachTo);
  55785. }
  55786. else
  55787. {
  55788. return show (itemIdThatMustBeVisible,
  55789. minimumWidth,
  55790. maximumNumColumns,
  55791. standardItemHeight);
  55792. }
  55793. }
  55794. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  55795. {
  55796. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  55797. {
  55798. Window* const pmw = Window::getActiveWindows()[i];
  55799. if (pmw != 0)
  55800. pmw->dismissMenu (0);
  55801. }
  55802. }
  55803. int PopupMenu::getNumItems() const throw()
  55804. {
  55805. int num = 0;
  55806. for (int i = items.size(); --i >= 0;)
  55807. if (! (items.getUnchecked(i))->isSeparator)
  55808. ++num;
  55809. return num;
  55810. }
  55811. bool PopupMenu::containsCommandItem (const int commandID) const
  55812. {
  55813. for (int i = items.size(); --i >= 0;)
  55814. {
  55815. const Item* mi = items.getUnchecked (i);
  55816. if ((mi->itemId == commandID && mi->commandManager != 0)
  55817. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  55818. {
  55819. return true;
  55820. }
  55821. }
  55822. return false;
  55823. }
  55824. bool PopupMenu::containsAnyActiveItems() const throw()
  55825. {
  55826. for (int i = items.size(); --i >= 0;)
  55827. {
  55828. const Item* const mi = items.getUnchecked (i);
  55829. if (mi->subMenu != 0)
  55830. {
  55831. if (mi->subMenu->containsAnyActiveItems())
  55832. return true;
  55833. }
  55834. else if (mi->active)
  55835. {
  55836. return true;
  55837. }
  55838. }
  55839. return false;
  55840. }
  55841. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  55842. {
  55843. lookAndFeel = newLookAndFeel;
  55844. }
  55845. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  55846. : isHighlighted (false),
  55847. isTriggeredAutomatically (isTriggeredAutomatically_)
  55848. {
  55849. }
  55850. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  55851. {
  55852. }
  55853. void PopupMenuCustomComponent::triggerMenuItem()
  55854. {
  55855. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  55856. if (mic != 0)
  55857. {
  55858. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  55859. if (pmw != 0)
  55860. {
  55861. pmw->dismissMenu (&mic->itemInfo);
  55862. }
  55863. else
  55864. {
  55865. // something must have gone wrong with the component hierarchy if this happens..
  55866. jassertfalse
  55867. }
  55868. }
  55869. else
  55870. {
  55871. // why isn't this component inside a menu? Not much point triggering the item if
  55872. // there's no menu.
  55873. jassertfalse
  55874. }
  55875. }
  55876. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  55877. : subMenu (0),
  55878. itemId (0),
  55879. isSeparator (false),
  55880. isTicked (false),
  55881. isEnabled (false),
  55882. isCustomComponent (false),
  55883. isSectionHeader (false),
  55884. customColour (0),
  55885. customImage (0),
  55886. menu (menu_),
  55887. index (0)
  55888. {
  55889. }
  55890. PopupMenu::MenuItemIterator::~MenuItemIterator()
  55891. {
  55892. }
  55893. bool PopupMenu::MenuItemIterator::next()
  55894. {
  55895. if (index >= menu.items.size())
  55896. return false;
  55897. const Item* const item = menu.items.getUnchecked (index);
  55898. ++index;
  55899. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  55900. subMenu = item->subMenu;
  55901. itemId = item->itemId;
  55902. isSeparator = item->isSeparator;
  55903. isTicked = item->isTicked;
  55904. isEnabled = item->active;
  55905. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  55906. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  55907. customColour = item->usesColour ? &(item->textColour) : 0;
  55908. customImage = item->image;
  55909. commandManager = item->commandManager;
  55910. return true;
  55911. }
  55912. END_JUCE_NAMESPACE
  55913. /*** End of inlined file: juce_PopupMenu.cpp ***/
  55914. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  55915. BEGIN_JUCE_NAMESPACE
  55916. ComponentDragger::ComponentDragger()
  55917. : constrainer (0)
  55918. {
  55919. }
  55920. ComponentDragger::~ComponentDragger()
  55921. {
  55922. }
  55923. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  55924. ComponentBoundsConstrainer* const constrainer_)
  55925. {
  55926. jassert (componentToDrag->isValidComponent());
  55927. if (componentToDrag != 0)
  55928. {
  55929. constrainer = constrainer_;
  55930. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  55931. }
  55932. }
  55933. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  55934. {
  55935. jassert (componentToDrag->isValidComponent());
  55936. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  55937. if (componentToDrag != 0)
  55938. {
  55939. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  55940. const Component* const parentComp = componentToDrag->getParentComponent();
  55941. if (parentComp != 0)
  55942. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  55943. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  55944. if (constrainer != 0)
  55945. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  55946. else
  55947. componentToDrag->setBounds (bounds);
  55948. }
  55949. }
  55950. END_JUCE_NAMESPACE
  55951. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  55952. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  55953. BEGIN_JUCE_NAMESPACE
  55954. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  55955. bool juce_performDragDropText (const String& text, bool& shouldStop);
  55956. class DragImageComponent : public Component,
  55957. public Timer
  55958. {
  55959. public:
  55960. DragImageComponent (Image* const im,
  55961. const String& desc,
  55962. Component* const sourceComponent,
  55963. Component* const mouseDragSource_,
  55964. DragAndDropContainer* const o,
  55965. const Point<int>& imageOffset_)
  55966. : image (im),
  55967. source (sourceComponent),
  55968. mouseDragSource (mouseDragSource_),
  55969. owner (o),
  55970. dragDesc (desc),
  55971. imageOffset (imageOffset_),
  55972. hasCheckedForExternalDrag (false),
  55973. drawImage (true)
  55974. {
  55975. setSize (im->getWidth(), im->getHeight());
  55976. if (mouseDragSource == 0)
  55977. mouseDragSource = source;
  55978. mouseDragSource->addMouseListener (this, false);
  55979. startTimer (200);
  55980. setInterceptsMouseClicks (false, false);
  55981. setAlwaysOnTop (true);
  55982. }
  55983. ~DragImageComponent()
  55984. {
  55985. if (owner->dragImageComponent == this)
  55986. owner->dragImageComponent.release();
  55987. if (mouseDragSource != 0)
  55988. {
  55989. mouseDragSource->removeMouseListener (this);
  55990. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  55991. getCurrentlyOver()->itemDragExit (dragDesc, source);
  55992. }
  55993. }
  55994. void paint (Graphics& g)
  55995. {
  55996. if (isOpaque())
  55997. g.fillAll (Colours::white);
  55998. if (drawImage)
  55999. {
  56000. g.setOpacity (1.0f);
  56001. g.drawImageAt (image, 0, 0);
  56002. }
  56003. }
  56004. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56005. {
  56006. Component* hit = getParentComponent();
  56007. if (hit == 0)
  56008. {
  56009. hit = Desktop::getInstance().findComponentAt (screenPos);
  56010. }
  56011. else
  56012. {
  56013. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56014. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56015. }
  56016. // (note: use a local copy of the dragDesc member in case the callback runs
  56017. // a modal loop and deletes this object before the method completes)
  56018. const String dragDescLocal (dragDesc);
  56019. while (hit != 0)
  56020. {
  56021. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56022. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56023. {
  56024. relativePos = hit->globalPositionToRelative (screenPos);
  56025. return ddt;
  56026. }
  56027. hit = hit->getParentComponent();
  56028. }
  56029. return 0;
  56030. }
  56031. void mouseUp (const MouseEvent& e)
  56032. {
  56033. if (e.originalComponent != this)
  56034. {
  56035. if (mouseDragSource != 0)
  56036. mouseDragSource->removeMouseListener (this);
  56037. bool dropAccepted = false;
  56038. DragAndDropTarget* ddt = 0;
  56039. Point<int> relPos;
  56040. if (isVisible())
  56041. {
  56042. setVisible (false);
  56043. ddt = findTarget (e.getScreenPosition(), relPos);
  56044. // fade this component and remove it - it'll be deleted later by the timer callback
  56045. dropAccepted = ddt != 0;
  56046. setVisible (true);
  56047. if (dropAccepted || source == 0)
  56048. {
  56049. fadeOutComponent (120);
  56050. }
  56051. else
  56052. {
  56053. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56054. source->getHeight() / 2)));
  56055. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56056. getHeight() / 2)));
  56057. fadeOutComponent (120,
  56058. target.getX() - ourCentre.getX(),
  56059. target.getY() - ourCentre.getY());
  56060. }
  56061. }
  56062. if (getParentComponent() != 0)
  56063. getParentComponent()->removeChildComponent (this);
  56064. if (dropAccepted && ddt != 0)
  56065. {
  56066. // (note: use a local copy of the dragDesc member in case the callback runs
  56067. // a modal loop and deletes this object before the method completes)
  56068. const String dragDescLocal (dragDesc);
  56069. currentlyOverComp = 0;
  56070. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56071. }
  56072. // careful - this object could now be deleted..
  56073. }
  56074. }
  56075. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56076. {
  56077. // (note: use a local copy of the dragDesc member in case the callback runs
  56078. // a modal loop and deletes this object before it returns)
  56079. const String dragDescLocal (dragDesc);
  56080. Point<int> newPos (screenPos + imageOffset);
  56081. if (getParentComponent() != 0)
  56082. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56083. //if (newX != getX() || newY != getY())
  56084. {
  56085. setTopLeftPosition (newPos.getX(), newPos.getY());
  56086. Point<int> relPos;
  56087. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56088. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56089. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56090. if (ddtComp != currentlyOverComp)
  56091. {
  56092. if (currentlyOverComp != 0 && source != 0
  56093. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56094. {
  56095. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56096. }
  56097. currentlyOverComp = ddtComp;
  56098. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56099. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56100. }
  56101. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56102. getCurrentlyOver()->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56103. if (getCurrentlyOver() == 0
  56104. && canDoExternalDrag
  56105. && ! hasCheckedForExternalDrag)
  56106. {
  56107. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56108. {
  56109. hasCheckedForExternalDrag = true;
  56110. StringArray files;
  56111. bool canMoveFiles = false;
  56112. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56113. && files.size() > 0)
  56114. {
  56115. Component::SafePointer<Component> cdw (this);
  56116. setVisible (false);
  56117. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56118. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56119. if (cdw != 0)
  56120. delete this;
  56121. return;
  56122. }
  56123. }
  56124. }
  56125. }
  56126. }
  56127. void mouseDrag (const MouseEvent& e)
  56128. {
  56129. if (e.originalComponent != this)
  56130. updateLocation (true, e.getScreenPosition());
  56131. }
  56132. void timerCallback()
  56133. {
  56134. if (source == 0)
  56135. {
  56136. delete this;
  56137. }
  56138. else if (! isMouseButtonDownAnywhere())
  56139. {
  56140. if (mouseDragSource != 0)
  56141. mouseDragSource->removeMouseListener (this);
  56142. delete this;
  56143. }
  56144. }
  56145. private:
  56146. ScopedPointer<Image> image;
  56147. Component::SafePointer<Component> source;
  56148. Component::SafePointer<Component> mouseDragSource;
  56149. DragAndDropContainer* const owner;
  56150. Component::SafePointer<Component> currentlyOverComp;
  56151. DragAndDropTarget* getCurrentlyOver()
  56152. {
  56153. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56154. }
  56155. String dragDesc;
  56156. const Point<int> imageOffset;
  56157. bool hasCheckedForExternalDrag, drawImage;
  56158. DragImageComponent (const DragImageComponent&);
  56159. DragImageComponent& operator= (const DragImageComponent&);
  56160. };
  56161. DragAndDropContainer::DragAndDropContainer()
  56162. {
  56163. }
  56164. DragAndDropContainer::~DragAndDropContainer()
  56165. {
  56166. dragImageComponent = 0;
  56167. }
  56168. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56169. Component* sourceComponent,
  56170. Image* dragImage_,
  56171. const bool allowDraggingToExternalWindows,
  56172. const Point<int>* imageOffsetFromMouse)
  56173. {
  56174. ScopedPointer <Image> dragImage (dragImage_);
  56175. if (dragImageComponent == 0)
  56176. {
  56177. Component* const thisComp = dynamic_cast <Component*> (this);
  56178. if (thisComp == 0)
  56179. {
  56180. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56181. return;
  56182. }
  56183. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56184. if (draggingSource == 0 || ! draggingSource->isDragging())
  56185. {
  56186. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56187. return;
  56188. }
  56189. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56190. Point<int> imageOffset;
  56191. if (dragImage == 0)
  56192. {
  56193. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds());
  56194. if (dragImage->getFormat() != Image::ARGB)
  56195. {
  56196. Image* newIm = Image::createNativeImage (Image::ARGB, dragImage->getWidth(), dragImage->getHeight(), true);
  56197. Graphics g2 (*newIm);
  56198. g2.drawImageAt (dragImage, 0, 0);
  56199. dragImage = newIm;
  56200. }
  56201. dragImage->multiplyAllAlphas (0.6f);
  56202. const int lo = 150;
  56203. const int hi = 400;
  56204. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56205. Point<int> clipped (dragImage->getBounds().getConstrainedPoint (relPos));
  56206. for (int y = dragImage->getHeight(); --y >= 0;)
  56207. {
  56208. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56209. for (int x = dragImage->getWidth(); --x >= 0;)
  56210. {
  56211. const int dx = x - clipped.getX();
  56212. const int distance = roundToInt (sqrt (dx * dx + dy));
  56213. if (distance > lo)
  56214. {
  56215. const float alpha = (distance > hi) ? 0
  56216. : (hi - distance) / (float) (hi - lo)
  56217. + Random::getSystemRandom().nextFloat() * 0.008f;
  56218. dragImage->multiplyAlphaAt (x, y, alpha);
  56219. }
  56220. }
  56221. }
  56222. imageOffset = -clipped;
  56223. }
  56224. else
  56225. {
  56226. if (imageOffsetFromMouse == 0)
  56227. imageOffset = -dragImage->getBounds().getCentre();
  56228. else
  56229. imageOffset = -(dragImage->getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56230. }
  56231. dragImageComponent = new DragImageComponent (dragImage.release(), sourceDescription, sourceComponent,
  56232. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56233. currentDragDesc = sourceDescription;
  56234. if (allowDraggingToExternalWindows)
  56235. {
  56236. if (! Desktop::canUseSemiTransparentWindows())
  56237. dragImageComponent->setOpaque (true);
  56238. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56239. | ComponentPeer::windowIsTemporary
  56240. | ComponentPeer::windowIgnoresKeyPresses);
  56241. }
  56242. else
  56243. thisComp->addChildComponent (dragImageComponent);
  56244. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56245. dragImageComponent->setVisible (true);
  56246. }
  56247. }
  56248. bool DragAndDropContainer::isDragAndDropActive() const
  56249. {
  56250. return dragImageComponent != 0;
  56251. }
  56252. const String DragAndDropContainer::getCurrentDragDescription() const
  56253. {
  56254. return (dragImageComponent != 0) ? currentDragDesc
  56255. : String::empty;
  56256. }
  56257. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56258. {
  56259. if (c == 0)
  56260. return 0;
  56261. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  56262. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56263. }
  56264. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56265. {
  56266. return false;
  56267. }
  56268. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56269. {
  56270. }
  56271. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56272. {
  56273. }
  56274. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56275. {
  56276. }
  56277. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56278. {
  56279. return true;
  56280. }
  56281. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56282. {
  56283. }
  56284. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56285. {
  56286. }
  56287. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56288. {
  56289. }
  56290. END_JUCE_NAMESPACE
  56291. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56292. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56293. BEGIN_JUCE_NAMESPACE
  56294. class MouseCursor::SharedCursorHandle
  56295. {
  56296. public:
  56297. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56298. : handle (createStandardMouseCursor (type)),
  56299. refCount (1),
  56300. standardType (type),
  56301. isStandard (true)
  56302. {
  56303. }
  56304. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56305. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56306. refCount (1),
  56307. standardType (MouseCursor::NormalCursor),
  56308. isStandard (false)
  56309. {
  56310. }
  56311. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56312. {
  56313. const ScopedLock sl (getLock());
  56314. for (int i = getCursors().size(); --i >= 0;)
  56315. {
  56316. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56317. if (sc->standardType == type)
  56318. return sc->retain();
  56319. }
  56320. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56321. getCursors().add (sc);
  56322. return sc;
  56323. }
  56324. SharedCursorHandle* retain() throw()
  56325. {
  56326. ++refCount;
  56327. return this;
  56328. }
  56329. void release()
  56330. {
  56331. if (--refCount == 0)
  56332. {
  56333. if (isStandard)
  56334. {
  56335. const ScopedLock sl (getLock());
  56336. getCursors().removeValue (this);
  56337. }
  56338. delete this;
  56339. }
  56340. }
  56341. void* getHandle() const throw() { return handle; }
  56342. juce_UseDebuggingNewOperator
  56343. private:
  56344. void* const handle;
  56345. Atomic <int> refCount;
  56346. const MouseCursor::StandardCursorType standardType;
  56347. const bool isStandard;
  56348. static CriticalSection& getLock()
  56349. {
  56350. static CriticalSection lock;
  56351. return lock;
  56352. }
  56353. static Array <SharedCursorHandle*>& getCursors()
  56354. {
  56355. static Array <SharedCursorHandle*> cursors;
  56356. return cursors;
  56357. }
  56358. ~SharedCursorHandle()
  56359. {
  56360. deleteMouseCursor (handle, isStandard);
  56361. }
  56362. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56363. };
  56364. MouseCursor::MouseCursor()
  56365. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56366. {
  56367. jassert (cursorHandle != 0);
  56368. }
  56369. MouseCursor::MouseCursor (const StandardCursorType type)
  56370. : cursorHandle (SharedCursorHandle::createStandard (type))
  56371. {
  56372. jassert (cursorHandle != 0);
  56373. }
  56374. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56375. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56376. {
  56377. }
  56378. MouseCursor::MouseCursor (const MouseCursor& other)
  56379. : cursorHandle (other.cursorHandle->retain())
  56380. {
  56381. }
  56382. MouseCursor::~MouseCursor()
  56383. {
  56384. cursorHandle->release();
  56385. }
  56386. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56387. {
  56388. other.cursorHandle->retain();
  56389. cursorHandle->release();
  56390. cursorHandle = other.cursorHandle;
  56391. return *this;
  56392. }
  56393. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56394. {
  56395. return getHandle() == other.getHandle();
  56396. }
  56397. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56398. {
  56399. return getHandle() != other.getHandle();
  56400. }
  56401. void* MouseCursor::getHandle() const throw()
  56402. {
  56403. return cursorHandle->getHandle();
  56404. }
  56405. void MouseCursor::showWaitCursor()
  56406. {
  56407. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56408. }
  56409. void MouseCursor::hideWaitCursor()
  56410. {
  56411. Desktop::getInstance().getMainMouseSource().revealCursor();
  56412. }
  56413. END_JUCE_NAMESPACE
  56414. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56415. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56416. BEGIN_JUCE_NAMESPACE
  56417. MouseEvent::MouseEvent (MouseInputSource& source_,
  56418. const Point<int>& position,
  56419. const ModifierKeys& mods_,
  56420. Component* const originator,
  56421. const Time& eventTime_,
  56422. const Point<int> mouseDownPos_,
  56423. const Time& mouseDownTime_,
  56424. const int numberOfClicks_,
  56425. const bool mouseWasDragged) throw()
  56426. : x (position.getX()),
  56427. y (position.getY()),
  56428. mods (mods_),
  56429. eventComponent (originator),
  56430. originalComponent (originator),
  56431. eventTime (eventTime_),
  56432. source (source_),
  56433. mouseDownPos (mouseDownPos_),
  56434. mouseDownTime (mouseDownTime_),
  56435. numberOfClicks (numberOfClicks_),
  56436. wasMovedSinceMouseDown (mouseWasDragged)
  56437. {
  56438. }
  56439. MouseEvent::~MouseEvent() throw()
  56440. {
  56441. }
  56442. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56443. {
  56444. if (otherComponent == 0)
  56445. {
  56446. jassertfalse
  56447. return *this;
  56448. }
  56449. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56450. mods, originalComponent, eventTime,
  56451. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56452. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56453. }
  56454. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56455. {
  56456. return MouseEvent (source, newPosition, mods, originalComponent,
  56457. eventTime, mouseDownPos, mouseDownTime,
  56458. numberOfClicks, wasMovedSinceMouseDown);
  56459. }
  56460. bool MouseEvent::mouseWasClicked() const throw()
  56461. {
  56462. return ! wasMovedSinceMouseDown;
  56463. }
  56464. int MouseEvent::getMouseDownX() const throw()
  56465. {
  56466. return mouseDownPos.getX();
  56467. }
  56468. int MouseEvent::getMouseDownY() const throw()
  56469. {
  56470. return mouseDownPos.getY();
  56471. }
  56472. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56473. {
  56474. return mouseDownPos;
  56475. }
  56476. int MouseEvent::getDistanceFromDragStartX() const throw()
  56477. {
  56478. return x - mouseDownPos.getX();
  56479. }
  56480. int MouseEvent::getDistanceFromDragStartY() const throw()
  56481. {
  56482. return y - mouseDownPos.getY();
  56483. }
  56484. int MouseEvent::getDistanceFromDragStart() const throw()
  56485. {
  56486. return mouseDownPos.getDistanceFrom (getPosition());
  56487. }
  56488. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56489. {
  56490. return getPosition() - mouseDownPos;
  56491. }
  56492. int MouseEvent::getLengthOfMousePress() const throw()
  56493. {
  56494. if (mouseDownTime.toMilliseconds() > 0)
  56495. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56496. return 0;
  56497. }
  56498. const Point<int> MouseEvent::getPosition() const throw()
  56499. {
  56500. return Point<int> (x, y);
  56501. }
  56502. int MouseEvent::getScreenX() const
  56503. {
  56504. return getScreenPosition().getX();
  56505. }
  56506. int MouseEvent::getScreenY() const
  56507. {
  56508. return getScreenPosition().getY();
  56509. }
  56510. const Point<int> MouseEvent::getScreenPosition() const
  56511. {
  56512. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56513. }
  56514. int MouseEvent::getMouseDownScreenX() const
  56515. {
  56516. return getMouseDownScreenPosition().getX();
  56517. }
  56518. int MouseEvent::getMouseDownScreenY() const
  56519. {
  56520. return getMouseDownScreenPosition().getY();
  56521. }
  56522. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56523. {
  56524. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56525. }
  56526. static int doubleClickTimeOutMs = 400;
  56527. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56528. {
  56529. doubleClickTimeOutMs = newTime;
  56530. }
  56531. int MouseEvent::getDoubleClickTimeout() throw()
  56532. {
  56533. return doubleClickTimeOutMs;
  56534. }
  56535. END_JUCE_NAMESPACE
  56536. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56537. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56538. BEGIN_JUCE_NAMESPACE
  56539. class MouseInputSourceInternal : public AsyncUpdater
  56540. {
  56541. public:
  56542. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56543. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56544. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56545. mouseEventCounter (0)
  56546. {
  56547. zerostruct (mouseDowns);
  56548. }
  56549. ~MouseInputSourceInternal()
  56550. {
  56551. }
  56552. bool isDragging() const throw()
  56553. {
  56554. return buttonState.isAnyMouseButtonDown();
  56555. }
  56556. Component* getComponentUnderMouse() const
  56557. {
  56558. return static_cast <Component*> (componentUnderMouse);
  56559. }
  56560. const ModifierKeys getCurrentModifiers() const
  56561. {
  56562. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56563. }
  56564. ComponentPeer* getPeer()
  56565. {
  56566. if (! ComponentPeer::isValidPeer (lastPeer))
  56567. lastPeer = 0;
  56568. return lastPeer;
  56569. }
  56570. Component* findComponentAt (const Point<int>& screenPos)
  56571. {
  56572. ComponentPeer* const peer = getPeer();
  56573. if (peer != 0)
  56574. {
  56575. Component* const comp = peer->getComponent();
  56576. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56577. // (the contains() call is needed to test for overlapping desktop windows)
  56578. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56579. return comp->getComponentAt (relativePos);
  56580. }
  56581. return 0;
  56582. }
  56583. const Point<int> getScreenPosition() const throw()
  56584. {
  56585. return lastScreenPos + unboundedMouseOffset;
  56586. }
  56587. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56588. {
  56589. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56590. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56591. }
  56592. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56593. {
  56594. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56595. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56596. }
  56597. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56598. {
  56599. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56600. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56601. }
  56602. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56603. {
  56604. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56605. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56606. }
  56607. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56608. {
  56609. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56610. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56611. }
  56612. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56613. {
  56614. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56615. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56616. }
  56617. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56618. {
  56619. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56620. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56621. }
  56622. // (returns true if the button change caused a modal event loop)
  56623. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56624. {
  56625. if (buttonState == newButtonState)
  56626. return false;
  56627. // (ignore secondary clicks when there's already a button down)
  56628. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56629. {
  56630. buttonState = newButtonState;
  56631. return false;
  56632. }
  56633. const int lastCounter = mouseEventCounter;
  56634. if (buttonState.isAnyMouseButtonDown())
  56635. {
  56636. Component* const current = getComponentUnderMouse();
  56637. if (current != 0)
  56638. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56639. enableUnboundedMouseMovement (false, false);
  56640. }
  56641. buttonState = newButtonState;
  56642. if (buttonState.isAnyMouseButtonDown())
  56643. {
  56644. Desktop::getInstance().incrementMouseClickCounter();
  56645. Component* const current = getComponentUnderMouse();
  56646. if (current != 0)
  56647. {
  56648. registerMouseDown (screenPos, time, current);
  56649. sendMouseDown (current, screenPos, time);
  56650. }
  56651. }
  56652. return lastCounter != mouseEventCounter;
  56653. }
  56654. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56655. {
  56656. Component* current = getComponentUnderMouse();
  56657. if (newComponent != current)
  56658. {
  56659. Component::SafePointer<Component> safeNewComp (newComponent);
  56660. const ModifierKeys originalButtonState (buttonState);
  56661. if (current != 0)
  56662. {
  56663. setButtons (screenPos, time, ModifierKeys());
  56664. sendMouseExit (current, screenPos, time);
  56665. buttonState = originalButtonState;
  56666. }
  56667. componentUnderMouse = safeNewComp;
  56668. current = getComponentUnderMouse();
  56669. if (current != 0)
  56670. sendMouseEnter (current, screenPos, time);
  56671. revealCursor (false);
  56672. setButtons (screenPos, time, originalButtonState);
  56673. }
  56674. }
  56675. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56676. {
  56677. ModifierKeys::updateCurrentModifiers();
  56678. if (newPeer != lastPeer)
  56679. {
  56680. setComponentUnderMouse (0, screenPos, time);
  56681. lastPeer = newPeer;
  56682. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56683. }
  56684. }
  56685. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56686. {
  56687. if (! isDragging())
  56688. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56689. if (newScreenPos != lastScreenPos || forceUpdate)
  56690. {
  56691. cancelPendingUpdate();
  56692. lastScreenPos = newScreenPos;
  56693. Component* const current = getComponentUnderMouse();
  56694. if (current != 0)
  56695. {
  56696. if (isDragging())
  56697. {
  56698. registerMouseDrag (newScreenPos);
  56699. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56700. if (isUnboundedMouseModeOn)
  56701. handleUnboundedDrag (current);
  56702. }
  56703. else
  56704. {
  56705. sendMouseMove (current, newScreenPos, time);
  56706. }
  56707. }
  56708. revealCursor (false);
  56709. }
  56710. }
  56711. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56712. {
  56713. jassert (newPeer != 0);
  56714. lastTime = time;
  56715. ++mouseEventCounter;
  56716. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56717. if (isDragging() && newMods.isAnyMouseButtonDown())
  56718. {
  56719. setScreenPos (screenPos, time, false);
  56720. }
  56721. else
  56722. {
  56723. setPeer (newPeer, screenPos, time);
  56724. ComponentPeer* peer = getPeer();
  56725. if (peer != 0)
  56726. {
  56727. if (setButtons (screenPos, time, newMods))
  56728. return; // some modal events have been dispatched, so the current event is now out-of-date
  56729. peer = getPeer();
  56730. if (peer != 0)
  56731. setScreenPos (screenPos, time, false);
  56732. }
  56733. }
  56734. }
  56735. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56736. {
  56737. jassert (peer != 0);
  56738. lastTime = time;
  56739. ++mouseEventCounter;
  56740. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56741. setPeer (peer, screenPos, time);
  56742. setScreenPos (screenPos, time, false);
  56743. triggerFakeMove();
  56744. if (! isDragging())
  56745. {
  56746. Component* current = getComponentUnderMouse();
  56747. if (current != 0)
  56748. sendMouseWheel (current, screenPos, time, x, y);
  56749. }
  56750. }
  56751. const Time getLastMouseDownTime() const throw()
  56752. {
  56753. return Time (mouseDowns[0].time);
  56754. }
  56755. const Point<int> getLastMouseDownPosition() const throw()
  56756. {
  56757. return mouseDowns[0].position;
  56758. }
  56759. int getNumberOfMultipleClicks() const throw()
  56760. {
  56761. int numClicks = 0;
  56762. if (mouseDowns[0].time != 0)
  56763. {
  56764. if (! mouseMovedSignificantlySincePressed)
  56765. ++numClicks;
  56766. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  56767. {
  56768. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  56769. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  56770. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8
  56771. && mouseDowns[0].component == mouseDowns[i].component)
  56772. {
  56773. ++numClicks;
  56774. }
  56775. else
  56776. {
  56777. break;
  56778. }
  56779. }
  56780. }
  56781. return numClicks;
  56782. }
  56783. bool hasMouseMovedSignificantlySincePressed() const throw()
  56784. {
  56785. return mouseMovedSignificantlySincePressed
  56786. || lastTime > mouseDowns[0].time + 300;
  56787. }
  56788. void triggerFakeMove()
  56789. {
  56790. triggerAsyncUpdate();
  56791. }
  56792. void handleAsyncUpdate()
  56793. {
  56794. if (! isDragging())
  56795. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  56796. }
  56797. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  56798. {
  56799. enable = enable && isDragging();
  56800. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  56801. if (enable != isUnboundedMouseModeOn)
  56802. {
  56803. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  56804. {
  56805. // when released, return the mouse to within the component's bounds
  56806. Component* current = getComponentUnderMouse();
  56807. if (current != 0)
  56808. Desktop::setMousePosition (current->getScreenBounds()
  56809. .getConstrainedPoint (current->getMouseXYRelative()));
  56810. }
  56811. isUnboundedMouseModeOn = enable;
  56812. unboundedMouseOffset = Point<int>();
  56813. revealCursor (true);
  56814. }
  56815. }
  56816. void handleUnboundedDrag (Component* current)
  56817. {
  56818. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  56819. if (! screenArea.contains (lastScreenPos))
  56820. {
  56821. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  56822. unboundedMouseOffset += (lastScreenPos - componentCentre);
  56823. Desktop::setMousePosition (componentCentre);
  56824. }
  56825. else if (isCursorVisibleUntilOffscreen
  56826. && (! unboundedMouseOffset.isOrigin())
  56827. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  56828. {
  56829. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  56830. unboundedMouseOffset = Point<int>();
  56831. }
  56832. }
  56833. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  56834. {
  56835. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  56836. {
  56837. cursor = MouseCursor::NoCursor;
  56838. forcedUpdate = true;
  56839. }
  56840. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  56841. {
  56842. currentCursorHandle = cursor.getHandle();
  56843. cursor.showInWindow (getPeer());
  56844. }
  56845. }
  56846. void hideCursor()
  56847. {
  56848. showMouseCursor (MouseCursor::NoCursor, true);
  56849. }
  56850. void revealCursor (bool forcedUpdate)
  56851. {
  56852. MouseCursor mc (MouseCursor::NormalCursor);
  56853. Component* current = getComponentUnderMouse();
  56854. if (current != 0)
  56855. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  56856. showMouseCursor (mc, forcedUpdate);
  56857. }
  56858. int index;
  56859. bool isMouseDevice;
  56860. Point<int> lastScreenPos;
  56861. ModifierKeys buttonState;
  56862. private:
  56863. MouseInputSource& source;
  56864. Component::SafePointer<Component> componentUnderMouse;
  56865. ComponentPeer* lastPeer;
  56866. Point<int> unboundedMouseOffset;
  56867. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  56868. void* currentCursorHandle;
  56869. int mouseEventCounter;
  56870. struct RecentMouseDown
  56871. {
  56872. Point<int> position;
  56873. int64 time;
  56874. Component* component;
  56875. };
  56876. RecentMouseDown mouseDowns[4];
  56877. bool mouseMovedSignificantlySincePressed;
  56878. int64 lastTime;
  56879. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  56880. {
  56881. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  56882. mouseDowns[i] = mouseDowns[i - 1];
  56883. mouseDowns[0].position = screenPos;
  56884. mouseDowns[0].time = time;
  56885. mouseDowns[0].component = component;
  56886. mouseMovedSignificantlySincePressed = false;
  56887. }
  56888. void registerMouseDrag (const Point<int>& screenPos) throw()
  56889. {
  56890. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  56891. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  56892. }
  56893. MouseInputSourceInternal (const MouseInputSourceInternal&);
  56894. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  56895. };
  56896. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  56897. {
  56898. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  56899. }
  56900. MouseInputSource::~MouseInputSource()
  56901. {
  56902. }
  56903. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  56904. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  56905. bool MouseInputSource::canHover() const { return isMouse(); }
  56906. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  56907. int MouseInputSource::getIndex() const { return pimpl->index; }
  56908. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  56909. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  56910. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  56911. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  56912. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  56913. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  56914. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  56915. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  56916. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  56917. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  56918. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  56919. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  56920. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  56921. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  56922. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  56923. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  56924. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  56925. {
  56926. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  56927. }
  56928. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  56929. {
  56930. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  56931. }
  56932. END_JUCE_NAMESPACE
  56933. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  56934. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  56935. BEGIN_JUCE_NAMESPACE
  56936. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  56937. : source (0),
  56938. hoverTimeMillisecs (hoverTimeMillisecs_),
  56939. hasJustHovered (false)
  56940. {
  56941. internalTimer.owner = this;
  56942. }
  56943. MouseHoverDetector::~MouseHoverDetector()
  56944. {
  56945. setHoverComponent (0);
  56946. }
  56947. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  56948. {
  56949. hoverTimeMillisecs = newTimeInMillisecs;
  56950. }
  56951. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  56952. {
  56953. if (source != newSourceComponent)
  56954. {
  56955. internalTimer.stopTimer();
  56956. hasJustHovered = false;
  56957. if (source != 0)
  56958. {
  56959. // ! you need to delete the hover detector before deleting its component
  56960. jassert (source->isValidComponent());
  56961. source->removeMouseListener (&internalTimer);
  56962. }
  56963. source = newSourceComponent;
  56964. if (newSourceComponent != 0)
  56965. newSourceComponent->addMouseListener (&internalTimer, false);
  56966. }
  56967. }
  56968. void MouseHoverDetector::hoverTimerCallback()
  56969. {
  56970. internalTimer.stopTimer();
  56971. if (source != 0)
  56972. {
  56973. const Point<int> pos (source->getMouseXYRelative());
  56974. if (source->reallyContains (pos.getX(), pos.getY(), false))
  56975. {
  56976. hasJustHovered = true;
  56977. mouseHovered (pos.getX(), pos.getY());
  56978. }
  56979. }
  56980. }
  56981. void MouseHoverDetector::checkJustHoveredCallback()
  56982. {
  56983. if (hasJustHovered)
  56984. {
  56985. hasJustHovered = false;
  56986. mouseMovedAfterHover();
  56987. }
  56988. }
  56989. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  56990. {
  56991. owner->hoverTimerCallback();
  56992. }
  56993. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  56994. {
  56995. stopTimer();
  56996. owner->checkJustHoveredCallback();
  56997. }
  56998. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  56999. {
  57000. stopTimer();
  57001. owner->checkJustHoveredCallback();
  57002. }
  57003. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57004. {
  57005. stopTimer();
  57006. owner->checkJustHoveredCallback();
  57007. }
  57008. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57009. {
  57010. stopTimer();
  57011. owner->checkJustHoveredCallback();
  57012. }
  57013. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57014. {
  57015. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57016. {
  57017. lastX = e.x;
  57018. lastY = e.y;
  57019. if (owner->source != 0)
  57020. startTimer (owner->hoverTimeMillisecs);
  57021. owner->checkJustHoveredCallback();
  57022. }
  57023. }
  57024. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57025. {
  57026. stopTimer();
  57027. owner->checkJustHoveredCallback();
  57028. }
  57029. END_JUCE_NAMESPACE
  57030. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57031. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57032. BEGIN_JUCE_NAMESPACE
  57033. void MouseListener::mouseEnter (const MouseEvent&)
  57034. {
  57035. }
  57036. void MouseListener::mouseExit (const MouseEvent&)
  57037. {
  57038. }
  57039. void MouseListener::mouseDown (const MouseEvent&)
  57040. {
  57041. }
  57042. void MouseListener::mouseUp (const MouseEvent&)
  57043. {
  57044. }
  57045. void MouseListener::mouseDrag (const MouseEvent&)
  57046. {
  57047. }
  57048. void MouseListener::mouseMove (const MouseEvent&)
  57049. {
  57050. }
  57051. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57052. {
  57053. }
  57054. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57055. {
  57056. }
  57057. END_JUCE_NAMESPACE
  57058. /*** End of inlined file: juce_MouseListener.cpp ***/
  57059. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57060. BEGIN_JUCE_NAMESPACE
  57061. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57062. const String& buttonTextWhenTrue,
  57063. const String& buttonTextWhenFalse)
  57064. : PropertyComponent (name),
  57065. onText (buttonTextWhenTrue),
  57066. offText (buttonTextWhenFalse)
  57067. {
  57068. createButton();
  57069. button->addButtonListener (this);
  57070. }
  57071. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57072. const String& name,
  57073. const String& buttonText)
  57074. : PropertyComponent (name),
  57075. onText (buttonText),
  57076. offText (buttonText)
  57077. {
  57078. createButton();
  57079. button->setButtonText (buttonText);
  57080. button->getToggleStateValue().referTo (valueToControl);
  57081. button->setClickingTogglesState (true);
  57082. }
  57083. BooleanPropertyComponent::~BooleanPropertyComponent()
  57084. {
  57085. deleteAllChildren();
  57086. }
  57087. void BooleanPropertyComponent::createButton()
  57088. {
  57089. addAndMakeVisible (button = new ToggleButton (String::empty));
  57090. button->setClickingTogglesState (false);
  57091. }
  57092. void BooleanPropertyComponent::setState (const bool newState)
  57093. {
  57094. button->setToggleState (newState, true);
  57095. }
  57096. bool BooleanPropertyComponent::getState() const
  57097. {
  57098. return button->getToggleState();
  57099. }
  57100. void BooleanPropertyComponent::paint (Graphics& g)
  57101. {
  57102. PropertyComponent::paint (g);
  57103. g.setColour (Colours::white);
  57104. g.fillRect (button->getBounds());
  57105. g.setColour (findColour (ComboBox::outlineColourId));
  57106. g.drawRect (button->getBounds());
  57107. }
  57108. void BooleanPropertyComponent::refresh()
  57109. {
  57110. button->setToggleState (getState(), false);
  57111. button->setButtonText (button->getToggleState() ? onText : offText);
  57112. }
  57113. void BooleanPropertyComponent::buttonClicked (Button*)
  57114. {
  57115. setState (! getState());
  57116. }
  57117. END_JUCE_NAMESPACE
  57118. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57119. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57120. BEGIN_JUCE_NAMESPACE
  57121. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57122. const bool triggerOnMouseDown)
  57123. : PropertyComponent (name)
  57124. {
  57125. addAndMakeVisible (button = new TextButton (String::empty));
  57126. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  57127. button->addButtonListener (this);
  57128. }
  57129. ButtonPropertyComponent::~ButtonPropertyComponent()
  57130. {
  57131. deleteAllChildren();
  57132. }
  57133. void ButtonPropertyComponent::refresh()
  57134. {
  57135. button->setButtonText (getButtonText());
  57136. }
  57137. void ButtonPropertyComponent::buttonClicked (Button*)
  57138. {
  57139. buttonClicked();
  57140. }
  57141. END_JUCE_NAMESPACE
  57142. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57143. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57144. BEGIN_JUCE_NAMESPACE
  57145. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57146. : PropertyComponent (name),
  57147. comboBox (0)
  57148. {
  57149. }
  57150. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57151. const String& name,
  57152. const StringArray& choices_,
  57153. const Array <int>* choiceIDs)
  57154. : PropertyComponent (name),
  57155. choices (choices_),
  57156. comboBox (0)
  57157. {
  57158. createComboBox (choiceIDs);
  57159. comboBox->getSelectedIdAsValue().referTo (valueToControl);
  57160. }
  57161. ChoicePropertyComponent::~ChoicePropertyComponent()
  57162. {
  57163. deleteAllChildren();
  57164. }
  57165. void ChoicePropertyComponent::createComboBox (const Array <int>* choiceIDs)
  57166. {
  57167. // The array of IDs must contain the same number of values as the choices list!
  57168. jassert (choiceIDs == 0 || choiceIDs->size() == choices.size());
  57169. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  57170. int itemId = 0;
  57171. for (int i = 0; i < choices.size(); ++i)
  57172. {
  57173. if (choices[i].isNotEmpty())
  57174. comboBox->addItem (choices[i], choiceIDs == 0 ? ++itemId
  57175. : ((*choiceIDs)[i]));
  57176. else
  57177. comboBox->addSeparator();
  57178. }
  57179. comboBox->setEditableText (false);
  57180. }
  57181. void ChoicePropertyComponent::setIndex (const int newIndex)
  57182. {
  57183. comboBox->setSelectedId (comboBox->getItemId (newIndex));
  57184. }
  57185. int ChoicePropertyComponent::getIndex() const
  57186. {
  57187. return comboBox->getSelectedItemIndex();
  57188. }
  57189. const StringArray& ChoicePropertyComponent::getChoices() const
  57190. {
  57191. return choices;
  57192. }
  57193. void ChoicePropertyComponent::refresh()
  57194. {
  57195. if (comboBox == 0)
  57196. {
  57197. createComboBox (0);
  57198. comboBox->addListener (this);
  57199. }
  57200. comboBox->setSelectedId (getIndex() + 1, true);
  57201. }
  57202. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57203. {
  57204. const int newIndex = comboBox->getSelectedId() - 1;
  57205. if (newIndex != getIndex())
  57206. setIndex (newIndex);
  57207. }
  57208. END_JUCE_NAMESPACE
  57209. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57210. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57211. BEGIN_JUCE_NAMESPACE
  57212. PropertyComponent::PropertyComponent (const String& name,
  57213. const int preferredHeight_)
  57214. : Component (name),
  57215. preferredHeight (preferredHeight_)
  57216. {
  57217. jassert (name.isNotEmpty());
  57218. }
  57219. PropertyComponent::~PropertyComponent()
  57220. {
  57221. }
  57222. void PropertyComponent::paint (Graphics& g)
  57223. {
  57224. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57225. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57226. }
  57227. void PropertyComponent::resized()
  57228. {
  57229. if (getNumChildComponents() > 0)
  57230. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57231. }
  57232. void PropertyComponent::enablementChanged()
  57233. {
  57234. repaint();
  57235. }
  57236. END_JUCE_NAMESPACE
  57237. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57238. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57239. BEGIN_JUCE_NAMESPACE
  57240. class PropertyPanel::PropertyHolderComponent : public Component
  57241. {
  57242. public:
  57243. PropertyHolderComponent()
  57244. {
  57245. }
  57246. ~PropertyHolderComponent()
  57247. {
  57248. deleteAllChildren();
  57249. }
  57250. void paint (Graphics&)
  57251. {
  57252. }
  57253. void updateLayout (int width);
  57254. void refreshAll() const;
  57255. private:
  57256. PropertyHolderComponent (const PropertyHolderComponent&);
  57257. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57258. };
  57259. class PropertySectionComponent : public Component
  57260. {
  57261. public:
  57262. PropertySectionComponent (const String& sectionTitle,
  57263. const Array <PropertyComponent*>& newProperties,
  57264. const bool open)
  57265. : Component (sectionTitle),
  57266. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57267. isOpen_ (open)
  57268. {
  57269. for (int i = newProperties.size(); --i >= 0;)
  57270. {
  57271. addAndMakeVisible (newProperties.getUnchecked(i));
  57272. newProperties.getUnchecked(i)->refresh();
  57273. }
  57274. }
  57275. ~PropertySectionComponent()
  57276. {
  57277. deleteAllChildren();
  57278. }
  57279. void paint (Graphics& g)
  57280. {
  57281. if (titleHeight > 0)
  57282. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57283. }
  57284. void resized()
  57285. {
  57286. int y = titleHeight;
  57287. for (int i = getNumChildComponents(); --i >= 0;)
  57288. {
  57289. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57290. if (pec != 0)
  57291. {
  57292. const int prefH = pec->getPreferredHeight();
  57293. pec->setBounds (1, y, getWidth() - 2, prefH);
  57294. y += prefH;
  57295. }
  57296. }
  57297. }
  57298. int getPreferredHeight() const
  57299. {
  57300. int y = titleHeight;
  57301. if (isOpen())
  57302. {
  57303. for (int i = 0; i < getNumChildComponents(); ++i)
  57304. {
  57305. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57306. if (pec != 0)
  57307. y += pec->getPreferredHeight();
  57308. }
  57309. }
  57310. return y;
  57311. }
  57312. void setOpen (const bool open)
  57313. {
  57314. if (isOpen_ != open)
  57315. {
  57316. isOpen_ = open;
  57317. for (int i = 0; i < getNumChildComponents(); ++i)
  57318. {
  57319. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57320. if (pec != 0)
  57321. pec->setVisible (open);
  57322. }
  57323. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57324. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57325. if (pp != 0)
  57326. pp->resized();
  57327. }
  57328. }
  57329. bool isOpen() const
  57330. {
  57331. return isOpen_;
  57332. }
  57333. void refreshAll() const
  57334. {
  57335. for (int i = 0; i < getNumChildComponents(); ++i)
  57336. {
  57337. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57338. if (pec != 0)
  57339. pec->refresh();
  57340. }
  57341. }
  57342. void mouseDown (const MouseEvent&)
  57343. {
  57344. }
  57345. void mouseUp (const MouseEvent& e)
  57346. {
  57347. if (e.getMouseDownX() < titleHeight
  57348. && e.x < titleHeight
  57349. && e.y < titleHeight
  57350. && e.getNumberOfClicks() != 2)
  57351. {
  57352. setOpen (! isOpen());
  57353. }
  57354. }
  57355. void mouseDoubleClick (const MouseEvent& e)
  57356. {
  57357. if (e.y < titleHeight)
  57358. setOpen (! isOpen());
  57359. }
  57360. private:
  57361. int titleHeight;
  57362. bool isOpen_;
  57363. PropertySectionComponent (const PropertySectionComponent&);
  57364. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57365. };
  57366. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57367. {
  57368. int y = 0;
  57369. for (int i = getNumChildComponents(); --i >= 0;)
  57370. {
  57371. PropertySectionComponent* const section
  57372. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57373. if (section != 0)
  57374. {
  57375. const int prefH = section->getPreferredHeight();
  57376. section->setBounds (0, y, width, prefH);
  57377. y += prefH;
  57378. }
  57379. }
  57380. setSize (width, y);
  57381. repaint();
  57382. }
  57383. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57384. {
  57385. for (int i = getNumChildComponents(); --i >= 0;)
  57386. {
  57387. PropertySectionComponent* const section
  57388. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57389. if (section != 0)
  57390. section->refreshAll();
  57391. }
  57392. }
  57393. PropertyPanel::PropertyPanel()
  57394. {
  57395. messageWhenEmpty = TRANS("(nothing selected)");
  57396. addAndMakeVisible (viewport = new Viewport());
  57397. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57398. viewport->setFocusContainer (true);
  57399. }
  57400. PropertyPanel::~PropertyPanel()
  57401. {
  57402. clear();
  57403. deleteAllChildren();
  57404. }
  57405. void PropertyPanel::paint (Graphics& g)
  57406. {
  57407. if (propertyHolderComponent->getNumChildComponents() == 0)
  57408. {
  57409. g.setColour (Colours::black.withAlpha (0.5f));
  57410. g.setFont (14.0f);
  57411. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57412. Justification::centred, true);
  57413. }
  57414. }
  57415. void PropertyPanel::resized()
  57416. {
  57417. viewport->setBounds (0, 0, getWidth(), getHeight());
  57418. updatePropHolderLayout();
  57419. }
  57420. void PropertyPanel::clear()
  57421. {
  57422. if (propertyHolderComponent->getNumChildComponents() > 0)
  57423. {
  57424. propertyHolderComponent->deleteAllChildren();
  57425. repaint();
  57426. }
  57427. }
  57428. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57429. {
  57430. if (propertyHolderComponent->getNumChildComponents() == 0)
  57431. repaint();
  57432. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57433. newProperties,
  57434. true), 0);
  57435. updatePropHolderLayout();
  57436. }
  57437. void PropertyPanel::addSection (const String& sectionTitle,
  57438. const Array <PropertyComponent*>& newProperties,
  57439. const bool shouldBeOpen)
  57440. {
  57441. jassert (sectionTitle.isNotEmpty());
  57442. if (propertyHolderComponent->getNumChildComponents() == 0)
  57443. repaint();
  57444. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57445. newProperties,
  57446. shouldBeOpen), 0);
  57447. updatePropHolderLayout();
  57448. }
  57449. void PropertyPanel::updatePropHolderLayout() const
  57450. {
  57451. const int maxWidth = viewport->getMaximumVisibleWidth();
  57452. propertyHolderComponent->updateLayout (maxWidth);
  57453. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  57454. if (maxWidth != newMaxWidth)
  57455. {
  57456. // need to do this twice because of scrollbars changing the size, etc.
  57457. propertyHolderComponent->updateLayout (newMaxWidth);
  57458. }
  57459. }
  57460. void PropertyPanel::refreshAll() const
  57461. {
  57462. propertyHolderComponent->refreshAll();
  57463. }
  57464. const StringArray PropertyPanel::getSectionNames() const
  57465. {
  57466. StringArray s;
  57467. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57468. {
  57469. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57470. if (section != 0 && section->getName().isNotEmpty())
  57471. s.add (section->getName());
  57472. }
  57473. return s;
  57474. }
  57475. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57476. {
  57477. int index = 0;
  57478. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57479. {
  57480. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57481. if (section != 0 && section->getName().isNotEmpty())
  57482. {
  57483. if (index == sectionIndex)
  57484. return section->isOpen();
  57485. ++index;
  57486. }
  57487. }
  57488. return false;
  57489. }
  57490. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57491. {
  57492. int index = 0;
  57493. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57494. {
  57495. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57496. if (section != 0 && section->getName().isNotEmpty())
  57497. {
  57498. if (index == sectionIndex)
  57499. {
  57500. section->setOpen (shouldBeOpen);
  57501. break;
  57502. }
  57503. ++index;
  57504. }
  57505. }
  57506. }
  57507. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57508. {
  57509. int index = 0;
  57510. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57511. {
  57512. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57513. if (section != 0 && section->getName().isNotEmpty())
  57514. {
  57515. if (index == sectionIndex)
  57516. {
  57517. section->setEnabled (shouldBeEnabled);
  57518. break;
  57519. }
  57520. ++index;
  57521. }
  57522. }
  57523. }
  57524. XmlElement* PropertyPanel::getOpennessState() const
  57525. {
  57526. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57527. xml->setAttribute ("scrollPos", viewport->getViewPositionY());
  57528. const StringArray sections (getSectionNames());
  57529. for (int i = 0; i < sections.size(); ++i)
  57530. {
  57531. if (sections[i].isNotEmpty())
  57532. {
  57533. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57534. e->setAttribute ("name", sections[i]);
  57535. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57536. }
  57537. }
  57538. return xml;
  57539. }
  57540. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57541. {
  57542. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57543. {
  57544. const StringArray sections (getSectionNames());
  57545. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57546. {
  57547. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57548. e->getBoolAttribute ("open"));
  57549. }
  57550. viewport->setViewPosition (viewport->getViewPositionX(),
  57551. xml.getIntAttribute ("scrollPos", viewport->getViewPositionY()));
  57552. }
  57553. }
  57554. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57555. {
  57556. if (messageWhenEmpty != newMessage)
  57557. {
  57558. messageWhenEmpty = newMessage;
  57559. repaint();
  57560. }
  57561. }
  57562. const String& PropertyPanel::getMessageWhenEmpty() const
  57563. {
  57564. return messageWhenEmpty;
  57565. }
  57566. END_JUCE_NAMESPACE
  57567. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57568. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57569. BEGIN_JUCE_NAMESPACE
  57570. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57571. const double rangeMin,
  57572. const double rangeMax,
  57573. const double interval,
  57574. const double skewFactor)
  57575. : PropertyComponent (name)
  57576. {
  57577. addAndMakeVisible (slider = new Slider (name));
  57578. slider->setRange (rangeMin, rangeMax, interval);
  57579. slider->setSkewFactor (skewFactor);
  57580. slider->setSliderStyle (Slider::LinearBar);
  57581. slider->addListener (this);
  57582. }
  57583. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57584. const String& name,
  57585. const double rangeMin,
  57586. const double rangeMax,
  57587. const double interval,
  57588. const double skewFactor)
  57589. : PropertyComponent (name)
  57590. {
  57591. addAndMakeVisible (slider = new Slider (name));
  57592. slider->setRange (rangeMin, rangeMax, interval);
  57593. slider->setSkewFactor (skewFactor);
  57594. slider->setSliderStyle (Slider::LinearBar);
  57595. slider->getValueObject().referTo (valueToControl);
  57596. }
  57597. SliderPropertyComponent::~SliderPropertyComponent()
  57598. {
  57599. deleteAllChildren();
  57600. }
  57601. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57602. {
  57603. }
  57604. double SliderPropertyComponent::getValue() const
  57605. {
  57606. return slider->getValue();
  57607. }
  57608. void SliderPropertyComponent::refresh()
  57609. {
  57610. slider->setValue (getValue(), false);
  57611. }
  57612. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57613. {
  57614. if (getValue() != slider->getValue())
  57615. setValue (slider->getValue());
  57616. }
  57617. END_JUCE_NAMESPACE
  57618. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57619. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57620. BEGIN_JUCE_NAMESPACE
  57621. class TextPropLabel : public Label
  57622. {
  57623. TextPropertyComponent& owner;
  57624. int maxChars;
  57625. bool isMultiline;
  57626. public:
  57627. TextPropLabel (TextPropertyComponent& owner_,
  57628. const int maxChars_, const bool isMultiline_)
  57629. : Label (String::empty, String::empty),
  57630. owner (owner_),
  57631. maxChars (maxChars_),
  57632. isMultiline (isMultiline_)
  57633. {
  57634. setEditable (true, true, false);
  57635. setColour (backgroundColourId, Colours::white);
  57636. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57637. }
  57638. ~TextPropLabel()
  57639. {
  57640. }
  57641. TextEditor* createEditorComponent()
  57642. {
  57643. TextEditor* const textEditor = Label::createEditorComponent();
  57644. textEditor->setInputRestrictions (maxChars);
  57645. if (isMultiline)
  57646. {
  57647. textEditor->setMultiLine (true, true);
  57648. textEditor->setReturnKeyStartsNewLine (true);
  57649. }
  57650. return textEditor;
  57651. }
  57652. void textWasEdited()
  57653. {
  57654. owner.textWasEdited();
  57655. }
  57656. };
  57657. TextPropertyComponent::TextPropertyComponent (const String& name,
  57658. const int maxNumChars,
  57659. const bool isMultiLine)
  57660. : PropertyComponent (name)
  57661. {
  57662. createEditor (maxNumChars, isMultiLine);
  57663. }
  57664. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57665. const String& name,
  57666. const int maxNumChars,
  57667. const bool isMultiLine)
  57668. : PropertyComponent (name)
  57669. {
  57670. createEditor (maxNumChars, isMultiLine);
  57671. textEditor->getTextValue().referTo (valueToControl);
  57672. }
  57673. TextPropertyComponent::~TextPropertyComponent()
  57674. {
  57675. deleteAllChildren();
  57676. }
  57677. void TextPropertyComponent::setText (const String& newText)
  57678. {
  57679. textEditor->setText (newText, true);
  57680. }
  57681. const String TextPropertyComponent::getText() const
  57682. {
  57683. return textEditor->getText();
  57684. }
  57685. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57686. {
  57687. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57688. if (isMultiLine)
  57689. {
  57690. textEditor->setJustificationType (Justification::topLeft);
  57691. preferredHeight = 120;
  57692. }
  57693. }
  57694. void TextPropertyComponent::refresh()
  57695. {
  57696. textEditor->setText (getText(), false);
  57697. }
  57698. void TextPropertyComponent::textWasEdited()
  57699. {
  57700. const String newText (textEditor->getText());
  57701. if (getText() != newText)
  57702. setText (newText);
  57703. }
  57704. END_JUCE_NAMESPACE
  57705. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57706. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57707. BEGIN_JUCE_NAMESPACE
  57708. class SimpleDeviceManagerInputLevelMeter : public Component,
  57709. public Timer
  57710. {
  57711. public:
  57712. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57713. : manager (manager_),
  57714. level (0)
  57715. {
  57716. startTimer (50);
  57717. manager->enableInputLevelMeasurement (true);
  57718. }
  57719. ~SimpleDeviceManagerInputLevelMeter()
  57720. {
  57721. manager->enableInputLevelMeasurement (false);
  57722. }
  57723. void timerCallback()
  57724. {
  57725. const float newLevel = (float) manager->getCurrentInputLevel();
  57726. if (fabsf (level - newLevel) > 0.005f)
  57727. {
  57728. level = newLevel;
  57729. repaint();
  57730. }
  57731. }
  57732. void paint (Graphics& g)
  57733. {
  57734. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  57735. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  57736. }
  57737. private:
  57738. AudioDeviceManager* const manager;
  57739. float level;
  57740. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  57741. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  57742. };
  57743. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  57744. public ListBoxModel
  57745. {
  57746. public:
  57747. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  57748. const String& noItemsMessage_,
  57749. const int minNumber_,
  57750. const int maxNumber_)
  57751. : ListBox (String::empty, 0),
  57752. deviceManager (deviceManager_),
  57753. noItemsMessage (noItemsMessage_),
  57754. minNumber (minNumber_),
  57755. maxNumber (maxNumber_)
  57756. {
  57757. items = MidiInput::getDevices();
  57758. setModel (this);
  57759. setOutlineThickness (1);
  57760. }
  57761. ~MidiInputSelectorComponentListBox()
  57762. {
  57763. }
  57764. int getNumRows()
  57765. {
  57766. return items.size();
  57767. }
  57768. void paintListBoxItem (int row,
  57769. Graphics& g,
  57770. int width, int height,
  57771. bool rowIsSelected)
  57772. {
  57773. if (((unsigned int) row) < (unsigned int) items.size())
  57774. {
  57775. if (rowIsSelected)
  57776. g.fillAll (findColour (TextEditor::highlightColourId)
  57777. .withMultipliedAlpha (0.3f));
  57778. const String item (items [row]);
  57779. bool enabled = deviceManager.isMidiInputEnabled (item);
  57780. const int x = getTickX();
  57781. const float tickW = height * 0.75f;
  57782. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  57783. enabled, true, true, false);
  57784. g.setFont (height * 0.6f);
  57785. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  57786. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  57787. }
  57788. }
  57789. void listBoxItemClicked (int row, const MouseEvent& e)
  57790. {
  57791. selectRow (row);
  57792. if (e.x < getTickX())
  57793. flipEnablement (row);
  57794. }
  57795. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  57796. {
  57797. flipEnablement (row);
  57798. }
  57799. void returnKeyPressed (int row)
  57800. {
  57801. flipEnablement (row);
  57802. }
  57803. void paint (Graphics& g)
  57804. {
  57805. ListBox::paint (g);
  57806. if (items.size() == 0)
  57807. {
  57808. g.setColour (Colours::grey);
  57809. g.setFont (13.0f);
  57810. g.drawText (noItemsMessage,
  57811. 0, 0, getWidth(), getHeight() / 2,
  57812. Justification::centred, true);
  57813. }
  57814. }
  57815. int getBestHeight (const int preferredHeight)
  57816. {
  57817. const int extra = getOutlineThickness() * 2;
  57818. return jmax (getRowHeight() * 2 + extra,
  57819. jmin (getRowHeight() * getNumRows() + extra,
  57820. preferredHeight));
  57821. }
  57822. juce_UseDebuggingNewOperator
  57823. private:
  57824. AudioDeviceManager& deviceManager;
  57825. const String noItemsMessage;
  57826. StringArray items;
  57827. int minNumber, maxNumber;
  57828. void flipEnablement (const int row)
  57829. {
  57830. if (((unsigned int) row) < (unsigned int) items.size())
  57831. {
  57832. const String item (items [row]);
  57833. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  57834. }
  57835. }
  57836. int getTickX() const
  57837. {
  57838. return getRowHeight() + 5;
  57839. }
  57840. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  57841. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  57842. };
  57843. class AudioDeviceSettingsPanel : public Component,
  57844. public ComboBoxListener,
  57845. public ChangeListener,
  57846. public ButtonListener
  57847. {
  57848. public:
  57849. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  57850. AudioIODeviceType::DeviceSetupDetails& setup_,
  57851. const bool hideAdvancedOptionsWithButton)
  57852. : type (type_),
  57853. setup (setup_)
  57854. {
  57855. sampleRateDropDown = 0;
  57856. sampleRateLabel = 0;
  57857. bufferSizeDropDown = 0;
  57858. bufferSizeLabel = 0;
  57859. outputDeviceDropDown = 0;
  57860. outputDeviceLabel = 0;
  57861. inputDeviceDropDown = 0;
  57862. inputDeviceLabel = 0;
  57863. testButton = 0;
  57864. inputLevelMeter = 0;
  57865. showUIButton = 0;
  57866. inputChanList = 0;
  57867. outputChanList = 0;
  57868. inputChanLabel = 0;
  57869. outputChanLabel = 0;
  57870. showAdvancedSettingsButton = 0;
  57871. if (hideAdvancedOptionsWithButton)
  57872. {
  57873. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  57874. showAdvancedSettingsButton->addButtonListener (this);
  57875. }
  57876. type->scanForDevices();
  57877. setup.manager->addChangeListener (this);
  57878. changeListenerCallback (0);
  57879. }
  57880. ~AudioDeviceSettingsPanel()
  57881. {
  57882. setup.manager->removeChangeListener (this);
  57883. deleteAndZero (outputDeviceLabel);
  57884. deleteAndZero (inputDeviceLabel);
  57885. deleteAndZero (sampleRateLabel);
  57886. deleteAndZero (bufferSizeLabel);
  57887. deleteAndZero (showUIButton);
  57888. deleteAndZero (inputChanLabel);
  57889. deleteAndZero (outputChanLabel);
  57890. deleteAndZero (showAdvancedSettingsButton);
  57891. deleteAllChildren();
  57892. }
  57893. void resized()
  57894. {
  57895. const int lx = proportionOfWidth (0.35f);
  57896. const int w = proportionOfWidth (0.4f);
  57897. const int h = 24;
  57898. const int space = 6;
  57899. const int dh = h + space;
  57900. int y = 0;
  57901. if (outputDeviceDropDown != 0)
  57902. {
  57903. outputDeviceDropDown->setBounds (lx, y, w, h);
  57904. if (testButton != 0)
  57905. testButton->setBounds (proportionOfWidth (0.77f),
  57906. outputDeviceDropDown->getY(),
  57907. proportionOfWidth (0.18f),
  57908. h);
  57909. y += dh;
  57910. }
  57911. if (inputDeviceDropDown != 0)
  57912. {
  57913. inputDeviceDropDown->setBounds (lx, y, w, h);
  57914. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  57915. inputDeviceDropDown->getY(),
  57916. proportionOfWidth (0.18f),
  57917. h);
  57918. y += dh;
  57919. }
  57920. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  57921. if (outputChanList != 0)
  57922. {
  57923. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  57924. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57925. y += bh + space;
  57926. }
  57927. if (inputChanList != 0)
  57928. {
  57929. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  57930. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57931. y += bh + space;
  57932. }
  57933. y += space * 2;
  57934. if (showAdvancedSettingsButton != 0)
  57935. {
  57936. showAdvancedSettingsButton->changeWidthToFitText (h);
  57937. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  57938. }
  57939. if (sampleRateDropDown != 0)
  57940. {
  57941. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  57942. || ! showAdvancedSettingsButton->isVisible());
  57943. sampleRateDropDown->setBounds (lx, y, w, h);
  57944. y += dh;
  57945. }
  57946. if (bufferSizeDropDown != 0)
  57947. {
  57948. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  57949. || ! showAdvancedSettingsButton->isVisible());
  57950. bufferSizeDropDown->setBounds (lx, y, w, h);
  57951. y += dh;
  57952. }
  57953. if (showUIButton != 0)
  57954. {
  57955. showUIButton->setVisible (showAdvancedSettingsButton == 0
  57956. || ! showAdvancedSettingsButton->isVisible());
  57957. showUIButton->changeWidthToFitText (h);
  57958. showUIButton->setTopLeftPosition (lx, y);
  57959. }
  57960. }
  57961. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  57962. {
  57963. if (comboBoxThatHasChanged == 0)
  57964. return;
  57965. AudioDeviceManager::AudioDeviceSetup config;
  57966. setup.manager->getAudioDeviceSetup (config);
  57967. String error;
  57968. if (comboBoxThatHasChanged == outputDeviceDropDown
  57969. || comboBoxThatHasChanged == inputDeviceDropDown)
  57970. {
  57971. if (outputDeviceDropDown != 0)
  57972. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  57973. : outputDeviceDropDown->getText();
  57974. if (inputDeviceDropDown != 0)
  57975. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  57976. : inputDeviceDropDown->getText();
  57977. if (! type->hasSeparateInputsAndOutputs())
  57978. config.inputDeviceName = config.outputDeviceName;
  57979. if (comboBoxThatHasChanged == inputDeviceDropDown)
  57980. config.useDefaultInputChannels = true;
  57981. else
  57982. config.useDefaultOutputChannels = true;
  57983. error = setup.manager->setAudioDeviceSetup (config, true);
  57984. showCorrectDeviceName (inputDeviceDropDown, true);
  57985. showCorrectDeviceName (outputDeviceDropDown, false);
  57986. updateControlPanelButton();
  57987. resized();
  57988. }
  57989. else if (comboBoxThatHasChanged == sampleRateDropDown)
  57990. {
  57991. if (sampleRateDropDown->getSelectedId() > 0)
  57992. {
  57993. config.sampleRate = sampleRateDropDown->getSelectedId();
  57994. error = setup.manager->setAudioDeviceSetup (config, true);
  57995. }
  57996. }
  57997. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  57998. {
  57999. if (bufferSizeDropDown->getSelectedId() > 0)
  58000. {
  58001. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58002. error = setup.manager->setAudioDeviceSetup (config, true);
  58003. }
  58004. }
  58005. if (error.isNotEmpty())
  58006. {
  58007. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58008. "Error when trying to open audio device!",
  58009. error);
  58010. }
  58011. }
  58012. void buttonClicked (Button* button)
  58013. {
  58014. if (button == showAdvancedSettingsButton)
  58015. {
  58016. showAdvancedSettingsButton->setVisible (false);
  58017. resized();
  58018. }
  58019. else if (button == showUIButton)
  58020. {
  58021. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58022. if (device != 0 && device->showControlPanel())
  58023. {
  58024. setup.manager->closeAudioDevice();
  58025. setup.manager->restartLastAudioDevice();
  58026. getTopLevelComponent()->toFront (true);
  58027. }
  58028. }
  58029. else if (button == testButton && testButton != 0)
  58030. {
  58031. setup.manager->playTestSound();
  58032. }
  58033. }
  58034. void updateControlPanelButton()
  58035. {
  58036. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58037. deleteAndZero (showUIButton);
  58038. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58039. {
  58040. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58041. TRANS ("opens the device's own control panel")));
  58042. showUIButton->addButtonListener (this);
  58043. }
  58044. resized();
  58045. }
  58046. void changeListenerCallback (void*)
  58047. {
  58048. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58049. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58050. {
  58051. if (outputDeviceDropDown == 0)
  58052. {
  58053. outputDeviceDropDown = new ComboBox (String::empty);
  58054. outputDeviceDropDown->addListener (this);
  58055. addAndMakeVisible (outputDeviceDropDown);
  58056. outputDeviceLabel = new Label (String::empty,
  58057. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58058. : TRANS ("device:"));
  58059. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58060. if (setup.maxNumOutputChannels > 0)
  58061. {
  58062. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58063. testButton->addButtonListener (this);
  58064. }
  58065. }
  58066. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58067. }
  58068. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58069. {
  58070. if (inputDeviceDropDown == 0)
  58071. {
  58072. inputDeviceDropDown = new ComboBox (String::empty);
  58073. inputDeviceDropDown->addListener (this);
  58074. addAndMakeVisible (inputDeviceDropDown);
  58075. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58076. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58077. addAndMakeVisible (inputLevelMeter
  58078. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58079. }
  58080. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58081. }
  58082. updateControlPanelButton();
  58083. showCorrectDeviceName (inputDeviceDropDown, true);
  58084. showCorrectDeviceName (outputDeviceDropDown, false);
  58085. if (currentDevice != 0)
  58086. {
  58087. if (setup.maxNumOutputChannels > 0
  58088. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58089. {
  58090. if (outputChanList == 0)
  58091. {
  58092. addAndMakeVisible (outputChanList
  58093. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58094. TRANS ("(no audio output channels found)")));
  58095. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58096. outputChanLabel->attachToComponent (outputChanList, true);
  58097. }
  58098. outputChanList->refresh();
  58099. }
  58100. else
  58101. {
  58102. deleteAndZero (outputChanLabel);
  58103. deleteAndZero (outputChanList);
  58104. }
  58105. if (setup.maxNumInputChannels > 0
  58106. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58107. {
  58108. if (inputChanList == 0)
  58109. {
  58110. addAndMakeVisible (inputChanList
  58111. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58112. TRANS ("(no audio input channels found)")));
  58113. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58114. inputChanLabel->attachToComponent (inputChanList, true);
  58115. }
  58116. inputChanList->refresh();
  58117. }
  58118. else
  58119. {
  58120. deleteAndZero (inputChanLabel);
  58121. deleteAndZero (inputChanList);
  58122. }
  58123. // sample rate..
  58124. {
  58125. if (sampleRateDropDown == 0)
  58126. {
  58127. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58128. sampleRateDropDown->addListener (this);
  58129. delete sampleRateLabel;
  58130. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58131. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58132. }
  58133. else
  58134. {
  58135. sampleRateDropDown->clear();
  58136. sampleRateDropDown->removeListener (this);
  58137. }
  58138. const int numRates = currentDevice->getNumSampleRates();
  58139. for (int i = 0; i < numRates; ++i)
  58140. {
  58141. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58142. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58143. }
  58144. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58145. sampleRateDropDown->addListener (this);
  58146. }
  58147. // buffer size
  58148. {
  58149. if (bufferSizeDropDown == 0)
  58150. {
  58151. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58152. bufferSizeDropDown->addListener (this);
  58153. delete bufferSizeLabel;
  58154. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58155. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58156. }
  58157. else
  58158. {
  58159. bufferSizeDropDown->clear();
  58160. }
  58161. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58162. double currentRate = currentDevice->getCurrentSampleRate();
  58163. if (currentRate == 0)
  58164. currentRate = 48000.0;
  58165. for (int i = 0; i < numBufferSizes; ++i)
  58166. {
  58167. const int bs = currentDevice->getBufferSizeSamples (i);
  58168. bufferSizeDropDown->addItem (String (bs)
  58169. + " samples ("
  58170. + String (bs * 1000.0 / currentRate, 1)
  58171. + " ms)",
  58172. bs);
  58173. }
  58174. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58175. }
  58176. }
  58177. else
  58178. {
  58179. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58180. deleteAndZero (sampleRateLabel);
  58181. deleteAndZero (bufferSizeLabel);
  58182. deleteAndZero (sampleRateDropDown);
  58183. deleteAndZero (bufferSizeDropDown);
  58184. if (outputDeviceDropDown != 0)
  58185. outputDeviceDropDown->setSelectedId (-1, true);
  58186. if (inputDeviceDropDown != 0)
  58187. inputDeviceDropDown->setSelectedId (-1, true);
  58188. }
  58189. resized();
  58190. setSize (getWidth(), getLowestY() + 4);
  58191. }
  58192. private:
  58193. AudioIODeviceType* const type;
  58194. const AudioIODeviceType::DeviceSetupDetails setup;
  58195. ComboBox* outputDeviceDropDown;
  58196. ComboBox* inputDeviceDropDown;
  58197. ComboBox* sampleRateDropDown;
  58198. ComboBox* bufferSizeDropDown;
  58199. Label* outputDeviceLabel;
  58200. Label* inputDeviceLabel;
  58201. Label* sampleRateLabel;
  58202. Label* bufferSizeLabel;
  58203. Label* inputChanLabel;
  58204. Label* outputChanLabel;
  58205. TextButton* testButton;
  58206. Component* inputLevelMeter;
  58207. TextButton* showUIButton;
  58208. TextButton* showAdvancedSettingsButton;
  58209. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58210. {
  58211. if (box != 0)
  58212. {
  58213. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58214. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58215. box->setSelectedId (index + 1, true);
  58216. if (testButton != 0 && ! isInput)
  58217. testButton->setEnabled (index >= 0);
  58218. }
  58219. }
  58220. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58221. {
  58222. const StringArray devs (type->getDeviceNames (isInputs));
  58223. combo.clear (true);
  58224. for (int i = 0; i < devs.size(); ++i)
  58225. combo.addItem (devs[i], i + 1);
  58226. combo.addItem (TRANS("<< none >>"), -1);
  58227. combo.setSelectedId (-1, true);
  58228. }
  58229. int getLowestY() const
  58230. {
  58231. int y = 0;
  58232. for (int i = getNumChildComponents(); --i >= 0;)
  58233. y = jmax (y, getChildComponent (i)->getBottom());
  58234. return y;
  58235. }
  58236. public:
  58237. class ChannelSelectorListBox : public ListBox,
  58238. public ListBoxModel
  58239. {
  58240. public:
  58241. enum BoxType
  58242. {
  58243. audioInputType,
  58244. audioOutputType
  58245. };
  58246. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58247. const BoxType type_,
  58248. const String& noItemsMessage_)
  58249. : ListBox (String::empty, 0),
  58250. setup (setup_),
  58251. type (type_),
  58252. noItemsMessage (noItemsMessage_)
  58253. {
  58254. refresh();
  58255. setModel (this);
  58256. setOutlineThickness (1);
  58257. }
  58258. ~ChannelSelectorListBox()
  58259. {
  58260. }
  58261. void refresh()
  58262. {
  58263. items.clear();
  58264. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58265. if (currentDevice != 0)
  58266. {
  58267. if (type == audioInputType)
  58268. items = currentDevice->getInputChannelNames();
  58269. else if (type == audioOutputType)
  58270. items = currentDevice->getOutputChannelNames();
  58271. if (setup.useStereoPairs)
  58272. {
  58273. StringArray pairs;
  58274. for (int i = 0; i < items.size(); i += 2)
  58275. {
  58276. const String name (items[i]);
  58277. const String name2 (items[i + 1]);
  58278. String commonBit;
  58279. for (int j = 0; j < name.length(); ++j)
  58280. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58281. commonBit = name.substring (0, j);
  58282. // Make sure we only split the name at a space, because otherwise, things
  58283. // like "input 11" + "input 12" would become "input 11 + 2"
  58284. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58285. commonBit = commonBit.dropLastCharacters (1);
  58286. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58287. }
  58288. items = pairs;
  58289. }
  58290. }
  58291. updateContent();
  58292. repaint();
  58293. }
  58294. int getNumRows()
  58295. {
  58296. return items.size();
  58297. }
  58298. void paintListBoxItem (int row,
  58299. Graphics& g,
  58300. int width, int height,
  58301. bool rowIsSelected)
  58302. {
  58303. if (((unsigned int) row) < (unsigned int) items.size())
  58304. {
  58305. if (rowIsSelected)
  58306. g.fillAll (findColour (TextEditor::highlightColourId)
  58307. .withMultipliedAlpha (0.3f));
  58308. const String item (items [row]);
  58309. bool enabled = false;
  58310. AudioDeviceManager::AudioDeviceSetup config;
  58311. setup.manager->getAudioDeviceSetup (config);
  58312. if (setup.useStereoPairs)
  58313. {
  58314. if (type == audioInputType)
  58315. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58316. else if (type == audioOutputType)
  58317. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58318. }
  58319. else
  58320. {
  58321. if (type == audioInputType)
  58322. enabled = config.inputChannels [row];
  58323. else if (type == audioOutputType)
  58324. enabled = config.outputChannels [row];
  58325. }
  58326. const int x = getTickX();
  58327. const float tickW = height * 0.75f;
  58328. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58329. enabled, true, true, false);
  58330. g.setFont (height * 0.6f);
  58331. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58332. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58333. }
  58334. }
  58335. void listBoxItemClicked (int row, const MouseEvent& e)
  58336. {
  58337. selectRow (row);
  58338. if (e.x < getTickX())
  58339. flipEnablement (row);
  58340. }
  58341. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58342. {
  58343. flipEnablement (row);
  58344. }
  58345. void returnKeyPressed (int row)
  58346. {
  58347. flipEnablement (row);
  58348. }
  58349. void paint (Graphics& g)
  58350. {
  58351. ListBox::paint (g);
  58352. if (items.size() == 0)
  58353. {
  58354. g.setColour (Colours::grey);
  58355. g.setFont (13.0f);
  58356. g.drawText (noItemsMessage,
  58357. 0, 0, getWidth(), getHeight() / 2,
  58358. Justification::centred, true);
  58359. }
  58360. }
  58361. int getBestHeight (int maxHeight)
  58362. {
  58363. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58364. getNumRows())
  58365. + getOutlineThickness() * 2;
  58366. }
  58367. juce_UseDebuggingNewOperator
  58368. private:
  58369. const AudioIODeviceType::DeviceSetupDetails setup;
  58370. const BoxType type;
  58371. const String noItemsMessage;
  58372. StringArray items;
  58373. void flipEnablement (const int row)
  58374. {
  58375. jassert (type == audioInputType || type == audioOutputType);
  58376. if (((unsigned int) row) < (unsigned int) items.size())
  58377. {
  58378. AudioDeviceManager::AudioDeviceSetup config;
  58379. setup.manager->getAudioDeviceSetup (config);
  58380. if (setup.useStereoPairs)
  58381. {
  58382. BigInteger bits;
  58383. BigInteger& original = (type == audioInputType ? config.inputChannels
  58384. : config.outputChannels);
  58385. int i;
  58386. for (i = 0; i < 256; i += 2)
  58387. bits.setBit (i / 2, original [i] || original [i + 1]);
  58388. if (type == audioInputType)
  58389. {
  58390. config.useDefaultInputChannels = false;
  58391. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58392. }
  58393. else
  58394. {
  58395. config.useDefaultOutputChannels = false;
  58396. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58397. }
  58398. for (i = 0; i < 256; ++i)
  58399. original.setBit (i, bits [i / 2]);
  58400. }
  58401. else
  58402. {
  58403. if (type == audioInputType)
  58404. {
  58405. config.useDefaultInputChannels = false;
  58406. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58407. }
  58408. else
  58409. {
  58410. config.useDefaultOutputChannels = false;
  58411. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58412. }
  58413. }
  58414. String error (setup.manager->setAudioDeviceSetup (config, true));
  58415. if (! error.isEmpty())
  58416. {
  58417. //xxx
  58418. }
  58419. }
  58420. }
  58421. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58422. {
  58423. const int numActive = chans.countNumberOfSetBits();
  58424. if (chans [index])
  58425. {
  58426. if (numActive > minNumber)
  58427. chans.setBit (index, false);
  58428. }
  58429. else
  58430. {
  58431. if (numActive >= maxNumber)
  58432. {
  58433. const int firstActiveChan = chans.findNextSetBit();
  58434. chans.setBit (index > firstActiveChan
  58435. ? firstActiveChan : chans.getHighestBit(),
  58436. false);
  58437. }
  58438. chans.setBit (index, true);
  58439. }
  58440. }
  58441. int getTickX() const
  58442. {
  58443. return getRowHeight() + 5;
  58444. }
  58445. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58446. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58447. };
  58448. private:
  58449. ChannelSelectorListBox* inputChanList;
  58450. ChannelSelectorListBox* outputChanList;
  58451. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58452. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58453. };
  58454. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58455. const int minInputChannels_,
  58456. const int maxInputChannels_,
  58457. const int minOutputChannels_,
  58458. const int maxOutputChannels_,
  58459. const bool showMidiInputOptions,
  58460. const bool showMidiOutputSelector,
  58461. const bool showChannelsAsStereoPairs_,
  58462. const bool hideAdvancedOptionsWithButton_)
  58463. : deviceManager (deviceManager_),
  58464. deviceTypeDropDown (0),
  58465. deviceTypeDropDownLabel (0),
  58466. audioDeviceSettingsComp (0),
  58467. minOutputChannels (minOutputChannels_),
  58468. maxOutputChannels (maxOutputChannels_),
  58469. minInputChannels (minInputChannels_),
  58470. maxInputChannels (maxInputChannels_),
  58471. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58472. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58473. {
  58474. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58475. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58476. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58477. {
  58478. deviceTypeDropDown = new ComboBox (String::empty);
  58479. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58480. {
  58481. deviceTypeDropDown
  58482. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58483. i + 1);
  58484. }
  58485. addAndMakeVisible (deviceTypeDropDown);
  58486. deviceTypeDropDown->addListener (this);
  58487. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58488. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58489. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58490. }
  58491. if (showMidiInputOptions)
  58492. {
  58493. addAndMakeVisible (midiInputsList
  58494. = new MidiInputSelectorComponentListBox (deviceManager,
  58495. TRANS("(no midi inputs available)"),
  58496. 0, 0));
  58497. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58498. midiInputsLabel->setJustificationType (Justification::topRight);
  58499. midiInputsLabel->attachToComponent (midiInputsList, true);
  58500. }
  58501. else
  58502. {
  58503. midiInputsList = 0;
  58504. midiInputsLabel = 0;
  58505. }
  58506. if (showMidiOutputSelector)
  58507. {
  58508. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58509. midiOutputSelector->addListener (this);
  58510. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58511. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58512. }
  58513. else
  58514. {
  58515. midiOutputSelector = 0;
  58516. midiOutputLabel = 0;
  58517. }
  58518. deviceManager_.addChangeListener (this);
  58519. changeListenerCallback (0);
  58520. }
  58521. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58522. {
  58523. deviceManager.removeChangeListener (this);
  58524. deleteAllChildren();
  58525. }
  58526. void AudioDeviceSelectorComponent::resized()
  58527. {
  58528. const int lx = proportionOfWidth (0.35f);
  58529. const int w = proportionOfWidth (0.4f);
  58530. const int h = 24;
  58531. const int space = 6;
  58532. const int dh = h + space;
  58533. int y = 15;
  58534. if (deviceTypeDropDown != 0)
  58535. {
  58536. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58537. y += dh + space * 2;
  58538. }
  58539. if (audioDeviceSettingsComp != 0)
  58540. {
  58541. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58542. y += audioDeviceSettingsComp->getHeight() + space;
  58543. }
  58544. if (midiInputsList != 0)
  58545. {
  58546. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58547. midiInputsList->setBounds (lx, y, w, bh);
  58548. y += bh + space;
  58549. }
  58550. if (midiOutputSelector != 0)
  58551. midiOutputSelector->setBounds (lx, y, w, h);
  58552. }
  58553. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58554. {
  58555. if (child == audioDeviceSettingsComp)
  58556. resized();
  58557. }
  58558. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58559. {
  58560. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58561. if (device != 0 && device->hasControlPanel())
  58562. {
  58563. if (device->showControlPanel())
  58564. deviceManager.restartLastAudioDevice();
  58565. getTopLevelComponent()->toFront (true);
  58566. }
  58567. }
  58568. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58569. {
  58570. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58571. {
  58572. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58573. if (type != 0)
  58574. {
  58575. deleteAndZero (audioDeviceSettingsComp);
  58576. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58577. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58578. }
  58579. }
  58580. else if (comboBoxThatHasChanged == midiOutputSelector)
  58581. {
  58582. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58583. }
  58584. }
  58585. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58586. {
  58587. if (deviceTypeDropDown != 0)
  58588. {
  58589. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58590. }
  58591. if (audioDeviceSettingsComp == 0
  58592. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58593. {
  58594. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58595. deleteAndZero (audioDeviceSettingsComp);
  58596. AudioIODeviceType* const type
  58597. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58598. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58599. if (type != 0)
  58600. {
  58601. AudioIODeviceType::DeviceSetupDetails details;
  58602. details.manager = &deviceManager;
  58603. details.minNumInputChannels = minInputChannels;
  58604. details.maxNumInputChannels = maxInputChannels;
  58605. details.minNumOutputChannels = minOutputChannels;
  58606. details.maxNumOutputChannels = maxOutputChannels;
  58607. details.useStereoPairs = showChannelsAsStereoPairs;
  58608. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58609. if (audioDeviceSettingsComp != 0)
  58610. {
  58611. addAndMakeVisible (audioDeviceSettingsComp);
  58612. audioDeviceSettingsComp->resized();
  58613. }
  58614. }
  58615. }
  58616. if (midiInputsList != 0)
  58617. {
  58618. midiInputsList->updateContent();
  58619. midiInputsList->repaint();
  58620. }
  58621. if (midiOutputSelector != 0)
  58622. {
  58623. midiOutputSelector->clear();
  58624. const StringArray midiOuts (MidiOutput::getDevices());
  58625. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58626. midiOutputSelector->addSeparator();
  58627. for (int i = 0; i < midiOuts.size(); ++i)
  58628. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58629. int current = -1;
  58630. if (deviceManager.getDefaultMidiOutput() != 0)
  58631. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58632. midiOutputSelector->setSelectedId (current, true);
  58633. }
  58634. resized();
  58635. }
  58636. END_JUCE_NAMESPACE
  58637. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58638. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58639. BEGIN_JUCE_NAMESPACE
  58640. BubbleComponent::BubbleComponent()
  58641. : side (0),
  58642. allowablePlacements (above | below | left | right),
  58643. arrowTipX (0.0f),
  58644. arrowTipY (0.0f)
  58645. {
  58646. setInterceptsMouseClicks (false, false);
  58647. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58648. setComponentEffect (&shadow);
  58649. }
  58650. BubbleComponent::~BubbleComponent()
  58651. {
  58652. }
  58653. void BubbleComponent::paint (Graphics& g)
  58654. {
  58655. int x = content.getX();
  58656. int y = content.getY();
  58657. int w = content.getWidth();
  58658. int h = content.getHeight();
  58659. int cw, ch;
  58660. getContentSize (cw, ch);
  58661. if (side == 3)
  58662. x += w - cw;
  58663. else if (side != 1)
  58664. x += (w - cw) / 2;
  58665. w = cw;
  58666. if (side == 2)
  58667. y += h - ch;
  58668. else if (side != 0)
  58669. y += (h - ch) / 2;
  58670. h = ch;
  58671. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58672. (float) x, (float) y,
  58673. (float) w, (float) h);
  58674. const int cx = x + (w - cw) / 2;
  58675. const int cy = y + (h - ch) / 2;
  58676. const int indent = 3;
  58677. g.setOrigin (cx + indent, cy + indent);
  58678. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58679. paintContent (g, cw - indent * 2, ch - indent * 2);
  58680. }
  58681. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58682. {
  58683. allowablePlacements = newPlacement;
  58684. }
  58685. void BubbleComponent::setPosition (Component* componentToPointTo)
  58686. {
  58687. jassert (componentToPointTo->isValidComponent());
  58688. Point<int> pos;
  58689. if (getParentComponent() != 0)
  58690. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58691. else
  58692. pos = componentToPointTo->relativePositionToGlobal (pos);
  58693. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58694. }
  58695. void BubbleComponent::setPosition (const int arrowTipX_,
  58696. const int arrowTipY_)
  58697. {
  58698. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58699. }
  58700. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58701. {
  58702. Rectangle<int> availableSpace;
  58703. if (getParentComponent() != 0)
  58704. {
  58705. availableSpace.setSize (getParentComponent()->getWidth(),
  58706. getParentComponent()->getHeight());
  58707. }
  58708. else
  58709. {
  58710. availableSpace = getParentMonitorArea();
  58711. }
  58712. int x = 0;
  58713. int y = 0;
  58714. int w = 150;
  58715. int h = 30;
  58716. getContentSize (w, h);
  58717. w += 30;
  58718. h += 30;
  58719. const float edgeIndent = 2.0f;
  58720. const int arrowLength = jmin (10, h / 3, w / 3);
  58721. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58722. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58723. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58724. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58725. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58726. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58727. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58728. {
  58729. spaceLeft = spaceRight = 0;
  58730. }
  58731. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58732. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58733. {
  58734. spaceAbove = spaceBelow = 0;
  58735. }
  58736. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58737. {
  58738. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58739. arrowTipX = w * 0.5f;
  58740. content.setSize (w, h - arrowLength);
  58741. if (spaceAbove >= spaceBelow)
  58742. {
  58743. // above
  58744. y = rectangleToPointTo.getY() - h;
  58745. content.setPosition (0, 0);
  58746. arrowTipY = h - edgeIndent;
  58747. side = 2;
  58748. }
  58749. else
  58750. {
  58751. // below
  58752. y = rectangleToPointTo.getBottom();
  58753. content.setPosition (0, arrowLength);
  58754. arrowTipY = edgeIndent;
  58755. side = 0;
  58756. }
  58757. }
  58758. else
  58759. {
  58760. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58761. arrowTipY = h * 0.5f;
  58762. content.setSize (w - arrowLength, h);
  58763. if (spaceLeft > spaceRight)
  58764. {
  58765. // on the left
  58766. x = rectangleToPointTo.getX() - w;
  58767. content.setPosition (0, 0);
  58768. arrowTipX = w - edgeIndent;
  58769. side = 3;
  58770. }
  58771. else
  58772. {
  58773. // on the right
  58774. x = rectangleToPointTo.getRight();
  58775. content.setPosition (arrowLength, 0);
  58776. arrowTipX = edgeIndent;
  58777. side = 1;
  58778. }
  58779. }
  58780. setBounds (x, y, w, h);
  58781. }
  58782. END_JUCE_NAMESPACE
  58783. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  58784. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  58785. BEGIN_JUCE_NAMESPACE
  58786. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  58787. : fadeOutLength (fadeOutLengthMs),
  58788. deleteAfterUse (false)
  58789. {
  58790. }
  58791. BubbleMessageComponent::~BubbleMessageComponent()
  58792. {
  58793. fadeOutComponent (fadeOutLength);
  58794. }
  58795. void BubbleMessageComponent::showAt (int x, int y,
  58796. const String& text,
  58797. const int numMillisecondsBeforeRemoving,
  58798. const bool removeWhenMouseClicked,
  58799. const bool deleteSelfAfterUse)
  58800. {
  58801. textLayout.clear();
  58802. textLayout.setText (text, Font (14.0f));
  58803. textLayout.layout (256, Justification::centredLeft, true);
  58804. setPosition (x, y);
  58805. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58806. }
  58807. void BubbleMessageComponent::showAt (Component* const component,
  58808. const String& text,
  58809. const int numMillisecondsBeforeRemoving,
  58810. const bool removeWhenMouseClicked,
  58811. const bool deleteSelfAfterUse)
  58812. {
  58813. textLayout.clear();
  58814. textLayout.setText (text, Font (14.0f));
  58815. textLayout.layout (256, Justification::centredLeft, true);
  58816. setPosition (component);
  58817. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58818. }
  58819. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  58820. const bool removeWhenMouseClicked,
  58821. const bool deleteSelfAfterUse)
  58822. {
  58823. setVisible (true);
  58824. deleteAfterUse = deleteSelfAfterUse;
  58825. if (numMillisecondsBeforeRemoving > 0)
  58826. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  58827. else
  58828. expiryTime = 0;
  58829. startTimer (77);
  58830. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  58831. if (! (removeWhenMouseClicked && isShowing()))
  58832. mouseClickCounter += 0xfffff;
  58833. repaint();
  58834. }
  58835. void BubbleMessageComponent::getContentSize (int& w, int& h)
  58836. {
  58837. w = textLayout.getWidth() + 16;
  58838. h = textLayout.getHeight() + 16;
  58839. }
  58840. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  58841. {
  58842. g.setColour (findColour (TooltipWindow::textColourId));
  58843. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  58844. }
  58845. void BubbleMessageComponent::timerCallback()
  58846. {
  58847. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  58848. {
  58849. stopTimer();
  58850. setVisible (false);
  58851. if (deleteAfterUse)
  58852. delete this;
  58853. }
  58854. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  58855. {
  58856. stopTimer();
  58857. fadeOutComponent (fadeOutLength);
  58858. if (deleteAfterUse)
  58859. delete this;
  58860. }
  58861. }
  58862. END_JUCE_NAMESPACE
  58863. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  58864. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  58865. BEGIN_JUCE_NAMESPACE
  58866. static const int swatchesPerRow = 8;
  58867. static const int swatchHeight = 22;
  58868. class ColourComponentSlider : public Slider
  58869. {
  58870. public:
  58871. ColourComponentSlider (const String& name)
  58872. : Slider (name)
  58873. {
  58874. setRange (0.0, 255.0, 1.0);
  58875. }
  58876. ~ColourComponentSlider()
  58877. {
  58878. }
  58879. const String getTextFromValue (double value)
  58880. {
  58881. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  58882. }
  58883. double getValueFromText (const String& text)
  58884. {
  58885. return (double) text.getHexValue32();
  58886. }
  58887. private:
  58888. ColourComponentSlider (const ColourComponentSlider&);
  58889. ColourComponentSlider& operator= (const ColourComponentSlider&);
  58890. };
  58891. class ColourSpaceMarker : public Component
  58892. {
  58893. public:
  58894. ColourSpaceMarker()
  58895. {
  58896. setInterceptsMouseClicks (false, false);
  58897. }
  58898. ~ColourSpaceMarker()
  58899. {
  58900. }
  58901. void paint (Graphics& g)
  58902. {
  58903. g.setColour (Colour::greyLevel (0.1f));
  58904. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  58905. g.setColour (Colour::greyLevel (0.9f));
  58906. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  58907. }
  58908. private:
  58909. ColourSpaceMarker (const ColourSpaceMarker&);
  58910. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  58911. };
  58912. class ColourSelector::ColourSpaceView : public Component
  58913. {
  58914. public:
  58915. ColourSpaceView (ColourSelector* owner_,
  58916. float& h_, float& s_, float& v_,
  58917. const int edgeSize)
  58918. : owner (owner_),
  58919. h (h_), s (s_), v (v_),
  58920. lastHue (0.0f),
  58921. edge (edgeSize)
  58922. {
  58923. addAndMakeVisible (marker = new ColourSpaceMarker());
  58924. setMouseCursor (MouseCursor::CrosshairCursor);
  58925. }
  58926. ~ColourSpaceView()
  58927. {
  58928. deleteAllChildren();
  58929. }
  58930. void paint (Graphics& g)
  58931. {
  58932. if (colours == 0)
  58933. {
  58934. const int width = getWidth() / 2;
  58935. const int height = getHeight() / 2;
  58936. colours = new Image (Image::RGB, width, height, false);
  58937. Image::BitmapData pixels (*colours, 0, 0, width, height, true);
  58938. for (int y = 0; y < height; ++y)
  58939. {
  58940. const float val = 1.0f - y / (float) height;
  58941. for (int x = 0; x < width; ++x)
  58942. {
  58943. const float sat = x / (float) width;
  58944. const Colour col (h, sat, val, 1.0f);
  58945. PixelRGB* const pix = (PixelRGB*) pixels.getPixelPointer (x, y);
  58946. pix->set (col.getPixelARGB());
  58947. }
  58948. }
  58949. }
  58950. g.setOpacity (1.0f);
  58951. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  58952. 0, 0, colours->getWidth(), colours->getHeight());
  58953. }
  58954. void mouseDown (const MouseEvent& e)
  58955. {
  58956. mouseDrag (e);
  58957. }
  58958. void mouseDrag (const MouseEvent& e)
  58959. {
  58960. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  58961. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  58962. owner->setSV (sat, val);
  58963. }
  58964. void updateIfNeeded()
  58965. {
  58966. if (lastHue != h)
  58967. {
  58968. lastHue = h;
  58969. colours = 0;
  58970. repaint();
  58971. }
  58972. updateMarker();
  58973. }
  58974. void resized()
  58975. {
  58976. colours = 0;
  58977. updateMarker();
  58978. }
  58979. private:
  58980. ColourSelector* const owner;
  58981. float& h;
  58982. float& s;
  58983. float& v;
  58984. float lastHue;
  58985. ColourSpaceMarker* marker;
  58986. const int edge;
  58987. ScopedPointer <Image> colours;
  58988. void updateMarker() const
  58989. {
  58990. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  58991. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  58992. edge * 2, edge * 2);
  58993. }
  58994. ColourSpaceView (const ColourSpaceView&);
  58995. ColourSpaceView& operator= (const ColourSpaceView&);
  58996. };
  58997. class HueSelectorMarker : public Component
  58998. {
  58999. public:
  59000. HueSelectorMarker()
  59001. {
  59002. setInterceptsMouseClicks (false, false);
  59003. }
  59004. ~HueSelectorMarker()
  59005. {
  59006. }
  59007. void paint (Graphics& g)
  59008. {
  59009. Path p;
  59010. p.addTriangle (1.0f, 1.0f,
  59011. getWidth() * 0.3f, getHeight() * 0.5f,
  59012. 1.0f, getHeight() - 1.0f);
  59013. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59014. getWidth() * 0.7f, getHeight() * 0.5f,
  59015. getWidth() - 1.0f, getHeight() - 1.0f);
  59016. g.setColour (Colours::white.withAlpha (0.75f));
  59017. g.fillPath (p);
  59018. g.setColour (Colours::black.withAlpha (0.75f));
  59019. g.strokePath (p, PathStrokeType (1.2f));
  59020. }
  59021. private:
  59022. HueSelectorMarker (const HueSelectorMarker&);
  59023. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59024. };
  59025. class ColourSelector::HueSelectorComp : public Component
  59026. {
  59027. public:
  59028. HueSelectorComp (ColourSelector* owner_,
  59029. float& h_, float& s_, float& v_,
  59030. const int edgeSize)
  59031. : owner (owner_),
  59032. h (h_), s (s_), v (v_),
  59033. lastHue (0.0f),
  59034. edge (edgeSize)
  59035. {
  59036. addAndMakeVisible (marker = new HueSelectorMarker());
  59037. }
  59038. ~HueSelectorComp()
  59039. {
  59040. deleteAllChildren();
  59041. }
  59042. void paint (Graphics& g)
  59043. {
  59044. const float yScale = 1.0f / (getHeight() - edge * 2);
  59045. const Rectangle<int> clip (g.getClipBounds());
  59046. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59047. {
  59048. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59049. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59050. }
  59051. }
  59052. void resized()
  59053. {
  59054. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59055. getWidth(), edge * 2);
  59056. }
  59057. void mouseDown (const MouseEvent& e)
  59058. {
  59059. mouseDrag (e);
  59060. }
  59061. void mouseDrag (const MouseEvent& e)
  59062. {
  59063. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59064. owner->setHue (hue);
  59065. }
  59066. void updateIfNeeded()
  59067. {
  59068. resized();
  59069. }
  59070. private:
  59071. ColourSelector* const owner;
  59072. float& h;
  59073. float& s;
  59074. float& v;
  59075. float lastHue;
  59076. HueSelectorMarker* marker;
  59077. const int edge;
  59078. HueSelectorComp (const HueSelectorComp&);
  59079. HueSelectorComp& operator= (const HueSelectorComp&);
  59080. };
  59081. class ColourSelector::SwatchComponent : public Component
  59082. {
  59083. public:
  59084. SwatchComponent (ColourSelector* owner_, int index_)
  59085. : owner (owner_),
  59086. index (index_)
  59087. {
  59088. }
  59089. ~SwatchComponent()
  59090. {
  59091. }
  59092. void paint (Graphics& g)
  59093. {
  59094. const Colour colour (owner->getSwatchColour (index));
  59095. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59096. 6, 6,
  59097. Colour (0xffdddddd).overlaidWith (colour),
  59098. Colour (0xffffffff).overlaidWith (colour));
  59099. }
  59100. void mouseDown (const MouseEvent&)
  59101. {
  59102. PopupMenu m;
  59103. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59104. m.addSeparator();
  59105. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59106. const int r = m.showAt (this);
  59107. if (r == 1)
  59108. {
  59109. owner->setCurrentColour (owner->getSwatchColour (index));
  59110. }
  59111. else if (r == 2)
  59112. {
  59113. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59114. {
  59115. owner->setSwatchColour (index, owner->getCurrentColour());
  59116. repaint();
  59117. }
  59118. }
  59119. }
  59120. private:
  59121. ColourSelector* const owner;
  59122. const int index;
  59123. SwatchComponent (const SwatchComponent&);
  59124. SwatchComponent& operator= (const SwatchComponent&);
  59125. };
  59126. ColourSelector::ColourSelector (const int flags_,
  59127. const int edgeGap_,
  59128. const int gapAroundColourSpaceComponent)
  59129. : colour (Colours::white),
  59130. flags (flags_),
  59131. topSpace (0),
  59132. edgeGap (edgeGap_)
  59133. {
  59134. // not much point having a selector with no components in it!
  59135. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59136. updateHSV();
  59137. if ((flags & showSliders) != 0)
  59138. {
  59139. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59140. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59141. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59142. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59143. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59144. for (int i = 4; --i >= 0;)
  59145. sliders[i]->addListener (this);
  59146. }
  59147. else
  59148. {
  59149. zeromem (sliders, sizeof (sliders));
  59150. }
  59151. if ((flags & showColourspace) != 0)
  59152. {
  59153. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59154. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59155. }
  59156. else
  59157. {
  59158. colourSpace = 0;
  59159. hueSelector = 0;
  59160. }
  59161. update();
  59162. }
  59163. ColourSelector::~ColourSelector()
  59164. {
  59165. dispatchPendingMessages();
  59166. swatchComponents.clear();
  59167. deleteAllChildren();
  59168. }
  59169. const Colour ColourSelector::getCurrentColour() const
  59170. {
  59171. return ((flags & showAlphaChannel) != 0) ? colour
  59172. : colour.withAlpha ((uint8) 0xff);
  59173. }
  59174. void ColourSelector::setCurrentColour (const Colour& c)
  59175. {
  59176. if (c != colour)
  59177. {
  59178. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59179. updateHSV();
  59180. update();
  59181. }
  59182. }
  59183. void ColourSelector::setHue (float newH)
  59184. {
  59185. newH = jlimit (0.0f, 1.0f, newH);
  59186. if (h != newH)
  59187. {
  59188. h = newH;
  59189. colour = Colour (h, s, v, colour.getFloatAlpha());
  59190. update();
  59191. }
  59192. }
  59193. void ColourSelector::setSV (float newS, float newV)
  59194. {
  59195. newS = jlimit (0.0f, 1.0f, newS);
  59196. newV = jlimit (0.0f, 1.0f, newV);
  59197. if (s != newS || v != newV)
  59198. {
  59199. s = newS;
  59200. v = newV;
  59201. colour = Colour (h, s, v, colour.getFloatAlpha());
  59202. update();
  59203. }
  59204. }
  59205. void ColourSelector::updateHSV()
  59206. {
  59207. colour.getHSB (h, s, v);
  59208. }
  59209. void ColourSelector::update()
  59210. {
  59211. if (sliders[0] != 0)
  59212. {
  59213. sliders[0]->setValue ((int) colour.getRed());
  59214. sliders[1]->setValue ((int) colour.getGreen());
  59215. sliders[2]->setValue ((int) colour.getBlue());
  59216. sliders[3]->setValue ((int) colour.getAlpha());
  59217. }
  59218. if (colourSpace != 0)
  59219. {
  59220. colourSpace->updateIfNeeded();
  59221. hueSelector->updateIfNeeded();
  59222. }
  59223. if ((flags & showColourAtTop) != 0)
  59224. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59225. sendChangeMessage (this);
  59226. }
  59227. void ColourSelector::paint (Graphics& g)
  59228. {
  59229. g.fillAll (findColour (backgroundColourId));
  59230. if ((flags & showColourAtTop) != 0)
  59231. {
  59232. const Colour currentColour (getCurrentColour());
  59233. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59234. 10, 10,
  59235. Colour (0xffdddddd).overlaidWith (currentColour),
  59236. Colour (0xffffffff).overlaidWith (currentColour));
  59237. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59238. g.setFont (14.0f, true);
  59239. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59240. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59241. Justification::centred, false);
  59242. }
  59243. if ((flags & showSliders) != 0)
  59244. {
  59245. g.setColour (findColour (labelTextColourId));
  59246. g.setFont (11.0f);
  59247. for (int i = 4; --i >= 0;)
  59248. {
  59249. if (sliders[i]->isVisible())
  59250. g.drawText (sliders[i]->getName() + ":",
  59251. 0, sliders[i]->getY(),
  59252. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59253. Justification::centredRight, false);
  59254. }
  59255. }
  59256. }
  59257. void ColourSelector::resized()
  59258. {
  59259. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59260. const int numSwatches = getNumSwatches();
  59261. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59262. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59263. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59264. int y = topSpace;
  59265. if ((flags & showColourspace) != 0)
  59266. {
  59267. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59268. colourSpace->setBounds (edgeGap, y,
  59269. getWidth() - hueWidth - edgeGap - 4,
  59270. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59271. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59272. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59273. colourSpace->getHeight());
  59274. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59275. }
  59276. if ((flags & showSliders) != 0)
  59277. {
  59278. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59279. for (int i = 0; i < numSliders; ++i)
  59280. {
  59281. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59282. proportionOfWidth (0.72f), sliderHeight - 2);
  59283. y += sliderHeight;
  59284. }
  59285. }
  59286. if (numSwatches > 0)
  59287. {
  59288. const int startX = 8;
  59289. const int xGap = 4;
  59290. const int yGap = 4;
  59291. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59292. y += edgeGap;
  59293. if (swatchComponents.size() != numSwatches)
  59294. {
  59295. swatchComponents.clear();
  59296. for (int i = 0; i < numSwatches; ++i)
  59297. {
  59298. SwatchComponent* const sc = new SwatchComponent (this, i);
  59299. swatchComponents.add (sc);
  59300. addAndMakeVisible (sc);
  59301. }
  59302. }
  59303. int x = startX;
  59304. for (int i = 0; i < swatchComponents.size(); ++i)
  59305. {
  59306. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59307. sc->setBounds (x + xGap / 2,
  59308. y + yGap / 2,
  59309. swatchWidth - xGap,
  59310. swatchHeight - yGap);
  59311. if (((i + 1) % swatchesPerRow) == 0)
  59312. {
  59313. x = startX;
  59314. y += swatchHeight;
  59315. }
  59316. else
  59317. {
  59318. x += swatchWidth;
  59319. }
  59320. }
  59321. }
  59322. }
  59323. void ColourSelector::sliderValueChanged (Slider*)
  59324. {
  59325. if (sliders[0] != 0)
  59326. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59327. (uint8) sliders[1]->getValue(),
  59328. (uint8) sliders[2]->getValue(),
  59329. (uint8) sliders[3]->getValue()));
  59330. }
  59331. int ColourSelector::getNumSwatches() const
  59332. {
  59333. return 0;
  59334. }
  59335. const Colour ColourSelector::getSwatchColour (const int) const
  59336. {
  59337. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59338. return Colours::black;
  59339. }
  59340. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59341. {
  59342. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59343. }
  59344. END_JUCE_NAMESPACE
  59345. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59346. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59347. BEGIN_JUCE_NAMESPACE
  59348. class ShadowWindow : public Component
  59349. {
  59350. Component* owner;
  59351. Image** shadowImageSections;
  59352. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59353. public:
  59354. ShadowWindow (Component* const owner_,
  59355. const int type_,
  59356. Image** const shadowImageSections_)
  59357. : owner (owner_),
  59358. shadowImageSections (shadowImageSections_),
  59359. type (type_)
  59360. {
  59361. setInterceptsMouseClicks (false, false);
  59362. if (owner_->isOnDesktop())
  59363. {
  59364. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59365. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59366. | ComponentPeer::windowIsTemporary
  59367. | ComponentPeer::windowIgnoresKeyPresses);
  59368. }
  59369. else if (owner_->getParentComponent() != 0)
  59370. {
  59371. owner_->getParentComponent()->addChildComponent (this);
  59372. }
  59373. }
  59374. ~ShadowWindow()
  59375. {
  59376. }
  59377. void paint (Graphics& g)
  59378. {
  59379. Image* const topLeft = shadowImageSections [type * 3];
  59380. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  59381. Image* const filler = shadowImageSections [type * 3 + 2];
  59382. g.setOpacity (1.0f);
  59383. if (type < 2)
  59384. {
  59385. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  59386. g.drawImage (topLeft,
  59387. 0, 0, topLeft->getWidth(), imH,
  59388. 0, 0, topLeft->getWidth(), imH);
  59389. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  59390. g.drawImage (bottomRight,
  59391. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  59392. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  59393. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59394. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  59395. }
  59396. else
  59397. {
  59398. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  59399. g.drawImage (topLeft,
  59400. 0, 0, imW, topLeft->getHeight(),
  59401. 0, 0, imW, topLeft->getHeight());
  59402. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  59403. g.drawImage (bottomRight,
  59404. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  59405. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  59406. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59407. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  59408. }
  59409. }
  59410. void resized()
  59411. {
  59412. repaint(); // (needed for correct repainting)
  59413. }
  59414. private:
  59415. ShadowWindow (const ShadowWindow&);
  59416. ShadowWindow& operator= (const ShadowWindow&);
  59417. };
  59418. DropShadower::DropShadower (const float alpha_,
  59419. const int xOffset_,
  59420. const int yOffset_,
  59421. const float blurRadius_)
  59422. : owner (0),
  59423. numShadows (0),
  59424. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59425. xOffset (xOffset_),
  59426. yOffset (yOffset_),
  59427. alpha (alpha_),
  59428. blurRadius (blurRadius_),
  59429. inDestructor (false),
  59430. reentrant (false)
  59431. {
  59432. }
  59433. DropShadower::~DropShadower()
  59434. {
  59435. if (owner != 0)
  59436. owner->removeComponentListener (this);
  59437. inDestructor = true;
  59438. deleteShadowWindows();
  59439. }
  59440. void DropShadower::deleteShadowWindows()
  59441. {
  59442. if (numShadows > 0)
  59443. {
  59444. int i;
  59445. for (i = numShadows; --i >= 0;)
  59446. delete shadowWindows[i];
  59447. for (i = 12; --i >= 0;)
  59448. delete shadowImageSections[i];
  59449. numShadows = 0;
  59450. }
  59451. }
  59452. void DropShadower::setOwner (Component* componentToFollow)
  59453. {
  59454. if (componentToFollow != owner)
  59455. {
  59456. if (owner != 0)
  59457. owner->removeComponentListener (this);
  59458. // (the component can't be null)
  59459. jassert (componentToFollow != 0);
  59460. owner = componentToFollow;
  59461. jassert (owner != 0);
  59462. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59463. owner->addComponentListener (this);
  59464. updateShadows();
  59465. }
  59466. }
  59467. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59468. {
  59469. updateShadows();
  59470. }
  59471. void DropShadower::componentBroughtToFront (Component&)
  59472. {
  59473. bringShadowWindowsToFront();
  59474. }
  59475. void DropShadower::componentChildrenChanged (Component&)
  59476. {
  59477. }
  59478. void DropShadower::componentParentHierarchyChanged (Component&)
  59479. {
  59480. deleteShadowWindows();
  59481. updateShadows();
  59482. }
  59483. void DropShadower::componentVisibilityChanged (Component&)
  59484. {
  59485. updateShadows();
  59486. }
  59487. void DropShadower::updateShadows()
  59488. {
  59489. if (reentrant || inDestructor || (owner == 0))
  59490. return;
  59491. reentrant = true;
  59492. ComponentPeer* const nw = owner->getPeer();
  59493. const bool isOwnerVisible = owner->isVisible()
  59494. && (nw == 0 || ! nw->isMinimised());
  59495. const bool createShadowWindows = numShadows == 0
  59496. && owner->getWidth() > 0
  59497. && owner->getHeight() > 0
  59498. && isOwnerVisible
  59499. && (Desktop::canUseSemiTransparentWindows()
  59500. || owner->getParentComponent() != 0);
  59501. if (createShadowWindows)
  59502. {
  59503. // keep a cached version of the image to save doing the gaussian too often
  59504. String imageId;
  59505. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59506. const int hash = imageId.hashCode();
  59507. Image* bigIm = ImageCache::getFromHashCode (hash);
  59508. if (bigIm == 0)
  59509. {
  59510. bigIm = Image::createNativeImage (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  59511. Graphics bigG (*bigIm);
  59512. bigG.setColour (Colours::black.withAlpha (alpha));
  59513. bigG.fillRect (shadowEdge + xOffset,
  59514. shadowEdge + yOffset,
  59515. bigIm->getWidth() - (shadowEdge * 2),
  59516. bigIm->getHeight() - (shadowEdge * 2));
  59517. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59518. blurKernel.createGaussianBlur (blurRadius);
  59519. blurKernel.applyToImage (*bigIm, 0,
  59520. Rectangle<int> (xOffset, yOffset,
  59521. bigIm->getWidth(), bigIm->getHeight()));
  59522. ImageCache::addImageToCache (bigIm, hash);
  59523. }
  59524. const int iw = bigIm->getWidth();
  59525. const int ih = bigIm->getHeight();
  59526. const int shadowEdge2 = shadowEdge * 2;
  59527. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59528. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59529. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59530. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59531. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59532. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59533. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59534. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59535. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59536. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59537. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59538. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59539. ImageCache::release (bigIm);
  59540. for (int i = 0; i < 4; ++i)
  59541. {
  59542. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59543. ++numShadows;
  59544. }
  59545. }
  59546. if (numShadows > 0)
  59547. {
  59548. for (int i = numShadows; --i >= 0;)
  59549. {
  59550. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59551. shadowWindows[i]->setVisible (isOwnerVisible);
  59552. }
  59553. const int x = owner->getX();
  59554. const int y = owner->getY() - shadowEdge;
  59555. const int w = owner->getWidth();
  59556. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59557. shadowWindows[0]->setBounds (x - shadowEdge,
  59558. y,
  59559. shadowEdge,
  59560. h);
  59561. shadowWindows[1]->setBounds (x + w,
  59562. y,
  59563. shadowEdge,
  59564. h);
  59565. shadowWindows[2]->setBounds (x,
  59566. y,
  59567. w,
  59568. shadowEdge);
  59569. shadowWindows[3]->setBounds (x,
  59570. owner->getBottom(),
  59571. w,
  59572. shadowEdge);
  59573. }
  59574. reentrant = false;
  59575. if (createShadowWindows)
  59576. bringShadowWindowsToFront();
  59577. }
  59578. void DropShadower::setShadowImage (Image* const src, const int num, const int w, const int h,
  59579. const int sx, const int sy)
  59580. {
  59581. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  59582. Graphics g (*shadowImageSections[num]);
  59583. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59584. }
  59585. void DropShadower::bringShadowWindowsToFront()
  59586. {
  59587. if (! (inDestructor || reentrant))
  59588. {
  59589. updateShadows();
  59590. reentrant = true;
  59591. for (int i = numShadows; --i >= 0;)
  59592. shadowWindows[i]->toBehind (owner);
  59593. reentrant = false;
  59594. }
  59595. }
  59596. END_JUCE_NAMESPACE
  59597. /*** End of inlined file: juce_DropShadower.cpp ***/
  59598. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59599. BEGIN_JUCE_NAMESPACE
  59600. class MagnifyingPeer : public ComponentPeer
  59601. {
  59602. public:
  59603. MagnifyingPeer (Component* const component_,
  59604. MagnifierComponent* const magnifierComp_)
  59605. : ComponentPeer (component_, 0),
  59606. magnifierComp (magnifierComp_)
  59607. {
  59608. }
  59609. ~MagnifyingPeer()
  59610. {
  59611. }
  59612. void* getNativeHandle() const { return 0; }
  59613. void setVisible (bool) {}
  59614. void setTitle (const String&) {}
  59615. void setPosition (int, int) {}
  59616. void setSize (int, int) {}
  59617. void setBounds (int, int, int, int, bool) {}
  59618. void setMinimised (bool) {}
  59619. bool isMinimised() const { return false; }
  59620. void setFullScreen (bool) {}
  59621. bool isFullScreen() const { return false; }
  59622. const BorderSize getFrameSize() const { return BorderSize (0); }
  59623. bool setAlwaysOnTop (bool) { return true; }
  59624. void toFront (bool) {}
  59625. void toBehind (ComponentPeer*) {}
  59626. void setIcon (const Image&) {}
  59627. bool isFocused() const
  59628. {
  59629. return magnifierComp->hasKeyboardFocus (true);
  59630. }
  59631. void grabFocus()
  59632. {
  59633. ComponentPeer* peer = magnifierComp->getPeer();
  59634. if (peer != 0)
  59635. peer->grabFocus();
  59636. }
  59637. void textInputRequired (const Point<int>& position)
  59638. {
  59639. ComponentPeer* peer = magnifierComp->getPeer();
  59640. if (peer != 0)
  59641. peer->textInputRequired (position);
  59642. }
  59643. const Rectangle<int> getBounds() const
  59644. {
  59645. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59646. component->getWidth(), component->getHeight());
  59647. }
  59648. const Point<int> getScreenPosition() const
  59649. {
  59650. return magnifierComp->getScreenPosition();
  59651. }
  59652. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59653. {
  59654. const double zoom = magnifierComp->getScaleFactor();
  59655. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59656. roundToInt (relativePosition.getY() * zoom)));
  59657. }
  59658. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59659. {
  59660. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59661. const double zoom = magnifierComp->getScaleFactor();
  59662. return Point<int> (roundToInt (p.getX() / zoom),
  59663. roundToInt (p.getY() / zoom));
  59664. }
  59665. bool contains (const Point<int>& position, bool) const
  59666. {
  59667. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59668. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59669. }
  59670. void repaint (int x, int y, int w, int h)
  59671. {
  59672. const double zoom = magnifierComp->getScaleFactor();
  59673. magnifierComp->repaint ((int) (x * zoom),
  59674. (int) (y * zoom),
  59675. roundToInt (w * zoom) + 1,
  59676. roundToInt (h * zoom) + 1);
  59677. }
  59678. void performAnyPendingRepaintsNow()
  59679. {
  59680. }
  59681. juce_UseDebuggingNewOperator
  59682. private:
  59683. MagnifierComponent* const magnifierComp;
  59684. MagnifyingPeer (const MagnifyingPeer&);
  59685. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59686. };
  59687. class PeerHolderComp : public Component
  59688. {
  59689. public:
  59690. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59691. : magnifierComp (magnifierComp_)
  59692. {
  59693. setVisible (true);
  59694. }
  59695. ~PeerHolderComp()
  59696. {
  59697. }
  59698. ComponentPeer* createNewPeer (int, void*)
  59699. {
  59700. return new MagnifyingPeer (this, magnifierComp);
  59701. }
  59702. void childBoundsChanged (Component* c)
  59703. {
  59704. if (c != 0)
  59705. {
  59706. setSize (c->getWidth(), c->getHeight());
  59707. magnifierComp->childBoundsChanged (this);
  59708. }
  59709. }
  59710. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59711. {
  59712. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59713. Component* const p = magnifierComp->getParentComponent();
  59714. if (p != 0)
  59715. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59716. }
  59717. private:
  59718. MagnifierComponent* const magnifierComp;
  59719. PeerHolderComp (const PeerHolderComp&);
  59720. PeerHolderComp& operator= (const PeerHolderComp&);
  59721. };
  59722. MagnifierComponent::MagnifierComponent (Component* const content_,
  59723. const bool deleteContentCompWhenNoLongerNeeded)
  59724. : content (content_),
  59725. scaleFactor (0.0),
  59726. peer (0),
  59727. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59728. quality (Graphics::lowResamplingQuality),
  59729. mouseSource (0, true)
  59730. {
  59731. holderComp = new PeerHolderComp (this);
  59732. setScaleFactor (1.0);
  59733. }
  59734. MagnifierComponent::~MagnifierComponent()
  59735. {
  59736. delete holderComp;
  59737. if (deleteContent)
  59738. delete content;
  59739. }
  59740. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59741. {
  59742. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59743. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59744. if (scaleFactor != newScaleFactor)
  59745. {
  59746. scaleFactor = newScaleFactor;
  59747. if (scaleFactor == 1.0)
  59748. {
  59749. holderComp->removeFromDesktop();
  59750. peer = 0;
  59751. addChildComponent (content);
  59752. childBoundsChanged (content);
  59753. }
  59754. else
  59755. {
  59756. holderComp->addAndMakeVisible (content);
  59757. holderComp->childBoundsChanged (content);
  59758. childBoundsChanged (holderComp);
  59759. holderComp->addToDesktop (0);
  59760. peer = holderComp->getPeer();
  59761. }
  59762. repaint();
  59763. }
  59764. }
  59765. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59766. {
  59767. quality = newQuality;
  59768. }
  59769. void MagnifierComponent::paint (Graphics& g)
  59770. {
  59771. const int w = holderComp->getWidth();
  59772. const int h = holderComp->getHeight();
  59773. if (w == 0 || h == 0)
  59774. return;
  59775. const Rectangle<int> r (g.getClipBounds());
  59776. const int srcX = (int) (r.getX() / scaleFactor);
  59777. const int srcY = (int) (r.getY() / scaleFactor);
  59778. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59779. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  59780. if (scaleFactor >= 1.0)
  59781. {
  59782. ++srcW;
  59783. ++srcH;
  59784. }
  59785. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  59786. temp.clear (srcX, srcY, srcW, srcH);
  59787. {
  59788. Graphics g2 (temp);
  59789. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  59790. holderComp->paintEntireComponent (g2);
  59791. }
  59792. g.setImageResamplingQuality (quality);
  59793. g.drawImageTransformed (&temp, temp.getBounds(),
  59794. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  59795. false);
  59796. }
  59797. void MagnifierComponent::childBoundsChanged (Component* c)
  59798. {
  59799. if (c != 0)
  59800. setSize (roundToInt (c->getWidth() * scaleFactor),
  59801. roundToInt (c->getHeight() * scaleFactor));
  59802. }
  59803. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  59804. {
  59805. if (peer != 0)
  59806. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  59807. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  59808. }
  59809. void MagnifierComponent::mouseDown (const MouseEvent& e)
  59810. {
  59811. passOnMouseEventToPeer (e);
  59812. }
  59813. void MagnifierComponent::mouseUp (const MouseEvent& e)
  59814. {
  59815. passOnMouseEventToPeer (e);
  59816. }
  59817. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  59818. {
  59819. passOnMouseEventToPeer (e);
  59820. }
  59821. void MagnifierComponent::mouseMove (const MouseEvent& e)
  59822. {
  59823. passOnMouseEventToPeer (e);
  59824. }
  59825. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  59826. {
  59827. passOnMouseEventToPeer (e);
  59828. }
  59829. void MagnifierComponent::mouseExit (const MouseEvent& e)
  59830. {
  59831. passOnMouseEventToPeer (e);
  59832. }
  59833. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59834. {
  59835. if (peer != 0)
  59836. peer->handleMouseWheel (e.source.getIndex(),
  59837. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  59838. ix * 256.0f, iy * 256.0f);
  59839. else
  59840. Component::mouseWheelMove (e, ix, iy);
  59841. }
  59842. int MagnifierComponent::scaleInt (const int n) const
  59843. {
  59844. return roundToInt (n / scaleFactor);
  59845. }
  59846. END_JUCE_NAMESPACE
  59847. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  59848. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  59849. BEGIN_JUCE_NAMESPACE
  59850. class MidiKeyboardUpDownButton : public Button
  59851. {
  59852. public:
  59853. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  59854. const int delta_)
  59855. : Button (String::empty),
  59856. owner (owner_),
  59857. delta (delta_)
  59858. {
  59859. setOpaque (true);
  59860. }
  59861. ~MidiKeyboardUpDownButton()
  59862. {
  59863. }
  59864. void clicked()
  59865. {
  59866. int note = owner->getLowestVisibleKey();
  59867. if (delta < 0)
  59868. note = (note - 1) / 12;
  59869. else
  59870. note = note / 12 + 1;
  59871. owner->setLowestVisibleKey (note * 12);
  59872. }
  59873. void paintButton (Graphics& g,
  59874. bool isMouseOverButton,
  59875. bool isButtonDown)
  59876. {
  59877. owner->drawUpDownButton (g, getWidth(), getHeight(),
  59878. isMouseOverButton, isButtonDown,
  59879. delta > 0);
  59880. }
  59881. private:
  59882. MidiKeyboardComponent* const owner;
  59883. const int delta;
  59884. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  59885. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  59886. };
  59887. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  59888. const Orientation orientation_)
  59889. : state (state_),
  59890. xOffset (0),
  59891. blackNoteLength (1),
  59892. keyWidth (16.0f),
  59893. orientation (orientation_),
  59894. midiChannel (1),
  59895. midiInChannelMask (0xffff),
  59896. velocity (1.0f),
  59897. noteUnderMouse (-1),
  59898. mouseDownNote (-1),
  59899. rangeStart (0),
  59900. rangeEnd (127),
  59901. firstKey (12 * 4),
  59902. canScroll (true),
  59903. mouseDragging (false),
  59904. useMousePositionForVelocity (true),
  59905. keyMappingOctave (6),
  59906. octaveNumForMiddleC (3)
  59907. {
  59908. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  59909. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  59910. // initialise with a default set of querty key-mappings..
  59911. const char* const keymap = "awsedftgyhujkolp;";
  59912. for (int i = String (keymap).length(); --i >= 0;)
  59913. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  59914. setOpaque (true);
  59915. setWantsKeyboardFocus (true);
  59916. state.addListener (this);
  59917. }
  59918. MidiKeyboardComponent::~MidiKeyboardComponent()
  59919. {
  59920. state.removeListener (this);
  59921. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  59922. deleteAllChildren();
  59923. }
  59924. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  59925. {
  59926. keyWidth = widthInPixels;
  59927. resized();
  59928. }
  59929. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  59930. {
  59931. if (orientation != newOrientation)
  59932. {
  59933. orientation = newOrientation;
  59934. resized();
  59935. }
  59936. }
  59937. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  59938. const int highestNote)
  59939. {
  59940. jassert (lowestNote >= 0 && lowestNote <= 127);
  59941. jassert (highestNote >= 0 && highestNote <= 127);
  59942. jassert (lowestNote <= highestNote);
  59943. if (rangeStart != lowestNote || rangeEnd != highestNote)
  59944. {
  59945. rangeStart = jlimit (0, 127, lowestNote);
  59946. rangeEnd = jlimit (0, 127, highestNote);
  59947. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  59948. resized();
  59949. }
  59950. }
  59951. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  59952. {
  59953. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  59954. if (noteNumber != firstKey)
  59955. {
  59956. firstKey = noteNumber;
  59957. sendChangeMessage (this);
  59958. resized();
  59959. }
  59960. }
  59961. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  59962. {
  59963. if (canScroll != canScroll_)
  59964. {
  59965. canScroll = canScroll_;
  59966. resized();
  59967. }
  59968. }
  59969. void MidiKeyboardComponent::colourChanged()
  59970. {
  59971. repaint();
  59972. }
  59973. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  59974. {
  59975. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  59976. if (midiChannel != midiChannelNumber)
  59977. {
  59978. resetAnyKeysInUse();
  59979. midiChannel = jlimit (1, 16, midiChannelNumber);
  59980. }
  59981. }
  59982. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  59983. {
  59984. midiInChannelMask = midiChannelMask;
  59985. triggerAsyncUpdate();
  59986. }
  59987. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  59988. {
  59989. velocity = jlimit (0.0f, 1.0f, velocity_);
  59990. useMousePositionForVelocity = useMousePositionForVelocity_;
  59991. }
  59992. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  59993. {
  59994. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  59995. static const float blackNoteWidth = 0.7f;
  59996. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  59997. 1.0f, 2 - blackNoteWidth * 0.4f,
  59998. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  59999. 4.0f, 5 - blackNoteWidth * 0.5f,
  60000. 5.0f, 6 - blackNoteWidth * 0.3f,
  60001. 6.0f };
  60002. static const float widths[] = { 1.0f, blackNoteWidth,
  60003. 1.0f, blackNoteWidth,
  60004. 1.0f, 1.0f, blackNoteWidth,
  60005. 1.0f, blackNoteWidth,
  60006. 1.0f, blackNoteWidth,
  60007. 1.0f };
  60008. const int octave = midiNoteNumber / 12;
  60009. const int note = midiNoteNumber % 12;
  60010. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60011. w = roundToInt (widths [note] * keyWidth_);
  60012. }
  60013. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60014. {
  60015. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60016. int rx, rw;
  60017. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60018. x -= xOffset + rx;
  60019. }
  60020. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60021. {
  60022. int x, y;
  60023. getKeyPos (midiNoteNumber, x, y);
  60024. return x;
  60025. }
  60026. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60027. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  60028. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60029. {
  60030. if (! reallyContains (pos.getX(), pos.getY(), false))
  60031. return -1;
  60032. Point<int> p (pos);
  60033. if (orientation != horizontalKeyboard)
  60034. {
  60035. p = Point<int> (p.getY(), p.getX());
  60036. if (orientation == verticalKeyboardFacingLeft)
  60037. p = Point<int> (p.getX(), getWidth() - p.getY());
  60038. else
  60039. p = Point<int> (getHeight() - p.getX(), p.getY());
  60040. }
  60041. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60042. }
  60043. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60044. {
  60045. if (pos.getY() < blackNoteLength)
  60046. {
  60047. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60048. {
  60049. for (int i = 0; i < 5; ++i)
  60050. {
  60051. const int note = octaveStart + blackNotes [i];
  60052. if (note >= rangeStart && note <= rangeEnd)
  60053. {
  60054. int kx, kw;
  60055. getKeyPos (note, kx, kw);
  60056. kx += xOffset;
  60057. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60058. {
  60059. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60060. return note;
  60061. }
  60062. }
  60063. }
  60064. }
  60065. }
  60066. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60067. {
  60068. for (int i = 0; i < 7; ++i)
  60069. {
  60070. const int note = octaveStart + whiteNotes [i];
  60071. if (note >= rangeStart && note <= rangeEnd)
  60072. {
  60073. int kx, kw;
  60074. getKeyPos (note, kx, kw);
  60075. kx += xOffset;
  60076. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60077. {
  60078. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60079. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60080. return note;
  60081. }
  60082. }
  60083. }
  60084. }
  60085. mousePositionVelocity = 0;
  60086. return -1;
  60087. }
  60088. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60089. {
  60090. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60091. {
  60092. int x, w;
  60093. getKeyPos (noteNum, x, w);
  60094. if (orientation == horizontalKeyboard)
  60095. repaint (x, 0, w, getHeight());
  60096. else if (orientation == verticalKeyboardFacingLeft)
  60097. repaint (0, x, getWidth(), w);
  60098. else if (orientation == verticalKeyboardFacingRight)
  60099. repaint (0, getHeight() - x - w, getWidth(), w);
  60100. }
  60101. }
  60102. void MidiKeyboardComponent::paint (Graphics& g)
  60103. {
  60104. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60105. const Colour lineColour (findColour (keySeparatorLineColourId));
  60106. const Colour textColour (findColour (textLabelColourId));
  60107. int x, w, octave;
  60108. for (octave = 0; octave < 128; octave += 12)
  60109. {
  60110. for (int white = 0; white < 7; ++white)
  60111. {
  60112. const int noteNum = octave + whiteNotes [white];
  60113. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60114. {
  60115. getKeyPos (noteNum, x, w);
  60116. if (orientation == horizontalKeyboard)
  60117. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60118. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60119. noteUnderMouse == noteNum,
  60120. lineColour, textColour);
  60121. else if (orientation == verticalKeyboardFacingLeft)
  60122. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60123. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60124. noteUnderMouse == noteNum,
  60125. lineColour, textColour);
  60126. else if (orientation == verticalKeyboardFacingRight)
  60127. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60128. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60129. noteUnderMouse == noteNum,
  60130. lineColour, textColour);
  60131. }
  60132. }
  60133. }
  60134. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60135. if (orientation == verticalKeyboardFacingLeft)
  60136. {
  60137. x1 = getWidth() - 1.0f;
  60138. x2 = getWidth() - 5.0f;
  60139. }
  60140. else if (orientation == verticalKeyboardFacingRight)
  60141. x2 = 5.0f;
  60142. else
  60143. y2 = 5.0f;
  60144. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60145. Colours::transparentBlack, x2, y2, false));
  60146. getKeyPos (rangeEnd, x, w);
  60147. x += w;
  60148. if (orientation == verticalKeyboardFacingLeft)
  60149. g.fillRect (getWidth() - 5, 0, 5, x);
  60150. else if (orientation == verticalKeyboardFacingRight)
  60151. g.fillRect (0, 0, 5, x);
  60152. else
  60153. g.fillRect (0, 0, x, 5);
  60154. g.setColour (lineColour);
  60155. if (orientation == verticalKeyboardFacingLeft)
  60156. g.fillRect (0, 0, 1, x);
  60157. else if (orientation == verticalKeyboardFacingRight)
  60158. g.fillRect (getWidth() - 1, 0, 1, x);
  60159. else
  60160. g.fillRect (0, getHeight() - 1, x, 1);
  60161. const Colour blackNoteColour (findColour (blackNoteColourId));
  60162. for (octave = 0; octave < 128; octave += 12)
  60163. {
  60164. for (int black = 0; black < 5; ++black)
  60165. {
  60166. const int noteNum = octave + blackNotes [black];
  60167. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60168. {
  60169. getKeyPos (noteNum, x, w);
  60170. if (orientation == horizontalKeyboard)
  60171. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60172. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60173. noteUnderMouse == noteNum,
  60174. blackNoteColour);
  60175. else if (orientation == verticalKeyboardFacingLeft)
  60176. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60177. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60178. noteUnderMouse == noteNum,
  60179. blackNoteColour);
  60180. else if (orientation == verticalKeyboardFacingRight)
  60181. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60182. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60183. noteUnderMouse == noteNum,
  60184. blackNoteColour);
  60185. }
  60186. }
  60187. }
  60188. }
  60189. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60190. Graphics& g, int x, int y, int w, int h,
  60191. bool isDown, bool isOver,
  60192. const Colour& lineColour,
  60193. const Colour& textColour)
  60194. {
  60195. Colour c (Colours::transparentWhite);
  60196. if (isDown)
  60197. c = findColour (keyDownOverlayColourId);
  60198. if (isOver)
  60199. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60200. g.setColour (c);
  60201. g.fillRect (x, y, w, h);
  60202. const String text (getWhiteNoteText (midiNoteNumber));
  60203. if (! text.isEmpty())
  60204. {
  60205. g.setColour (textColour);
  60206. Font f (jmin (12.0f, keyWidth * 0.9f));
  60207. f.setHorizontalScale (0.8f);
  60208. g.setFont (f);
  60209. Justification justification (Justification::centredBottom);
  60210. if (orientation == verticalKeyboardFacingLeft)
  60211. justification = Justification::centredLeft;
  60212. else if (orientation == verticalKeyboardFacingRight)
  60213. justification = Justification::centredRight;
  60214. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60215. }
  60216. g.setColour (lineColour);
  60217. if (orientation == horizontalKeyboard)
  60218. g.fillRect (x, y, 1, h);
  60219. else if (orientation == verticalKeyboardFacingLeft)
  60220. g.fillRect (x, y, w, 1);
  60221. else if (orientation == verticalKeyboardFacingRight)
  60222. g.fillRect (x, y + h - 1, w, 1);
  60223. if (midiNoteNumber == rangeEnd)
  60224. {
  60225. if (orientation == horizontalKeyboard)
  60226. g.fillRect (x + w, y, 1, h);
  60227. else if (orientation == verticalKeyboardFacingLeft)
  60228. g.fillRect (x, y + h, w, 1);
  60229. else if (orientation == verticalKeyboardFacingRight)
  60230. g.fillRect (x, y - 1, w, 1);
  60231. }
  60232. }
  60233. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60234. Graphics& g, int x, int y, int w, int h,
  60235. bool isDown, bool isOver,
  60236. const Colour& noteFillColour)
  60237. {
  60238. Colour c (noteFillColour);
  60239. if (isDown)
  60240. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60241. if (isOver)
  60242. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60243. g.setColour (c);
  60244. g.fillRect (x, y, w, h);
  60245. if (isDown)
  60246. {
  60247. g.setColour (noteFillColour);
  60248. g.drawRect (x, y, w, h);
  60249. }
  60250. else
  60251. {
  60252. const int xIndent = jmax (1, jmin (w, h) / 8);
  60253. g.setColour (c.brighter());
  60254. if (orientation == horizontalKeyboard)
  60255. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60256. else if (orientation == verticalKeyboardFacingLeft)
  60257. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60258. else if (orientation == verticalKeyboardFacingRight)
  60259. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60260. }
  60261. }
  60262. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60263. {
  60264. octaveNumForMiddleC = octaveNumForMiddleC_;
  60265. repaint();
  60266. }
  60267. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60268. {
  60269. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60270. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60271. return String::empty;
  60272. }
  60273. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60274. const bool isMouseOver_,
  60275. const bool isButtonDown,
  60276. const bool movesOctavesUp)
  60277. {
  60278. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60279. float angle;
  60280. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60281. angle = movesOctavesUp ? 0.0f : 0.5f;
  60282. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60283. angle = movesOctavesUp ? 0.25f : 0.75f;
  60284. else
  60285. angle = movesOctavesUp ? 0.75f : 0.25f;
  60286. Path path;
  60287. path.lineTo (0.0f, 1.0f);
  60288. path.lineTo (1.0f, 0.5f);
  60289. path.closeSubPath();
  60290. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60291. g.setColour (findColour (upDownButtonArrowColourId)
  60292. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60293. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60294. w - 2.0f,
  60295. h - 2.0f,
  60296. true));
  60297. }
  60298. void MidiKeyboardComponent::resized()
  60299. {
  60300. int w = getWidth();
  60301. int h = getHeight();
  60302. if (w > 0 && h > 0)
  60303. {
  60304. if (orientation != horizontalKeyboard)
  60305. swapVariables (w, h);
  60306. blackNoteLength = roundToInt (h * 0.7f);
  60307. int kx2, kw2;
  60308. getKeyPos (rangeEnd, kx2, kw2);
  60309. kx2 += kw2;
  60310. if (firstKey != rangeStart)
  60311. {
  60312. int kx1, kw1;
  60313. getKeyPos (rangeStart, kx1, kw1);
  60314. if (kx2 - kx1 <= w)
  60315. {
  60316. firstKey = rangeStart;
  60317. sendChangeMessage (this);
  60318. repaint();
  60319. }
  60320. }
  60321. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60322. scrollDown->setVisible (showScrollButtons);
  60323. scrollUp->setVisible (showScrollButtons);
  60324. xOffset = 0;
  60325. if (showScrollButtons)
  60326. {
  60327. const int scrollButtonW = jmin (12, w / 2);
  60328. if (orientation == horizontalKeyboard)
  60329. {
  60330. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60331. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60332. }
  60333. else if (orientation == verticalKeyboardFacingLeft)
  60334. {
  60335. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60336. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60337. }
  60338. else if (orientation == verticalKeyboardFacingRight)
  60339. {
  60340. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60341. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60342. }
  60343. int endOfLastKey, kw;
  60344. getKeyPos (rangeEnd, endOfLastKey, kw);
  60345. endOfLastKey += kw;
  60346. float mousePositionVelocity;
  60347. const int spaceAvailable = w - scrollButtonW * 2;
  60348. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60349. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60350. {
  60351. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60352. sendChangeMessage (this);
  60353. }
  60354. int newOffset = 0;
  60355. getKeyPos (firstKey, newOffset, kw);
  60356. xOffset = newOffset - scrollButtonW;
  60357. }
  60358. else
  60359. {
  60360. firstKey = rangeStart;
  60361. }
  60362. timerCallback();
  60363. repaint();
  60364. }
  60365. }
  60366. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60367. {
  60368. triggerAsyncUpdate();
  60369. }
  60370. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60371. {
  60372. triggerAsyncUpdate();
  60373. }
  60374. void MidiKeyboardComponent::handleAsyncUpdate()
  60375. {
  60376. for (int i = rangeStart; i <= rangeEnd; ++i)
  60377. {
  60378. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60379. {
  60380. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60381. repaintNote (i);
  60382. }
  60383. }
  60384. }
  60385. void MidiKeyboardComponent::resetAnyKeysInUse()
  60386. {
  60387. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60388. {
  60389. state.allNotesOff (midiChannel);
  60390. keysPressed.clear();
  60391. mouseDownNote = -1;
  60392. }
  60393. }
  60394. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60395. {
  60396. float mousePositionVelocity = 0.0f;
  60397. const int newNote = (mouseDragging || isMouseOver())
  60398. ? xyToNote (pos, mousePositionVelocity) : -1;
  60399. if (noteUnderMouse != newNote)
  60400. {
  60401. if (mouseDownNote >= 0)
  60402. {
  60403. state.noteOff (midiChannel, mouseDownNote);
  60404. mouseDownNote = -1;
  60405. }
  60406. if (mouseDragging && newNote >= 0)
  60407. {
  60408. if (! useMousePositionForVelocity)
  60409. mousePositionVelocity = 1.0f;
  60410. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60411. mouseDownNote = newNote;
  60412. }
  60413. repaintNote (noteUnderMouse);
  60414. noteUnderMouse = newNote;
  60415. repaintNote (noteUnderMouse);
  60416. }
  60417. else if (mouseDownNote >= 0 && ! mouseDragging)
  60418. {
  60419. state.noteOff (midiChannel, mouseDownNote);
  60420. mouseDownNote = -1;
  60421. }
  60422. }
  60423. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60424. {
  60425. updateNoteUnderMouse (e.getPosition());
  60426. stopTimer();
  60427. }
  60428. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60429. {
  60430. float mousePositionVelocity;
  60431. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60432. if (newNote >= 0)
  60433. mouseDraggedToKey (newNote, e);
  60434. updateNoteUnderMouse (e.getPosition());
  60435. }
  60436. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60437. {
  60438. return true;
  60439. }
  60440. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60441. {
  60442. }
  60443. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60444. {
  60445. float mousePositionVelocity;
  60446. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60447. mouseDragging = false;
  60448. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60449. {
  60450. repaintNote (noteUnderMouse);
  60451. noteUnderMouse = -1;
  60452. mouseDragging = true;
  60453. updateNoteUnderMouse (e.getPosition());
  60454. startTimer (500);
  60455. }
  60456. }
  60457. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60458. {
  60459. mouseDragging = false;
  60460. updateNoteUnderMouse (e.getPosition());
  60461. stopTimer();
  60462. }
  60463. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60464. {
  60465. updateNoteUnderMouse (e.getPosition());
  60466. }
  60467. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60468. {
  60469. updateNoteUnderMouse (e.getPosition());
  60470. }
  60471. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60472. {
  60473. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60474. }
  60475. void MidiKeyboardComponent::timerCallback()
  60476. {
  60477. updateNoteUnderMouse (getMouseXYRelative());
  60478. }
  60479. void MidiKeyboardComponent::clearKeyMappings()
  60480. {
  60481. resetAnyKeysInUse();
  60482. keyPressNotes.clear();
  60483. keyPresses.clear();
  60484. }
  60485. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60486. const int midiNoteOffsetFromC)
  60487. {
  60488. removeKeyPressForNote (midiNoteOffsetFromC);
  60489. keyPressNotes.add (midiNoteOffsetFromC);
  60490. keyPresses.add (key);
  60491. }
  60492. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60493. {
  60494. for (int i = keyPressNotes.size(); --i >= 0;)
  60495. {
  60496. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60497. {
  60498. keyPressNotes.remove (i);
  60499. keyPresses.remove (i);
  60500. }
  60501. }
  60502. }
  60503. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60504. {
  60505. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60506. keyMappingOctave = newOctaveNumber;
  60507. }
  60508. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60509. {
  60510. bool keyPressUsed = false;
  60511. for (int i = keyPresses.size(); --i >= 0;)
  60512. {
  60513. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60514. if (keyPresses.getReference(i).isCurrentlyDown())
  60515. {
  60516. if (! keysPressed [note])
  60517. {
  60518. keysPressed.setBit (note);
  60519. state.noteOn (midiChannel, note, velocity);
  60520. keyPressUsed = true;
  60521. }
  60522. }
  60523. else
  60524. {
  60525. if (keysPressed [note])
  60526. {
  60527. keysPressed.clearBit (note);
  60528. state.noteOff (midiChannel, note);
  60529. keyPressUsed = true;
  60530. }
  60531. }
  60532. }
  60533. return keyPressUsed;
  60534. }
  60535. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60536. {
  60537. resetAnyKeysInUse();
  60538. }
  60539. END_JUCE_NAMESPACE
  60540. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60541. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60542. #if JUCE_OPENGL
  60543. BEGIN_JUCE_NAMESPACE
  60544. extern void juce_glViewport (const int w, const int h);
  60545. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60546. const int alphaBits_,
  60547. const int depthBufferBits_,
  60548. const int stencilBufferBits_)
  60549. : redBits (bitsPerRGBComponent),
  60550. greenBits (bitsPerRGBComponent),
  60551. blueBits (bitsPerRGBComponent),
  60552. alphaBits (alphaBits_),
  60553. depthBufferBits (depthBufferBits_),
  60554. stencilBufferBits (stencilBufferBits_),
  60555. accumulationBufferRedBits (0),
  60556. accumulationBufferGreenBits (0),
  60557. accumulationBufferBlueBits (0),
  60558. accumulationBufferAlphaBits (0),
  60559. fullSceneAntiAliasingNumSamples (0)
  60560. {
  60561. }
  60562. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60563. : redBits (other.redBits),
  60564. greenBits (other.greenBits),
  60565. blueBits (other.blueBits),
  60566. alphaBits (other.alphaBits),
  60567. depthBufferBits (other.depthBufferBits),
  60568. stencilBufferBits (other.stencilBufferBits),
  60569. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60570. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60571. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60572. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60573. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60574. {
  60575. }
  60576. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60577. {
  60578. redBits = other.redBits;
  60579. greenBits = other.greenBits;
  60580. blueBits = other.blueBits;
  60581. alphaBits = other.alphaBits;
  60582. depthBufferBits = other.depthBufferBits;
  60583. stencilBufferBits = other.stencilBufferBits;
  60584. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60585. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60586. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60587. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60588. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60589. return *this;
  60590. }
  60591. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60592. {
  60593. return redBits == other.redBits
  60594. && greenBits == other.greenBits
  60595. && blueBits == other.blueBits
  60596. && alphaBits == other.alphaBits
  60597. && depthBufferBits == other.depthBufferBits
  60598. && stencilBufferBits == other.stencilBufferBits
  60599. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60600. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60601. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60602. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60603. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60604. }
  60605. static VoidArray knownContexts;
  60606. OpenGLContext::OpenGLContext() throw()
  60607. {
  60608. knownContexts.add (this);
  60609. }
  60610. OpenGLContext::~OpenGLContext()
  60611. {
  60612. knownContexts.removeValue (this);
  60613. }
  60614. OpenGLContext* OpenGLContext::getCurrentContext()
  60615. {
  60616. for (int i = knownContexts.size(); --i >= 0;)
  60617. {
  60618. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  60619. if (oglc->isActive())
  60620. return oglc;
  60621. }
  60622. return 0;
  60623. }
  60624. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60625. {
  60626. public:
  60627. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60628. : ComponentMovementWatcher (owner_),
  60629. owner (owner_),
  60630. wasShowing (false)
  60631. {
  60632. }
  60633. ~OpenGLComponentWatcher() {}
  60634. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60635. {
  60636. owner->updateContextPosition();
  60637. }
  60638. void componentPeerChanged()
  60639. {
  60640. const ScopedLock sl (owner->getContextLock());
  60641. owner->deleteContext();
  60642. }
  60643. void componentVisibilityChanged (Component&)
  60644. {
  60645. const bool isShowingNow = owner->isShowing();
  60646. if (wasShowing != isShowingNow)
  60647. {
  60648. wasShowing = isShowingNow;
  60649. owner->updateContextPosition();
  60650. }
  60651. }
  60652. juce_UseDebuggingNewOperator
  60653. private:
  60654. OpenGLComponent* const owner;
  60655. bool wasShowing;
  60656. };
  60657. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60658. : type (type_),
  60659. contextToShareListsWith (0),
  60660. needToUpdateViewport (true)
  60661. {
  60662. setOpaque (true);
  60663. componentWatcher = new OpenGLComponentWatcher (this);
  60664. }
  60665. OpenGLComponent::~OpenGLComponent()
  60666. {
  60667. deleteContext();
  60668. componentWatcher = 0;
  60669. }
  60670. void OpenGLComponent::deleteContext()
  60671. {
  60672. const ScopedLock sl (contextLock);
  60673. context = 0;
  60674. }
  60675. void OpenGLComponent::updateContextPosition()
  60676. {
  60677. needToUpdateViewport = true;
  60678. if (getWidth() > 0 && getHeight() > 0)
  60679. {
  60680. Component* const topComp = getTopLevelComponent();
  60681. if (topComp->getPeer() != 0)
  60682. {
  60683. const ScopedLock sl (contextLock);
  60684. if (context != 0)
  60685. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60686. getScreenY() - topComp->getScreenY(),
  60687. getWidth(),
  60688. getHeight(),
  60689. topComp->getHeight());
  60690. }
  60691. }
  60692. }
  60693. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60694. {
  60695. OpenGLPixelFormat pf;
  60696. const ScopedLock sl (contextLock);
  60697. if (context != 0)
  60698. pf = context->getPixelFormat();
  60699. return pf;
  60700. }
  60701. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60702. {
  60703. if (! (preferredPixelFormat == formatToUse))
  60704. {
  60705. const ScopedLock sl (contextLock);
  60706. deleteContext();
  60707. preferredPixelFormat = formatToUse;
  60708. }
  60709. }
  60710. void OpenGLComponent::shareWith (OpenGLContext* c)
  60711. {
  60712. if (contextToShareListsWith != c)
  60713. {
  60714. const ScopedLock sl (contextLock);
  60715. deleteContext();
  60716. contextToShareListsWith = c;
  60717. }
  60718. }
  60719. bool OpenGLComponent::makeCurrentContextActive()
  60720. {
  60721. if (context == 0)
  60722. {
  60723. const ScopedLock sl (contextLock);
  60724. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60725. {
  60726. context = createContext();
  60727. if (context != 0)
  60728. {
  60729. updateContextPosition();
  60730. if (context->makeActive())
  60731. newOpenGLContextCreated();
  60732. }
  60733. }
  60734. }
  60735. return context != 0 && context->makeActive();
  60736. }
  60737. void OpenGLComponent::makeCurrentContextInactive()
  60738. {
  60739. if (context != 0)
  60740. context->makeInactive();
  60741. }
  60742. bool OpenGLComponent::isActiveContext() const throw()
  60743. {
  60744. return context != 0 && context->isActive();
  60745. }
  60746. void OpenGLComponent::swapBuffers()
  60747. {
  60748. if (context != 0)
  60749. context->swapBuffers();
  60750. }
  60751. void OpenGLComponent::paint (Graphics&)
  60752. {
  60753. if (renderAndSwapBuffers())
  60754. {
  60755. ComponentPeer* const peer = getPeer();
  60756. if (peer != 0)
  60757. {
  60758. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60759. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60760. }
  60761. }
  60762. }
  60763. bool OpenGLComponent::renderAndSwapBuffers()
  60764. {
  60765. const ScopedLock sl (contextLock);
  60766. if (! makeCurrentContextActive())
  60767. return false;
  60768. if (needToUpdateViewport)
  60769. {
  60770. needToUpdateViewport = false;
  60771. juce_glViewport (getWidth(), getHeight());
  60772. }
  60773. renderOpenGL();
  60774. swapBuffers();
  60775. return true;
  60776. }
  60777. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60778. {
  60779. Component::internalRepaint (x, y, w, h);
  60780. if (context != 0)
  60781. context->repaint();
  60782. }
  60783. END_JUCE_NAMESPACE
  60784. #endif
  60785. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60786. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60787. BEGIN_JUCE_NAMESPACE
  60788. PreferencesPanel::PreferencesPanel()
  60789. : buttonSize (70)
  60790. {
  60791. }
  60792. PreferencesPanel::~PreferencesPanel()
  60793. {
  60794. currentPage = 0;
  60795. deleteAllChildren();
  60796. }
  60797. void PreferencesPanel::addSettingsPage (const String& title,
  60798. const Drawable* icon,
  60799. const Drawable* overIcon,
  60800. const Drawable* downIcon)
  60801. {
  60802. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60803. button->setImages (icon, overIcon, downIcon);
  60804. button->setRadioGroupId (1);
  60805. button->addButtonListener (this);
  60806. button->setClickingTogglesState (true);
  60807. button->setWantsKeyboardFocus (false);
  60808. addAndMakeVisible (button);
  60809. resized();
  60810. if (currentPage == 0)
  60811. setCurrentPage (title);
  60812. }
  60813. void PreferencesPanel::addSettingsPage (const String& title,
  60814. const char* imageData,
  60815. const int imageDataSize)
  60816. {
  60817. DrawableImage icon, iconOver, iconDown;
  60818. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60819. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60820. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60821. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60822. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60823. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60824. }
  60825. class PrefsDialogWindow : public DialogWindow
  60826. {
  60827. public:
  60828. PrefsDialogWindow (const String& dialogtitle,
  60829. const Colour& backgroundColour)
  60830. : DialogWindow (dialogtitle, backgroundColour, true)
  60831. {
  60832. }
  60833. ~PrefsDialogWindow()
  60834. {
  60835. }
  60836. void closeButtonPressed()
  60837. {
  60838. exitModalState (0);
  60839. }
  60840. private:
  60841. PrefsDialogWindow (const PrefsDialogWindow&);
  60842. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  60843. };
  60844. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  60845. int dialogWidth,
  60846. int dialogHeight,
  60847. const Colour& backgroundColour)
  60848. {
  60849. setSize (dialogWidth, dialogHeight);
  60850. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  60851. dw.setContentComponent (this, true, true);
  60852. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  60853. dw.runModalLoop();
  60854. dw.setContentComponent (0, false, false);
  60855. }
  60856. void PreferencesPanel::resized()
  60857. {
  60858. int x = 0;
  60859. for (int i = 0; i < getNumChildComponents(); ++i)
  60860. {
  60861. Component* c = getChildComponent (i);
  60862. if (dynamic_cast <DrawableButton*> (c) == 0)
  60863. {
  60864. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  60865. }
  60866. else
  60867. {
  60868. c->setBounds (x, 0, buttonSize, buttonSize);
  60869. x += buttonSize;
  60870. }
  60871. }
  60872. }
  60873. void PreferencesPanel::paint (Graphics& g)
  60874. {
  60875. g.setColour (Colours::grey);
  60876. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  60877. }
  60878. void PreferencesPanel::setCurrentPage (const String& pageName)
  60879. {
  60880. if (currentPageName != pageName)
  60881. {
  60882. currentPageName = pageName;
  60883. currentPage = 0;
  60884. currentPage = createComponentForPage (pageName);
  60885. if (currentPage != 0)
  60886. {
  60887. addAndMakeVisible (currentPage);
  60888. currentPage->toBack();
  60889. resized();
  60890. }
  60891. for (int i = 0; i < getNumChildComponents(); ++i)
  60892. {
  60893. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60894. if (db != 0 && db->getName() == pageName)
  60895. {
  60896. db->setToggleState (true, false);
  60897. break;
  60898. }
  60899. }
  60900. }
  60901. }
  60902. void PreferencesPanel::buttonClicked (Button*)
  60903. {
  60904. for (int i = 0; i < getNumChildComponents(); ++i)
  60905. {
  60906. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60907. if (db != 0 && db->getToggleState())
  60908. {
  60909. setCurrentPage (db->getName());
  60910. break;
  60911. }
  60912. }
  60913. }
  60914. END_JUCE_NAMESPACE
  60915. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  60916. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60917. #if JUCE_WINDOWS || JUCE_LINUX
  60918. BEGIN_JUCE_NAMESPACE
  60919. SystemTrayIconComponent::SystemTrayIconComponent()
  60920. {
  60921. addToDesktop (0);
  60922. }
  60923. SystemTrayIconComponent::~SystemTrayIconComponent()
  60924. {
  60925. }
  60926. END_JUCE_NAMESPACE
  60927. #endif
  60928. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60929. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  60930. BEGIN_JUCE_NAMESPACE
  60931. class AlertWindowTextEditor : public TextEditor
  60932. {
  60933. public:
  60934. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  60935. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  60936. {
  60937. setSelectAllWhenFocused (true);
  60938. }
  60939. ~AlertWindowTextEditor()
  60940. {
  60941. }
  60942. void returnPressed()
  60943. {
  60944. // pass these up the component hierarchy to be trigger the buttons
  60945. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  60946. }
  60947. void escapePressed()
  60948. {
  60949. // pass these up the component hierarchy to be trigger the buttons
  60950. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  60951. }
  60952. private:
  60953. AlertWindowTextEditor (const AlertWindowTextEditor&);
  60954. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  60955. static juce_wchar getDefaultPasswordChar() throw()
  60956. {
  60957. #if JUCE_LINUX
  60958. return 0x2022;
  60959. #else
  60960. return 0x25cf;
  60961. #endif
  60962. }
  60963. };
  60964. AlertWindow::AlertWindow (const String& title,
  60965. const String& message,
  60966. AlertIconType iconType,
  60967. Component* associatedComponent_)
  60968. : TopLevelWindow (title, true),
  60969. alertIconType (iconType),
  60970. associatedComponent (associatedComponent_)
  60971. {
  60972. if (message.isEmpty())
  60973. text = " "; // to force an update if the message is empty
  60974. setMessage (message);
  60975. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  60976. {
  60977. Component* const c = Desktop::getInstance().getComponent (i);
  60978. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  60979. {
  60980. setAlwaysOnTop (true);
  60981. break;
  60982. }
  60983. }
  60984. if (JUCEApplication::getInstance() == 0)
  60985. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  60986. lookAndFeelChanged();
  60987. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  60988. }
  60989. AlertWindow::~AlertWindow()
  60990. {
  60991. for (int i = customComps.size(); --i >= 0;)
  60992. removeChildComponent ((Component*) customComps[i]);
  60993. deleteAllChildren();
  60994. }
  60995. void AlertWindow::userTriedToCloseWindow()
  60996. {
  60997. exitModalState (0);
  60998. }
  60999. void AlertWindow::setMessage (const String& message)
  61000. {
  61001. const String newMessage (message.substring (0, 2048));
  61002. if (text != newMessage)
  61003. {
  61004. text = newMessage;
  61005. font.setHeight (15.0f);
  61006. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61007. textLayout.setText (getName() + "\n\n", titleFont);
  61008. textLayout.appendText (text, font);
  61009. updateLayout (true);
  61010. repaint();
  61011. }
  61012. }
  61013. void AlertWindow::buttonClicked (Button* button)
  61014. {
  61015. for (int i = 0; i < buttons.size(); i++)
  61016. {
  61017. TextButton* const c = (TextButton*) buttons[i];
  61018. if (button->getName() == c->getName())
  61019. {
  61020. if (c->getParentComponent() != 0)
  61021. c->getParentComponent()->exitModalState (c->getCommandID());
  61022. break;
  61023. }
  61024. }
  61025. }
  61026. void AlertWindow::addButton (const String& name,
  61027. const int returnValue,
  61028. const KeyPress& shortcutKey1,
  61029. const KeyPress& shortcutKey2)
  61030. {
  61031. TextButton* const b = new TextButton (name, String::empty);
  61032. b->setWantsKeyboardFocus (true);
  61033. b->setMouseClickGrabsKeyboardFocus (false);
  61034. b->setCommandToTrigger (0, returnValue, false);
  61035. b->addShortcut (shortcutKey1);
  61036. b->addShortcut (shortcutKey2);
  61037. b->addButtonListener (this);
  61038. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61039. addAndMakeVisible (b, 0);
  61040. buttons.add (b);
  61041. updateLayout (false);
  61042. }
  61043. int AlertWindow::getNumButtons() const
  61044. {
  61045. return buttons.size();
  61046. }
  61047. void AlertWindow::triggerButtonClick (const String& buttonName)
  61048. {
  61049. for (int i = buttons.size(); --i >= 0;)
  61050. {
  61051. TextButton* const b = (TextButton*) buttons[i];
  61052. if (buttonName == b->getName())
  61053. {
  61054. b->triggerClick();
  61055. break;
  61056. }
  61057. }
  61058. }
  61059. void AlertWindow::addTextEditor (const String& name,
  61060. const String& initialContents,
  61061. const String& onScreenLabel,
  61062. const bool isPasswordBox)
  61063. {
  61064. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61065. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61066. tc->setFont (font);
  61067. tc->setText (initialContents);
  61068. tc->setCaretPosition (initialContents.length());
  61069. addAndMakeVisible (tc);
  61070. textBoxes.add (tc);
  61071. allComps.add (tc);
  61072. textboxNames.add (onScreenLabel);
  61073. updateLayout (false);
  61074. }
  61075. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61076. {
  61077. for (int i = textBoxes.size(); --i >= 0;)
  61078. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61079. return ((TextEditor*)textBoxes[i])->getText();
  61080. return String::empty;
  61081. }
  61082. void AlertWindow::addComboBox (const String& name,
  61083. const StringArray& items,
  61084. const String& onScreenLabel)
  61085. {
  61086. ComboBox* const cb = new ComboBox (name);
  61087. for (int i = 0; i < items.size(); ++i)
  61088. cb->addItem (items[i], i + 1);
  61089. addAndMakeVisible (cb);
  61090. cb->setSelectedItemIndex (0);
  61091. comboBoxes.add (cb);
  61092. allComps.add (cb);
  61093. comboBoxNames.add (onScreenLabel);
  61094. updateLayout (false);
  61095. }
  61096. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61097. {
  61098. for (int i = comboBoxes.size(); --i >= 0;)
  61099. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61100. return (ComboBox*) comboBoxes[i];
  61101. return 0;
  61102. }
  61103. class AlertTextComp : public TextEditor
  61104. {
  61105. public:
  61106. AlertTextComp (const String& message,
  61107. const Font& font)
  61108. {
  61109. setReadOnly (true);
  61110. setMultiLine (true, true);
  61111. setCaretVisible (false);
  61112. setScrollbarsShown (true);
  61113. lookAndFeelChanged();
  61114. setWantsKeyboardFocus (false);
  61115. setFont (font);
  61116. setText (message, false);
  61117. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  61118. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61119. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61120. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61121. }
  61122. ~AlertTextComp()
  61123. {
  61124. }
  61125. int getPreferredWidth() const throw() { return bestWidth; }
  61126. void updateLayout (const int width)
  61127. {
  61128. TextLayout text;
  61129. text.appendText (getText(), getFont());
  61130. text.layout (width - 8, Justification::topLeft, true);
  61131. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61132. }
  61133. private:
  61134. int bestWidth;
  61135. AlertTextComp (const AlertTextComp&);
  61136. AlertTextComp& operator= (const AlertTextComp&);
  61137. };
  61138. void AlertWindow::addTextBlock (const String& textBlock)
  61139. {
  61140. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61141. textBlocks.add (c);
  61142. allComps.add (c);
  61143. addAndMakeVisible (c);
  61144. updateLayout (false);
  61145. }
  61146. void AlertWindow::addProgressBarComponent (double& progressValue)
  61147. {
  61148. ProgressBar* const pb = new ProgressBar (progressValue);
  61149. progressBars.add (pb);
  61150. allComps.add (pb);
  61151. addAndMakeVisible (pb);
  61152. updateLayout (false);
  61153. }
  61154. void AlertWindow::addCustomComponent (Component* const component)
  61155. {
  61156. customComps.add (component);
  61157. allComps.add (component);
  61158. addAndMakeVisible (component);
  61159. updateLayout (false);
  61160. }
  61161. int AlertWindow::getNumCustomComponents() const
  61162. {
  61163. return customComps.size();
  61164. }
  61165. Component* AlertWindow::getCustomComponent (const int index) const
  61166. {
  61167. return (Component*) customComps [index];
  61168. }
  61169. Component* AlertWindow::removeCustomComponent (const int index)
  61170. {
  61171. Component* const c = getCustomComponent (index);
  61172. if (c != 0)
  61173. {
  61174. customComps.removeValue (c);
  61175. allComps.removeValue (c);
  61176. removeChildComponent (c);
  61177. updateLayout (false);
  61178. }
  61179. return c;
  61180. }
  61181. void AlertWindow::paint (Graphics& g)
  61182. {
  61183. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61184. g.setColour (findColour (textColourId));
  61185. g.setFont (getLookAndFeel().getAlertWindowFont());
  61186. int i;
  61187. for (i = textBoxes.size(); --i >= 0;)
  61188. {
  61189. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61190. g.drawFittedText (textboxNames[i],
  61191. te->getX(), te->getY() - 14,
  61192. te->getWidth(), 14,
  61193. Justification::centredLeft, 1);
  61194. }
  61195. for (i = comboBoxNames.size(); --i >= 0;)
  61196. {
  61197. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61198. g.drawFittedText (comboBoxNames[i],
  61199. cb->getX(), cb->getY() - 14,
  61200. cb->getWidth(), 14,
  61201. Justification::centredLeft, 1);
  61202. }
  61203. for (i = customComps.size(); --i >= 0;)
  61204. {
  61205. const Component* const c = (Component*) customComps[i];
  61206. g.drawFittedText (c->getName(),
  61207. c->getX(), c->getY() - 14,
  61208. c->getWidth(), 14,
  61209. Justification::centredLeft, 1);
  61210. }
  61211. }
  61212. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61213. {
  61214. const int titleH = 24;
  61215. const int iconWidth = 80;
  61216. const int wid = jmax (font.getStringWidth (text),
  61217. font.getStringWidth (getName()));
  61218. const int sw = (int) sqrt (font.getHeight() * wid);
  61219. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61220. const int edgeGap = 10;
  61221. const int labelHeight = 18;
  61222. int iconSpace;
  61223. if (alertIconType == NoIcon)
  61224. {
  61225. textLayout.layout (w, Justification::horizontallyCentred, true);
  61226. iconSpace = 0;
  61227. }
  61228. else
  61229. {
  61230. textLayout.layout (w, Justification::left, true);
  61231. iconSpace = iconWidth;
  61232. }
  61233. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61234. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61235. const int textLayoutH = textLayout.getHeight();
  61236. const int textBottom = 16 + titleH + textLayoutH;
  61237. int h = textBottom;
  61238. int buttonW = 40;
  61239. int i;
  61240. for (i = 0; i < buttons.size(); ++i)
  61241. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61242. w = jmax (buttonW, w);
  61243. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61244. if (buttons.size() > 0)
  61245. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61246. for (i = customComps.size(); --i >= 0;)
  61247. {
  61248. Component* c = (Component*) customComps[i];
  61249. w = jmax (w, (c->getWidth() * 100) / 80);
  61250. h += 10 + c->getHeight();
  61251. if (c->getName().isNotEmpty())
  61252. h += labelHeight;
  61253. }
  61254. for (i = textBlocks.size(); --i >= 0;)
  61255. {
  61256. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61257. w = jmax (w, ac->getPreferredWidth());
  61258. }
  61259. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61260. for (i = textBlocks.size(); --i >= 0;)
  61261. {
  61262. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61263. ac->updateLayout ((int) (w * 0.8f));
  61264. h += ac->getHeight() + 10;
  61265. }
  61266. h = jmin (getParentHeight() - 50, h);
  61267. if (onlyIncreaseSize)
  61268. {
  61269. w = jmax (w, getWidth());
  61270. h = jmax (h, getHeight());
  61271. }
  61272. if (! isVisible())
  61273. {
  61274. centreAroundComponent (associatedComponent, w, h);
  61275. }
  61276. else
  61277. {
  61278. const int cx = getX() + getWidth() / 2;
  61279. const int cy = getY() + getHeight() / 2;
  61280. setBounds (cx - w / 2,
  61281. cy - h / 2,
  61282. w, h);
  61283. }
  61284. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61285. const int spacer = 16;
  61286. int totalWidth = -spacer;
  61287. for (i = buttons.size(); --i >= 0;)
  61288. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61289. int x = (w - totalWidth) / 2;
  61290. int y = (int) (getHeight() * 0.95f);
  61291. for (i = 0; i < buttons.size(); ++i)
  61292. {
  61293. TextButton* const c = (TextButton*) buttons[i];
  61294. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61295. c->setTopLeftPosition (x, ny);
  61296. if (ny < y)
  61297. y = ny;
  61298. x += c->getWidth() + spacer;
  61299. c->toFront (false);
  61300. }
  61301. y = textBottom;
  61302. for (i = 0; i < allComps.size(); ++i)
  61303. {
  61304. Component* const c = (Component*) allComps[i];
  61305. h = 22;
  61306. const int comboIndex = comboBoxes.indexOf (c);
  61307. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61308. y += labelHeight;
  61309. const int tbIndex = textBoxes.indexOf (c);
  61310. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61311. y += labelHeight;
  61312. if (customComps.contains (c))
  61313. {
  61314. if (c->getName().isNotEmpty())
  61315. y += labelHeight;
  61316. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61317. h = c->getHeight();
  61318. }
  61319. else if (textBlocks.contains (c))
  61320. {
  61321. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61322. h = c->getHeight();
  61323. }
  61324. else
  61325. {
  61326. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61327. }
  61328. y += h + 10;
  61329. }
  61330. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61331. }
  61332. bool AlertWindow::containsAnyExtraComponents() const
  61333. {
  61334. return textBoxes.size()
  61335. + comboBoxes.size()
  61336. + progressBars.size()
  61337. + customComps.size() > 0;
  61338. }
  61339. void AlertWindow::mouseDown (const MouseEvent&)
  61340. {
  61341. dragger.startDraggingComponent (this, &constrainer);
  61342. }
  61343. void AlertWindow::mouseDrag (const MouseEvent& e)
  61344. {
  61345. dragger.dragComponent (this, e);
  61346. }
  61347. bool AlertWindow::keyPressed (const KeyPress& key)
  61348. {
  61349. for (int i = buttons.size(); --i >= 0;)
  61350. {
  61351. TextButton* const b = (TextButton*) buttons[i];
  61352. if (b->isRegisteredForShortcut (key))
  61353. {
  61354. b->triggerClick();
  61355. return true;
  61356. }
  61357. }
  61358. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61359. {
  61360. exitModalState (0);
  61361. return true;
  61362. }
  61363. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61364. {
  61365. ((TextButton*) buttons.getFirst())->triggerClick();
  61366. return true;
  61367. }
  61368. return false;
  61369. }
  61370. void AlertWindow::lookAndFeelChanged()
  61371. {
  61372. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61373. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61374. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61375. }
  61376. int AlertWindow::getDesktopWindowStyleFlags() const
  61377. {
  61378. return getLookAndFeel().getAlertBoxWindowFlags();
  61379. }
  61380. struct AlertWindowInfo
  61381. {
  61382. String title, message, button1, button2, button3;
  61383. AlertWindow::AlertIconType iconType;
  61384. int numButtons;
  61385. Component::SafePointer<Component> associatedComponent;
  61386. int run() const
  61387. {
  61388. return (int) (pointer_sized_int)
  61389. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61390. }
  61391. private:
  61392. int show() const
  61393. {
  61394. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61395. : LookAndFeel::getDefaultLookAndFeel();
  61396. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61397. iconType, numButtons, associatedComponent));
  61398. jassert (alertBox != 0); // you have to return one of these!
  61399. return alertBox->runModalLoop();
  61400. }
  61401. static void* showCallback (void* userData)
  61402. {
  61403. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61404. }
  61405. };
  61406. void AlertWindow::showMessageBox (AlertIconType iconType,
  61407. const String& title,
  61408. const String& message,
  61409. const String& buttonText,
  61410. Component* associatedComponent)
  61411. {
  61412. AlertWindowInfo info;
  61413. info.title = title;
  61414. info.message = message;
  61415. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61416. info.iconType = iconType;
  61417. info.numButtons = 1;
  61418. info.associatedComponent = associatedComponent;
  61419. info.run();
  61420. }
  61421. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61422. const String& title,
  61423. const String& message,
  61424. const String& button1Text,
  61425. const String& button2Text,
  61426. Component* associatedComponent)
  61427. {
  61428. AlertWindowInfo info;
  61429. info.title = title;
  61430. info.message = message;
  61431. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61432. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61433. info.iconType = iconType;
  61434. info.numButtons = 2;
  61435. info.associatedComponent = associatedComponent;
  61436. return info.run() != 0;
  61437. }
  61438. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61439. const String& title,
  61440. const String& message,
  61441. const String& button1Text,
  61442. const String& button2Text,
  61443. const String& button3Text,
  61444. Component* associatedComponent)
  61445. {
  61446. AlertWindowInfo info;
  61447. info.title = title;
  61448. info.message = message;
  61449. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61450. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61451. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61452. info.iconType = iconType;
  61453. info.numButtons = 3;
  61454. info.associatedComponent = associatedComponent;
  61455. return info.run();
  61456. }
  61457. END_JUCE_NAMESPACE
  61458. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61459. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61460. BEGIN_JUCE_NAMESPACE
  61461. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61462. static VoidArray heavyweightPeers;
  61463. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61464. : component (component_),
  61465. styleFlags (styleFlags_),
  61466. lastPaintTime (0),
  61467. constrainer (0),
  61468. lastDragAndDropCompUnderMouse (0),
  61469. fakeMouseMessageSent (false),
  61470. isWindowMinimised (false)
  61471. {
  61472. heavyweightPeers.add (this);
  61473. }
  61474. ComponentPeer::~ComponentPeer()
  61475. {
  61476. heavyweightPeers.removeValue (this);
  61477. Desktop::getInstance().triggerFocusCallback();
  61478. }
  61479. int ComponentPeer::getNumPeers() throw()
  61480. {
  61481. return heavyweightPeers.size();
  61482. }
  61483. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61484. {
  61485. return (ComponentPeer*) heavyweightPeers [index];
  61486. }
  61487. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61488. {
  61489. for (int i = heavyweightPeers.size(); --i >= 0;)
  61490. {
  61491. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  61492. if (peer->getComponent() == component)
  61493. return peer;
  61494. }
  61495. return 0;
  61496. }
  61497. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61498. {
  61499. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61500. }
  61501. void ComponentPeer::updateCurrentModifiers() throw()
  61502. {
  61503. ModifierKeys::updateCurrentModifiers();
  61504. }
  61505. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61506. {
  61507. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61508. jassert (mouse != 0); // not enough sources!
  61509. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61510. }
  61511. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61512. {
  61513. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61514. jassert (mouse != 0); // not enough sources!
  61515. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61516. }
  61517. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61518. {
  61519. Graphics g (&contextToPaintTo);
  61520. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61521. g.saveState();
  61522. #endif
  61523. JUCE_TRY
  61524. {
  61525. component->paintEntireComponent (g);
  61526. }
  61527. JUCE_CATCH_EXCEPTION
  61528. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61529. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61530. // clearly when things are being repainted.
  61531. {
  61532. g.restoreState();
  61533. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61534. (uint8) Random::getSystemRandom().nextInt (255),
  61535. (uint8) Random::getSystemRandom().nextInt (255),
  61536. (uint8) 0x50));
  61537. }
  61538. #endif
  61539. }
  61540. bool ComponentPeer::handleKeyPress (const int keyCode,
  61541. const juce_wchar textCharacter)
  61542. {
  61543. updateCurrentModifiers();
  61544. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61545. ? Component::getCurrentlyFocusedComponent()
  61546. : component;
  61547. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61548. {
  61549. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61550. if (currentModalComp != 0)
  61551. target = currentModalComp;
  61552. }
  61553. const KeyPress keyInfo (keyCode,
  61554. ModifierKeys::getCurrentModifiers().getRawFlags()
  61555. & ModifierKeys::allKeyboardModifiers,
  61556. textCharacter);
  61557. bool keyWasUsed = false;
  61558. while (target != 0)
  61559. {
  61560. const Component::SafePointer<Component> deletionChecker (target);
  61561. if (target->keyListeners_ != 0)
  61562. {
  61563. for (int i = target->keyListeners_->size(); --i >= 0;)
  61564. {
  61565. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  61566. if (keyWasUsed || deletionChecker == 0)
  61567. return keyWasUsed;
  61568. i = jmin (i, target->keyListeners_->size());
  61569. }
  61570. }
  61571. keyWasUsed = target->keyPressed (keyInfo);
  61572. if (keyWasUsed || deletionChecker == 0)
  61573. break;
  61574. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61575. {
  61576. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61577. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61578. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61579. break;
  61580. }
  61581. target = target->parentComponent_;
  61582. }
  61583. return keyWasUsed;
  61584. }
  61585. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61586. {
  61587. updateCurrentModifiers();
  61588. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61589. ? Component::getCurrentlyFocusedComponent()
  61590. : component;
  61591. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61592. {
  61593. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61594. if (currentModalComp != 0)
  61595. target = currentModalComp;
  61596. }
  61597. bool keyWasUsed = false;
  61598. while (target != 0)
  61599. {
  61600. const Component::SafePointer<Component> deletionChecker (target);
  61601. keyWasUsed = target->keyStateChanged (isKeyDown);
  61602. if (keyWasUsed || deletionChecker == 0)
  61603. break;
  61604. if (target->keyListeners_ != 0)
  61605. {
  61606. for (int i = target->keyListeners_->size(); --i >= 0;)
  61607. {
  61608. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  61609. if (keyWasUsed || deletionChecker == 0)
  61610. return keyWasUsed;
  61611. i = jmin (i, target->keyListeners_->size());
  61612. }
  61613. }
  61614. target = target->parentComponent_;
  61615. }
  61616. return keyWasUsed;
  61617. }
  61618. void ComponentPeer::handleModifierKeysChange()
  61619. {
  61620. updateCurrentModifiers();
  61621. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61622. if (target == 0)
  61623. target = Component::getCurrentlyFocusedComponent();
  61624. if (target == 0)
  61625. target = component;
  61626. if (target != 0)
  61627. target->internalModifierKeysChanged();
  61628. }
  61629. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61630. {
  61631. Component* const c = Component::getCurrentlyFocusedComponent();
  61632. if (component->isParentOf (c))
  61633. {
  61634. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61635. if (ti != 0 && ti->isTextInputActive())
  61636. return ti;
  61637. }
  61638. return 0;
  61639. }
  61640. void ComponentPeer::handleBroughtToFront()
  61641. {
  61642. updateCurrentModifiers();
  61643. if (component != 0)
  61644. component->internalBroughtToFront();
  61645. }
  61646. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61647. {
  61648. constrainer = newConstrainer;
  61649. }
  61650. void ComponentPeer::handleMovedOrResized()
  61651. {
  61652. jassert (component->isValidComponent());
  61653. updateCurrentModifiers();
  61654. const bool nowMinimised = isMinimised();
  61655. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61656. {
  61657. const Component::SafePointer<Component> deletionChecker (component);
  61658. const Rectangle<int> newBounds (getBounds());
  61659. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61660. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61661. if (wasMoved || wasResized)
  61662. {
  61663. component->bounds_ = newBounds;
  61664. if (wasResized)
  61665. component->repaint();
  61666. component->sendMovedResizedMessages (wasMoved, wasResized);
  61667. if (deletionChecker == 0)
  61668. return;
  61669. }
  61670. }
  61671. if (isWindowMinimised != nowMinimised)
  61672. {
  61673. isWindowMinimised = nowMinimised;
  61674. component->minimisationStateChanged (nowMinimised);
  61675. component->sendVisibilityChangeMessage();
  61676. }
  61677. if (! isFullScreen())
  61678. lastNonFullscreenBounds = component->getBounds();
  61679. }
  61680. void ComponentPeer::handleFocusGain()
  61681. {
  61682. updateCurrentModifiers();
  61683. if (component->isParentOf (lastFocusedComponent))
  61684. {
  61685. Component::currentlyFocusedComponent = lastFocusedComponent;
  61686. Desktop::getInstance().triggerFocusCallback();
  61687. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61688. }
  61689. else
  61690. {
  61691. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61692. component->grabKeyboardFocus();
  61693. else
  61694. Component::bringModalComponentToFront();
  61695. }
  61696. }
  61697. void ComponentPeer::handleFocusLoss()
  61698. {
  61699. updateCurrentModifiers();
  61700. if (component->hasKeyboardFocus (true))
  61701. {
  61702. lastFocusedComponent = Component::currentlyFocusedComponent;
  61703. if (lastFocusedComponent != 0)
  61704. {
  61705. Component::currentlyFocusedComponent = 0;
  61706. Desktop::getInstance().triggerFocusCallback();
  61707. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  61708. }
  61709. }
  61710. }
  61711. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  61712. {
  61713. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  61714. ? static_cast <Component*> (lastFocusedComponent)
  61715. : component;
  61716. }
  61717. void ComponentPeer::handleScreenSizeChange()
  61718. {
  61719. updateCurrentModifiers();
  61720. component->parentSizeChanged();
  61721. handleMovedOrResized();
  61722. }
  61723. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  61724. {
  61725. lastNonFullscreenBounds = newBounds;
  61726. }
  61727. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  61728. {
  61729. return lastNonFullscreenBounds;
  61730. }
  61731. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  61732. const StringArray& files,
  61733. FileDragAndDropTarget* const lastOne)
  61734. {
  61735. while (c != 0)
  61736. {
  61737. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  61738. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  61739. return t;
  61740. c = c->getParentComponent();
  61741. }
  61742. return 0;
  61743. }
  61744. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  61745. {
  61746. updateCurrentModifiers();
  61747. FileDragAndDropTarget* lastTarget
  61748. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61749. FileDragAndDropTarget* newTarget = 0;
  61750. Component* const compUnderMouse = component->getComponentAt (position);
  61751. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  61752. {
  61753. lastDragAndDropCompUnderMouse = compUnderMouse;
  61754. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  61755. if (newTarget != lastTarget)
  61756. {
  61757. if (lastTarget != 0)
  61758. lastTarget->fileDragExit (files);
  61759. dragAndDropTargetComponent = 0;
  61760. if (newTarget != 0)
  61761. {
  61762. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  61763. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  61764. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  61765. }
  61766. }
  61767. }
  61768. else
  61769. {
  61770. newTarget = lastTarget;
  61771. }
  61772. if (newTarget != 0)
  61773. {
  61774. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  61775. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61776. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  61777. }
  61778. }
  61779. void ComponentPeer::handleFileDragExit (const StringArray& files)
  61780. {
  61781. handleFileDragMove (files, Point<int> (-1, -1));
  61782. jassert (dragAndDropTargetComponent == 0);
  61783. lastDragAndDropCompUnderMouse = 0;
  61784. }
  61785. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  61786. {
  61787. handleFileDragMove (files, position);
  61788. if (dragAndDropTargetComponent != 0)
  61789. {
  61790. FileDragAndDropTarget* const target
  61791. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61792. dragAndDropTargetComponent = 0;
  61793. lastDragAndDropCompUnderMouse = 0;
  61794. if (target != 0)
  61795. {
  61796. Component* const targetComp = dynamic_cast <Component*> (target);
  61797. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61798. {
  61799. targetComp->internalModalInputAttempt();
  61800. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61801. return;
  61802. }
  61803. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61804. target->filesDropped (files, pos.getX(), pos.getY());
  61805. }
  61806. }
  61807. }
  61808. void ComponentPeer::handleUserClosingWindow()
  61809. {
  61810. updateCurrentModifiers();
  61811. component->userTriedToCloseWindow();
  61812. }
  61813. void ComponentPeer::bringModalComponentToFront()
  61814. {
  61815. Component::bringModalComponentToFront();
  61816. }
  61817. void ComponentPeer::clearMaskedRegion()
  61818. {
  61819. maskedRegion.clear();
  61820. }
  61821. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  61822. {
  61823. maskedRegion.add (x, y, w, h);
  61824. }
  61825. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  61826. {
  61827. StringArray s;
  61828. s.add ("Software Renderer");
  61829. return s;
  61830. }
  61831. int ComponentPeer::getCurrentRenderingEngine() throw()
  61832. {
  61833. return 0;
  61834. }
  61835. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  61836. {
  61837. }
  61838. END_JUCE_NAMESPACE
  61839. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  61840. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  61841. BEGIN_JUCE_NAMESPACE
  61842. DialogWindow::DialogWindow (const String& name,
  61843. const Colour& backgroundColour_,
  61844. const bool escapeKeyTriggersCloseButton_,
  61845. const bool addToDesktop_)
  61846. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  61847. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  61848. {
  61849. }
  61850. DialogWindow::~DialogWindow()
  61851. {
  61852. }
  61853. void DialogWindow::resized()
  61854. {
  61855. DocumentWindow::resized();
  61856. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  61857. if (escapeKeyTriggersCloseButton
  61858. && getCloseButton() != 0
  61859. && ! getCloseButton()->isRegisteredForShortcut (esc))
  61860. {
  61861. getCloseButton()->addShortcut (esc);
  61862. }
  61863. }
  61864. class TempDialogWindow : public DialogWindow
  61865. {
  61866. public:
  61867. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  61868. : DialogWindow (title, colour, escapeCloses, true)
  61869. {
  61870. }
  61871. ~TempDialogWindow()
  61872. {
  61873. }
  61874. void closeButtonPressed()
  61875. {
  61876. setVisible (false);
  61877. }
  61878. private:
  61879. TempDialogWindow (const TempDialogWindow&);
  61880. TempDialogWindow& operator= (const TempDialogWindow&);
  61881. };
  61882. int DialogWindow::showModalDialog (const String& dialogTitle,
  61883. Component* contentComponent,
  61884. Component* componentToCentreAround,
  61885. const Colour& colour,
  61886. const bool escapeKeyTriggersCloseButton,
  61887. const bool shouldBeResizable,
  61888. const bool useBottomRightCornerResizer)
  61889. {
  61890. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  61891. dw.setContentComponent (contentComponent, true, true);
  61892. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  61893. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  61894. const int result = dw.runModalLoop();
  61895. dw.setContentComponent (0, false);
  61896. return result;
  61897. }
  61898. END_JUCE_NAMESPACE
  61899. /*** End of inlined file: juce_DialogWindow.cpp ***/
  61900. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  61901. BEGIN_JUCE_NAMESPACE
  61902. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  61903. {
  61904. public:
  61905. ButtonListenerProxy (DocumentWindow& owner_)
  61906. : owner (owner_)
  61907. {
  61908. }
  61909. void buttonClicked (Button* button)
  61910. {
  61911. if (button == owner.getMinimiseButton())
  61912. owner.minimiseButtonPressed();
  61913. else if (button == owner.getMaximiseButton())
  61914. owner.maximiseButtonPressed();
  61915. else if (button == owner.getCloseButton())
  61916. owner.closeButtonPressed();
  61917. }
  61918. juce_UseDebuggingNewOperator
  61919. private:
  61920. DocumentWindow& owner;
  61921. ButtonListenerProxy (const ButtonListenerProxy&);
  61922. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  61923. };
  61924. DocumentWindow::DocumentWindow (const String& title,
  61925. const Colour& backgroundColour,
  61926. const int requiredButtons_,
  61927. const bool addToDesktop_)
  61928. : ResizableWindow (title, backgroundColour, addToDesktop_),
  61929. titleBarHeight (26),
  61930. menuBarHeight (24),
  61931. requiredButtons (requiredButtons_),
  61932. #if JUCE_MAC
  61933. positionTitleBarButtonsOnLeft (true),
  61934. #else
  61935. positionTitleBarButtonsOnLeft (false),
  61936. #endif
  61937. drawTitleTextCentred (true),
  61938. menuBarModel (0)
  61939. {
  61940. setResizeLimits (128, 128, 32768, 32768);
  61941. lookAndFeelChanged();
  61942. }
  61943. DocumentWindow::~DocumentWindow()
  61944. {
  61945. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  61946. titleBarButtons[i] = 0;
  61947. menuBar = 0;
  61948. }
  61949. void DocumentWindow::repaintTitleBar()
  61950. {
  61951. const Rectangle<int> titleBarArea (getTitleBarArea());
  61952. repaint (titleBarArea.getX(), titleBarArea.getY(),
  61953. titleBarArea.getWidth(), titleBarArea.getHeight());
  61954. }
  61955. void DocumentWindow::setName (const String& newName)
  61956. {
  61957. if (newName != getName())
  61958. {
  61959. Component::setName (newName);
  61960. repaintTitleBar();
  61961. }
  61962. }
  61963. void DocumentWindow::setIcon (const Image* imageToUse)
  61964. {
  61965. titleBarIcon = imageToUse != 0 ? imageToUse->createCopy() : 0;
  61966. repaintTitleBar();
  61967. }
  61968. void DocumentWindow::setTitleBarHeight (const int newHeight)
  61969. {
  61970. titleBarHeight = newHeight;
  61971. resized();
  61972. repaintTitleBar();
  61973. }
  61974. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  61975. const bool positionTitleBarButtonsOnLeft_)
  61976. {
  61977. requiredButtons = requiredButtons_;
  61978. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  61979. lookAndFeelChanged();
  61980. }
  61981. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  61982. {
  61983. drawTitleTextCentred = textShouldBeCentred;
  61984. repaintTitleBar();
  61985. }
  61986. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  61987. const int menuBarHeight_)
  61988. {
  61989. if (menuBarModel != menuBarModel_)
  61990. {
  61991. menuBar = 0;
  61992. menuBarModel = menuBarModel_;
  61993. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  61994. : getLookAndFeel().getDefaultMenuBarHeight();
  61995. if (menuBarModel != 0)
  61996. {
  61997. // (call the Component method directly to avoid the assertion in ResizableWindow)
  61998. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  61999. menuBar->setEnabled (isActiveWindow());
  62000. }
  62001. resized();
  62002. }
  62003. }
  62004. void DocumentWindow::closeButtonPressed()
  62005. {
  62006. /* If you've got a close button, you have to override this method to get
  62007. rid of your window!
  62008. If the window is just a pop-up, you should override this method and make
  62009. it delete the window in whatever way is appropriate for your app. E.g. you
  62010. might just want to call "delete this".
  62011. If your app is centred around this window such that the whole app should quit when
  62012. the window is closed, then you will probably want to use this method as an opportunity
  62013. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62014. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62015. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62016. or closing it via the taskbar icon on Windows).
  62017. */
  62018. jassertfalse
  62019. }
  62020. void DocumentWindow::minimiseButtonPressed()
  62021. {
  62022. setMinimised (true);
  62023. }
  62024. void DocumentWindow::maximiseButtonPressed()
  62025. {
  62026. setFullScreen (! isFullScreen());
  62027. }
  62028. void DocumentWindow::paint (Graphics& g)
  62029. {
  62030. ResizableWindow::paint (g);
  62031. if (resizableBorder == 0)
  62032. {
  62033. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62034. const BorderSize border (getBorderThickness());
  62035. g.fillRect (0, 0, getWidth(), border.getTop());
  62036. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62037. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62038. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62039. }
  62040. const Rectangle<int> titleBarArea (getTitleBarArea());
  62041. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62042. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62043. int titleSpaceX1 = 6;
  62044. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62045. for (int i = 0; i < 3; ++i)
  62046. {
  62047. if (titleBarButtons[i] != 0)
  62048. {
  62049. if (positionTitleBarButtonsOnLeft)
  62050. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62051. else
  62052. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62053. }
  62054. }
  62055. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62056. titleBarArea.getWidth(),
  62057. titleBarArea.getHeight(),
  62058. titleSpaceX1,
  62059. jmax (1, titleSpaceX2 - titleSpaceX1),
  62060. titleBarIcon,
  62061. ! drawTitleTextCentred);
  62062. }
  62063. void DocumentWindow::resized()
  62064. {
  62065. ResizableWindow::resized();
  62066. if (titleBarButtons[1] != 0)
  62067. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62068. const Rectangle<int> titleBarArea (getTitleBarArea());
  62069. getLookAndFeel()
  62070. .positionDocumentWindowButtons (*this,
  62071. titleBarArea.getX(), titleBarArea.getY(),
  62072. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62073. titleBarButtons[0],
  62074. titleBarButtons[1],
  62075. titleBarButtons[2],
  62076. positionTitleBarButtonsOnLeft);
  62077. if (menuBar != 0)
  62078. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62079. titleBarArea.getWidth(), menuBarHeight);
  62080. }
  62081. const BorderSize DocumentWindow::getBorderThickness()
  62082. {
  62083. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62084. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62085. }
  62086. const BorderSize DocumentWindow::getContentComponentBorder()
  62087. {
  62088. BorderSize border (getBorderThickness());
  62089. border.setTop (border.getTop()
  62090. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62091. + (menuBar != 0 ? menuBarHeight : 0));
  62092. return border;
  62093. }
  62094. int DocumentWindow::getTitleBarHeight() const
  62095. {
  62096. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62097. }
  62098. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62099. {
  62100. const BorderSize border (getBorderThickness());
  62101. return Rectangle<int> (border.getLeft(), border.getTop(),
  62102. getWidth() - border.getLeftAndRight(),
  62103. getTitleBarHeight());
  62104. }
  62105. Button* DocumentWindow::getCloseButton() const throw()
  62106. {
  62107. return titleBarButtons[2];
  62108. }
  62109. Button* DocumentWindow::getMinimiseButton() const throw()
  62110. {
  62111. return titleBarButtons[0];
  62112. }
  62113. Button* DocumentWindow::getMaximiseButton() const throw()
  62114. {
  62115. return titleBarButtons[1];
  62116. }
  62117. int DocumentWindow::getDesktopWindowStyleFlags() const
  62118. {
  62119. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62120. if ((requiredButtons & minimiseButton) != 0)
  62121. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62122. if ((requiredButtons & maximiseButton) != 0)
  62123. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62124. if ((requiredButtons & closeButton) != 0)
  62125. styleFlags |= ComponentPeer::windowHasCloseButton;
  62126. return styleFlags;
  62127. }
  62128. void DocumentWindow::lookAndFeelChanged()
  62129. {
  62130. int i;
  62131. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62132. titleBarButtons[i] = 0;
  62133. if (! isUsingNativeTitleBar())
  62134. {
  62135. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62136. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62137. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62138. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62139. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62140. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62141. for (i = 0; i < 3; ++i)
  62142. {
  62143. if (titleBarButtons[i] != 0)
  62144. {
  62145. if (buttonListener == 0)
  62146. buttonListener = new ButtonListenerProxy (*this);
  62147. titleBarButtons[i]->addButtonListener (buttonListener);
  62148. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62149. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62150. Component::addAndMakeVisible (titleBarButtons[i]);
  62151. }
  62152. }
  62153. if (getCloseButton() != 0)
  62154. {
  62155. #if JUCE_MAC
  62156. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62157. #else
  62158. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62159. #endif
  62160. }
  62161. }
  62162. activeWindowStatusChanged();
  62163. ResizableWindow::lookAndFeelChanged();
  62164. }
  62165. void DocumentWindow::parentHierarchyChanged()
  62166. {
  62167. lookAndFeelChanged();
  62168. }
  62169. void DocumentWindow::activeWindowStatusChanged()
  62170. {
  62171. ResizableWindow::activeWindowStatusChanged();
  62172. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62173. if (titleBarButtons[i] != 0)
  62174. titleBarButtons[i]->setEnabled (isActiveWindow());
  62175. if (menuBar != 0)
  62176. menuBar->setEnabled (isActiveWindow());
  62177. }
  62178. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62179. {
  62180. if (getTitleBarArea().contains (e.x, e.y)
  62181. && getMaximiseButton() != 0)
  62182. {
  62183. getMaximiseButton()->triggerClick();
  62184. }
  62185. }
  62186. void DocumentWindow::userTriedToCloseWindow()
  62187. {
  62188. closeButtonPressed();
  62189. }
  62190. END_JUCE_NAMESPACE
  62191. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62192. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62193. BEGIN_JUCE_NAMESPACE
  62194. ResizableWindow::ResizableWindow (const String& name,
  62195. const bool addToDesktop_)
  62196. : TopLevelWindow (name, addToDesktop_),
  62197. resizeToFitContent (false),
  62198. fullscreen (false),
  62199. lastNonFullScreenPos (50, 50, 256, 256),
  62200. constrainer (0)
  62201. #if JUCE_DEBUG
  62202. , hasBeenResized (false)
  62203. #endif
  62204. {
  62205. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62206. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62207. if (addToDesktop_)
  62208. Component::addToDesktop (getDesktopWindowStyleFlags());
  62209. }
  62210. ResizableWindow::ResizableWindow (const String& name,
  62211. const Colour& backgroundColour_,
  62212. const bool addToDesktop_)
  62213. : TopLevelWindow (name, addToDesktop_),
  62214. resizeToFitContent (false),
  62215. fullscreen (false),
  62216. lastNonFullScreenPos (50, 50, 256, 256),
  62217. constrainer (0)
  62218. #if JUCE_DEBUG
  62219. , hasBeenResized (false)
  62220. #endif
  62221. {
  62222. setBackgroundColour (backgroundColour_);
  62223. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62224. if (addToDesktop_)
  62225. Component::addToDesktop (getDesktopWindowStyleFlags());
  62226. }
  62227. ResizableWindow::~ResizableWindow()
  62228. {
  62229. resizableCorner = 0;
  62230. resizableBorder = 0;
  62231. contentComponent = 0;
  62232. // have you been adding your own components directly to this window..? tut tut tut.
  62233. // Read the instructions for using a ResizableWindow!
  62234. jassert (getNumChildComponents() == 0);
  62235. }
  62236. int ResizableWindow::getDesktopWindowStyleFlags() const
  62237. {
  62238. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62239. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62240. styleFlags |= ComponentPeer::windowIsResizable;
  62241. return styleFlags;
  62242. }
  62243. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62244. const bool deleteOldOne,
  62245. const bool resizeToFit)
  62246. {
  62247. resizeToFitContent = resizeToFit;
  62248. if (newContentComponent != static_cast <Component*> (contentComponent))
  62249. {
  62250. if (! deleteOldOne)
  62251. removeChildComponent (contentComponent.release());
  62252. contentComponent = newContentComponent;
  62253. Component::addAndMakeVisible (contentComponent);
  62254. }
  62255. if (resizeToFit)
  62256. childBoundsChanged (contentComponent);
  62257. resized(); // must always be called to position the new content comp
  62258. }
  62259. void ResizableWindow::setContentComponentSize (int width, int height)
  62260. {
  62261. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62262. const BorderSize border (getContentComponentBorder());
  62263. setSize (width + border.getLeftAndRight(),
  62264. height + border.getTopAndBottom());
  62265. }
  62266. const BorderSize ResizableWindow::getBorderThickness()
  62267. {
  62268. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62269. }
  62270. const BorderSize ResizableWindow::getContentComponentBorder()
  62271. {
  62272. return getBorderThickness();
  62273. }
  62274. void ResizableWindow::moved()
  62275. {
  62276. updateLastPos();
  62277. }
  62278. void ResizableWindow::visibilityChanged()
  62279. {
  62280. TopLevelWindow::visibilityChanged();
  62281. updateLastPos();
  62282. }
  62283. void ResizableWindow::resized()
  62284. {
  62285. if (resizableBorder != 0)
  62286. {
  62287. resizableBorder->setVisible (! isFullScreen());
  62288. resizableBorder->setBorderThickness (getBorderThickness());
  62289. resizableBorder->setSize (getWidth(), getHeight());
  62290. resizableBorder->toBack();
  62291. }
  62292. if (resizableCorner != 0)
  62293. {
  62294. resizableCorner->setVisible (! isFullScreen());
  62295. const int resizerSize = 18;
  62296. resizableCorner->setBounds (getWidth() - resizerSize,
  62297. getHeight() - resizerSize,
  62298. resizerSize, resizerSize);
  62299. }
  62300. if (contentComponent != 0)
  62301. contentComponent->setBoundsInset (getContentComponentBorder());
  62302. updateLastPos();
  62303. #if JUCE_DEBUG
  62304. hasBeenResized = true;
  62305. #endif
  62306. }
  62307. void ResizableWindow::childBoundsChanged (Component* child)
  62308. {
  62309. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62310. {
  62311. // not going to look very good if this component has a zero size..
  62312. jassert (child->getWidth() > 0);
  62313. jassert (child->getHeight() > 0);
  62314. const BorderSize borders (getContentComponentBorder());
  62315. setSize (child->getWidth() + borders.getLeftAndRight(),
  62316. child->getHeight() + borders.getTopAndBottom());
  62317. }
  62318. }
  62319. void ResizableWindow::activeWindowStatusChanged()
  62320. {
  62321. const BorderSize borders (getContentComponentBorder());
  62322. repaint (0, 0, getWidth(), borders.getTop());
  62323. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62324. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62325. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62326. }
  62327. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62328. const bool useBottomRightCornerResizer)
  62329. {
  62330. if (shouldBeResizable)
  62331. {
  62332. if (useBottomRightCornerResizer)
  62333. {
  62334. resizableBorder = 0;
  62335. if (resizableCorner == 0)
  62336. {
  62337. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62338. resizableCorner->setAlwaysOnTop (true);
  62339. }
  62340. }
  62341. else
  62342. {
  62343. resizableCorner = 0;
  62344. if (resizableBorder == 0)
  62345. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62346. }
  62347. }
  62348. else
  62349. {
  62350. resizableCorner = 0;
  62351. resizableBorder = 0;
  62352. }
  62353. if (isUsingNativeTitleBar())
  62354. recreateDesktopWindow();
  62355. childBoundsChanged (contentComponent);
  62356. resized();
  62357. }
  62358. bool ResizableWindow::isResizable() const throw()
  62359. {
  62360. return resizableCorner != 0
  62361. || resizableBorder != 0;
  62362. }
  62363. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62364. const int newMinimumHeight,
  62365. const int newMaximumWidth,
  62366. const int newMaximumHeight) throw()
  62367. {
  62368. // if you've set up a custom constrainer then these settings won't have any effect..
  62369. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62370. if (constrainer == 0)
  62371. setConstrainer (&defaultConstrainer);
  62372. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62373. newMaximumWidth, newMaximumHeight);
  62374. setBoundsConstrained (getBounds());
  62375. }
  62376. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62377. {
  62378. if (constrainer != newConstrainer)
  62379. {
  62380. constrainer = newConstrainer;
  62381. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62382. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62383. resizableCorner = 0;
  62384. resizableBorder = 0;
  62385. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62386. ComponentPeer* const peer = getPeer();
  62387. if (peer != 0)
  62388. peer->setConstrainer (newConstrainer);
  62389. }
  62390. }
  62391. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62392. {
  62393. if (constrainer != 0)
  62394. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62395. else
  62396. setBounds (bounds);
  62397. }
  62398. void ResizableWindow::paint (Graphics& g)
  62399. {
  62400. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62401. getBorderThickness(), *this);
  62402. if (! isFullScreen())
  62403. {
  62404. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62405. getBorderThickness(), *this);
  62406. }
  62407. #if JUCE_DEBUG
  62408. /* If this fails, then you've probably written a subclass with a resized()
  62409. callback but forgotten to make it call its parent class's resized() method.
  62410. It's important when you override methods like resized(), moved(),
  62411. etc., that you make sure the base class methods also get called.
  62412. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62413. because your content should all be inside the content component - and it's the
  62414. content component's resized() method that you should be using to do your
  62415. layout.
  62416. */
  62417. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62418. #endif
  62419. }
  62420. void ResizableWindow::lookAndFeelChanged()
  62421. {
  62422. resized();
  62423. if (isOnDesktop())
  62424. {
  62425. Component::addToDesktop (getDesktopWindowStyleFlags());
  62426. ComponentPeer* const peer = getPeer();
  62427. if (peer != 0)
  62428. peer->setConstrainer (constrainer);
  62429. }
  62430. }
  62431. const Colour ResizableWindow::getBackgroundColour() const throw()
  62432. {
  62433. return findColour (backgroundColourId, false);
  62434. }
  62435. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62436. {
  62437. Colour backgroundColour (newColour);
  62438. if (! Desktop::canUseSemiTransparentWindows())
  62439. backgroundColour = newColour.withAlpha (1.0f);
  62440. setColour (backgroundColourId, backgroundColour);
  62441. setOpaque (backgroundColour.isOpaque());
  62442. repaint();
  62443. }
  62444. bool ResizableWindow::isFullScreen() const
  62445. {
  62446. if (isOnDesktop())
  62447. {
  62448. ComponentPeer* const peer = getPeer();
  62449. return peer != 0 && peer->isFullScreen();
  62450. }
  62451. return fullscreen;
  62452. }
  62453. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62454. {
  62455. if (shouldBeFullScreen != isFullScreen())
  62456. {
  62457. updateLastPos();
  62458. fullscreen = shouldBeFullScreen;
  62459. if (isOnDesktop())
  62460. {
  62461. ComponentPeer* const peer = getPeer();
  62462. if (peer != 0)
  62463. {
  62464. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62465. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62466. peer->setFullScreen (shouldBeFullScreen);
  62467. if (! shouldBeFullScreen)
  62468. setBounds (lastPos);
  62469. }
  62470. else
  62471. {
  62472. jassertfalse
  62473. }
  62474. }
  62475. else
  62476. {
  62477. if (shouldBeFullScreen)
  62478. setBounds (0, 0, getParentWidth(), getParentHeight());
  62479. else
  62480. setBounds (lastNonFullScreenPos);
  62481. }
  62482. resized();
  62483. }
  62484. }
  62485. bool ResizableWindow::isMinimised() const
  62486. {
  62487. ComponentPeer* const peer = getPeer();
  62488. return (peer != 0) && peer->isMinimised();
  62489. }
  62490. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62491. {
  62492. if (shouldMinimise != isMinimised())
  62493. {
  62494. ComponentPeer* const peer = getPeer();
  62495. if (peer != 0)
  62496. {
  62497. updateLastPos();
  62498. peer->setMinimised (shouldMinimise);
  62499. }
  62500. else
  62501. {
  62502. jassertfalse
  62503. }
  62504. }
  62505. }
  62506. void ResizableWindow::updateLastPos()
  62507. {
  62508. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62509. {
  62510. lastNonFullScreenPos = getBounds();
  62511. }
  62512. }
  62513. void ResizableWindow::parentSizeChanged()
  62514. {
  62515. if (isFullScreen() && getParentComponent() != 0)
  62516. {
  62517. setBounds (0, 0, getParentWidth(), getParentHeight());
  62518. }
  62519. }
  62520. const String ResizableWindow::getWindowStateAsString()
  62521. {
  62522. updateLastPos();
  62523. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62524. }
  62525. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62526. {
  62527. StringArray tokens;
  62528. tokens.addTokens (s, false);
  62529. tokens.removeEmptyStrings();
  62530. tokens.trim();
  62531. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62532. const int firstCoord = fs ? 1 : 0;
  62533. if (tokens.size() != firstCoord + 4)
  62534. return false;
  62535. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62536. tokens[firstCoord + 1].getIntValue(),
  62537. tokens[firstCoord + 2].getIntValue(),
  62538. tokens[firstCoord + 3].getIntValue());
  62539. if (newPos.isEmpty())
  62540. return false;
  62541. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62542. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62543. if (peer != 0)
  62544. peer->getFrameSize().addTo (newPos);
  62545. if (! screen.contains (newPos))
  62546. {
  62547. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62548. jmin (newPos.getHeight(), screen.getHeight()));
  62549. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62550. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62551. }
  62552. if (peer != 0)
  62553. {
  62554. peer->getFrameSize().subtractFrom (newPos);
  62555. peer->setNonFullScreenBounds (newPos);
  62556. }
  62557. lastNonFullScreenPos = newPos;
  62558. setFullScreen (fs);
  62559. if (! fs)
  62560. setBoundsConstrained (newPos);
  62561. return true;
  62562. }
  62563. void ResizableWindow::mouseDown (const MouseEvent&)
  62564. {
  62565. if (! isFullScreen())
  62566. dragger.startDraggingComponent (this, constrainer);
  62567. }
  62568. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62569. {
  62570. if (! isFullScreen())
  62571. dragger.dragComponent (this, e);
  62572. }
  62573. #if JUCE_DEBUG
  62574. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62575. {
  62576. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62577. manages its child components automatically, and if you add your own it'll cause
  62578. trouble. Instead, use setContentComponent() to give it a component which
  62579. will be automatically resized and kept in the right place - then you can add
  62580. subcomponents to the content comp. See the notes for the ResizableWindow class
  62581. for more info.
  62582. If you really know what you're doing and want to avoid this assertion, just call
  62583. Component::addChildComponent directly.
  62584. */
  62585. jassertfalse
  62586. Component::addChildComponent (child, zOrder);
  62587. }
  62588. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62589. {
  62590. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62591. manages its child components automatically, and if you add your own it'll cause
  62592. trouble. Instead, use setContentComponent() to give it a component which
  62593. will be automatically resized and kept in the right place - then you can add
  62594. subcomponents to the content comp. See the notes for the ResizableWindow class
  62595. for more info.
  62596. If you really know what you're doing and want to avoid this assertion, just call
  62597. Component::addAndMakeVisible directly.
  62598. */
  62599. jassertfalse
  62600. Component::addAndMakeVisible (child, zOrder);
  62601. }
  62602. #endif
  62603. END_JUCE_NAMESPACE
  62604. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62605. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62606. BEGIN_JUCE_NAMESPACE
  62607. SplashScreen::SplashScreen()
  62608. : backgroundImage (0)
  62609. {
  62610. setOpaque (true);
  62611. }
  62612. SplashScreen::~SplashScreen()
  62613. {
  62614. ImageCache::releaseOrDelete (backgroundImage);
  62615. }
  62616. void SplashScreen::show (const String& title,
  62617. Image* const backgroundImage_,
  62618. const int minimumTimeToDisplayFor,
  62619. const bool useDropShadow,
  62620. const bool removeOnMouseClick)
  62621. {
  62622. backgroundImage = backgroundImage_;
  62623. jassert (backgroundImage_ != 0);
  62624. if (backgroundImage_ != 0)
  62625. {
  62626. setOpaque (! backgroundImage_->hasAlphaChannel());
  62627. show (title,
  62628. backgroundImage_->getWidth(),
  62629. backgroundImage_->getHeight(),
  62630. minimumTimeToDisplayFor,
  62631. useDropShadow,
  62632. removeOnMouseClick);
  62633. }
  62634. }
  62635. void SplashScreen::show (const String& title,
  62636. const int width,
  62637. const int height,
  62638. const int minimumTimeToDisplayFor,
  62639. const bool useDropShadow,
  62640. const bool removeOnMouseClick)
  62641. {
  62642. setName (title);
  62643. setAlwaysOnTop (true);
  62644. setVisible (true);
  62645. centreWithSize (width, height);
  62646. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62647. toFront (false);
  62648. MessageManager::getInstance()->runDispatchLoopUntil (300);
  62649. repaint();
  62650. originalClickCounter = removeOnMouseClick
  62651. ? Desktop::getMouseButtonClickCounter()
  62652. : std::numeric_limits<int>::max();
  62653. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  62654. startTimer (50);
  62655. }
  62656. void SplashScreen::paint (Graphics& g)
  62657. {
  62658. if (backgroundImage != 0)
  62659. {
  62660. g.setOpacity (1.0f);
  62661. g.drawImage (backgroundImage,
  62662. 0, 0, getWidth(), getHeight(),
  62663. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  62664. }
  62665. }
  62666. void SplashScreen::timerCallback()
  62667. {
  62668. if (Time::getCurrentTime() > earliestTimeToDelete
  62669. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  62670. {
  62671. delete this;
  62672. }
  62673. }
  62674. END_JUCE_NAMESPACE
  62675. /*** End of inlined file: juce_SplashScreen.cpp ***/
  62676. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62677. BEGIN_JUCE_NAMESPACE
  62678. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  62679. const bool hasProgressBar,
  62680. const bool hasCancelButton,
  62681. const int timeOutMsWhenCancelling_,
  62682. const String& cancelButtonText)
  62683. : Thread ("Juce Progress Window"),
  62684. progress (0.0),
  62685. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  62686. {
  62687. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  62688. .createAlertWindow (title, String::empty, cancelButtonText,
  62689. String::empty, String::empty,
  62690. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  62691. if (hasProgressBar)
  62692. alertWindow->addProgressBarComponent (progress);
  62693. }
  62694. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  62695. {
  62696. stopThread (timeOutMsWhenCancelling);
  62697. }
  62698. bool ThreadWithProgressWindow::runThread (const int priority)
  62699. {
  62700. startThread (priority);
  62701. startTimer (100);
  62702. {
  62703. const ScopedLock sl (messageLock);
  62704. alertWindow->setMessage (message);
  62705. }
  62706. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  62707. stopThread (timeOutMsWhenCancelling);
  62708. alertWindow->setVisible (false);
  62709. return finishedNaturally;
  62710. }
  62711. void ThreadWithProgressWindow::setProgress (const double newProgress)
  62712. {
  62713. progress = newProgress;
  62714. }
  62715. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  62716. {
  62717. const ScopedLock sl (messageLock);
  62718. message = newStatusMessage;
  62719. }
  62720. void ThreadWithProgressWindow::timerCallback()
  62721. {
  62722. if (! isThreadRunning())
  62723. {
  62724. // thread has finished normally..
  62725. alertWindow->exitModalState (1);
  62726. alertWindow->setVisible (false);
  62727. }
  62728. else
  62729. {
  62730. const ScopedLock sl (messageLock);
  62731. alertWindow->setMessage (message);
  62732. }
  62733. }
  62734. END_JUCE_NAMESPACE
  62735. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62736. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  62737. BEGIN_JUCE_NAMESPACE
  62738. TooltipWindow::TooltipWindow (Component* const parentComponent,
  62739. const int millisecondsBeforeTipAppears_)
  62740. : Component ("tooltip"),
  62741. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  62742. mouseClicks (0),
  62743. lastHideTime (0),
  62744. lastComponentUnderMouse (0),
  62745. changedCompsSinceShown (true)
  62746. {
  62747. if (Desktop::getInstance().getMainMouseSource().canHover())
  62748. startTimer (123);
  62749. setAlwaysOnTop (true);
  62750. setOpaque (true);
  62751. if (parentComponent != 0)
  62752. parentComponent->addChildComponent (this);
  62753. }
  62754. TooltipWindow::~TooltipWindow()
  62755. {
  62756. hide();
  62757. }
  62758. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  62759. {
  62760. millisecondsBeforeTipAppears = newTimeMs;
  62761. }
  62762. void TooltipWindow::paint (Graphics& g)
  62763. {
  62764. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  62765. }
  62766. void TooltipWindow::mouseEnter (const MouseEvent&)
  62767. {
  62768. hide();
  62769. }
  62770. void TooltipWindow::showFor (const String& tip)
  62771. {
  62772. jassert (tip.isNotEmpty());
  62773. tipShowing = tip;
  62774. Point<int> mousePos (Desktop::getMousePosition());
  62775. if (getParentComponent() != 0)
  62776. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  62777. int x, y, w, h;
  62778. getLookAndFeel().getTooltipSize (tip, w, h);
  62779. if (mousePos.getX() > getParentWidth() / 2)
  62780. x = mousePos.getX() - (w + 12);
  62781. else
  62782. x = mousePos.getX() + 24;
  62783. if (mousePos.getY() > getParentHeight() / 2)
  62784. y = mousePos.getY() - (h + 6);
  62785. else
  62786. y = mousePos.getY() + 6;
  62787. setBounds (x, y, w, h);
  62788. setVisible (true);
  62789. if (getParentComponent() == 0)
  62790. {
  62791. addToDesktop (ComponentPeer::windowHasDropShadow
  62792. | ComponentPeer::windowIsTemporary
  62793. | ComponentPeer::windowIgnoresKeyPresses);
  62794. }
  62795. toFront (false);
  62796. }
  62797. const String TooltipWindow::getTipFor (Component* const c)
  62798. {
  62799. if (c != 0
  62800. && Process::isForegroundProcess()
  62801. && ! Component::isMouseButtonDownAnywhere())
  62802. {
  62803. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  62804. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  62805. return ttc->getTooltip();
  62806. }
  62807. return String::empty;
  62808. }
  62809. void TooltipWindow::hide()
  62810. {
  62811. tipShowing = String::empty;
  62812. removeFromDesktop();
  62813. setVisible (false);
  62814. }
  62815. void TooltipWindow::timerCallback()
  62816. {
  62817. const unsigned int now = Time::getApproximateMillisecondCounter();
  62818. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62819. const String newTip (getTipFor (newComp));
  62820. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  62821. lastComponentUnderMouse = newComp;
  62822. lastTipUnderMouse = newTip;
  62823. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  62824. const bool mouseWasClicked = clickCount > mouseClicks;
  62825. mouseClicks = clickCount;
  62826. const Point<int> mousePos (Desktop::getMousePosition());
  62827. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  62828. lastMousePos = mousePos;
  62829. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  62830. lastCompChangeTime = now;
  62831. if (isVisible() || now < lastHideTime + 500)
  62832. {
  62833. // if a tip is currently visible (or has just disappeared), update to a new one
  62834. // immediately if needed..
  62835. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  62836. {
  62837. if (isVisible())
  62838. {
  62839. lastHideTime = now;
  62840. hide();
  62841. }
  62842. }
  62843. else if (tipChanged)
  62844. {
  62845. showFor (newTip);
  62846. }
  62847. }
  62848. else
  62849. {
  62850. // if there isn't currently a tip, but one is needed, only let it
  62851. // appear after a timeout..
  62852. if (newTip.isNotEmpty()
  62853. && newTip != tipShowing
  62854. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  62855. {
  62856. showFor (newTip);
  62857. }
  62858. }
  62859. }
  62860. END_JUCE_NAMESPACE
  62861. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  62862. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  62863. BEGIN_JUCE_NAMESPACE
  62864. /** Keeps track of the active top level window.
  62865. */
  62866. class TopLevelWindowManager : public Timer,
  62867. public DeletedAtShutdown
  62868. {
  62869. public:
  62870. TopLevelWindowManager()
  62871. : currentActive (0)
  62872. {
  62873. }
  62874. ~TopLevelWindowManager()
  62875. {
  62876. clearSingletonInstance();
  62877. }
  62878. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  62879. void timerCallback()
  62880. {
  62881. startTimer (jmin (1731, getTimerInterval() * 2));
  62882. TopLevelWindow* active = 0;
  62883. if (Process::isForegroundProcess())
  62884. {
  62885. active = currentActive;
  62886. Component* const c = Component::getCurrentlyFocusedComponent();
  62887. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  62888. if (tlw == 0 && c != 0)
  62889. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  62890. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  62891. if (tlw != 0)
  62892. active = tlw;
  62893. }
  62894. if (active != currentActive)
  62895. {
  62896. currentActive = active;
  62897. for (int i = windows.size(); --i >= 0;)
  62898. {
  62899. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  62900. tlw->setWindowActive (isWindowActive (tlw));
  62901. i = jmin (i, windows.size() - 1);
  62902. }
  62903. Desktop::getInstance().triggerFocusCallback();
  62904. }
  62905. }
  62906. bool addWindow (TopLevelWindow* const w)
  62907. {
  62908. windows.add (w);
  62909. startTimer (10);
  62910. return isWindowActive (w);
  62911. }
  62912. void removeWindow (TopLevelWindow* const w)
  62913. {
  62914. startTimer (10);
  62915. if (currentActive == w)
  62916. currentActive = 0;
  62917. windows.removeValue (w);
  62918. if (windows.size() == 0)
  62919. deleteInstance();
  62920. }
  62921. VoidArray windows;
  62922. private:
  62923. TopLevelWindow* currentActive;
  62924. bool isWindowActive (TopLevelWindow* const tlw) const
  62925. {
  62926. return (tlw == currentActive
  62927. || tlw->isParentOf (currentActive)
  62928. || tlw->hasKeyboardFocus (true))
  62929. && tlw->isShowing();
  62930. }
  62931. TopLevelWindowManager (const TopLevelWindowManager&);
  62932. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  62933. };
  62934. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  62935. void juce_CheckCurrentlyFocusedTopLevelWindow()
  62936. {
  62937. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  62938. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  62939. }
  62940. TopLevelWindow::TopLevelWindow (const String& name,
  62941. const bool addToDesktop_)
  62942. : Component (name),
  62943. useDropShadow (true),
  62944. useNativeTitleBar (false),
  62945. windowIsActive_ (false)
  62946. {
  62947. setOpaque (true);
  62948. if (addToDesktop_)
  62949. Component::addToDesktop (getDesktopWindowStyleFlags());
  62950. else
  62951. setDropShadowEnabled (true);
  62952. setWantsKeyboardFocus (true);
  62953. setBroughtToFrontOnMouseClick (true);
  62954. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  62955. }
  62956. TopLevelWindow::~TopLevelWindow()
  62957. {
  62958. shadower = 0;
  62959. TopLevelWindowManager::getInstance()->removeWindow (this);
  62960. }
  62961. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  62962. {
  62963. if (hasKeyboardFocus (true))
  62964. TopLevelWindowManager::getInstance()->timerCallback();
  62965. else
  62966. TopLevelWindowManager::getInstance()->startTimer (10);
  62967. }
  62968. void TopLevelWindow::setWindowActive (const bool isNowActive)
  62969. {
  62970. if (windowIsActive_ != isNowActive)
  62971. {
  62972. windowIsActive_ = isNowActive;
  62973. activeWindowStatusChanged();
  62974. }
  62975. }
  62976. void TopLevelWindow::activeWindowStatusChanged()
  62977. {
  62978. }
  62979. void TopLevelWindow::parentHierarchyChanged()
  62980. {
  62981. setDropShadowEnabled (useDropShadow);
  62982. }
  62983. void TopLevelWindow::visibilityChanged()
  62984. {
  62985. if (isShowing())
  62986. toFront (true);
  62987. }
  62988. int TopLevelWindow::getDesktopWindowStyleFlags() const
  62989. {
  62990. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  62991. if (useDropShadow)
  62992. styleFlags |= ComponentPeer::windowHasDropShadow;
  62993. if (useNativeTitleBar)
  62994. styleFlags |= ComponentPeer::windowHasTitleBar;
  62995. return styleFlags;
  62996. }
  62997. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  62998. {
  62999. useDropShadow = useShadow;
  63000. if (isOnDesktop())
  63001. {
  63002. shadower = 0;
  63003. Component::addToDesktop (getDesktopWindowStyleFlags());
  63004. }
  63005. else
  63006. {
  63007. if (useShadow && isOpaque())
  63008. {
  63009. if (shadower == 0)
  63010. {
  63011. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63012. if (shadower != 0)
  63013. shadower->setOwner (this);
  63014. }
  63015. }
  63016. else
  63017. {
  63018. shadower = 0;
  63019. }
  63020. }
  63021. }
  63022. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63023. {
  63024. if (useNativeTitleBar != useNativeTitleBar_)
  63025. {
  63026. useNativeTitleBar = useNativeTitleBar_;
  63027. recreateDesktopWindow();
  63028. sendLookAndFeelChange();
  63029. }
  63030. }
  63031. void TopLevelWindow::recreateDesktopWindow()
  63032. {
  63033. if (isOnDesktop())
  63034. {
  63035. Component::addToDesktop (getDesktopWindowStyleFlags());
  63036. toFront (true);
  63037. }
  63038. }
  63039. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63040. {
  63041. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63042. because this class needs to make sure its layout corresponds with settings like whether
  63043. it's got a native title bar or not.
  63044. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63045. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63046. method, then add or remove whatever flags are necessary from this value before returning it.
  63047. */
  63048. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63049. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63050. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63051. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63052. sendLookAndFeelChange();
  63053. }
  63054. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63055. {
  63056. if (c == 0)
  63057. c = TopLevelWindow::getActiveTopLevelWindow();
  63058. if (c == 0)
  63059. {
  63060. centreWithSize (width, height);
  63061. }
  63062. else
  63063. {
  63064. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63065. (c->getHeight() - height) / 2)));
  63066. Rectangle<int> parentArea (c->getParentMonitorArea());
  63067. if (getParentComponent() != 0)
  63068. {
  63069. p = getParentComponent()->globalPositionToRelative (p);
  63070. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63071. }
  63072. parentArea.reduce (12, 12);
  63073. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63074. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63075. width, height);
  63076. }
  63077. }
  63078. int TopLevelWindow::getNumTopLevelWindows() throw()
  63079. {
  63080. return TopLevelWindowManager::getInstance()->windows.size();
  63081. }
  63082. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63083. {
  63084. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63085. }
  63086. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63087. {
  63088. TopLevelWindow* best = 0;
  63089. int bestNumTWLParents = -1;
  63090. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63091. {
  63092. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63093. if (tlw->isActiveWindow())
  63094. {
  63095. int numTWLParents = 0;
  63096. const Component* c = tlw->getParentComponent();
  63097. while (c != 0)
  63098. {
  63099. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63100. ++numTWLParents;
  63101. c = c->getParentComponent();
  63102. }
  63103. if (bestNumTWLParents < numTWLParents)
  63104. {
  63105. best = tlw;
  63106. bestNumTWLParents = numTWLParents;
  63107. }
  63108. }
  63109. }
  63110. return best;
  63111. }
  63112. END_JUCE_NAMESPACE
  63113. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63114. #endif
  63115. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63116. /*** Start of inlined file: juce_Colour.cpp ***/
  63117. BEGIN_JUCE_NAMESPACE
  63118. namespace ColourHelpers
  63119. {
  63120. static uint8 floatAlphaToInt (const float alpha) throw()
  63121. {
  63122. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63123. }
  63124. static void convertHSBtoRGB (float h, float s, float v,
  63125. uint8& r, uint8& g, uint8& b) throw()
  63126. {
  63127. v = jlimit (0.0f, 1.0f, v);
  63128. v *= 255.0f;
  63129. const uint8 intV = (uint8) roundToInt (v);
  63130. if (s <= 0)
  63131. {
  63132. r = intV;
  63133. g = intV;
  63134. b = intV;
  63135. }
  63136. else
  63137. {
  63138. s = jmin (1.0f, s);
  63139. h = jlimit (0.0f, 1.0f, h);
  63140. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63141. const float f = h - floorf (h);
  63142. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63143. const float y = v * (1.0f - s * f);
  63144. const float z = v * (1.0f - (s * (1.0f - f)));
  63145. if (h < 1.0f)
  63146. {
  63147. r = intV;
  63148. g = (uint8) roundToInt (z);
  63149. b = x;
  63150. }
  63151. else if (h < 2.0f)
  63152. {
  63153. r = (uint8) roundToInt (y);
  63154. g = intV;
  63155. b = x;
  63156. }
  63157. else if (h < 3.0f)
  63158. {
  63159. r = x;
  63160. g = intV;
  63161. b = (uint8) roundToInt (z);
  63162. }
  63163. else if (h < 4.0f)
  63164. {
  63165. r = x;
  63166. g = (uint8) roundToInt (y);
  63167. b = intV;
  63168. }
  63169. else if (h < 5.0f)
  63170. {
  63171. r = (uint8) roundToInt (z);
  63172. g = x;
  63173. b = intV;
  63174. }
  63175. else if (h < 6.0f)
  63176. {
  63177. r = intV;
  63178. g = x;
  63179. b = (uint8) roundToInt (y);
  63180. }
  63181. else
  63182. {
  63183. r = 0;
  63184. g = 0;
  63185. b = 0;
  63186. }
  63187. }
  63188. }
  63189. }
  63190. Colour::Colour() throw()
  63191. : argb (0)
  63192. {
  63193. }
  63194. Colour::Colour (const Colour& other) throw()
  63195. : argb (other.argb)
  63196. {
  63197. }
  63198. Colour& Colour::operator= (const Colour& other) throw()
  63199. {
  63200. argb = other.argb;
  63201. return *this;
  63202. }
  63203. bool Colour::operator== (const Colour& other) const throw()
  63204. {
  63205. return argb.getARGB() == other.argb.getARGB();
  63206. }
  63207. bool Colour::operator!= (const Colour& other) const throw()
  63208. {
  63209. return argb.getARGB() != other.argb.getARGB();
  63210. }
  63211. Colour::Colour (const uint32 argb_) throw()
  63212. : argb (argb_)
  63213. {
  63214. }
  63215. Colour::Colour (const uint8 red,
  63216. const uint8 green,
  63217. const uint8 blue) throw()
  63218. {
  63219. argb.setARGB (0xff, red, green, blue);
  63220. }
  63221. const Colour Colour::fromRGB (const uint8 red,
  63222. const uint8 green,
  63223. const uint8 blue) throw()
  63224. {
  63225. return Colour (red, green, blue);
  63226. }
  63227. Colour::Colour (const uint8 red,
  63228. const uint8 green,
  63229. const uint8 blue,
  63230. const uint8 alpha) throw()
  63231. {
  63232. argb.setARGB (alpha, red, green, blue);
  63233. }
  63234. const Colour Colour::fromRGBA (const uint8 red,
  63235. const uint8 green,
  63236. const uint8 blue,
  63237. const uint8 alpha) throw()
  63238. {
  63239. return Colour (red, green, blue, alpha);
  63240. }
  63241. Colour::Colour (const uint8 red,
  63242. const uint8 green,
  63243. const uint8 blue,
  63244. const float alpha) throw()
  63245. {
  63246. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63247. }
  63248. const Colour Colour::fromRGBAFloat (const uint8 red,
  63249. const uint8 green,
  63250. const uint8 blue,
  63251. const float alpha) throw()
  63252. {
  63253. return Colour (red, green, blue, alpha);
  63254. }
  63255. Colour::Colour (const float hue,
  63256. const float saturation,
  63257. const float brightness,
  63258. const float alpha) throw()
  63259. {
  63260. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63261. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63262. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63263. }
  63264. const Colour Colour::fromHSV (const float hue,
  63265. const float saturation,
  63266. const float brightness,
  63267. const float alpha) throw()
  63268. {
  63269. return Colour (hue, saturation, brightness, alpha);
  63270. }
  63271. Colour::Colour (const float hue,
  63272. const float saturation,
  63273. const float brightness,
  63274. const uint8 alpha) throw()
  63275. {
  63276. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63277. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63278. argb.setARGB (alpha, r, g, b);
  63279. }
  63280. Colour::~Colour() throw()
  63281. {
  63282. }
  63283. const PixelARGB Colour::getPixelARGB() const throw()
  63284. {
  63285. PixelARGB p (argb);
  63286. p.premultiply();
  63287. return p;
  63288. }
  63289. uint32 Colour::getARGB() const throw()
  63290. {
  63291. return argb.getARGB();
  63292. }
  63293. bool Colour::isTransparent() const throw()
  63294. {
  63295. return getAlpha() == 0;
  63296. }
  63297. bool Colour::isOpaque() const throw()
  63298. {
  63299. return getAlpha() == 0xff;
  63300. }
  63301. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63302. {
  63303. PixelARGB newCol (argb);
  63304. newCol.setAlpha (newAlpha);
  63305. return Colour (newCol.getARGB());
  63306. }
  63307. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63308. {
  63309. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63310. PixelARGB newCol (argb);
  63311. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63312. return Colour (newCol.getARGB());
  63313. }
  63314. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63315. {
  63316. jassert (alphaMultiplier >= 0);
  63317. PixelARGB newCol (argb);
  63318. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63319. return Colour (newCol.getARGB());
  63320. }
  63321. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63322. {
  63323. const int destAlpha = getAlpha();
  63324. if (destAlpha > 0)
  63325. {
  63326. const int invA = 0xff - (int) src.getAlpha();
  63327. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63328. if (resA > 0)
  63329. {
  63330. const int da = (invA * destAlpha) / resA;
  63331. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63332. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63333. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63334. (uint8) resA);
  63335. }
  63336. return *this;
  63337. }
  63338. else
  63339. {
  63340. return src;
  63341. }
  63342. }
  63343. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63344. {
  63345. if (proportionOfOther <= 0)
  63346. return *this;
  63347. if (proportionOfOther >= 1.0f)
  63348. return other;
  63349. PixelARGB c1 (getPixelARGB());
  63350. const PixelARGB c2 (other.getPixelARGB());
  63351. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63352. c1.unpremultiply();
  63353. return Colour (c1.getARGB());
  63354. }
  63355. float Colour::getFloatRed() const throw()
  63356. {
  63357. return getRed() / 255.0f;
  63358. }
  63359. float Colour::getFloatGreen() const throw()
  63360. {
  63361. return getGreen() / 255.0f;
  63362. }
  63363. float Colour::getFloatBlue() const throw()
  63364. {
  63365. return getBlue() / 255.0f;
  63366. }
  63367. float Colour::getFloatAlpha() const throw()
  63368. {
  63369. return getAlpha() / 255.0f;
  63370. }
  63371. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63372. {
  63373. const int r = getRed();
  63374. const int g = getGreen();
  63375. const int b = getBlue();
  63376. const int hi = jmax (r, g, b);
  63377. const int lo = jmin (r, g, b);
  63378. if (hi != 0)
  63379. {
  63380. s = (hi - lo) / (float) hi;
  63381. if (s != 0)
  63382. {
  63383. const float invDiff = 1.0f / (hi - lo);
  63384. const float red = (hi - r) * invDiff;
  63385. const float green = (hi - g) * invDiff;
  63386. const float blue = (hi - b) * invDiff;
  63387. if (r == hi)
  63388. h = blue - green;
  63389. else if (g == hi)
  63390. h = 2.0f + red - blue;
  63391. else
  63392. h = 4.0f + green - red;
  63393. h *= 1.0f / 6.0f;
  63394. if (h < 0)
  63395. ++h;
  63396. }
  63397. else
  63398. {
  63399. h = 0;
  63400. }
  63401. }
  63402. else
  63403. {
  63404. s = 0;
  63405. h = 0;
  63406. }
  63407. v = hi / 255.0f;
  63408. }
  63409. float Colour::getHue() const throw()
  63410. {
  63411. float h, s, b;
  63412. getHSB (h, s, b);
  63413. return h;
  63414. }
  63415. const Colour Colour::withHue (const float hue) const throw()
  63416. {
  63417. float h, s, b;
  63418. getHSB (h, s, b);
  63419. return Colour (hue, s, b, getAlpha());
  63420. }
  63421. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63422. {
  63423. float h, s, b;
  63424. getHSB (h, s, b);
  63425. h += amountToRotate;
  63426. h -= floorf (h);
  63427. return Colour (h, s, b, getAlpha());
  63428. }
  63429. float Colour::getSaturation() const throw()
  63430. {
  63431. float h, s, b;
  63432. getHSB (h, s, b);
  63433. return s;
  63434. }
  63435. const Colour Colour::withSaturation (const float saturation) const throw()
  63436. {
  63437. float h, s, b;
  63438. getHSB (h, s, b);
  63439. return Colour (h, saturation, b, getAlpha());
  63440. }
  63441. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63442. {
  63443. float h, s, b;
  63444. getHSB (h, s, b);
  63445. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63446. }
  63447. float Colour::getBrightness() const throw()
  63448. {
  63449. float h, s, b;
  63450. getHSB (h, s, b);
  63451. return b;
  63452. }
  63453. const Colour Colour::withBrightness (const float brightness) const throw()
  63454. {
  63455. float h, s, b;
  63456. getHSB (h, s, b);
  63457. return Colour (h, s, brightness, getAlpha());
  63458. }
  63459. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63460. {
  63461. float h, s, b;
  63462. getHSB (h, s, b);
  63463. b *= amount;
  63464. if (b > 1.0f)
  63465. b = 1.0f;
  63466. return Colour (h, s, b, getAlpha());
  63467. }
  63468. const Colour Colour::brighter (float amount) const throw()
  63469. {
  63470. amount = 1.0f / (1.0f + amount);
  63471. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63472. (uint8) (255 - (amount * (255 - getGreen()))),
  63473. (uint8) (255 - (amount * (255 - getBlue()))),
  63474. getAlpha());
  63475. }
  63476. const Colour Colour::darker (float amount) const throw()
  63477. {
  63478. amount = 1.0f / (1.0f + amount);
  63479. return Colour ((uint8) (amount * getRed()),
  63480. (uint8) (amount * getGreen()),
  63481. (uint8) (amount * getBlue()),
  63482. getAlpha());
  63483. }
  63484. const Colour Colour::greyLevel (const float brightness) throw()
  63485. {
  63486. const uint8 level
  63487. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63488. return Colour (level, level, level);
  63489. }
  63490. const Colour Colour::contrasting (const float amount) const throw()
  63491. {
  63492. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63493. ? Colours::black
  63494. : Colours::white).withAlpha (amount));
  63495. }
  63496. const Colour Colour::contrasting (const Colour& colour1,
  63497. const Colour& colour2) throw()
  63498. {
  63499. const float b1 = colour1.getBrightness();
  63500. const float b2 = colour2.getBrightness();
  63501. float best = 0.0f;
  63502. float bestDist = 0.0f;
  63503. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63504. {
  63505. const float d1 = fabsf (i - b1);
  63506. const float d2 = fabsf (i - b2);
  63507. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63508. if (dist > bestDist)
  63509. {
  63510. best = i;
  63511. bestDist = dist;
  63512. }
  63513. }
  63514. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63515. .withBrightness (best);
  63516. }
  63517. const String Colour::toString() const
  63518. {
  63519. return String::toHexString ((int) argb.getARGB());
  63520. }
  63521. const Colour Colour::fromString (const String& encodedColourString)
  63522. {
  63523. return Colour ((uint32) encodedColourString.getHexValue32());
  63524. }
  63525. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63526. {
  63527. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63528. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63529. .toUpperCase();
  63530. }
  63531. END_JUCE_NAMESPACE
  63532. /*** End of inlined file: juce_Colour.cpp ***/
  63533. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63534. BEGIN_JUCE_NAMESPACE
  63535. ColourGradient::ColourGradient() throw()
  63536. {
  63537. #if JUCE_DEBUG
  63538. x1 = 987654.0f;
  63539. #endif
  63540. }
  63541. ColourGradient::ColourGradient (const Colour& colour1,
  63542. const float x1_,
  63543. const float y1_,
  63544. const Colour& colour2,
  63545. const float x2_,
  63546. const float y2_,
  63547. const bool isRadial_)
  63548. : x1 (x1_),
  63549. y1 (y1_),
  63550. x2 (x2_),
  63551. y2 (y2_),
  63552. isRadial (isRadial_)
  63553. {
  63554. colours.add (0);
  63555. colours.add (colour1.getARGB());
  63556. colours.add (1 << 16);
  63557. colours.add (colour2.getARGB());
  63558. }
  63559. ColourGradient::~ColourGradient()
  63560. {
  63561. }
  63562. void ColourGradient::clearColours()
  63563. {
  63564. colours.clear();
  63565. }
  63566. void ColourGradient::addColour (const double proportionAlongGradient,
  63567. const Colour& colour)
  63568. {
  63569. // must be within the two end-points
  63570. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63571. const uint32 pos = jlimit (0, 65535, roundToInt (proportionAlongGradient * 65536.0));
  63572. int i;
  63573. for (i = 0; i < colours.size(); i += 2)
  63574. if (colours.getUnchecked(i) > pos)
  63575. break;
  63576. colours.insert (i, pos);
  63577. colours.insert (i + 1, colour.getARGB());
  63578. }
  63579. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63580. {
  63581. for (int i = 1; i < colours.size(); i += 2)
  63582. {
  63583. const Colour c (colours.getUnchecked(i));
  63584. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  63585. }
  63586. }
  63587. int ColourGradient::getNumColours() const throw()
  63588. {
  63589. return colours.size() >> 1;
  63590. }
  63591. double ColourGradient::getColourPosition (const int index) const throw()
  63592. {
  63593. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  63594. }
  63595. const Colour ColourGradient::getColour (const int index) const throw()
  63596. {
  63597. return Colour (colours [(index << 1) + 1]);
  63598. }
  63599. const Colour ColourGradient::getColourAtPosition (const float position) const throw()
  63600. {
  63601. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63602. const int integerPos = jlimit (0, 65535, roundToInt (position * 65536.0f));
  63603. if (integerPos <= 0 || colours.size() <= 2)
  63604. return getColour (0);
  63605. int i = colours.size() - 2;
  63606. while (integerPos < (int) colours.getUnchecked(i))
  63607. i -= 2;
  63608. if (i >= colours.size() - 2)
  63609. return Colour (colours.getUnchecked(i));
  63610. const int pos1 = colours.getUnchecked (i);
  63611. const Colour col1 (colours.getUnchecked (i + 1));
  63612. const int pos2 = colours.getUnchecked (i + 2);
  63613. const Colour col2 (colours.getUnchecked (i + 3));
  63614. return col1.interpolatedWith (col2, (integerPos - pos1) / (float) (pos2 - pos1));
  63615. }
  63616. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  63617. {
  63618. #if JUCE_DEBUG
  63619. // trying to use the object without setting its co-ordinates? Have a careful read of
  63620. // the comments for the constructors.
  63621. jassert (x1 != 987654.0f);
  63622. #endif
  63623. const int numColours = colours.size() >> 1;
  63624. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  63625. transform.transformPoint (tx1, ty1);
  63626. transform.transformPoint (tx2, ty2);
  63627. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  63628. const int numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  63629. lookupTable.malloc (numEntries);
  63630. if (numColours >= 2)
  63631. {
  63632. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63633. PixelARGB pix1 (colours.getUnchecked (1));
  63634. pix1.premultiply();
  63635. int index = 0;
  63636. for (int j = 2; j < colours.size(); j += 2)
  63637. {
  63638. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  63639. PixelARGB pix2 (colours.getUnchecked (j + 1));
  63640. pix2.premultiply();
  63641. for (int i = 0; i < numToDo; ++i)
  63642. {
  63643. jassert (index >= 0 && index < numEntries);
  63644. lookupTable[index] = pix1;
  63645. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  63646. ++index;
  63647. }
  63648. pix1 = pix2;
  63649. }
  63650. while (index < numEntries)
  63651. lookupTable [index++] = pix1;
  63652. }
  63653. else
  63654. {
  63655. jassertfalse // no colours specified!
  63656. }
  63657. return numEntries;
  63658. }
  63659. bool ColourGradient::isOpaque() const throw()
  63660. {
  63661. for (int i = 1; i < colours.size(); i += 2)
  63662. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  63663. return false;
  63664. return true;
  63665. }
  63666. bool ColourGradient::isInvisible() const throw()
  63667. {
  63668. for (int i = 1; i < colours.size(); i += 2)
  63669. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  63670. return false;
  63671. return true;
  63672. }
  63673. END_JUCE_NAMESPACE
  63674. /*** End of inlined file: juce_ColourGradient.cpp ***/
  63675. /*** Start of inlined file: juce_Colours.cpp ***/
  63676. BEGIN_JUCE_NAMESPACE
  63677. const Colour Colours::transparentBlack (0);
  63678. const Colour Colours::transparentWhite (0x00ffffff);
  63679. const Colour Colours::aliceblue (0xfff0f8ff);
  63680. const Colour Colours::antiquewhite (0xfffaebd7);
  63681. const Colour Colours::aqua (0xff00ffff);
  63682. const Colour Colours::aquamarine (0xff7fffd4);
  63683. const Colour Colours::azure (0xfff0ffff);
  63684. const Colour Colours::beige (0xfff5f5dc);
  63685. const Colour Colours::bisque (0xffffe4c4);
  63686. const Colour Colours::black (0xff000000);
  63687. const Colour Colours::blanchedalmond (0xffffebcd);
  63688. const Colour Colours::blue (0xff0000ff);
  63689. const Colour Colours::blueviolet (0xff8a2be2);
  63690. const Colour Colours::brown (0xffa52a2a);
  63691. const Colour Colours::burlywood (0xffdeb887);
  63692. const Colour Colours::cadetblue (0xff5f9ea0);
  63693. const Colour Colours::chartreuse (0xff7fff00);
  63694. const Colour Colours::chocolate (0xffd2691e);
  63695. const Colour Colours::coral (0xffff7f50);
  63696. const Colour Colours::cornflowerblue (0xff6495ed);
  63697. const Colour Colours::cornsilk (0xfffff8dc);
  63698. const Colour Colours::crimson (0xffdc143c);
  63699. const Colour Colours::cyan (0xff00ffff);
  63700. const Colour Colours::darkblue (0xff00008b);
  63701. const Colour Colours::darkcyan (0xff008b8b);
  63702. const Colour Colours::darkgoldenrod (0xffb8860b);
  63703. const Colour Colours::darkgrey (0xff555555);
  63704. const Colour Colours::darkgreen (0xff006400);
  63705. const Colour Colours::darkkhaki (0xffbdb76b);
  63706. const Colour Colours::darkmagenta (0xff8b008b);
  63707. const Colour Colours::darkolivegreen (0xff556b2f);
  63708. const Colour Colours::darkorange (0xffff8c00);
  63709. const Colour Colours::darkorchid (0xff9932cc);
  63710. const Colour Colours::darkred (0xff8b0000);
  63711. const Colour Colours::darksalmon (0xffe9967a);
  63712. const Colour Colours::darkseagreen (0xff8fbc8f);
  63713. const Colour Colours::darkslateblue (0xff483d8b);
  63714. const Colour Colours::darkslategrey (0xff2f4f4f);
  63715. const Colour Colours::darkturquoise (0xff00ced1);
  63716. const Colour Colours::darkviolet (0xff9400d3);
  63717. const Colour Colours::deeppink (0xffff1493);
  63718. const Colour Colours::deepskyblue (0xff00bfff);
  63719. const Colour Colours::dimgrey (0xff696969);
  63720. const Colour Colours::dodgerblue (0xff1e90ff);
  63721. const Colour Colours::firebrick (0xffb22222);
  63722. const Colour Colours::floralwhite (0xfffffaf0);
  63723. const Colour Colours::forestgreen (0xff228b22);
  63724. const Colour Colours::fuchsia (0xffff00ff);
  63725. const Colour Colours::gainsboro (0xffdcdcdc);
  63726. const Colour Colours::gold (0xffffd700);
  63727. const Colour Colours::goldenrod (0xffdaa520);
  63728. const Colour Colours::grey (0xff808080);
  63729. const Colour Colours::green (0xff008000);
  63730. const Colour Colours::greenyellow (0xffadff2f);
  63731. const Colour Colours::honeydew (0xfff0fff0);
  63732. const Colour Colours::hotpink (0xffff69b4);
  63733. const Colour Colours::indianred (0xffcd5c5c);
  63734. const Colour Colours::indigo (0xff4b0082);
  63735. const Colour Colours::ivory (0xfffffff0);
  63736. const Colour Colours::khaki (0xfff0e68c);
  63737. const Colour Colours::lavender (0xffe6e6fa);
  63738. const Colour Colours::lavenderblush (0xfffff0f5);
  63739. const Colour Colours::lemonchiffon (0xfffffacd);
  63740. const Colour Colours::lightblue (0xffadd8e6);
  63741. const Colour Colours::lightcoral (0xfff08080);
  63742. const Colour Colours::lightcyan (0xffe0ffff);
  63743. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  63744. const Colour Colours::lightgreen (0xff90ee90);
  63745. const Colour Colours::lightgrey (0xffd3d3d3);
  63746. const Colour Colours::lightpink (0xffffb6c1);
  63747. const Colour Colours::lightsalmon (0xffffa07a);
  63748. const Colour Colours::lightseagreen (0xff20b2aa);
  63749. const Colour Colours::lightskyblue (0xff87cefa);
  63750. const Colour Colours::lightslategrey (0xff778899);
  63751. const Colour Colours::lightsteelblue (0xffb0c4de);
  63752. const Colour Colours::lightyellow (0xffffffe0);
  63753. const Colour Colours::lime (0xff00ff00);
  63754. const Colour Colours::limegreen (0xff32cd32);
  63755. const Colour Colours::linen (0xfffaf0e6);
  63756. const Colour Colours::magenta (0xffff00ff);
  63757. const Colour Colours::maroon (0xff800000);
  63758. const Colour Colours::mediumaquamarine (0xff66cdaa);
  63759. const Colour Colours::mediumblue (0xff0000cd);
  63760. const Colour Colours::mediumorchid (0xffba55d3);
  63761. const Colour Colours::mediumpurple (0xff9370db);
  63762. const Colour Colours::mediumseagreen (0xff3cb371);
  63763. const Colour Colours::mediumslateblue (0xff7b68ee);
  63764. const Colour Colours::mediumspringgreen (0xff00fa9a);
  63765. const Colour Colours::mediumturquoise (0xff48d1cc);
  63766. const Colour Colours::mediumvioletred (0xffc71585);
  63767. const Colour Colours::midnightblue (0xff191970);
  63768. const Colour Colours::mintcream (0xfff5fffa);
  63769. const Colour Colours::mistyrose (0xffffe4e1);
  63770. const Colour Colours::navajowhite (0xffffdead);
  63771. const Colour Colours::navy (0xff000080);
  63772. const Colour Colours::oldlace (0xfffdf5e6);
  63773. const Colour Colours::olive (0xff808000);
  63774. const Colour Colours::olivedrab (0xff6b8e23);
  63775. const Colour Colours::orange (0xffffa500);
  63776. const Colour Colours::orangered (0xffff4500);
  63777. const Colour Colours::orchid (0xffda70d6);
  63778. const Colour Colours::palegoldenrod (0xffeee8aa);
  63779. const Colour Colours::palegreen (0xff98fb98);
  63780. const Colour Colours::paleturquoise (0xffafeeee);
  63781. const Colour Colours::palevioletred (0xffdb7093);
  63782. const Colour Colours::papayawhip (0xffffefd5);
  63783. const Colour Colours::peachpuff (0xffffdab9);
  63784. const Colour Colours::peru (0xffcd853f);
  63785. const Colour Colours::pink (0xffffc0cb);
  63786. const Colour Colours::plum (0xffdda0dd);
  63787. const Colour Colours::powderblue (0xffb0e0e6);
  63788. const Colour Colours::purple (0xff800080);
  63789. const Colour Colours::red (0xffff0000);
  63790. const Colour Colours::rosybrown (0xffbc8f8f);
  63791. const Colour Colours::royalblue (0xff4169e1);
  63792. const Colour Colours::saddlebrown (0xff8b4513);
  63793. const Colour Colours::salmon (0xfffa8072);
  63794. const Colour Colours::sandybrown (0xfff4a460);
  63795. const Colour Colours::seagreen (0xff2e8b57);
  63796. const Colour Colours::seashell (0xfffff5ee);
  63797. const Colour Colours::sienna (0xffa0522d);
  63798. const Colour Colours::silver (0xffc0c0c0);
  63799. const Colour Colours::skyblue (0xff87ceeb);
  63800. const Colour Colours::slateblue (0xff6a5acd);
  63801. const Colour Colours::slategrey (0xff708090);
  63802. const Colour Colours::snow (0xfffffafa);
  63803. const Colour Colours::springgreen (0xff00ff7f);
  63804. const Colour Colours::steelblue (0xff4682b4);
  63805. const Colour Colours::tan (0xffd2b48c);
  63806. const Colour Colours::teal (0xff008080);
  63807. const Colour Colours::thistle (0xffd8bfd8);
  63808. const Colour Colours::tomato (0xffff6347);
  63809. const Colour Colours::turquoise (0xff40e0d0);
  63810. const Colour Colours::violet (0xffee82ee);
  63811. const Colour Colours::wheat (0xfff5deb3);
  63812. const Colour Colours::white (0xffffffff);
  63813. const Colour Colours::whitesmoke (0xfff5f5f5);
  63814. const Colour Colours::yellow (0xffffff00);
  63815. const Colour Colours::yellowgreen (0xff9acd32);
  63816. const Colour Colours::findColourForName (const String& colourName,
  63817. const Colour& defaultColour)
  63818. {
  63819. static const int presets[] =
  63820. {
  63821. // (first value is the string's hashcode, second is ARGB)
  63822. 0x05978fff, 0xff000000, /* black */
  63823. 0x06bdcc29, 0xffffffff, /* white */
  63824. 0x002e305a, 0xff0000ff, /* blue */
  63825. 0x00308adf, 0xff808080, /* grey */
  63826. 0x05e0cf03, 0xff008000, /* green */
  63827. 0x0001b891, 0xffff0000, /* red */
  63828. 0xd43c6474, 0xffffff00, /* yellow */
  63829. 0x620886da, 0xfff0f8ff, /* aliceblue */
  63830. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  63831. 0x002dcebc, 0xff00ffff, /* aqua */
  63832. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  63833. 0x0590228f, 0xfff0ffff, /* azure */
  63834. 0x05947fe4, 0xfff5f5dc, /* beige */
  63835. 0xad388e35, 0xffffe4c4, /* bisque */
  63836. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  63837. 0x39129959, 0xff8a2be2, /* blueviolet */
  63838. 0x059a8136, 0xffa52a2a, /* brown */
  63839. 0x89cea8f9, 0xffdeb887, /* burlywood */
  63840. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  63841. 0x6b748956, 0xff7fff00, /* chartreuse */
  63842. 0x2903623c, 0xffd2691e, /* chocolate */
  63843. 0x05a74431, 0xffff7f50, /* coral */
  63844. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  63845. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  63846. 0x3d8c4edf, 0xffdc143c, /* crimson */
  63847. 0x002ed323, 0xff00ffff, /* cyan */
  63848. 0x67cc74d0, 0xff00008b, /* darkblue */
  63849. 0x67cd1799, 0xff008b8b, /* darkcyan */
  63850. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  63851. 0x67cecf55, 0xff555555, /* darkgrey */
  63852. 0x920b194d, 0xff006400, /* darkgreen */
  63853. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  63854. 0x5c293873, 0xff8b008b, /* darkmagenta */
  63855. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  63856. 0xbcfd2524, 0xffff8c00, /* darkorange */
  63857. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  63858. 0x55ee0d5b, 0xff8b0000, /* darkred */
  63859. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  63860. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  63861. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  63862. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  63863. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  63864. 0xc8769375, 0xff9400d3, /* darkviolet */
  63865. 0x25832862, 0xffff1493, /* deeppink */
  63866. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  63867. 0x634c8b67, 0xff696969, /* dimgrey */
  63868. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  63869. 0xef19e3cb, 0xffb22222, /* firebrick */
  63870. 0xb852b195, 0xfffffaf0, /* floralwhite */
  63871. 0xd086fd06, 0xff228b22, /* forestgreen */
  63872. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  63873. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  63874. 0x00308060, 0xffffd700, /* gold */
  63875. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  63876. 0xbab8a537, 0xffadff2f, /* greenyellow */
  63877. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  63878. 0x41892743, 0xffff69b4, /* hotpink */
  63879. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  63880. 0xb969fed2, 0xff4b0082, /* indigo */
  63881. 0x05fef6a9, 0xfffffff0, /* ivory */
  63882. 0x06149302, 0xfff0e68c, /* khaki */
  63883. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  63884. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  63885. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  63886. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  63887. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  63888. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  63889. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  63890. 0xf40157ad, 0xff90ee90, /* lightgreen */
  63891. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  63892. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  63893. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  63894. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  63895. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  63896. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  63897. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  63898. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  63899. 0x0032afd5, 0xff00ff00, /* lime */
  63900. 0x607bbc4e, 0xff32cd32, /* limegreen */
  63901. 0x06234efa, 0xfffaf0e6, /* linen */
  63902. 0x316858a9, 0xffff00ff, /* magenta */
  63903. 0xbf8ca470, 0xff800000, /* maroon */
  63904. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  63905. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  63906. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  63907. 0x07556b71, 0xff9370db, /* mediumpurple */
  63908. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  63909. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  63910. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  63911. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  63912. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  63913. 0x168eb32a, 0xff191970, /* midnightblue */
  63914. 0x4306b960, 0xfff5fffa, /* mintcream */
  63915. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  63916. 0xe97218a6, 0xffffdead, /* navajowhite */
  63917. 0x00337bb6, 0xff000080, /* navy */
  63918. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  63919. 0x064ee1db, 0xff808000, /* olive */
  63920. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  63921. 0xc3de262e, 0xffffa500, /* orange */
  63922. 0x58bebba3, 0xffff4500, /* orangered */
  63923. 0xc3def8a3, 0xffda70d6, /* orchid */
  63924. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  63925. 0x3d9dd619, 0xff98fb98, /* palegreen */
  63926. 0x74022737, 0xffafeeee, /* paleturquoise */
  63927. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  63928. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  63929. 0x93e1b776, 0xffffdab9, /* peachpuff */
  63930. 0x003472f8, 0xffcd853f, /* peru */
  63931. 0x00348176, 0xffffc0cb, /* pink */
  63932. 0x00348d94, 0xffdda0dd, /* plum */
  63933. 0xd036be93, 0xffb0e0e6, /* powderblue */
  63934. 0xc5c507bc, 0xff800080, /* purple */
  63935. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  63936. 0xbd9413e1, 0xff4169e1, /* royalblue */
  63937. 0xf456044f, 0xff8b4513, /* saddlebrown */
  63938. 0xc9c6f66e, 0xfffa8072, /* salmon */
  63939. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  63940. 0x34636c14, 0xff2e8b57, /* seagreen */
  63941. 0x3507fb41, 0xfffff5ee, /* seashell */
  63942. 0xca348772, 0xffa0522d, /* sienna */
  63943. 0xca37d30d, 0xffc0c0c0, /* silver */
  63944. 0x80da74fb, 0xff87ceeb, /* skyblue */
  63945. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  63946. 0x44ab37f8, 0xff708090, /* slategrey */
  63947. 0x0035f183, 0xfffffafa, /* snow */
  63948. 0xd5440d16, 0xff00ff7f, /* springgreen */
  63949. 0x3e1524a5, 0xff4682b4, /* steelblue */
  63950. 0x0001bfa1, 0xffd2b48c, /* tan */
  63951. 0x0036425c, 0xff008080, /* teal */
  63952. 0xafc8858f, 0xffd8bfd8, /* thistle */
  63953. 0xcc41600a, 0xffff6347, /* tomato */
  63954. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  63955. 0xcf57947f, 0xffee82ee, /* violet */
  63956. 0x06bdbae7, 0xfff5deb3, /* wheat */
  63957. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  63958. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  63959. };
  63960. const int hash = colourName.trim().toLowerCase().hashCode();
  63961. for (int i = 0; i < numElementsInArray (presets); i += 2)
  63962. if (presets [i] == hash)
  63963. return Colour (presets [i + 1]);
  63964. return defaultColour;
  63965. }
  63966. END_JUCE_NAMESPACE
  63967. /*** End of inlined file: juce_Colours.cpp ***/
  63968. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  63969. BEGIN_JUCE_NAMESPACE
  63970. const int juce_edgeTableDefaultEdgesPerLine = 32;
  63971. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  63972. const Path& path, const AffineTransform& transform)
  63973. : bounds (bounds_),
  63974. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  63975. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  63976. needToCheckEmptinesss (true)
  63977. {
  63978. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  63979. int* t = table;
  63980. for (int i = bounds.getHeight(); --i >= 0;)
  63981. {
  63982. *t = 0;
  63983. t += lineStrideElements;
  63984. }
  63985. const int topLimit = bounds.getY() << 8;
  63986. const int heightLimit = bounds.getHeight() << 8;
  63987. const int leftLimit = bounds.getX() << 8;
  63988. const int rightLimit = bounds.getRight() << 8;
  63989. PathFlatteningIterator iter (path, transform);
  63990. while (iter.next())
  63991. {
  63992. int y1 = roundToInt (iter.y1 * 256.0f);
  63993. int y2 = roundToInt (iter.y2 * 256.0f);
  63994. if (y1 != y2)
  63995. {
  63996. y1 -= topLimit;
  63997. y2 -= topLimit;
  63998. const int startY = y1;
  63999. int direction = -1;
  64000. if (y1 > y2)
  64001. {
  64002. swapVariables (y1, y2);
  64003. direction = 1;
  64004. }
  64005. if (y1 < 0)
  64006. y1 = 0;
  64007. if (y2 > heightLimit)
  64008. y2 = heightLimit;
  64009. if (y1 < y2)
  64010. {
  64011. const double startX = 256.0f * iter.x1;
  64012. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64013. const int stepSize = jlimit (1, 256, 256 / (1 + (int) fabs (multiplier)));
  64014. do
  64015. {
  64016. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64017. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64018. if (x < leftLimit)
  64019. x = leftLimit;
  64020. else if (x >= rightLimit)
  64021. x = rightLimit - 1;
  64022. addEdgePoint (x, y1 >> 8, direction * step);
  64023. y1 += step;
  64024. }
  64025. while (y1 < y2);
  64026. }
  64027. }
  64028. }
  64029. sanitiseLevels (path.isUsingNonZeroWinding());
  64030. }
  64031. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64032. : bounds (rectangleToAdd),
  64033. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64034. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64035. needToCheckEmptinesss (true)
  64036. {
  64037. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64038. table[0] = 0;
  64039. const int x1 = rectangleToAdd.getX() << 8;
  64040. const int x2 = rectangleToAdd.getRight() << 8;
  64041. int* t = table;
  64042. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64043. {
  64044. t[0] = 2;
  64045. t[1] = x1;
  64046. t[2] = 255;
  64047. t[3] = x2;
  64048. t[4] = 0;
  64049. t += lineStrideElements;
  64050. }
  64051. }
  64052. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64053. : bounds (rectanglesToAdd.getBounds()),
  64054. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64055. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64056. needToCheckEmptinesss (true)
  64057. {
  64058. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64059. int* t = table;
  64060. for (int i = bounds.getHeight(); --i >= 0;)
  64061. {
  64062. *t = 0;
  64063. t += lineStrideElements;
  64064. }
  64065. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64066. {
  64067. const Rectangle<int>* const r = iter.getRectangle();
  64068. const int x1 = r->getX() << 8;
  64069. const int x2 = r->getRight() << 8;
  64070. int y = r->getY() - bounds.getY();
  64071. for (int j = r->getHeight(); --j >= 0;)
  64072. {
  64073. addEdgePoint (x1, y, 255);
  64074. addEdgePoint (x2, y, -255);
  64075. ++y;
  64076. }
  64077. }
  64078. sanitiseLevels (true);
  64079. }
  64080. EdgeTable::EdgeTable (const float x, const float y, const float w, const float h)
  64081. : bounds (Rectangle<int> ((int) floorf (x), roundToInt (y * 256.0f) >> 8, 2 + (int) w, 2 + (int) h)),
  64082. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64083. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64084. needToCheckEmptinesss (true)
  64085. {
  64086. jassert (w > 0 && h > 0);
  64087. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64088. table[0] = 0;
  64089. const int x1 = roundToInt (x * 256.0f);
  64090. const int x2 = roundToInt ((x + w) * 256.0f);
  64091. int y1 = roundToInt (y * 256.0f) - (bounds.getY() << 8);
  64092. jassert (y1 < 256);
  64093. int y2 = roundToInt ((y + h) * 256.0f) - (bounds.getY() << 8);
  64094. if (x2 <= x1 || y2 <= y1)
  64095. {
  64096. bounds.setHeight (0);
  64097. return;
  64098. }
  64099. int lineY = 0;
  64100. int* t = table;
  64101. if ((y1 >> 8) == (y2 >> 8))
  64102. {
  64103. t[0] = 2;
  64104. t[1] = x1;
  64105. t[2] = y2 - y1;
  64106. t[3] = x2;
  64107. t[4] = 0;
  64108. ++lineY;
  64109. t += lineStrideElements;
  64110. }
  64111. else
  64112. {
  64113. t[0] = 2;
  64114. t[1] = x1;
  64115. t[2] = 255 - (y1 & 255);
  64116. t[3] = x2;
  64117. t[4] = 0;
  64118. ++lineY;
  64119. t += lineStrideElements;
  64120. while (lineY < (y2 >> 8))
  64121. {
  64122. t[0] = 2;
  64123. t[1] = x1;
  64124. t[2] = 255;
  64125. t[3] = x2;
  64126. t[4] = 0;
  64127. ++lineY;
  64128. t += lineStrideElements;
  64129. }
  64130. jassert (lineY < bounds.getHeight());
  64131. t[0] = 2;
  64132. t[1] = x1;
  64133. t[2] = y2 & 255;
  64134. t[3] = x2;
  64135. t[4] = 0;
  64136. ++lineY;
  64137. t += lineStrideElements;
  64138. }
  64139. while (lineY < bounds.getHeight())
  64140. {
  64141. t[0] = 0;
  64142. t += lineStrideElements;
  64143. ++lineY;
  64144. }
  64145. }
  64146. EdgeTable::EdgeTable (const EdgeTable& other)
  64147. : table (0)
  64148. {
  64149. operator= (other);
  64150. }
  64151. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64152. {
  64153. bounds = other.bounds;
  64154. maxEdgesPerLine = other.maxEdgesPerLine;
  64155. lineStrideElements = other.lineStrideElements;
  64156. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64157. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64158. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64159. return *this;
  64160. }
  64161. EdgeTable::~EdgeTable()
  64162. {
  64163. }
  64164. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64165. {
  64166. while (--numLines >= 0)
  64167. {
  64168. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64169. src += srcLineStride;
  64170. dest += destLineStride;
  64171. }
  64172. }
  64173. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64174. {
  64175. // Convert the table from relative windings to absolute levels..
  64176. int* lineStart = table;
  64177. for (int i = bounds.getHeight(); --i >= 0;)
  64178. {
  64179. int* line = lineStart;
  64180. lineStart += lineStrideElements;
  64181. int num = *line;
  64182. if (num == 0)
  64183. continue;
  64184. int level = 0;
  64185. if (useNonZeroWinding)
  64186. {
  64187. while (--num > 0)
  64188. {
  64189. line += 2;
  64190. level += *line;
  64191. int corrected = abs (level);
  64192. if (corrected >> 8)
  64193. corrected = 255;
  64194. *line = corrected;
  64195. }
  64196. }
  64197. else
  64198. {
  64199. while (--num > 0)
  64200. {
  64201. line += 2;
  64202. level += *line;
  64203. int corrected = abs (level);
  64204. if (corrected >> 8)
  64205. {
  64206. corrected &= 511;
  64207. if (corrected >> 8)
  64208. corrected = 511 - corrected;
  64209. }
  64210. *line = corrected;
  64211. }
  64212. }
  64213. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64214. }
  64215. }
  64216. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64217. {
  64218. if (newNumEdgesPerLine != maxEdgesPerLine)
  64219. {
  64220. maxEdgesPerLine = newNumEdgesPerLine;
  64221. jassert (bounds.getHeight() > 0);
  64222. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64223. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64224. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64225. table.swapWith (newTable);
  64226. lineStrideElements = newLineStrideElements;
  64227. }
  64228. }
  64229. void EdgeTable::optimiseTable() throw()
  64230. {
  64231. int maxLineElements = 0;
  64232. for (int i = bounds.getHeight(); --i >= 0;)
  64233. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64234. remapTableForNumEdges (maxLineElements);
  64235. }
  64236. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64237. {
  64238. jassert (y >= 0 && y < bounds.getHeight());
  64239. int* line = table + lineStrideElements * y;
  64240. const int numPoints = line[0];
  64241. int n = numPoints << 1;
  64242. if (n > 0)
  64243. {
  64244. while (n > 0)
  64245. {
  64246. const int cx = line [n - 1];
  64247. if (cx <= x)
  64248. {
  64249. if (cx == x)
  64250. {
  64251. line [n] += winding;
  64252. return;
  64253. }
  64254. break;
  64255. }
  64256. n -= 2;
  64257. }
  64258. if (numPoints >= maxEdgesPerLine)
  64259. {
  64260. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64261. jassert (numPoints < maxEdgesPerLine);
  64262. line = table + lineStrideElements * y;
  64263. }
  64264. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64265. }
  64266. line [n + 1] = x;
  64267. line [n + 2] = winding;
  64268. line[0]++;
  64269. }
  64270. void EdgeTable::translate (float dx, int dy) throw()
  64271. {
  64272. bounds.setPosition (bounds.getX() + (int) floorf (dx), bounds.getY() + dy);
  64273. int* lineStart = table;
  64274. const int intDx = (int) (dx * 256.0f);
  64275. for (int i = bounds.getHeight(); --i >= 0;)
  64276. {
  64277. int* line = lineStart;
  64278. lineStart += lineStrideElements;
  64279. int num = *line++;
  64280. while (--num >= 0)
  64281. {
  64282. *line += intDx;
  64283. line += 2;
  64284. }
  64285. }
  64286. }
  64287. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64288. {
  64289. jassert (y >= 0 && y < bounds.getHeight());
  64290. int* dest = table + lineStrideElements * y;
  64291. if (dest[0] == 0)
  64292. return;
  64293. int otherNumPoints = *otherLine;
  64294. if (otherNumPoints == 0)
  64295. {
  64296. *dest = 0;
  64297. return;
  64298. }
  64299. const int right = bounds.getRight() << 8;
  64300. // optimise for the common case where our line lies entirely within a
  64301. // single pair of points, as happens when clipping to a simple rect.
  64302. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64303. {
  64304. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64305. return;
  64306. }
  64307. ++otherLine;
  64308. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64309. int* temp = (int*) alloca (lineSizeBytes);
  64310. memcpy (temp, dest, lineSizeBytes);
  64311. const int* src1 = temp;
  64312. int srcNum1 = *src1++;
  64313. int x1 = *src1++;
  64314. const int* src2 = otherLine;
  64315. int srcNum2 = otherNumPoints;
  64316. int x2 = *src2++;
  64317. int destIndex = 0, destTotal = 0;
  64318. int level1 = 0, level2 = 0;
  64319. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64320. while (srcNum1 > 0 && srcNum2 > 0)
  64321. {
  64322. int nextX;
  64323. if (x1 < x2)
  64324. {
  64325. nextX = x1;
  64326. level1 = *src1++;
  64327. x1 = *src1++;
  64328. --srcNum1;
  64329. }
  64330. else if (x1 == x2)
  64331. {
  64332. nextX = x1;
  64333. level1 = *src1++;
  64334. level2 = *src2++;
  64335. x1 = *src1++;
  64336. x2 = *src2++;
  64337. --srcNum1;
  64338. --srcNum2;
  64339. }
  64340. else
  64341. {
  64342. nextX = x2;
  64343. level2 = *src2++;
  64344. x2 = *src2++;
  64345. --srcNum2;
  64346. }
  64347. if (nextX > lastX)
  64348. {
  64349. if (nextX >= right)
  64350. break;
  64351. lastX = nextX;
  64352. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64353. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64354. if (nextLevel != lastLevel)
  64355. {
  64356. if (destTotal >= maxEdgesPerLine)
  64357. {
  64358. dest[0] = destTotal;
  64359. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64360. dest = table + lineStrideElements * y;
  64361. }
  64362. ++destTotal;
  64363. lastLevel = nextLevel;
  64364. dest[++destIndex] = nextX;
  64365. dest[++destIndex] = nextLevel;
  64366. }
  64367. }
  64368. }
  64369. if (lastLevel > 0)
  64370. {
  64371. if (destTotal >= maxEdgesPerLine)
  64372. {
  64373. dest[0] = destTotal;
  64374. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64375. dest = table + lineStrideElements * y;
  64376. }
  64377. ++destTotal;
  64378. dest[++destIndex] = right;
  64379. dest[++destIndex] = 0;
  64380. }
  64381. dest[0] = destTotal;
  64382. #if JUCE_DEBUG
  64383. int last = std::numeric_limits<int>::min();
  64384. for (int i = 0; i < dest[0]; ++i)
  64385. {
  64386. jassert (dest[i * 2 + 1] > last);
  64387. last = dest[i * 2 + 1];
  64388. }
  64389. jassert (dest [dest[0] * 2] == 0);
  64390. #endif
  64391. }
  64392. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64393. {
  64394. int* lastItem = dest + (dest[0] * 2 - 1);
  64395. if (x2 < lastItem[0])
  64396. {
  64397. if (x2 <= dest[1])
  64398. {
  64399. dest[0] = 0;
  64400. return;
  64401. }
  64402. while (x2 < lastItem[-2])
  64403. {
  64404. --(dest[0]);
  64405. lastItem -= 2;
  64406. }
  64407. lastItem[0] = x2;
  64408. lastItem[1] = 0;
  64409. }
  64410. if (x1 > dest[1])
  64411. {
  64412. while (lastItem[0] > x1)
  64413. lastItem -= 2;
  64414. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64415. if (itemsRemoved > 0)
  64416. {
  64417. dest[0] -= itemsRemoved;
  64418. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64419. }
  64420. dest[1] = x1;
  64421. }
  64422. }
  64423. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64424. {
  64425. const Rectangle<int> clipped (r.getIntersection (bounds));
  64426. if (clipped.isEmpty())
  64427. {
  64428. needToCheckEmptinesss = false;
  64429. bounds.setHeight (0);
  64430. }
  64431. else
  64432. {
  64433. const int top = clipped.getY() - bounds.getY();
  64434. const int bottom = clipped.getBottom() - bounds.getY();
  64435. if (bottom < bounds.getHeight())
  64436. bounds.setHeight (bottom);
  64437. if (clipped.getRight() < bounds.getRight())
  64438. bounds.setRight (clipped.getRight());
  64439. for (int i = top; --i >= 0;)
  64440. table [lineStrideElements * i] = 0;
  64441. if (clipped.getX() > bounds.getX())
  64442. {
  64443. const int x1 = clipped.getX() << 8;
  64444. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64445. int* line = table + lineStrideElements * top;
  64446. for (int i = bottom - top; --i >= 0;)
  64447. {
  64448. if (line[0] != 0)
  64449. clipEdgeTableLineToRange (line, x1, x2);
  64450. line += lineStrideElements;
  64451. }
  64452. }
  64453. needToCheckEmptinesss = true;
  64454. }
  64455. }
  64456. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64457. {
  64458. const Rectangle<int> clipped (r.getIntersection (bounds));
  64459. if (! clipped.isEmpty())
  64460. {
  64461. const int top = clipped.getY() - bounds.getY();
  64462. const int bottom = clipped.getBottom() - bounds.getY();
  64463. //XXX optimise here by shortening the table if it fills top or bottom
  64464. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64465. clipped.getX() << 8, 0,
  64466. clipped.getRight() << 8, 255,
  64467. std::numeric_limits<int>::max(), 0 };
  64468. for (int i = top; i < bottom; ++i)
  64469. intersectWithEdgeTableLine (i, rectLine);
  64470. needToCheckEmptinesss = true;
  64471. }
  64472. }
  64473. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64474. {
  64475. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64476. if (clipped.isEmpty())
  64477. {
  64478. needToCheckEmptinesss = false;
  64479. bounds.setHeight (0);
  64480. }
  64481. else
  64482. {
  64483. const int top = clipped.getY() - bounds.getY();
  64484. const int bottom = clipped.getBottom() - bounds.getY();
  64485. if (bottom < bounds.getHeight())
  64486. bounds.setHeight (bottom);
  64487. if (clipped.getRight() < bounds.getRight())
  64488. bounds.setRight (clipped.getRight());
  64489. int i = 0;
  64490. for (i = top; --i >= 0;)
  64491. table [lineStrideElements * i] = 0;
  64492. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64493. for (i = top; i < bottom; ++i)
  64494. {
  64495. intersectWithEdgeTableLine (i, otherLine);
  64496. otherLine += other.lineStrideElements;
  64497. }
  64498. needToCheckEmptinesss = true;
  64499. }
  64500. }
  64501. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64502. {
  64503. y -= bounds.getY();
  64504. if (y < 0 || y >= bounds.getHeight())
  64505. return;
  64506. needToCheckEmptinesss = true;
  64507. if (numPixels <= 0)
  64508. {
  64509. table [lineStrideElements * y] = 0;
  64510. return;
  64511. }
  64512. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64513. int destIndex = 0, lastLevel = 0;
  64514. while (--numPixels >= 0)
  64515. {
  64516. const int alpha = *mask;
  64517. mask += maskStride;
  64518. if (alpha != lastLevel)
  64519. {
  64520. tempLine[++destIndex] = (x << 8);
  64521. tempLine[++destIndex] = alpha;
  64522. lastLevel = alpha;
  64523. }
  64524. ++x;
  64525. }
  64526. if (lastLevel > 0)
  64527. {
  64528. tempLine[++destIndex] = (x << 8);
  64529. tempLine[++destIndex] = 0;
  64530. }
  64531. tempLine[0] = destIndex >> 1;
  64532. intersectWithEdgeTableLine (y, tempLine);
  64533. }
  64534. bool EdgeTable::isEmpty() throw()
  64535. {
  64536. if (needToCheckEmptinesss)
  64537. {
  64538. needToCheckEmptinesss = false;
  64539. int* t = table;
  64540. for (int i = bounds.getHeight(); --i >= 0;)
  64541. {
  64542. if (t[0] > 1)
  64543. return false;
  64544. t += lineStrideElements;
  64545. }
  64546. bounds.setHeight (0);
  64547. }
  64548. return bounds.getHeight() == 0;
  64549. }
  64550. END_JUCE_NAMESPACE
  64551. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64552. /*** Start of inlined file: juce_FillType.cpp ***/
  64553. BEGIN_JUCE_NAMESPACE
  64554. FillType::FillType() throw()
  64555. : colour (0xff000000), image (0)
  64556. {
  64557. }
  64558. FillType::FillType (const Colour& colour_) throw()
  64559. : colour (colour_), image (0)
  64560. {
  64561. }
  64562. FillType::FillType (const ColourGradient& gradient_)
  64563. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64564. {
  64565. }
  64566. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64567. : colour (0xff000000), image (&image_), transform (transform_)
  64568. {
  64569. }
  64570. FillType::FillType (const FillType& other)
  64571. : colour (other.colour),
  64572. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64573. image (other.image), transform (other.transform)
  64574. {
  64575. }
  64576. FillType& FillType::operator= (const FillType& other)
  64577. {
  64578. if (this != &other)
  64579. {
  64580. colour = other.colour;
  64581. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64582. image = other.image;
  64583. transform = other.transform;
  64584. }
  64585. return *this;
  64586. }
  64587. FillType::~FillType() throw()
  64588. {
  64589. }
  64590. void FillType::setColour (const Colour& newColour) throw()
  64591. {
  64592. gradient = 0;
  64593. image = 0;
  64594. colour = newColour;
  64595. }
  64596. void FillType::setGradient (const ColourGradient& newGradient)
  64597. {
  64598. if (gradient != 0)
  64599. {
  64600. *gradient = newGradient;
  64601. }
  64602. else
  64603. {
  64604. image = 0;
  64605. gradient = new ColourGradient (newGradient);
  64606. colour = Colours::black;
  64607. }
  64608. }
  64609. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  64610. {
  64611. gradient = 0;
  64612. image = &image_;
  64613. transform = transform_;
  64614. colour = Colours::black;
  64615. }
  64616. void FillType::setOpacity (const float newOpacity) throw()
  64617. {
  64618. colour = colour.withAlpha (newOpacity);
  64619. }
  64620. END_JUCE_NAMESPACE
  64621. /*** End of inlined file: juce_FillType.cpp ***/
  64622. /*** Start of inlined file: juce_Graphics.cpp ***/
  64623. BEGIN_JUCE_NAMESPACE
  64624. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  64625. template <typename Type>
  64626. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  64627. {
  64628. const int maxVal = 0x3fffffff;
  64629. return (int) x >= -maxVal && (int) x <= maxVal
  64630. && (int) y >= -maxVal && (int) y <= maxVal
  64631. && (int) w >= -maxVal && (int) w <= maxVal
  64632. && (int) h >= -maxVal && (int) h <= maxVal;
  64633. }
  64634. LowLevelGraphicsContext::LowLevelGraphicsContext()
  64635. {
  64636. }
  64637. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  64638. {
  64639. }
  64640. Graphics::Graphics (Image& imageToDrawOnto)
  64641. : context (imageToDrawOnto.createLowLevelContext()),
  64642. contextToDelete (context),
  64643. saveStatePending (false)
  64644. {
  64645. }
  64646. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  64647. : context (internalContext),
  64648. saveStatePending (false)
  64649. {
  64650. }
  64651. Graphics::~Graphics()
  64652. {
  64653. }
  64654. void Graphics::resetToDefaultState()
  64655. {
  64656. saveStateIfPending();
  64657. context->setFill (FillType());
  64658. context->setFont (Font());
  64659. context->setInterpolationQuality (defaultQuality);
  64660. }
  64661. bool Graphics::isVectorDevice() const
  64662. {
  64663. return context->isVectorDevice();
  64664. }
  64665. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  64666. {
  64667. saveStateIfPending();
  64668. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  64669. }
  64670. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  64671. {
  64672. saveStateIfPending();
  64673. return context->clipToRectangleList (clipRegion);
  64674. }
  64675. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  64676. {
  64677. saveStateIfPending();
  64678. context->clipToPath (path, transform);
  64679. return ! context->isClipEmpty();
  64680. }
  64681. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  64682. {
  64683. saveStateIfPending();
  64684. context->clipToImageAlpha (image, sourceClipRegion, transform);
  64685. return ! context->isClipEmpty();
  64686. }
  64687. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  64688. {
  64689. saveStateIfPending();
  64690. context->excludeClipRectangle (rectangleToExclude);
  64691. }
  64692. bool Graphics::isClipEmpty() const
  64693. {
  64694. return context->isClipEmpty();
  64695. }
  64696. const Rectangle<int> Graphics::getClipBounds() const
  64697. {
  64698. return context->getClipBounds();
  64699. }
  64700. void Graphics::saveState()
  64701. {
  64702. saveStateIfPending();
  64703. saveStatePending = true;
  64704. }
  64705. void Graphics::restoreState()
  64706. {
  64707. if (saveStatePending)
  64708. saveStatePending = false;
  64709. else
  64710. context->restoreState();
  64711. }
  64712. void Graphics::saveStateIfPending()
  64713. {
  64714. if (saveStatePending)
  64715. {
  64716. saveStatePending = false;
  64717. context->saveState();
  64718. }
  64719. }
  64720. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  64721. {
  64722. saveStateIfPending();
  64723. context->setOrigin (newOriginX, newOriginY);
  64724. }
  64725. bool Graphics::clipRegionIntersects (const int x, const int y, const int w, const int h) const
  64726. {
  64727. return context->clipRegionIntersects (Rectangle<int> (x, y, w, h));
  64728. }
  64729. void Graphics::setColour (const Colour& newColour)
  64730. {
  64731. saveStateIfPending();
  64732. context->setFill (newColour);
  64733. }
  64734. void Graphics::setOpacity (const float newOpacity)
  64735. {
  64736. saveStateIfPending();
  64737. context->setOpacity (newOpacity);
  64738. }
  64739. void Graphics::setGradientFill (const ColourGradient& gradient)
  64740. {
  64741. setFillType (gradient);
  64742. }
  64743. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  64744. {
  64745. saveStateIfPending();
  64746. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  64747. context->setOpacity (opacity);
  64748. }
  64749. void Graphics::setFillType (const FillType& newFill)
  64750. {
  64751. saveStateIfPending();
  64752. context->setFill (newFill);
  64753. }
  64754. void Graphics::setFont (const Font& newFont)
  64755. {
  64756. saveStateIfPending();
  64757. context->setFont (newFont);
  64758. }
  64759. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  64760. {
  64761. saveStateIfPending();
  64762. Font f (context->getFont());
  64763. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  64764. context->setFont (f);
  64765. }
  64766. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  64767. {
  64768. if (text.isNotEmpty()
  64769. && startX < context->getClipBounds().getRight())
  64770. {
  64771. GlyphArrangement arr;
  64772. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  64773. arr.draw (*this);
  64774. }
  64775. }
  64776. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  64777. {
  64778. if (text.isNotEmpty())
  64779. {
  64780. GlyphArrangement arr;
  64781. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  64782. arr.draw (*this, transform);
  64783. }
  64784. }
  64785. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  64786. {
  64787. if (text.isNotEmpty()
  64788. && startX < context->getClipBounds().getRight())
  64789. {
  64790. GlyphArrangement arr;
  64791. arr.addJustifiedText (context->getFont(), text,
  64792. (float) startX, (float) baselineY, (float) maximumLineWidth,
  64793. Justification::left);
  64794. arr.draw (*this);
  64795. }
  64796. }
  64797. void Graphics::drawText (const String& text,
  64798. const int x, const int y, const int width, const int height,
  64799. const Justification& justificationType,
  64800. const bool useEllipsesIfTooBig) const
  64801. {
  64802. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64803. {
  64804. GlyphArrangement arr;
  64805. arr.addCurtailedLineOfText (context->getFont(), text,
  64806. 0.0f, 0.0f, (float) width,
  64807. useEllipsesIfTooBig);
  64808. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  64809. (float) x, (float) y, (float) width, (float) height,
  64810. justificationType);
  64811. arr.draw (*this);
  64812. }
  64813. }
  64814. void Graphics::drawFittedText (const String& text,
  64815. const int x, const int y, const int width, const int height,
  64816. const Justification& justification,
  64817. const int maximumNumberOfLines,
  64818. const float minimumHorizontalScale) const
  64819. {
  64820. if (text.isNotEmpty()
  64821. && width > 0 && height > 0
  64822. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64823. {
  64824. GlyphArrangement arr;
  64825. arr.addFittedText (context->getFont(), text,
  64826. (float) x, (float) y, (float) width, (float) height,
  64827. justification,
  64828. maximumNumberOfLines,
  64829. minimumHorizontalScale);
  64830. arr.draw (*this);
  64831. }
  64832. }
  64833. void Graphics::fillRect (int x, int y, int width, int height) const
  64834. {
  64835. // passing in a silly number can cause maths problems in rendering!
  64836. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64837. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64838. }
  64839. void Graphics::fillRect (const Rectangle<int>& r) const
  64840. {
  64841. context->fillRect (r, false);
  64842. }
  64843. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  64844. {
  64845. // passing in a silly number can cause maths problems in rendering!
  64846. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64847. Path p;
  64848. p.addRectangle (x, y, width, height);
  64849. fillPath (p);
  64850. }
  64851. void Graphics::setPixel (int x, int y) const
  64852. {
  64853. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  64854. }
  64855. void Graphics::fillAll() const
  64856. {
  64857. fillRect (context->getClipBounds());
  64858. }
  64859. void Graphics::fillAll (const Colour& colourToUse) const
  64860. {
  64861. if (! colourToUse.isTransparent())
  64862. {
  64863. const Rectangle<int> clip (context->getClipBounds());
  64864. context->saveState();
  64865. context->setFill (colourToUse);
  64866. context->fillRect (clip, false);
  64867. context->restoreState();
  64868. }
  64869. }
  64870. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  64871. {
  64872. if ((! context->isClipEmpty()) && ! path.isEmpty())
  64873. context->fillPath (path, transform);
  64874. }
  64875. void Graphics::strokePath (const Path& path,
  64876. const PathStrokeType& strokeType,
  64877. const AffineTransform& transform) const
  64878. {
  64879. Path stroke;
  64880. strokeType.createStrokedPath (stroke, path, transform);
  64881. fillPath (stroke);
  64882. }
  64883. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  64884. const int lineThickness) const
  64885. {
  64886. // passing in a silly number can cause maths problems in rendering!
  64887. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64888. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  64889. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64890. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64891. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  64892. }
  64893. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  64894. {
  64895. // passing in a silly number can cause maths problems in rendering!
  64896. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64897. Path p;
  64898. p.addRectangle (x, y, width, lineThickness);
  64899. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64900. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64901. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  64902. fillPath (p);
  64903. }
  64904. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  64905. {
  64906. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  64907. }
  64908. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  64909. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  64910. const bool useGradient, const bool sharpEdgeOnOutside) const
  64911. {
  64912. // passing in a silly number can cause maths problems in rendering!
  64913. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64914. if (clipRegionIntersects (x, y, width, height))
  64915. {
  64916. context->saveState();
  64917. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  64918. const float ramp = oldOpacity / bevelThickness;
  64919. for (int i = bevelThickness; --i >= 0;)
  64920. {
  64921. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  64922. : oldOpacity;
  64923. context->setFill (topLeftColour.withMultipliedAlpha (op));
  64924. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  64925. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  64926. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  64927. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  64928. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  64929. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  64930. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  64931. }
  64932. context->restoreState();
  64933. }
  64934. }
  64935. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  64936. {
  64937. // passing in a silly number can cause maths problems in rendering!
  64938. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64939. Path p;
  64940. p.addEllipse (x, y, width, height);
  64941. fillPath (p);
  64942. }
  64943. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  64944. const float lineThickness) const
  64945. {
  64946. // passing in a silly number can cause maths problems in rendering!
  64947. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64948. Path p;
  64949. p.addEllipse (x, y, width, height);
  64950. strokePath (p, PathStrokeType (lineThickness));
  64951. }
  64952. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  64953. {
  64954. // passing in a silly number can cause maths problems in rendering!
  64955. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64956. Path p;
  64957. p.addRoundedRectangle (x, y, width, height, cornerSize);
  64958. fillPath (p);
  64959. }
  64960. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  64961. {
  64962. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  64963. }
  64964. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  64965. const float cornerSize, const float lineThickness) const
  64966. {
  64967. // passing in a silly number can cause maths problems in rendering!
  64968. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64969. Path p;
  64970. p.addRoundedRectangle (x, y, width, height, cornerSize);
  64971. strokePath (p, PathStrokeType (lineThickness));
  64972. }
  64973. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  64974. {
  64975. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  64976. }
  64977. void Graphics::drawArrow (const float startX, const float startY, const float endX, const float endY,
  64978. const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  64979. {
  64980. Path p;
  64981. p.addArrow (startX, startY, endX, endY,
  64982. lineThickness, arrowheadWidth, arrowheadLength);
  64983. fillPath (p);
  64984. }
  64985. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  64986. const int checkWidth, const int checkHeight,
  64987. const Colour& colour1, const Colour& colour2) const
  64988. {
  64989. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  64990. if (checkWidth > 0 && checkHeight > 0)
  64991. {
  64992. context->saveState();
  64993. if (colour1 == colour2)
  64994. {
  64995. context->setFill (colour1);
  64996. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64997. }
  64998. else
  64999. {
  65000. const Rectangle<int> clip (context->getClipBounds());
  65001. const int right = jmin (x + width, clip.getRight());
  65002. const int bottom = jmin (y + height, clip.getBottom());
  65003. int cy = 0;
  65004. while (y < bottom)
  65005. {
  65006. int cx = cy;
  65007. for (int xx = x; xx < right; xx += checkWidth)
  65008. {
  65009. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65010. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65011. false);
  65012. }
  65013. ++cy;
  65014. y += checkHeight;
  65015. }
  65016. }
  65017. context->restoreState();
  65018. }
  65019. }
  65020. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65021. {
  65022. context->drawVerticalLine (x, top, bottom);
  65023. }
  65024. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65025. {
  65026. context->drawHorizontalLine (y, left, right);
  65027. }
  65028. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65029. {
  65030. context->drawLine (x1, y1, x2, y2);
  65031. }
  65032. void Graphics::drawLine (const float startX, const float startY,
  65033. const float endX, const float endY,
  65034. const float lineThickness) const
  65035. {
  65036. Path p;
  65037. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  65038. fillPath (p);
  65039. }
  65040. void Graphics::drawLine (const Line<float>& line) const
  65041. {
  65042. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65043. }
  65044. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65045. {
  65046. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  65047. }
  65048. void Graphics::drawDashedLine (const float startX, const float startY,
  65049. const float endX, const float endY,
  65050. const float* const dashLengths,
  65051. const int numDashLengths,
  65052. const float lineThickness) const
  65053. {
  65054. const double dx = endX - startX;
  65055. const double dy = endY - startY;
  65056. const double totalLen = juce_hypot (dx, dy);
  65057. if (totalLen >= 0.5)
  65058. {
  65059. const double onePixAlpha = 1.0 / totalLen;
  65060. double alpha = 0.0;
  65061. float x = startX;
  65062. float y = startY;
  65063. int n = 0;
  65064. while (alpha < 1.0f)
  65065. {
  65066. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65067. n = n % numDashLengths;
  65068. const float oldX = x;
  65069. const float oldY = y;
  65070. x = (float) (startX + dx * alpha);
  65071. y = (float) (startY + dy * alpha);
  65072. if ((n & 1) != 0)
  65073. {
  65074. if (lineThickness != 1.0f)
  65075. drawLine (oldX, oldY, x, y, lineThickness);
  65076. else
  65077. drawLine (oldX, oldY, x, y);
  65078. }
  65079. }
  65080. }
  65081. }
  65082. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65083. {
  65084. saveStateIfPending();
  65085. context->setInterpolationQuality (newQuality);
  65086. }
  65087. void Graphics::drawImageAt (const Image* const imageToDraw,
  65088. const int topLeftX, const int topLeftY,
  65089. const bool fillAlphaChannelWithCurrentBrush) const
  65090. {
  65091. if (imageToDraw != 0)
  65092. {
  65093. const int imageW = imageToDraw->getWidth();
  65094. const int imageH = imageToDraw->getHeight();
  65095. drawImage (imageToDraw,
  65096. topLeftX, topLeftY, imageW, imageH,
  65097. 0, 0, imageW, imageH,
  65098. fillAlphaChannelWithCurrentBrush);
  65099. }
  65100. }
  65101. void Graphics::drawImageWithin (const Image* const imageToDraw,
  65102. const int destX, const int destY,
  65103. const int destW, const int destH,
  65104. const RectanglePlacement& placementWithinTarget,
  65105. const bool fillAlphaChannelWithCurrentBrush) const
  65106. {
  65107. // passing in a silly number can cause maths problems in rendering!
  65108. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65109. if (imageToDraw != 0)
  65110. {
  65111. const int imageW = imageToDraw->getWidth();
  65112. const int imageH = imageToDraw->getHeight();
  65113. if (imageW > 0 && imageH > 0)
  65114. {
  65115. double newX = 0.0, newY = 0.0;
  65116. double newW = imageW;
  65117. double newH = imageH;
  65118. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65119. destX, destY, destW, destH);
  65120. if (newW > 0 && newH > 0)
  65121. {
  65122. drawImage (imageToDraw,
  65123. roundToInt (newX), roundToInt (newY),
  65124. roundToInt (newW), roundToInt (newH),
  65125. 0, 0, imageW, imageH,
  65126. fillAlphaChannelWithCurrentBrush);
  65127. }
  65128. }
  65129. }
  65130. }
  65131. void Graphics::drawImage (const Image* const imageToDraw,
  65132. int dx, int dy, int dw, int dh,
  65133. int sx, int sy, int sw, int sh,
  65134. const bool fillAlphaChannelWithCurrentBrush) const
  65135. {
  65136. // passing in a silly number can cause maths problems in rendering!
  65137. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65138. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65139. if (context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65140. {
  65141. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65142. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65143. .translated ((float) dx, (float) dy),
  65144. fillAlphaChannelWithCurrentBrush);
  65145. }
  65146. }
  65147. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  65148. const Rectangle<int>& imageSubRegion,
  65149. const AffineTransform& transform,
  65150. const bool fillAlphaChannelWithCurrentBrush) const
  65151. {
  65152. if (imageToDraw != 0 && ! context->isClipEmpty())
  65153. {
  65154. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw->getBounds()));
  65155. if (fillAlphaChannelWithCurrentBrush)
  65156. {
  65157. context->saveState();
  65158. context->clipToImageAlpha (*imageToDraw, srcClip, transform);
  65159. fillAll();
  65160. context->restoreState();
  65161. }
  65162. else
  65163. {
  65164. context->drawImage (*imageToDraw, srcClip, transform, false);
  65165. }
  65166. }
  65167. }
  65168. END_JUCE_NAMESPACE
  65169. /*** End of inlined file: juce_Graphics.cpp ***/
  65170. /*** Start of inlined file: juce_Justification.cpp ***/
  65171. BEGIN_JUCE_NAMESPACE
  65172. Justification::Justification (const Justification& other) throw()
  65173. : flags (other.flags)
  65174. {
  65175. }
  65176. Justification& Justification::operator= (const Justification& other) throw()
  65177. {
  65178. flags = other.flags;
  65179. return *this;
  65180. }
  65181. int Justification::getOnlyVerticalFlags() const throw()
  65182. {
  65183. return flags & (top | bottom | verticallyCentred);
  65184. }
  65185. int Justification::getOnlyHorizontalFlags() const throw()
  65186. {
  65187. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65188. }
  65189. void Justification::applyToRectangle (int& x, int& y,
  65190. const int w, const int h,
  65191. const int spaceX, const int spaceY,
  65192. const int spaceW, const int spaceH) const throw()
  65193. {
  65194. if ((flags & horizontallyCentred) != 0)
  65195. {
  65196. x = spaceX + ((spaceW - w) >> 1);
  65197. }
  65198. else if ((flags & right) != 0)
  65199. {
  65200. x = spaceX + spaceW - w;
  65201. }
  65202. else
  65203. {
  65204. x = spaceX;
  65205. }
  65206. if ((flags & verticallyCentred) != 0)
  65207. {
  65208. y = spaceY + ((spaceH - h) >> 1);
  65209. }
  65210. else if ((flags & bottom) != 0)
  65211. {
  65212. y = spaceY + spaceH - h;
  65213. }
  65214. else
  65215. {
  65216. y = spaceY;
  65217. }
  65218. }
  65219. END_JUCE_NAMESPACE
  65220. /*** End of inlined file: juce_Justification.cpp ***/
  65221. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65222. BEGIN_JUCE_NAMESPACE
  65223. // this will throw an assertion if you try to draw something that's not
  65224. // possible in postscript
  65225. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65226. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65227. #define notPossibleInPostscriptAssert jassertfalse
  65228. #else
  65229. #define notPossibleInPostscriptAssert
  65230. #endif
  65231. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65232. const String& documentTitle,
  65233. const int totalWidth_,
  65234. const int totalHeight_)
  65235. : out (resultingPostScript),
  65236. totalWidth (totalWidth_),
  65237. totalHeight (totalHeight_),
  65238. needToClip (true)
  65239. {
  65240. stateStack.add (new SavedState());
  65241. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65242. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65243. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65244. "\n%%BoundingBox: 0 0 600 824"
  65245. "\n%%Pages: 0"
  65246. "\n%%Creator: Raw Material Software JUCE"
  65247. "\n%%Title: " << documentTitle <<
  65248. "\n%%CreationDate: none"
  65249. "\n%%LanguageLevel: 2"
  65250. "\n%%EndComments"
  65251. "\n%%BeginProlog"
  65252. "\n%%BeginResource: JRes"
  65253. "\n/bd {bind def} bind def"
  65254. "\n/c {setrgbcolor} bd"
  65255. "\n/m {moveto} bd"
  65256. "\n/l {lineto} bd"
  65257. "\n/rl {rlineto} bd"
  65258. "\n/ct {curveto} bd"
  65259. "\n/cp {closepath} bd"
  65260. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65261. "\n/doclip {initclip newpath} bd"
  65262. "\n/endclip {clip newpath} bd"
  65263. "\n%%EndResource"
  65264. "\n%%EndProlog"
  65265. "\n%%BeginSetup"
  65266. "\n%%EndSetup"
  65267. "\n%%Page: 1 1"
  65268. "\n%%BeginPageSetup"
  65269. "\n%%EndPageSetup\n\n"
  65270. << "40 800 translate\n"
  65271. << scale << ' ' << scale << " scale\n\n";
  65272. }
  65273. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65274. {
  65275. }
  65276. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65277. {
  65278. return true;
  65279. }
  65280. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65281. {
  65282. if (x != 0 || y != 0)
  65283. {
  65284. stateStack.getLast()->xOffset += x;
  65285. stateStack.getLast()->yOffset += y;
  65286. needToClip = true;
  65287. }
  65288. }
  65289. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65290. {
  65291. needToClip = true;
  65292. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65293. }
  65294. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65295. {
  65296. needToClip = true;
  65297. return stateStack.getLast()->clip.clipTo (clipRegion);
  65298. }
  65299. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65300. {
  65301. needToClip = true;
  65302. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65303. }
  65304. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65305. {
  65306. writeClip();
  65307. Path p (path);
  65308. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65309. writePath (p);
  65310. out << "clip\n";
  65311. }
  65312. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65313. {
  65314. needToClip = true;
  65315. jassertfalse // xxx
  65316. }
  65317. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65318. {
  65319. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65320. }
  65321. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65322. {
  65323. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65324. -stateStack.getLast()->yOffset);
  65325. }
  65326. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65327. {
  65328. return stateStack.getLast()->clip.isEmpty();
  65329. }
  65330. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65331. : xOffset (0),
  65332. yOffset (0)
  65333. {
  65334. }
  65335. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65336. {
  65337. }
  65338. void LowLevelGraphicsPostScriptRenderer::saveState()
  65339. {
  65340. stateStack.add (new SavedState (*stateStack.getLast()));
  65341. }
  65342. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65343. {
  65344. jassert (stateStack.size() > 0);
  65345. if (stateStack.size() > 0)
  65346. stateStack.removeLast();
  65347. }
  65348. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65349. {
  65350. if (needToClip)
  65351. {
  65352. needToClip = false;
  65353. out << "doclip ";
  65354. int itemsOnLine = 0;
  65355. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65356. {
  65357. if (++itemsOnLine == 6)
  65358. {
  65359. itemsOnLine = 0;
  65360. out << '\n';
  65361. }
  65362. const Rectangle<int>& r = *i.getRectangle();
  65363. out << r.getX() << ' ' << -r.getY() << ' '
  65364. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65365. }
  65366. out << "endclip\n";
  65367. }
  65368. }
  65369. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65370. {
  65371. Colour c (Colours::white.overlaidWith (colour));
  65372. if (lastColour != c)
  65373. {
  65374. lastColour = c;
  65375. out << String (c.getFloatRed(), 3) << ' '
  65376. << String (c.getFloatGreen(), 3) << ' '
  65377. << String (c.getFloatBlue(), 3) << " c\n";
  65378. }
  65379. }
  65380. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65381. {
  65382. out << String (x, 2) << ' '
  65383. << String (-y, 2) << ' ';
  65384. }
  65385. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65386. {
  65387. out << "newpath ";
  65388. float lastX = 0.0f;
  65389. float lastY = 0.0f;
  65390. int itemsOnLine = 0;
  65391. Path::Iterator i (path);
  65392. while (i.next())
  65393. {
  65394. if (++itemsOnLine == 4)
  65395. {
  65396. itemsOnLine = 0;
  65397. out << '\n';
  65398. }
  65399. switch (i.elementType)
  65400. {
  65401. case Path::Iterator::startNewSubPath:
  65402. writeXY (i.x1, i.y1);
  65403. lastX = i.x1;
  65404. lastY = i.y1;
  65405. out << "m ";
  65406. break;
  65407. case Path::Iterator::lineTo:
  65408. writeXY (i.x1, i.y1);
  65409. lastX = i.x1;
  65410. lastY = i.y1;
  65411. out << "l ";
  65412. break;
  65413. case Path::Iterator::quadraticTo:
  65414. {
  65415. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65416. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65417. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65418. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65419. writeXY (cp1x, cp1y);
  65420. writeXY (cp2x, cp2y);
  65421. writeXY (i.x2, i.y2);
  65422. out << "ct ";
  65423. lastX = i.x2;
  65424. lastY = i.y2;
  65425. }
  65426. break;
  65427. case Path::Iterator::cubicTo:
  65428. writeXY (i.x1, i.y1);
  65429. writeXY (i.x2, i.y2);
  65430. writeXY (i.x3, i.y3);
  65431. out << "ct ";
  65432. lastX = i.x3;
  65433. lastY = i.y3;
  65434. break;
  65435. case Path::Iterator::closePath:
  65436. out << "cp ";
  65437. break;
  65438. default:
  65439. jassertfalse
  65440. break;
  65441. }
  65442. }
  65443. out << '\n';
  65444. }
  65445. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65446. {
  65447. out << "[ "
  65448. << trans.mat00 << ' '
  65449. << trans.mat10 << ' '
  65450. << trans.mat01 << ' '
  65451. << trans.mat11 << ' '
  65452. << trans.mat02 << ' '
  65453. << trans.mat12 << " ] concat ";
  65454. }
  65455. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65456. {
  65457. stateStack.getLast()->fillType = fillType;
  65458. }
  65459. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65460. {
  65461. }
  65462. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65463. {
  65464. }
  65465. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65466. {
  65467. if (stateStack.getLast()->fillType.isColour())
  65468. {
  65469. writeClip();
  65470. writeColour (stateStack.getLast()->fillType.colour);
  65471. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65472. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65473. }
  65474. else
  65475. {
  65476. Path p;
  65477. p.addRectangle (r);
  65478. fillPath (p, AffineTransform::identity);
  65479. }
  65480. }
  65481. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65482. {
  65483. if (stateStack.getLast()->fillType.isColour())
  65484. {
  65485. writeClip();
  65486. Path p (path);
  65487. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65488. (float) stateStack.getLast()->yOffset));
  65489. writePath (p);
  65490. writeColour (stateStack.getLast()->fillType.colour);
  65491. out << "fill\n";
  65492. }
  65493. else if (stateStack.getLast()->fillType.isGradient())
  65494. {
  65495. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65496. // postscript can't do semi-transparent ones.
  65497. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65498. writeClip();
  65499. out << "gsave ";
  65500. {
  65501. Path p (path);
  65502. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65503. writePath (p);
  65504. out << "clip\n";
  65505. }
  65506. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65507. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65508. // time-being, this just fills it with the average colour..
  65509. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65510. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65511. out << "grestore\n";
  65512. }
  65513. }
  65514. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65515. const int sx, const int sy,
  65516. const int maxW, const int maxH) const
  65517. {
  65518. out << "{<\n";
  65519. const int w = jmin (maxW, im.getWidth());
  65520. const int h = jmin (maxH, im.getHeight());
  65521. int charsOnLine = 0;
  65522. const Image::BitmapData srcData (im, 0, 0, w, h);
  65523. Colour pixel;
  65524. for (int y = h; --y >= 0;)
  65525. {
  65526. for (int x = 0; x < w; ++x)
  65527. {
  65528. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65529. if (x >= sx && y >= sy)
  65530. {
  65531. if (im.isARGB())
  65532. {
  65533. PixelARGB p (*(const PixelARGB*) pixelData);
  65534. p.unpremultiply();
  65535. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65536. }
  65537. else if (im.isRGB())
  65538. {
  65539. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65540. }
  65541. else
  65542. {
  65543. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65544. }
  65545. }
  65546. else
  65547. {
  65548. pixel = Colours::transparentWhite;
  65549. }
  65550. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65551. out << String::toHexString (pixelValues, 3, 0);
  65552. charsOnLine += 3;
  65553. if (charsOnLine > 100)
  65554. {
  65555. out << '\n';
  65556. charsOnLine = 0;
  65557. }
  65558. }
  65559. }
  65560. out << "\n>}\n";
  65561. }
  65562. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65563. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65564. {
  65565. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65566. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65567. writeClip();
  65568. out << "gsave ";
  65569. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65570. .scaled (1.0f, -1.0f));
  65571. RectangleList imageClip;
  65572. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65573. imageClip.clipTo (srcClip);
  65574. out << "newpath ";
  65575. int itemsOnLine = 0;
  65576. for (RectangleList::Iterator i (imageClip); i.next();)
  65577. {
  65578. if (++itemsOnLine == 6)
  65579. {
  65580. out << '\n';
  65581. itemsOnLine = 0;
  65582. }
  65583. const Rectangle<int>& r = *i.getRectangle();
  65584. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  65585. }
  65586. out << " clip newpath\n";
  65587. out << w << ' ' << h << " scale\n";
  65588. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  65589. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  65590. out << "false 3 colorimage grestore\n";
  65591. needToClip = true;
  65592. }
  65593. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2)
  65594. {
  65595. Path p;
  65596. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  65597. fillPath (p, AffineTransform::identity);
  65598. }
  65599. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom)
  65600. {
  65601. drawLine (x, top, x, bottom);
  65602. }
  65603. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right)
  65604. {
  65605. drawLine (left, y, right, y);
  65606. }
  65607. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  65608. {
  65609. stateStack.getLast()->font = newFont;
  65610. }
  65611. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  65612. {
  65613. return stateStack.getLast()->font;
  65614. }
  65615. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  65616. {
  65617. Path p;
  65618. Font& font = stateStack.getLast()->font;
  65619. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  65620. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  65621. }
  65622. END_JUCE_NAMESPACE
  65623. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65624. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  65625. BEGIN_JUCE_NAMESPACE
  65626. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  65627. #define JUCE_USE_SSE_INSTRUCTIONS 1
  65628. #endif
  65629. #if JUCE_MSVC
  65630. #if JUCE_DEBUG
  65631. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  65632. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  65633. #endif
  65634. #pragma warning (push)
  65635. #pragma warning (disable: 4127) // "expression is constant" warning
  65636. #endif
  65637. template <class PixelType, bool replaceExisting = false>
  65638. class SolidColourEdgeTableRenderer
  65639. {
  65640. public:
  65641. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour) throw()
  65642. : data (data_),
  65643. sourceColour (colour)
  65644. {
  65645. if (sizeof (PixelType) == 3)
  65646. {
  65647. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  65648. && sourceColour.getGreen() == sourceColour.getBlue();
  65649. filler[0].set (sourceColour);
  65650. filler[1].set (sourceColour);
  65651. filler[2].set (sourceColour);
  65652. filler[3].set (sourceColour);
  65653. }
  65654. }
  65655. forcedinline void setEdgeTableYPos (const int y) throw()
  65656. {
  65657. linePixels = (PixelType*) data.getLinePointer (y);
  65658. }
  65659. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65660. {
  65661. if (replaceExisting)
  65662. linePixels[x].set (sourceColour);
  65663. else
  65664. linePixels[x].blend (sourceColour, alphaLevel);
  65665. }
  65666. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  65667. {
  65668. PixelARGB p (sourceColour);
  65669. p.multiplyAlpha (alphaLevel);
  65670. PixelType* dest = linePixels + x;
  65671. if (replaceExisting || p.getAlpha() >= 0xff)
  65672. replaceLine (dest, p, width);
  65673. else
  65674. blendLine (dest, p, width);
  65675. }
  65676. private:
  65677. const Image::BitmapData& data;
  65678. PixelType* linePixels;
  65679. PixelARGB sourceColour;
  65680. PixelRGB filler [4];
  65681. bool areRGBComponentsEqual;
  65682. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  65683. {
  65684. do
  65685. {
  65686. dest->blend (colour);
  65687. ++dest;
  65688. } while (--width > 0);
  65689. }
  65690. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  65691. {
  65692. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  65693. {
  65694. memset (dest, colour.getRed(), width * 3);
  65695. }
  65696. else
  65697. {
  65698. if (width >> 5)
  65699. {
  65700. const int* const intFiller = (const int*) filler;
  65701. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  65702. {
  65703. dest->set (colour);
  65704. ++dest;
  65705. --width;
  65706. }
  65707. while (width > 4)
  65708. {
  65709. ((int*) dest) [0] = intFiller[0];
  65710. ((int*) dest) [1] = intFiller[1];
  65711. ((int*) dest) [2] = intFiller[2];
  65712. dest = (PixelRGB*) (((uint8*) dest) + 12);
  65713. width -= 4;
  65714. }
  65715. }
  65716. while (--width >= 0)
  65717. {
  65718. dest->set (colour);
  65719. ++dest;
  65720. }
  65721. }
  65722. }
  65723. forcedinline void replaceLine (PixelAlpha* dest, const PixelARGB& colour, int width) const throw()
  65724. {
  65725. memset (dest, colour.getAlpha(), width);
  65726. }
  65727. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  65728. {
  65729. do
  65730. {
  65731. dest->set (colour);
  65732. ++dest;
  65733. } while (--width > 0);
  65734. }
  65735. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  65736. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  65737. };
  65738. class LinearGradientPixelGenerator
  65739. {
  65740. public:
  65741. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  65742. : lookupTable (lookupTable_), numEntries (numEntries_)
  65743. {
  65744. jassert (numEntries_ >= 0);
  65745. Point<float> p1 (gradient.x1, gradient.y1);
  65746. Point<float> p2 (gradient.x2, gradient.y2);
  65747. if (! transform.isIdentity())
  65748. {
  65749. const Line<float> l (p2, p1);
  65750. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  65751. p1.applyTransform (transform);
  65752. p2.applyTransform (transform);
  65753. p3.applyTransform (transform);
  65754. const Line<float> l2 (p2, p3);
  65755. p2 = l2.getPointAlongLineProportionally (l2.findNearestPointTo (p1));
  65756. }
  65757. vertical = fabs (p1.getX() - p2.getX()) < 0.001f;
  65758. horizontal = fabs (p1.getY() - p2.getY()) < 0.001f;
  65759. if (vertical)
  65760. {
  65761. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  65762. start = roundToInt (p1.getY() * scale);
  65763. }
  65764. else if (horizontal)
  65765. {
  65766. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  65767. start = roundToInt (p1.getX() * scale);
  65768. }
  65769. else
  65770. {
  65771. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  65772. yTerm = p1.getY() - p1.getX() / grad;
  65773. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  65774. grad *= scale;
  65775. }
  65776. }
  65777. forcedinline void setY (const int y) throw()
  65778. {
  65779. if (vertical)
  65780. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  65781. else if (! horizontal)
  65782. start = roundToInt ((y - yTerm) * grad);
  65783. }
  65784. inline const PixelARGB getPixel (const int x) const throw()
  65785. {
  65786. return vertical ? linePix
  65787. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  65788. }
  65789. private:
  65790. const PixelARGB* const lookupTable;
  65791. const int numEntries;
  65792. PixelARGB linePix;
  65793. int start, scale;
  65794. double grad, yTerm;
  65795. bool vertical, horizontal;
  65796. enum { numScaleBits = 12 };
  65797. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  65798. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  65799. };
  65800. class RadialGradientPixelGenerator
  65801. {
  65802. public:
  65803. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  65804. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  65805. : lookupTable (lookupTable_),
  65806. numEntries (numEntries_),
  65807. gx1 (gradient.x1),
  65808. gy1 (gradient.y1)
  65809. {
  65810. jassert (numEntries_ >= 0);
  65811. const float gdx = gradient.x1 - gradient.x2;
  65812. const float gdy = gradient.y1 - gradient.y2;
  65813. maxDist = gdx * gdx + gdy * gdy;
  65814. invScale = numEntries / sqrt (maxDist);
  65815. jassert (roundToInt (sqrt (maxDist) * invScale) <= numEntries);
  65816. }
  65817. forcedinline void setY (const int y) throw()
  65818. {
  65819. dy = y - gy1;
  65820. dy *= dy;
  65821. }
  65822. inline const PixelARGB getPixel (const int px) const throw()
  65823. {
  65824. double x = px - gx1;
  65825. x *= x;
  65826. x += dy;
  65827. return lookupTable [x >= maxDist ? numEntries : roundToInt (sqrt (x) * invScale)];
  65828. }
  65829. protected:
  65830. const PixelARGB* const lookupTable;
  65831. const int numEntries;
  65832. const double gx1, gy1;
  65833. double maxDist, invScale, dy;
  65834. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  65835. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  65836. };
  65837. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  65838. {
  65839. public:
  65840. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  65841. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  65842. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  65843. inverseTransform (transform.inverted())
  65844. {
  65845. tM10 = inverseTransform.mat10;
  65846. tM00 = inverseTransform.mat00;
  65847. }
  65848. forcedinline void setY (const int y) throw()
  65849. {
  65850. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  65851. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  65852. }
  65853. inline const PixelARGB getPixel (const int px) const throw()
  65854. {
  65855. double x = px;
  65856. const double y = tM10 * x + lineYM11;
  65857. x = tM00 * x + lineYM01;
  65858. x *= x;
  65859. x += y * y;
  65860. if (x >= maxDist)
  65861. return lookupTable [numEntries];
  65862. else
  65863. return lookupTable [jmin (numEntries, roundToInt (sqrt (x) * invScale))];
  65864. }
  65865. private:
  65866. double tM10, tM00, lineYM01, lineYM11;
  65867. const AffineTransform inverseTransform;
  65868. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  65869. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  65870. };
  65871. template <class PixelType, class GradientType>
  65872. class GradientEdgeTableRenderer : public GradientType
  65873. {
  65874. public:
  65875. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  65876. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  65877. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  65878. destData (destData_)
  65879. {
  65880. }
  65881. forcedinline void setEdgeTableYPos (const int y) throw()
  65882. {
  65883. linePixels = (PixelType*) destData.getLinePointer (y);
  65884. GradientType::setY (y);
  65885. }
  65886. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65887. {
  65888. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  65889. }
  65890. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  65891. {
  65892. PixelType* dest = linePixels + x;
  65893. if (alphaLevel < 0xff)
  65894. {
  65895. do
  65896. {
  65897. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  65898. } while (--width > 0);
  65899. }
  65900. else
  65901. {
  65902. do
  65903. {
  65904. (dest++)->blend (GradientType::getPixel (x++));
  65905. } while (--width > 0);
  65906. }
  65907. }
  65908. private:
  65909. const Image::BitmapData& destData;
  65910. PixelType* linePixels;
  65911. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  65912. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  65913. };
  65914. static forcedinline int safeModulo (int n, const int divisor) throw()
  65915. {
  65916. jassert (divisor > 0);
  65917. n %= divisor;
  65918. return (n < 0) ? (n + divisor) : n;
  65919. }
  65920. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  65921. class ImageFillEdgeTableRenderer
  65922. {
  65923. public:
  65924. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  65925. const Image::BitmapData& srcData_,
  65926. const int extraAlpha_,
  65927. const int x, const int y) throw()
  65928. : destData (destData_),
  65929. srcData (srcData_),
  65930. extraAlpha (extraAlpha_ + 1),
  65931. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  65932. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  65933. {
  65934. }
  65935. forcedinline void setEdgeTableYPos (int y) throw()
  65936. {
  65937. linePixels = (DestPixelType*) destData.getLinePointer (y);
  65938. y -= yOffset;
  65939. if (repeatPattern)
  65940. {
  65941. jassert (y >= 0);
  65942. y %= srcData.height;
  65943. }
  65944. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  65945. }
  65946. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const throw()
  65947. {
  65948. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  65949. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  65950. }
  65951. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  65952. {
  65953. DestPixelType* dest = linePixels + x;
  65954. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  65955. x -= xOffset;
  65956. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  65957. if (alphaLevel < 0xfe)
  65958. {
  65959. do
  65960. {
  65961. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  65962. } while (--width > 0);
  65963. }
  65964. else
  65965. {
  65966. if (repeatPattern)
  65967. {
  65968. do
  65969. {
  65970. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  65971. } while (--width > 0);
  65972. }
  65973. else
  65974. {
  65975. copyRow (dest, sourceLineStart + x, width);
  65976. }
  65977. }
  65978. }
  65979. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width) throw()
  65980. {
  65981. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  65982. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  65983. uint8* mask = (uint8*) (s + x - xOffset);
  65984. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  65985. mask += PixelARGB::indexA;
  65986. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  65987. }
  65988. private:
  65989. const Image::BitmapData& destData;
  65990. const Image::BitmapData& srcData;
  65991. const int extraAlpha, xOffset, yOffset;
  65992. DestPixelType* linePixels;
  65993. SrcPixelType* sourceLineStart;
  65994. template <class PixelType1, class PixelType2>
  65995. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  65996. {
  65997. do
  65998. {
  65999. dest++ ->blend (*src++);
  66000. } while (--width > 0);
  66001. }
  66002. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66003. {
  66004. memcpy (dest, src, width * sizeof (PixelRGB));
  66005. }
  66006. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66007. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66008. };
  66009. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66010. class TransformedImageFillEdgeTableRenderer
  66011. {
  66012. public:
  66013. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66014. const Image::BitmapData& srcData_,
  66015. const AffineTransform& transform,
  66016. const int extraAlpha_,
  66017. const bool betterQuality_) throw()
  66018. : interpolator (transform),
  66019. destData (destData_),
  66020. srcData (srcData_),
  66021. extraAlpha (extraAlpha_ + 1),
  66022. betterQuality (betterQuality_),
  66023. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66024. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66025. maxX (srcData_.width - 1),
  66026. maxY (srcData_.height - 1),
  66027. scratchSize (2048)
  66028. {
  66029. scratchBuffer.malloc (scratchSize);
  66030. }
  66031. ~TransformedImageFillEdgeTableRenderer() throw()
  66032. {
  66033. }
  66034. forcedinline void setEdgeTableYPos (const int newY) throw()
  66035. {
  66036. y = newY;
  66037. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66038. }
  66039. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66040. {
  66041. alphaLevel *= extraAlpha;
  66042. alphaLevel >>= 8;
  66043. SrcPixelType p;
  66044. generate (&p, x, 1);
  66045. linePixels[x].blend (p, alphaLevel);
  66046. }
  66047. forcedinline void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66048. {
  66049. if (width > scratchSize)
  66050. {
  66051. scratchSize = width;
  66052. scratchBuffer.malloc (scratchSize);
  66053. }
  66054. SrcPixelType* span = scratchBuffer;
  66055. generate (span, x, width);
  66056. DestPixelType* dest = linePixels + x;
  66057. alphaLevel *= extraAlpha;
  66058. alphaLevel >>= 8;
  66059. if (alphaLevel < 0xfe)
  66060. {
  66061. do
  66062. {
  66063. dest++ ->blend (*span++, alphaLevel);
  66064. } while (--width > 0);
  66065. }
  66066. else
  66067. {
  66068. do
  66069. {
  66070. dest++ ->blend (*span++);
  66071. } while (--width > 0);
  66072. }
  66073. }
  66074. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width) throw()
  66075. {
  66076. if (width > scratchSize)
  66077. {
  66078. scratchSize = width;
  66079. scratchBuffer.malloc (scratchSize);
  66080. }
  66081. y = y_;
  66082. generate (scratchBuffer, x, width);
  66083. et.clipLineToMask (x, y_,
  66084. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66085. sizeof (SrcPixelType), width);
  66086. }
  66087. private:
  66088. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66089. {
  66090. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66091. do
  66092. {
  66093. int hiResX, hiResY;
  66094. this->interpolator.next (hiResX, hiResY);
  66095. hiResX += pixelOffsetInt;
  66096. hiResY += pixelOffsetInt;
  66097. int loResX = hiResX >> 8;
  66098. int loResY = hiResY >> 8;
  66099. if (repeatPattern)
  66100. {
  66101. loResX = safeModulo (loResX, srcData.width);
  66102. loResY = safeModulo (loResY, srcData.height);
  66103. }
  66104. if (betterQuality
  66105. && ((unsigned int) loResX) < (unsigned int) maxX
  66106. && ((unsigned int) loResY) < (unsigned int) maxY)
  66107. {
  66108. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66109. hiResX &= 255;
  66110. hiResY &= 255;
  66111. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66112. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66113. c[0] += weight * src[0];
  66114. c[1] += weight * src[1];
  66115. c[2] += weight * src[2];
  66116. c[3] += weight * src[3];
  66117. weight = hiResX * (256 - hiResY);
  66118. c[0] += weight * src[4];
  66119. c[1] += weight * src[5];
  66120. c[2] += weight * src[6];
  66121. c[3] += weight * src[7];
  66122. src += this->srcData.lineStride;
  66123. weight = (256 - hiResX) * hiResY;
  66124. c[0] += weight * src[0];
  66125. c[1] += weight * src[1];
  66126. c[2] += weight * src[2];
  66127. c[3] += weight * src[3];
  66128. weight = hiResX * hiResY;
  66129. c[0] += weight * src[4];
  66130. c[1] += weight * src[5];
  66131. c[2] += weight * src[6];
  66132. c[3] += weight * src[7];
  66133. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66134. (uint8) (c[PixelARGB::indexR] >> 16),
  66135. (uint8) (c[PixelARGB::indexG] >> 16),
  66136. (uint8) (c[PixelARGB::indexB] >> 16));
  66137. }
  66138. else
  66139. {
  66140. if (! repeatPattern)
  66141. {
  66142. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66143. if (loResX < 0) loResX = 0;
  66144. if (loResY < 0) loResY = 0;
  66145. if (loResX > maxX) loResX = maxX;
  66146. if (loResY > maxY) loResY = maxY;
  66147. }
  66148. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66149. }
  66150. ++dest;
  66151. } while (--numPixels > 0);
  66152. }
  66153. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66154. {
  66155. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66156. do
  66157. {
  66158. int hiResX, hiResY;
  66159. this->interpolator.next (hiResX, hiResY);
  66160. hiResX += pixelOffsetInt;
  66161. hiResY += pixelOffsetInt;
  66162. int loResX = hiResX >> 8;
  66163. int loResY = hiResY >> 8;
  66164. if (repeatPattern)
  66165. {
  66166. loResX = safeModulo (loResX, srcData.width);
  66167. loResY = safeModulo (loResY, srcData.height);
  66168. }
  66169. if (betterQuality
  66170. && ((unsigned int) loResX) < (unsigned int) maxX
  66171. && ((unsigned int) loResY) < (unsigned int) maxY)
  66172. {
  66173. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66174. hiResX &= 255;
  66175. hiResY &= 255;
  66176. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66177. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66178. c[0] += weight * src[0];
  66179. c[1] += weight * src[1];
  66180. c[2] += weight * src[2];
  66181. weight = hiResX * (256 - hiResY);
  66182. c[0] += weight * src[3];
  66183. c[1] += weight * src[4];
  66184. c[2] += weight * src[5];
  66185. src += this->srcData.lineStride;
  66186. weight = (256 - hiResX) * hiResY;
  66187. c[0] += weight * src[0];
  66188. c[1] += weight * src[1];
  66189. c[2] += weight * src[2];
  66190. weight = hiResX * hiResY;
  66191. c[0] += weight * src[3];
  66192. c[1] += weight * src[4];
  66193. c[2] += weight * src[5];
  66194. dest->setARGB ((uint8) 255,
  66195. (uint8) (c[PixelRGB::indexR] >> 16),
  66196. (uint8) (c[PixelRGB::indexG] >> 16),
  66197. (uint8) (c[PixelRGB::indexB] >> 16));
  66198. }
  66199. else
  66200. {
  66201. if (! repeatPattern)
  66202. {
  66203. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66204. if (loResX < 0) loResX = 0;
  66205. if (loResY < 0) loResY = 0;
  66206. if (loResX > maxX) loResX = maxX;
  66207. if (loResY > maxY) loResY = maxY;
  66208. }
  66209. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66210. }
  66211. ++dest;
  66212. } while (--numPixels > 0);
  66213. }
  66214. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66215. {
  66216. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66217. do
  66218. {
  66219. int hiResX, hiResY;
  66220. this->interpolator.next (hiResX, hiResY);
  66221. hiResX += pixelOffsetInt;
  66222. hiResY += pixelOffsetInt;
  66223. int loResX = hiResX >> 8;
  66224. int loResY = hiResY >> 8;
  66225. if (repeatPattern)
  66226. {
  66227. loResX = safeModulo (loResX, srcData.width);
  66228. loResY = safeModulo (loResY, srcData.height);
  66229. }
  66230. if (betterQuality
  66231. && ((unsigned int) loResX) < (unsigned int) maxX
  66232. && ((unsigned int) loResY) < (unsigned int) maxY)
  66233. {
  66234. hiResX &= 255;
  66235. hiResY &= 255;
  66236. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66237. uint32 c = 256 * 128;
  66238. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66239. c += src[1] * (hiResX * (256 - hiResY));
  66240. src += this->srcData.lineStride;
  66241. c += src[0] * ((256 - hiResX) * hiResY);
  66242. c += src[1] * (hiResX * hiResY);
  66243. *((uint8*) dest) = (uint8) c;
  66244. }
  66245. else
  66246. {
  66247. if (! repeatPattern)
  66248. {
  66249. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66250. if (loResX < 0) loResX = 0;
  66251. if (loResY < 0) loResY = 0;
  66252. if (loResX > maxX) loResX = maxX;
  66253. if (loResY > maxY) loResY = maxY;
  66254. }
  66255. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66256. }
  66257. ++dest;
  66258. } while (--numPixels > 0);
  66259. }
  66260. class TransformedImageSpanInterpolator
  66261. {
  66262. public:
  66263. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66264. : inverseTransform (transform.inverted())
  66265. {}
  66266. void setStartOfLine (float x, float y, const int numPixels) throw()
  66267. {
  66268. float x1 = x, y1 = y;
  66269. inverseTransform.transformPoint (x1, y1);
  66270. x += numPixels;
  66271. inverseTransform.transformPoint (x, y);
  66272. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66273. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66274. }
  66275. void next (int& x, int& y) throw()
  66276. {
  66277. x = xBresenham.n;
  66278. xBresenham.stepToNext();
  66279. y = yBresenham.n;
  66280. yBresenham.stepToNext();
  66281. }
  66282. private:
  66283. class BresenhamInterpolator
  66284. {
  66285. public:
  66286. BresenhamInterpolator() throw() {}
  66287. void set (const int n1, const int n2, const int numSteps_) throw()
  66288. {
  66289. numSteps = jmax (1, numSteps_);
  66290. step = (n2 - n1) / numSteps;
  66291. remainder = modulo = (n2 - n1) % numSteps;
  66292. n = n1;
  66293. if (modulo <= 0)
  66294. {
  66295. modulo += numSteps;
  66296. remainder += numSteps;
  66297. --step;
  66298. }
  66299. modulo -= numSteps;
  66300. }
  66301. forcedinline void stepToNext() throw()
  66302. {
  66303. modulo += remainder;
  66304. n += step;
  66305. if (modulo > 0)
  66306. {
  66307. modulo -= numSteps;
  66308. ++n;
  66309. }
  66310. }
  66311. int n;
  66312. private:
  66313. int numSteps, step, modulo, remainder;
  66314. };
  66315. const AffineTransform inverseTransform;
  66316. BresenhamInterpolator xBresenham, yBresenham;
  66317. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66318. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66319. };
  66320. TransformedImageSpanInterpolator interpolator;
  66321. const Image::BitmapData& destData;
  66322. const Image::BitmapData& srcData;
  66323. const int extraAlpha;
  66324. const bool betterQuality;
  66325. const float pixelOffset;
  66326. const int pixelOffsetInt, maxX, maxY;
  66327. int y;
  66328. DestPixelType* linePixels;
  66329. HeapBlock <SrcPixelType> scratchBuffer;
  66330. int scratchSize;
  66331. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66332. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66333. };
  66334. class LLGCSavedState
  66335. {
  66336. public:
  66337. LLGCSavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_,
  66338. const Font& font_, const FillType& fillType_,
  66339. const Graphics::ResamplingQuality interpolationQuality_) throw()
  66340. : edgeTable (new EdgeTableHolder (EdgeTable (clip_))),
  66341. xOffset (xOffset_), yOffset (yOffset_),
  66342. font (font_), fillType (fillType_),
  66343. interpolationQuality (interpolationQuality_)
  66344. {
  66345. }
  66346. LLGCSavedState (const LLGCSavedState& other) throw()
  66347. : edgeTable (other.edgeTable), xOffset (other.xOffset),
  66348. yOffset (other.yOffset), font (other.font),
  66349. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  66350. {
  66351. }
  66352. ~LLGCSavedState() throw()
  66353. {
  66354. }
  66355. bool clipToRectangle (const Rectangle<int>& r) throw()
  66356. {
  66357. dupeEdgeTableIfMultiplyReferenced();
  66358. edgeTable->edgeTable.clipToRectangle (r.translated (xOffset, yOffset));
  66359. return ! edgeTable->edgeTable.isEmpty();
  66360. }
  66361. bool clipToRectangleList (const RectangleList& r) throw()
  66362. {
  66363. dupeEdgeTableIfMultiplyReferenced();
  66364. RectangleList offsetList (r);
  66365. offsetList.offsetAll (xOffset, yOffset);
  66366. EdgeTable e2 (offsetList);
  66367. edgeTable->edgeTable.clipToEdgeTable (e2);
  66368. return ! edgeTable->edgeTable.isEmpty();
  66369. }
  66370. bool excludeClipRectangle (const Rectangle<int>& r) throw()
  66371. {
  66372. dupeEdgeTableIfMultiplyReferenced();
  66373. edgeTable->edgeTable.excludeRectangle (r.translated (xOffset, yOffset));
  66374. return ! edgeTable->edgeTable.isEmpty();
  66375. }
  66376. void clipToPath (const Path& p, const AffineTransform& transform) throw()
  66377. {
  66378. dupeEdgeTableIfMultiplyReferenced();
  66379. EdgeTable et (edgeTable->edgeTable.getMaximumBounds(), p, transform.translated ((float) xOffset, (float) yOffset));
  66380. edgeTable->edgeTable.clipToEdgeTable (et);
  66381. }
  66382. void fillEdgeTable (Image& image, EdgeTable& et, const bool replaceContents = false) throw()
  66383. {
  66384. et.clipToEdgeTable (edgeTable->edgeTable);
  66385. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  66386. if (fillType.isGradient())
  66387. {
  66388. jassert (! replaceContents); // that option is just for solid colours
  66389. ColourGradient g2 (*(fillType.gradient));
  66390. g2.multiplyOpacity (fillType.getOpacity());
  66391. g2.x1 -= 0.5f; g2.y1 -= 0.5f;
  66392. g2.x2 -= 0.5f; g2.y2 -= 0.5f;
  66393. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  66394. const bool isIdentity = transform.isOnlyTranslation();
  66395. if (isIdentity)
  66396. {
  66397. // If our translation doesn't involve any distortion, we can speed it up..
  66398. transform.transformPoint (g2.x1, g2.y1);
  66399. transform.transformPoint (g2.x2, g2.y2);
  66400. transform = AffineTransform::identity;
  66401. }
  66402. HeapBlock <PixelARGB> lookupTable;
  66403. const int numLookupEntries = g2.createLookupTable (transform, lookupTable);
  66404. jassert (numLookupEntries > 0);
  66405. switch (image.getFormat())
  66406. {
  66407. case Image::ARGB: renderGradient (et, destData, g2, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66408. case Image::RGB: renderGradient (et, destData, g2, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66409. default: renderGradient (et, destData, g2, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66410. }
  66411. }
  66412. else if (fillType.isTiledImage())
  66413. {
  66414. renderImage (image, *(fillType.image), fillType.image->getBounds(), fillType.transform, &et);
  66415. }
  66416. else
  66417. {
  66418. const PixelARGB fillColour (fillType.colour.getPixelARGB());
  66419. switch (image.getFormat())
  66420. {
  66421. case Image::ARGB: renderSolidFill (et, destData, fillColour, replaceContents, (PixelARGB*) 0); break;
  66422. case Image::RGB: renderSolidFill (et, destData, fillColour, replaceContents, (PixelRGB*) 0); break;
  66423. default: renderSolidFill (et, destData, fillColour, replaceContents, (PixelAlpha*) 0); break;
  66424. }
  66425. }
  66426. }
  66427. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  66428. const AffineTransform& t, const EdgeTable* const tiledFillClipRegion) throw()
  66429. {
  66430. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  66431. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  66432. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66433. const int alpha = fillType.colour.getAlpha();
  66434. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  66435. if (transform.isOnlyTranslation())
  66436. {
  66437. // If our translation doesn't involve any distortion, just use a simple blit..
  66438. int tx = (int) (transform.getTranslationX() * 256.0f);
  66439. int ty = (int) (transform.getTranslationY() * 256.0f);
  66440. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66441. {
  66442. tx = ((tx + 128) >> 8);
  66443. ty = ((ty + 128) >> 8);
  66444. if (tiledFillClipRegion != 0)
  66445. {
  66446. blittedRenderImage (sourceImage, destImage, *tiledFillClipRegion, destData, srcData, alpha, tx, ty, true);
  66447. }
  66448. else
  66449. {
  66450. EdgeTable et (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds()));
  66451. et.clipToEdgeTable (edgeTable->edgeTable);
  66452. if (! et.isEmpty())
  66453. blittedRenderImage (sourceImage, destImage, et, destData, srcData, alpha, tx, ty, false);
  66454. }
  66455. return;
  66456. }
  66457. }
  66458. if (transform.isSingularity())
  66459. return;
  66460. if (tiledFillClipRegion != 0)
  66461. {
  66462. transformedRenderImage (sourceImage, destImage, *tiledFillClipRegion, destData, srcData, alpha, transform, betterQuality, true);
  66463. }
  66464. else
  66465. {
  66466. Path p;
  66467. p.addRectangle (0.0f, 0.0f, (float) srcClip.getWidth(), (float) srcClip.getHeight());
  66468. EdgeTable et (edgeTable->edgeTable.getMaximumBounds(), p, transform);
  66469. et.clipToEdgeTable (edgeTable->edgeTable);
  66470. if (! et.isEmpty())
  66471. transformedRenderImage (sourceImage, destImage, et, destData, srcData, alpha, transform, betterQuality, false);
  66472. }
  66473. }
  66474. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t) throw()
  66475. {
  66476. if (! image.hasAlphaChannel())
  66477. {
  66478. Path p;
  66479. p.addRectangle (srcClip);
  66480. clipToPath (p, t);
  66481. return;
  66482. }
  66483. dupeEdgeTableIfMultiplyReferenced();
  66484. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  66485. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66486. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  66487. EdgeTable& et = edgeTable->edgeTable;
  66488. if (transform.isOnlyTranslation())
  66489. {
  66490. // If our translation doesn't involve any distortion, just use a simple blit..
  66491. const int tx = (int) (transform.getTranslationX() * 256.0f);
  66492. const int ty = (int) (transform.getTranslationY() * 256.0f);
  66493. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66494. {
  66495. const int imageX = ((tx + 128) >> 8);
  66496. const int imageY = ((ty + 128) >> 8);
  66497. if (image.getFormat() == Image::ARGB)
  66498. straightClipImage (et, srcData, imageX, imageY, (PixelARGB*)0);
  66499. else
  66500. straightClipImage (et, srcData, imageX, imageY, (PixelAlpha*)0);
  66501. return;
  66502. }
  66503. }
  66504. if (transform.isSingularity())
  66505. {
  66506. et.clipToRectangle (Rectangle<int>());
  66507. return;
  66508. }
  66509. {
  66510. Path p;
  66511. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  66512. EdgeTable et2 (et.getMaximumBounds(), p, transform);
  66513. et.clipToEdgeTable (et2);
  66514. }
  66515. if (! et.isEmpty())
  66516. {
  66517. if (image.getFormat() == Image::ARGB)
  66518. transformedClipImage (et, srcData, transform, betterQuality, (PixelARGB*)0);
  66519. else
  66520. transformedClipImage (et, srcData, transform, betterQuality, (PixelAlpha*)0);
  66521. }
  66522. }
  66523. template <class SrcPixelType>
  66524. void transformedClipImage (EdgeTable& et, const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType *) throw()
  66525. {
  66526. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  66527. for (int y = 0; y < et.getMaximumBounds().getHeight(); ++y)
  66528. renderer.clipEdgeTableLine (et, et.getMaximumBounds().getX(), y + et.getMaximumBounds().getY(),
  66529. et.getMaximumBounds().getWidth());
  66530. }
  66531. template <class SrcPixelType>
  66532. void straightClipImage (EdgeTable& et, const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType *) throw()
  66533. {
  66534. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  66535. et.clipToRectangle (r);
  66536. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  66537. for (int y = 0; y < r.getHeight(); ++y)
  66538. renderer.clipEdgeTableLine (et, r.getX(), y + r.getY(), r.getWidth());
  66539. }
  66540. class EdgeTableHolder : public ReferenceCountedObject
  66541. {
  66542. public:
  66543. EdgeTableHolder (const EdgeTable& e) throw() : edgeTable (e) {}
  66544. EdgeTable edgeTable;
  66545. };
  66546. ReferenceCountedObjectPtr<EdgeTableHolder> edgeTable;
  66547. int xOffset, yOffset;
  66548. Font font;
  66549. FillType fillType;
  66550. Graphics::ResamplingQuality interpolationQuality;
  66551. private:
  66552. LLGCSavedState& operator= (const LLGCSavedState&);
  66553. void dupeEdgeTableIfMultiplyReferenced() throw()
  66554. {
  66555. if (edgeTable->getReferenceCount() > 1)
  66556. edgeTable = new EdgeTableHolder (edgeTable->edgeTable);
  66557. }
  66558. template <class DestPixelType>
  66559. void renderGradient (EdgeTable& et, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66560. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*) throw()
  66561. {
  66562. jassert (destData.pixelStride == sizeof (DestPixelType));
  66563. if (g.isRadial)
  66564. {
  66565. if (isIdentity)
  66566. {
  66567. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66568. et.iterate (renderer);
  66569. }
  66570. else
  66571. {
  66572. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66573. et.iterate (renderer);
  66574. }
  66575. }
  66576. else
  66577. {
  66578. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66579. et.iterate (renderer);
  66580. }
  66581. }
  66582. template <class DestPixelType>
  66583. void renderSolidFill (EdgeTable& et, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*) throw()
  66584. {
  66585. jassert (destData.pixelStride == sizeof (DestPixelType));
  66586. if (replaceContents)
  66587. {
  66588. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66589. et.iterate (r);
  66590. }
  66591. else
  66592. {
  66593. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66594. et.iterate (r);
  66595. }
  66596. }
  66597. void transformedRenderImage (const Image& srcImage, Image& destImage, const EdgeTable& et, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66598. const int alpha, const AffineTransform& transform, const bool betterQuality, const bool repeatPattern) throw()
  66599. {
  66600. switch (destImage.getFormat())
  66601. {
  66602. case Image::ARGB:
  66603. switch (srcImage.getFormat())
  66604. {
  66605. case Image::ARGB:
  66606. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66607. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66608. break;
  66609. case Image::RGB:
  66610. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66611. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66612. break;
  66613. default:
  66614. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66615. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66616. break;
  66617. }
  66618. break;
  66619. case Image::RGB:
  66620. switch (srcImage.getFormat())
  66621. {
  66622. case Image::ARGB:
  66623. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66624. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66625. break;
  66626. case Image::RGB:
  66627. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66628. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66629. break;
  66630. default:
  66631. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66632. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66633. break;
  66634. }
  66635. break;
  66636. default:
  66637. switch (srcImage.getFormat())
  66638. {
  66639. case Image::ARGB:
  66640. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66641. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66642. break;
  66643. case Image::RGB:
  66644. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66645. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66646. break;
  66647. default:
  66648. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66649. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66650. break;
  66651. }
  66652. break;
  66653. }
  66654. }
  66655. void blittedRenderImage (const Image& srcImage, Image& destImage, const EdgeTable& et, const Image::BitmapData& destData,
  66656. const Image::BitmapData& srcData, const int alpha, int x, int y, const bool repeatPattern) throw()
  66657. {
  66658. switch (destImage.getFormat())
  66659. {
  66660. case Image::ARGB:
  66661. switch (srcImage.getFormat())
  66662. {
  66663. case Image::ARGB:
  66664. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66665. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66666. break;
  66667. case Image::RGB:
  66668. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66669. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66670. break;
  66671. default:
  66672. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66673. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66674. break;
  66675. }
  66676. break;
  66677. case Image::RGB:
  66678. switch (srcImage.getFormat())
  66679. {
  66680. case Image::ARGB:
  66681. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66682. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66683. break;
  66684. case Image::RGB:
  66685. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66686. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66687. break;
  66688. default:
  66689. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66690. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66691. break;
  66692. }
  66693. break;
  66694. default:
  66695. switch (srcImage.getFormat())
  66696. {
  66697. case Image::ARGB:
  66698. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66699. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66700. break;
  66701. case Image::RGB:
  66702. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66703. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66704. break;
  66705. default:
  66706. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66707. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66708. break;
  66709. }
  66710. break;
  66711. }
  66712. }
  66713. };
  66714. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  66715. : image (image_)
  66716. {
  66717. currentState = new LLGCSavedState (image_.getBounds(), 0, 0, Font(),
  66718. FillType(), Graphics::mediumResamplingQuality);
  66719. }
  66720. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  66721. {
  66722. }
  66723. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  66724. {
  66725. return false;
  66726. }
  66727. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  66728. {
  66729. currentState->xOffset += x;
  66730. currentState->yOffset += y;
  66731. }
  66732. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  66733. {
  66734. return currentState->clipToRectangle (r);
  66735. }
  66736. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66737. {
  66738. return currentState->clipToRectangleList (clipRegion);
  66739. }
  66740. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66741. {
  66742. currentState->excludeClipRectangle (r);
  66743. }
  66744. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66745. {
  66746. currentState->clipToPath (path, transform);
  66747. }
  66748. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  66749. {
  66750. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  66751. }
  66752. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66753. {
  66754. return currentState->edgeTable->edgeTable.getMaximumBounds()
  66755. .intersects (r.translated (currentState->xOffset, currentState->yOffset));
  66756. }
  66757. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  66758. {
  66759. return currentState->edgeTable->edgeTable.getMaximumBounds().translated (-currentState->xOffset, -currentState->yOffset);
  66760. }
  66761. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  66762. {
  66763. return currentState->edgeTable->edgeTable.isEmpty();
  66764. }
  66765. void LowLevelGraphicsSoftwareRenderer::saveState()
  66766. {
  66767. stateStack.add (new LLGCSavedState (*currentState));
  66768. }
  66769. void LowLevelGraphicsSoftwareRenderer::restoreState()
  66770. {
  66771. LLGCSavedState* const top = stateStack.getLast();
  66772. if (top != 0)
  66773. {
  66774. currentState = top;
  66775. stateStack.removeLast (1, false);
  66776. }
  66777. else
  66778. {
  66779. jassertfalse // trying to pop with an empty stack!
  66780. }
  66781. }
  66782. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  66783. {
  66784. currentState->fillType = fillType;
  66785. }
  66786. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  66787. {
  66788. currentState->fillType.setOpacity (newOpacity);
  66789. }
  66790. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  66791. {
  66792. currentState->interpolationQuality = quality;
  66793. }
  66794. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  66795. {
  66796. const Rectangle<int>& totalClip = currentState->edgeTable->edgeTable.getMaximumBounds();
  66797. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (currentState->xOffset, currentState->yOffset)));
  66798. if (! clipped.isEmpty())
  66799. {
  66800. EdgeTable et (clipped);
  66801. currentState->fillEdgeTable (image, et, replaceExistingContents);
  66802. }
  66803. }
  66804. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  66805. {
  66806. EdgeTable et (currentState->edgeTable->edgeTable.getMaximumBounds(),
  66807. path, transform.translated ((float) currentState->xOffset,
  66808. (float) currentState->yOffset));
  66809. currentState->fillEdgeTable (image, et);
  66810. }
  66811. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  66812. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  66813. {
  66814. jassert (sourceImage.getBounds().contains (srcClip));
  66815. currentState->renderImage (image, sourceImage, srcClip, transform,
  66816. fillEntireClipAsTiles ? &(currentState->edgeTable->edgeTable) : 0);
  66817. }
  66818. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2)
  66819. {
  66820. Path p;
  66821. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  66822. fillPath (p, AffineTransform::identity);
  66823. }
  66824. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom)
  66825. {
  66826. if (bottom > top)
  66827. {
  66828. EdgeTable et ((float) (x + currentState->xOffset), (float) (top + currentState->yOffset), 1.0f, (float) (bottom - top));
  66829. currentState->fillEdgeTable (image, et);
  66830. }
  66831. }
  66832. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right)
  66833. {
  66834. if (right > left)
  66835. {
  66836. EdgeTable et ((float) (left + currentState->xOffset), (float) (y + currentState->yOffset),
  66837. (float) (right - left), 1.0f);
  66838. currentState->fillEdgeTable (image, et);
  66839. }
  66840. }
  66841. class GlyphCache : private DeletedAtShutdown
  66842. {
  66843. public:
  66844. GlyphCache() throw()
  66845. : accessCounter (0), hits (0), misses (0)
  66846. {
  66847. for (int i = 120; --i >= 0;)
  66848. glyphs.add (new CachedGlyph());
  66849. }
  66850. ~GlyphCache() throw()
  66851. {
  66852. clearSingletonInstance();
  66853. }
  66854. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  66855. void drawGlyph (LLGCSavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y) throw()
  66856. {
  66857. ++accessCounter;
  66858. int oldestCounter = std::numeric_limits<int>::max();
  66859. CachedGlyph* oldest = 0;
  66860. for (int i = glyphs.size(); --i >= 0;)
  66861. {
  66862. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  66863. if (glyph->glyph == glyphNumber && glyph->font == font)
  66864. {
  66865. ++hits;
  66866. glyph->lastAccessCount = accessCounter;
  66867. glyph->draw (state, image, x, y);
  66868. return;
  66869. }
  66870. if (glyph->lastAccessCount <= oldestCounter)
  66871. {
  66872. oldestCounter = glyph->lastAccessCount;
  66873. oldest = glyph;
  66874. }
  66875. }
  66876. if (hits + ++misses > (glyphs.size() << 4))
  66877. {
  66878. if (misses * 2 > hits)
  66879. {
  66880. for (int i = 32; --i >= 0;)
  66881. glyphs.add (new CachedGlyph());
  66882. }
  66883. hits = misses = 0;
  66884. oldest = glyphs.getLast();
  66885. }
  66886. jassert (oldest != 0);
  66887. oldest->lastAccessCount = accessCounter;
  66888. oldest->generate (font, glyphNumber);
  66889. oldest->draw (state, image, x, y);
  66890. }
  66891. class CachedGlyph
  66892. {
  66893. public:
  66894. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  66895. ~CachedGlyph() {}
  66896. void draw (LLGCSavedState& state, Image& image, const float x, const float y) const throw()
  66897. {
  66898. if (edgeTable != 0)
  66899. {
  66900. EdgeTable et (*edgeTable);
  66901. et.translate (x, roundToInt (y));
  66902. state.fillEdgeTable (image, et, false);
  66903. }
  66904. }
  66905. void generate (const Font& newFont, const int glyphNumber) throw()
  66906. {
  66907. font = newFont;
  66908. glyph = glyphNumber;
  66909. edgeTable = 0;
  66910. Path glyphPath;
  66911. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  66912. if (! glyphPath.isEmpty())
  66913. {
  66914. const float fontHeight = font.getHeight();
  66915. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  66916. .translated (0.0f, -0.5f));
  66917. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  66918. glyphPath, transform);
  66919. }
  66920. }
  66921. int glyph, lastAccessCount;
  66922. Font font;
  66923. juce_UseDebuggingNewOperator
  66924. private:
  66925. ScopedPointer <EdgeTable> edgeTable;
  66926. CachedGlyph (const CachedGlyph&);
  66927. CachedGlyph& operator= (const CachedGlyph&);
  66928. };
  66929. juce_UseDebuggingNewOperator
  66930. private:
  66931. OwnedArray <CachedGlyph> glyphs;
  66932. int accessCounter, hits, misses;
  66933. GlyphCache (const GlyphCache&);
  66934. GlyphCache& operator= (const GlyphCache&);
  66935. };
  66936. juce_ImplementSingleton_SingleThreaded (GlyphCache);
  66937. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  66938. {
  66939. currentState->font = newFont;
  66940. }
  66941. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  66942. {
  66943. return currentState->font;
  66944. }
  66945. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66946. {
  66947. Font& f = currentState->font;
  66948. if (transform.isOnlyTranslation())
  66949. {
  66950. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  66951. transform.getTranslationX() + (float) currentState->xOffset,
  66952. transform.getTranslationY() + (float) currentState->yOffset);
  66953. }
  66954. else
  66955. {
  66956. Path p;
  66957. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66958. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  66959. }
  66960. }
  66961. #if JUCE_MSVC
  66962. #pragma warning (pop)
  66963. #if JUCE_DEBUG
  66964. #pragma optimize ("", on) // resets optimisations to the project defaults
  66965. #endif
  66966. #endif
  66967. END_JUCE_NAMESPACE
  66968. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66969. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  66970. BEGIN_JUCE_NAMESPACE
  66971. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  66972. : flags (other.flags)
  66973. {
  66974. }
  66975. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  66976. {
  66977. flags = other.flags;
  66978. return *this;
  66979. }
  66980. void RectanglePlacement::applyTo (double& x, double& y,
  66981. double& w, double& h,
  66982. const double dx, const double dy,
  66983. const double dw, const double dh) const throw()
  66984. {
  66985. if (w == 0 || h == 0)
  66986. return;
  66987. if ((flags & stretchToFit) != 0)
  66988. {
  66989. x = dx;
  66990. y = dy;
  66991. w = dw;
  66992. h = dh;
  66993. }
  66994. else
  66995. {
  66996. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  66997. : jmin (dw / w, dh / h);
  66998. if ((flags & onlyReduceInSize) != 0)
  66999. scale = jmin (scale, 1.0);
  67000. if ((flags & onlyIncreaseInSize) != 0)
  67001. scale = jmax (scale, 1.0);
  67002. w *= scale;
  67003. h *= scale;
  67004. if ((flags & xLeft) != 0)
  67005. x = dx;
  67006. else if ((flags & xRight) != 0)
  67007. x = dx + dw - w;
  67008. else
  67009. x = dx + (dw - w) * 0.5;
  67010. if ((flags & yTop) != 0)
  67011. y = dy;
  67012. else if ((flags & yBottom) != 0)
  67013. y = dy + dh - h;
  67014. else
  67015. y = dy + (dh - h) * 0.5;
  67016. }
  67017. }
  67018. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67019. float w, float h,
  67020. const float dx, const float dy,
  67021. const float dw, const float dh) const throw()
  67022. {
  67023. if (w == 0 || h == 0)
  67024. return AffineTransform::identity;
  67025. const float scaleX = dw / w;
  67026. const float scaleY = dh / h;
  67027. if ((flags & stretchToFit) != 0)
  67028. return AffineTransform::translation (-x, -y)
  67029. .scaled (scaleX, scaleY)
  67030. .translated (dx, dy);
  67031. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67032. : jmin (scaleX, scaleY);
  67033. if ((flags & onlyReduceInSize) != 0)
  67034. scale = jmin (scale, 1.0f);
  67035. if ((flags & onlyIncreaseInSize) != 0)
  67036. scale = jmax (scale, 1.0f);
  67037. w *= scale;
  67038. h *= scale;
  67039. float newX = dx;
  67040. if ((flags & xRight) != 0)
  67041. newX += dw - w; // right
  67042. else if ((flags & xLeft) == 0)
  67043. newX += (dw - w) / 2.0f; // centre
  67044. float newY = dy;
  67045. if ((flags & yBottom) != 0)
  67046. newY += dh - h; // bottom
  67047. else if ((flags & yTop) == 0)
  67048. newY += (dh - h) / 2.0f; // centre
  67049. return AffineTransform::translation (-x, -y)
  67050. .scaled (scale, scale)
  67051. .translated (newX, newY);
  67052. }
  67053. END_JUCE_NAMESPACE
  67054. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  67055. /*** Start of inlined file: juce_Drawable.cpp ***/
  67056. BEGIN_JUCE_NAMESPACE
  67057. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  67058. const AffineTransform& transform_,
  67059. const float opacity_) throw()
  67060. : g (g_),
  67061. transform (transform_),
  67062. opacity (opacity_)
  67063. {
  67064. }
  67065. Drawable::Drawable()
  67066. {
  67067. }
  67068. Drawable::~Drawable()
  67069. {
  67070. }
  67071. void Drawable::draw (Graphics& g, const float opacity,
  67072. const AffineTransform& transform) const
  67073. {
  67074. render (RenderingContext (g, transform, opacity));
  67075. }
  67076. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  67077. {
  67078. draw (g, opacity, AffineTransform::translation (x, y));
  67079. }
  67080. void Drawable::drawWithin (Graphics& g,
  67081. const int destX,
  67082. const int destY,
  67083. const int destW,
  67084. const int destH,
  67085. const RectanglePlacement& placement,
  67086. const float opacity) const
  67087. {
  67088. if (destW > 0 && destH > 0)
  67089. {
  67090. Rectangle<float> bounds (getBounds());
  67091. draw (g, opacity,
  67092. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  67093. (float) destX, (float) destY,
  67094. (float) destW, (float) destH));
  67095. }
  67096. }
  67097. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  67098. {
  67099. Drawable* result = 0;
  67100. Image* const image = ImageFileFormat::loadFrom (data, (int) numBytes);
  67101. if (image != 0)
  67102. {
  67103. DrawableImage* const di = new DrawableImage();
  67104. di->setImage (image, true);
  67105. result = di;
  67106. }
  67107. else
  67108. {
  67109. const String asString (String::createStringFromData (data, (int) numBytes));
  67110. XmlDocument doc (asString);
  67111. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  67112. if (outer != 0 && outer->hasTagName ("svg"))
  67113. {
  67114. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  67115. if (svg != 0)
  67116. result = Drawable::createFromSVG (*svg);
  67117. }
  67118. }
  67119. return result;
  67120. }
  67121. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  67122. {
  67123. MemoryBlock mb;
  67124. dataSource.readIntoMemoryBlock (mb);
  67125. return createFromImageData (mb.getData(), mb.getSize());
  67126. }
  67127. Drawable* Drawable::createFromImageFile (const File& file)
  67128. {
  67129. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  67130. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  67131. }
  67132. Drawable* Drawable::createFromValueTree (const ValueTree& tree)
  67133. {
  67134. Drawable* d = DrawablePath::createFromValueTree (tree);
  67135. if (d == 0)
  67136. {
  67137. d = DrawableComposite::createFromValueTree (tree);
  67138. if (d == 0)
  67139. {
  67140. d = DrawableImage::createFromValueTree (tree);
  67141. if (d == 0)
  67142. d = DrawableText::createFromValueTree (tree);
  67143. }
  67144. }
  67145. return d;
  67146. }
  67147. END_JUCE_NAMESPACE
  67148. /*** End of inlined file: juce_Drawable.cpp ***/
  67149. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  67150. BEGIN_JUCE_NAMESPACE
  67151. DrawableComposite::DrawableComposite()
  67152. {
  67153. }
  67154. DrawableComposite::~DrawableComposite()
  67155. {
  67156. }
  67157. void DrawableComposite::insertDrawable (Drawable* drawable,
  67158. const AffineTransform& transform,
  67159. const int index)
  67160. {
  67161. if (drawable != 0)
  67162. {
  67163. if (! drawables.contains (drawable))
  67164. {
  67165. drawables.insert (index, drawable);
  67166. if (transform.isIdentity())
  67167. transforms.insert (index, 0);
  67168. else
  67169. transforms.insert (index, new AffineTransform (transform));
  67170. }
  67171. else
  67172. {
  67173. jassertfalse // trying to add a drawable that's already in here!
  67174. }
  67175. }
  67176. }
  67177. void DrawableComposite::insertDrawable (const Drawable& drawable,
  67178. const AffineTransform& transform,
  67179. const int index)
  67180. {
  67181. insertDrawable (drawable.createCopy(), transform, index);
  67182. }
  67183. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  67184. {
  67185. drawables.remove (index, deleteDrawable);
  67186. transforms.remove (index);
  67187. }
  67188. void DrawableComposite::bringToFront (const int index)
  67189. {
  67190. if (index >= 0 && index < drawables.size() - 1)
  67191. {
  67192. drawables.move (index, -1);
  67193. transforms.move (index, -1);
  67194. }
  67195. }
  67196. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  67197. {
  67198. if (drawables.size() > 0 && context.opacity > 0)
  67199. {
  67200. if (context.opacity >= 1.0f || drawables.size() == 1)
  67201. {
  67202. Drawable::RenderingContext contextCopy (context);
  67203. for (int i = 0; i < drawables.size(); ++i)
  67204. {
  67205. const AffineTransform* const t = transforms.getUnchecked(i);
  67206. contextCopy.transform = (t == 0) ? context.transform
  67207. : t->followedBy (context.transform);
  67208. drawables.getUnchecked(i)->render (contextCopy);
  67209. }
  67210. }
  67211. else
  67212. {
  67213. // To correctly render a whole composite layer with an overall transparency,
  67214. // we need to render everything opaquely into a temp buffer, then blend that
  67215. // with the target opacity...
  67216. const Rectangle<int> clipBounds (context.g.getClipBounds());
  67217. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  67218. {
  67219. Graphics tempG (tempImage);
  67220. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  67221. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  67222. render (tempContext);
  67223. }
  67224. context.g.setOpacity (context.opacity);
  67225. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  67226. }
  67227. }
  67228. }
  67229. const Rectangle<float> DrawableComposite::getBounds() const
  67230. {
  67231. Rectangle<float> bounds;
  67232. for (int i = 0; i < drawables.size(); ++i)
  67233. {
  67234. const Drawable* const d = drawables.getUnchecked(i);
  67235. const AffineTransform* const t = transforms.getUnchecked(i);
  67236. const Rectangle<float> childBounds (t == 0 ? d->getBounds()
  67237. : d->getBounds().transformed (*t));
  67238. if (bounds.isEmpty())
  67239. bounds = childBounds;
  67240. else if (! childBounds.isEmpty())
  67241. bounds = bounds.getUnion (childBounds);
  67242. }
  67243. return bounds;
  67244. }
  67245. bool DrawableComposite::hitTest (float x, float y) const
  67246. {
  67247. for (int i = 0; i < drawables.size(); ++i)
  67248. {
  67249. float tx = x;
  67250. float ty = y;
  67251. const AffineTransform* const t = transforms.getUnchecked(i);
  67252. if (t != 0)
  67253. t->inverted().transformPoint (tx, ty);
  67254. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  67255. return true;
  67256. }
  67257. return false;
  67258. }
  67259. Drawable* DrawableComposite::createCopy() const
  67260. {
  67261. DrawableComposite* const dc = new DrawableComposite();
  67262. for (int i = 0; i < drawables.size(); ++i)
  67263. {
  67264. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  67265. const AffineTransform* const t = transforms.getUnchecked(i);
  67266. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  67267. }
  67268. return dc;
  67269. }
  67270. ValueTree DrawableComposite::createValueTree() const
  67271. {
  67272. ValueTree v ("Group");
  67273. if (getName().isNotEmpty())
  67274. v.setProperty ("id", getName(), 0);
  67275. for (int i = 0; i < drawables.size(); ++i)
  67276. {
  67277. Drawable* const d = drawables.getUnchecked(i);
  67278. ValueTree child (d->createValueTree());
  67279. AffineTransform* transform = transforms.getUnchecked(i);
  67280. if (transform != 0)
  67281. {
  67282. String t;
  67283. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  67284. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  67285. child.setProperty ("transform", t, 0);
  67286. }
  67287. v.addChild (child, -1, 0);
  67288. }
  67289. return v;
  67290. }
  67291. DrawableComposite* DrawableComposite::createFromValueTree (const ValueTree& tree)
  67292. {
  67293. if (! tree.hasType ("Group"))
  67294. return 0;
  67295. DrawableComposite* dc = new DrawableComposite();
  67296. dc->setName (tree ["id"]);
  67297. for (int i = 0; i < tree.getNumChildren(); ++i)
  67298. {
  67299. ValueTree childTree (tree.getChild (i));
  67300. Drawable* d = Drawable::createFromValueTree (childTree);
  67301. if (d != 0)
  67302. {
  67303. AffineTransform transform;
  67304. const String transformAtt (childTree ["transform"].toString());
  67305. if (transformAtt.isNotEmpty())
  67306. {
  67307. StringArray tokens;
  67308. tokens.addTokens (transformAtt.trim(), false);
  67309. tokens.removeEmptyStrings (true);
  67310. if (tokens.size() == 6)
  67311. {
  67312. float f[6];
  67313. for (int j = 0; j < 6; ++j)
  67314. f[j] = (float) tokens[j].getDoubleValue();
  67315. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  67316. }
  67317. }
  67318. dc->insertDrawable (d, transform);
  67319. }
  67320. }
  67321. return dc;
  67322. }
  67323. END_JUCE_NAMESPACE
  67324. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  67325. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  67326. BEGIN_JUCE_NAMESPACE
  67327. DrawableImage::DrawableImage()
  67328. : image (0),
  67329. canDeleteImage (false),
  67330. opacity (1.0f),
  67331. overlayColour (0x00000000)
  67332. {
  67333. }
  67334. DrawableImage::~DrawableImage()
  67335. {
  67336. clearImage();
  67337. }
  67338. void DrawableImage::clearImage()
  67339. {
  67340. if (canDeleteImage && image != 0)
  67341. ImageCache::releaseOrDelete (image);
  67342. image = 0;
  67343. }
  67344. void DrawableImage::setImage (const Image& imageToCopy)
  67345. {
  67346. clearImage();
  67347. image = new Image (imageToCopy);
  67348. canDeleteImage = true;
  67349. }
  67350. void DrawableImage::setImage (Image* imageToUse,
  67351. const bool releaseWhenNotNeeded)
  67352. {
  67353. clearImage();
  67354. image = imageToUse;
  67355. canDeleteImage = releaseWhenNotNeeded;
  67356. }
  67357. void DrawableImage::setOpacity (const float newOpacity)
  67358. {
  67359. opacity = newOpacity;
  67360. }
  67361. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  67362. {
  67363. overlayColour = newOverlayColour;
  67364. }
  67365. void DrawableImage::render (const Drawable::RenderingContext& context) const
  67366. {
  67367. if (image != 0)
  67368. {
  67369. if (opacity > 0.0f && ! overlayColour.isOpaque())
  67370. {
  67371. context.g.setOpacity (context.opacity * opacity);
  67372. context.g.drawImageTransformed (image, image->getBounds(),
  67373. context.transform, false);
  67374. }
  67375. if (! overlayColour.isTransparent())
  67376. {
  67377. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  67378. context.g.drawImageTransformed (image, image->getBounds(),
  67379. context.transform, true);
  67380. }
  67381. }
  67382. }
  67383. const Rectangle<float> DrawableImage::getBounds() const
  67384. {
  67385. if (image == 0)
  67386. return Rectangle<float>();
  67387. return Rectangle<float> (0, 0, (float) image->getWidth(), (float) image->getHeight());
  67388. }
  67389. bool DrawableImage::hitTest (float x, float y) const
  67390. {
  67391. return image != 0
  67392. && x >= 0.0f
  67393. && y >= 0.0f
  67394. && x < image->getWidth()
  67395. && y < image->getHeight()
  67396. && image->getPixelAt (roundToInt (x), roundToInt (y)).getAlpha() >= 127;
  67397. }
  67398. Drawable* DrawableImage::createCopy() const
  67399. {
  67400. DrawableImage* const di = new DrawableImage();
  67401. di->opacity = opacity;
  67402. di->overlayColour = overlayColour;
  67403. if (image != 0)
  67404. {
  67405. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  67406. {
  67407. di->setImage (*image);
  67408. }
  67409. else
  67410. {
  67411. ImageCache::incReferenceCount (image);
  67412. di->setImage (image, true);
  67413. }
  67414. }
  67415. return di;
  67416. }
  67417. ValueTree DrawableImage::createValueTree() const
  67418. {
  67419. ValueTree v ("Image");
  67420. if (getName().isNotEmpty())
  67421. v.setProperty ("id", getName(), 0);
  67422. if (opacity < 1.0f)
  67423. v.setProperty ("opacity", (double) opacity, 0);
  67424. if (! overlayColour.isTransparent())
  67425. v.setProperty ("overlay", String::toHexString ((int) overlayColour.getARGB()), 0);
  67426. if (image != 0)
  67427. {
  67428. MemoryOutputStream imageData;
  67429. PNGImageFormat pngFormat;
  67430. if (pngFormat.writeImageToStream (*image, imageData))
  67431. {
  67432. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  67433. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  67434. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  67435. v.setProperty ("data", base64, 0);
  67436. }
  67437. }
  67438. return v;
  67439. }
  67440. DrawableImage* DrawableImage::createFromValueTree (const ValueTree& tree)
  67441. {
  67442. if (! tree.hasType ("Image"))
  67443. return 0;
  67444. DrawableImage* di = new DrawableImage();
  67445. di->setName (tree ["id"]);
  67446. di->opacity = tree.hasProperty ("opacity") ? (float) tree ["opacity"] : 1.0f;
  67447. di->overlayColour = Colour (tree ["overlay"].toString().getHexValue32());
  67448. MemoryBlock imageData;
  67449. if (imageData.fromBase64Encoding (tree ["data"]))
  67450. {
  67451. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), (int) imageData.getSize());
  67452. if (im == 0)
  67453. return false;
  67454. di->setImage (im, true);
  67455. }
  67456. return di;
  67457. }
  67458. END_JUCE_NAMESPACE
  67459. /*** End of inlined file: juce_DrawableImage.cpp ***/
  67460. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  67461. BEGIN_JUCE_NAMESPACE
  67462. DrawablePath::DrawablePath()
  67463. : mainFill (Colours::black),
  67464. strokeFill (Colours::transparentBlack),
  67465. strokeType (0.0f)
  67466. {
  67467. }
  67468. DrawablePath::~DrawablePath()
  67469. {
  67470. }
  67471. void DrawablePath::setPath (const Path& newPath)
  67472. {
  67473. path = newPath;
  67474. updateOutline();
  67475. }
  67476. void DrawablePath::setFill (const FillType& newFill)
  67477. {
  67478. mainFill = newFill;
  67479. }
  67480. void DrawablePath::setStrokeFill (const FillType& newFill)
  67481. {
  67482. strokeFill = newFill;
  67483. }
  67484. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  67485. {
  67486. strokeType = newStrokeType;
  67487. updateOutline();
  67488. }
  67489. void DrawablePath::setStrokeThickness (const float newThickness)
  67490. {
  67491. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  67492. }
  67493. void DrawablePath::render (const Drawable::RenderingContext& context) const
  67494. {
  67495. {
  67496. FillType f (mainFill);
  67497. if (f.isGradient())
  67498. f.gradient->multiplyOpacity (context.opacity);
  67499. f.transform = f.transform.followedBy (context.transform);
  67500. context.g.setFillType (f);
  67501. context.g.fillPath (path, context.transform);
  67502. }
  67503. if (strokeType.getStrokeThickness() > 0.0f)
  67504. {
  67505. FillType f (strokeFill);
  67506. if (f.isGradient())
  67507. f.gradient->multiplyOpacity (context.opacity);
  67508. f.transform = f.transform.followedBy (context.transform);
  67509. context.g.setFillType (f);
  67510. context.g.fillPath (stroke, context.transform);
  67511. }
  67512. }
  67513. void DrawablePath::updateOutline()
  67514. {
  67515. stroke.clear();
  67516. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  67517. }
  67518. const Rectangle<float> DrawablePath::getBounds() const
  67519. {
  67520. if (strokeType.getStrokeThickness() > 0.0f)
  67521. return stroke.getBounds();
  67522. else
  67523. return path.getBounds();
  67524. }
  67525. bool DrawablePath::hitTest (float x, float y) const
  67526. {
  67527. return path.contains (x, y)
  67528. || stroke.contains (x, y);
  67529. }
  67530. Drawable* DrawablePath::createCopy() const
  67531. {
  67532. DrawablePath* const dp = new DrawablePath();
  67533. dp->path = path;
  67534. dp->stroke = stroke;
  67535. dp->mainFill = mainFill;
  67536. dp->strokeFill = strokeFill;
  67537. dp->strokeType = strokeType;
  67538. return dp;
  67539. }
  67540. static const FillType readFillTypeFromTree (const ValueTree& v)
  67541. {
  67542. const String type (v["type"].toString());
  67543. if (type.equalsIgnoreCase ("solid"))
  67544. {
  67545. const String colour (v ["colour"].toString());
  67546. return Colour (colour.isEmpty() ? (uint32) 0xff000000
  67547. : (uint32) colour.getHexValue32());
  67548. }
  67549. else if (type.equalsIgnoreCase ("gradient"))
  67550. {
  67551. ColourGradient g;
  67552. g.x1 = v["x1"];
  67553. g.y1 = v["y1"];
  67554. g.x2 = v["x2"];
  67555. g.y2 = v["y2"];
  67556. g.isRadial = v["radial"];
  67557. StringArray colours;
  67558. colours.addTokens (v["colours"].toString(), false);
  67559. for (int i = 0; i < colours.size() / 2; ++i)
  67560. g.addColour (colours[i * 2].getDoubleValue(),
  67561. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  67562. return g;
  67563. }
  67564. jassertfalse
  67565. return FillType();
  67566. }
  67567. static ValueTree createTreeForFillType (const String& tagName, const FillType& fillType)
  67568. {
  67569. ValueTree v (tagName);
  67570. if (fillType.isColour())
  67571. {
  67572. v.setProperty ("type", "solid", 0);
  67573. v.setProperty ("colour", String::toHexString ((int) fillType.colour.getARGB()), 0);
  67574. }
  67575. else if (fillType.isGradient())
  67576. {
  67577. v.setProperty ("type", "gradient", 0);
  67578. v.setProperty ("x1", fillType.gradient->x1, 0);
  67579. v.setProperty ("y1", fillType.gradient->y1, 0);
  67580. v.setProperty ("x2", fillType.gradient->x2, 0);
  67581. v.setProperty ("y2", fillType.gradient->y2, 0);
  67582. v.setProperty ("radial", fillType.gradient->isRadial, 0);
  67583. String s;
  67584. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  67585. s << " " << fillType.gradient->getColourPosition (i)
  67586. << " " << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  67587. v.setProperty ("colours", s.trimStart(), 0);
  67588. }
  67589. else
  67590. {
  67591. jassertfalse //xxx
  67592. }
  67593. return v;
  67594. }
  67595. ValueTree DrawablePath::createValueTree() const
  67596. {
  67597. ValueTree v ("Path");
  67598. v.addChild (createTreeForFillType ("fill", mainFill), -1, 0);
  67599. v.addChild (createTreeForFillType ("stroke", strokeFill), -1, 0);
  67600. if (getName().isNotEmpty())
  67601. v.setProperty ("id", getName(), 0);
  67602. v.setProperty ("strokeWidth", (double) strokeType.getStrokeThickness(), 0);
  67603. v.setProperty ("jointStyle", strokeType.getJointStyle() == PathStrokeType::mitered
  67604. ? "miter" : (strokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), 0);
  67605. v.setProperty ("capStyle", strokeType.getEndStyle() == PathStrokeType::butt
  67606. ? "butt" : (strokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), 0);
  67607. v.setProperty ("path", path.toString(), 0);
  67608. return v;
  67609. }
  67610. DrawablePath* DrawablePath::createFromValueTree (const ValueTree& tree)
  67611. {
  67612. if (! tree.hasType ("Path"))
  67613. return 0;
  67614. DrawablePath* p = new DrawablePath();
  67615. p->setName (tree ["id"]);
  67616. p->mainFill = readFillTypeFromTree (tree.getChildWithName ("fill"));
  67617. p->strokeFill = readFillTypeFromTree (tree.getChildWithName ("stroke"));
  67618. const String jointStyle (tree ["jointStyle"].toString());
  67619. const String endStyle (tree ["capStyle"].toString());
  67620. p->strokeType
  67621. = PathStrokeType (tree ["strokeWidth"],
  67622. jointStyle.equalsIgnoreCase ("curved") ? PathStrokeType::curved
  67623. : (jointStyle.equalsIgnoreCase ("bevel") ? PathStrokeType::beveled
  67624. : PathStrokeType::mitered),
  67625. endStyle.equalsIgnoreCase ("square") ? PathStrokeType::square
  67626. : (endStyle.equalsIgnoreCase ("round") ? PathStrokeType::rounded
  67627. : PathStrokeType::butt));
  67628. p->path.clear();
  67629. p->path.restoreFromString (tree ["path"]);
  67630. p->updateOutline();
  67631. return p;
  67632. }
  67633. END_JUCE_NAMESPACE
  67634. /*** End of inlined file: juce_DrawablePath.cpp ***/
  67635. /*** Start of inlined file: juce_DrawableText.cpp ***/
  67636. BEGIN_JUCE_NAMESPACE
  67637. DrawableText::DrawableText()
  67638. : colour (Colours::white)
  67639. {
  67640. }
  67641. DrawableText::~DrawableText()
  67642. {
  67643. }
  67644. void DrawableText::setText (const GlyphArrangement& newText)
  67645. {
  67646. text = newText;
  67647. }
  67648. void DrawableText::setText (const String& newText, const Font& fontToUse)
  67649. {
  67650. text.clear();
  67651. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  67652. }
  67653. void DrawableText::setColour (const Colour& newColour)
  67654. {
  67655. colour = newColour;
  67656. }
  67657. void DrawableText::render (const Drawable::RenderingContext& context) const
  67658. {
  67659. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  67660. text.draw (context.g, context.transform);
  67661. }
  67662. const Rectangle<float> DrawableText::getBounds() const
  67663. {
  67664. return text.getBoundingBox (0, -1, false);
  67665. }
  67666. bool DrawableText::hitTest (float x, float y) const
  67667. {
  67668. return text.findGlyphIndexAt (x, y) >= 0;
  67669. }
  67670. Drawable* DrawableText::createCopy() const
  67671. {
  67672. DrawableText* const dt = new DrawableText();
  67673. dt->text = text;
  67674. dt->colour = colour;
  67675. return dt;
  67676. }
  67677. ValueTree DrawableText::createValueTree() const
  67678. {
  67679. ValueTree v ("Text");
  67680. if (getName().isNotEmpty())
  67681. v.setProperty ("id", getName(), 0);
  67682. jassertfalse // xxx not finished!
  67683. return v;
  67684. }
  67685. DrawableText* DrawableText::createFromValueTree (const ValueTree& tree)
  67686. {
  67687. if (! tree.hasType ("Text"))
  67688. return 0;
  67689. DrawableText* dt = new DrawableText();
  67690. dt->setName (tree ["id"]);
  67691. jassertfalse // xxx not finished!
  67692. return dt;
  67693. }
  67694. END_JUCE_NAMESPACE
  67695. /*** End of inlined file: juce_DrawableText.cpp ***/
  67696. /*** Start of inlined file: juce_SVGParser.cpp ***/
  67697. BEGIN_JUCE_NAMESPACE
  67698. class SVGState
  67699. {
  67700. public:
  67701. SVGState (const XmlElement* const topLevel)
  67702. : topLevelXml (topLevel),
  67703. elementX (0), elementY (0),
  67704. width (512), height (512),
  67705. viewBoxW (0), viewBoxH (0)
  67706. {
  67707. }
  67708. ~SVGState()
  67709. {
  67710. }
  67711. Drawable* parseSVGElement (const XmlElement& xml)
  67712. {
  67713. if (! xml.hasTagName ("svg"))
  67714. return 0;
  67715. DrawableComposite* const drawable = new DrawableComposite();
  67716. drawable->setName (xml.getStringAttribute ("id"));
  67717. SVGState newState (*this);
  67718. if (xml.hasAttribute ("transform"))
  67719. newState.addTransform (xml);
  67720. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  67721. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  67722. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  67723. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  67724. if (xml.hasAttribute ("viewBox"))
  67725. {
  67726. const String viewParams (xml.getStringAttribute ("viewBox"));
  67727. int i = 0;
  67728. float vx, vy, vw, vh;
  67729. if (parseCoords (viewParams, vx, vy, i, true)
  67730. && parseCoords (viewParams, vw, vh, i, true)
  67731. && vw > 0
  67732. && vh > 0)
  67733. {
  67734. newState.viewBoxW = vw;
  67735. newState.viewBoxH = vh;
  67736. int placementFlags = 0;
  67737. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  67738. if (aspect.containsIgnoreCase ("none"))
  67739. {
  67740. placementFlags = RectanglePlacement::stretchToFit;
  67741. }
  67742. else
  67743. {
  67744. if (aspect.containsIgnoreCase ("slice"))
  67745. placementFlags |= RectanglePlacement::fillDestination;
  67746. if (aspect.containsIgnoreCase ("xMin"))
  67747. placementFlags |= RectanglePlacement::xLeft;
  67748. else if (aspect.containsIgnoreCase ("xMax"))
  67749. placementFlags |= RectanglePlacement::xRight;
  67750. else
  67751. placementFlags |= RectanglePlacement::xMid;
  67752. if (aspect.containsIgnoreCase ("yMin"))
  67753. placementFlags |= RectanglePlacement::yTop;
  67754. else if (aspect.containsIgnoreCase ("yMax"))
  67755. placementFlags |= RectanglePlacement::yBottom;
  67756. else
  67757. placementFlags |= RectanglePlacement::yMid;
  67758. }
  67759. const RectanglePlacement placement (placementFlags);
  67760. newState.transform
  67761. = placement.getTransformToFit (vx, vy, vw, vh,
  67762. 0.0f, 0.0f, newState.width, newState.height)
  67763. .followedBy (newState.transform);
  67764. }
  67765. }
  67766. else
  67767. {
  67768. if (viewBoxW == 0)
  67769. newState.viewBoxW = newState.width;
  67770. if (viewBoxH == 0)
  67771. newState.viewBoxH = newState.height;
  67772. }
  67773. newState.parseSubElements (xml, drawable);
  67774. return drawable;
  67775. }
  67776. private:
  67777. const XmlElement* const topLevelXml;
  67778. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  67779. AffineTransform transform;
  67780. String cssStyleText;
  67781. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  67782. {
  67783. forEachXmlChildElement (xml, e)
  67784. {
  67785. Drawable* d = 0;
  67786. if (e->hasTagName ("g"))
  67787. d = parseGroupElement (*e);
  67788. else if (e->hasTagName ("svg"))
  67789. d = parseSVGElement (*e);
  67790. else if (e->hasTagName ("path"))
  67791. d = parsePath (*e);
  67792. else if (e->hasTagName ("rect"))
  67793. d = parseRect (*e);
  67794. else if (e->hasTagName ("circle"))
  67795. d = parseCircle (*e);
  67796. else if (e->hasTagName ("ellipse"))
  67797. d = parseEllipse (*e);
  67798. else if (e->hasTagName ("line"))
  67799. d = parseLine (*e);
  67800. else if (e->hasTagName ("polyline"))
  67801. d = parsePolygon (*e, true);
  67802. else if (e->hasTagName ("polygon"))
  67803. d = parsePolygon (*e, false);
  67804. else if (e->hasTagName ("text"))
  67805. d = parseText (*e);
  67806. else if (e->hasTagName ("switch"))
  67807. d = parseSwitch (*e);
  67808. else if (e->hasTagName ("style"))
  67809. parseCSSStyle (*e);
  67810. parentDrawable->insertDrawable (d);
  67811. }
  67812. }
  67813. DrawableComposite* parseSwitch (const XmlElement& xml)
  67814. {
  67815. const XmlElement* const group = xml.getChildByName ("g");
  67816. if (group != 0)
  67817. return parseGroupElement (*group);
  67818. return 0;
  67819. }
  67820. DrawableComposite* parseGroupElement (const XmlElement& xml)
  67821. {
  67822. DrawableComposite* const drawable = new DrawableComposite();
  67823. drawable->setName (xml.getStringAttribute ("id"));
  67824. if (xml.hasAttribute ("transform"))
  67825. {
  67826. SVGState newState (*this);
  67827. newState.addTransform (xml);
  67828. newState.parseSubElements (xml, drawable);
  67829. }
  67830. else
  67831. {
  67832. parseSubElements (xml, drawable);
  67833. }
  67834. return drawable;
  67835. }
  67836. Drawable* parsePath (const XmlElement& xml) const
  67837. {
  67838. const String d (xml.getStringAttribute ("d").trimStart());
  67839. Path path;
  67840. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  67841. path.setUsingNonZeroWinding (false);
  67842. int index = 0;
  67843. float lastX = 0, lastY = 0;
  67844. float lastX2 = 0, lastY2 = 0;
  67845. juce_wchar lastCommandChar = 0;
  67846. bool isRelative = true;
  67847. bool carryOn = true;
  67848. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  67849. while (d[index] != 0)
  67850. {
  67851. float x, y, x2, y2, x3, y3;
  67852. if (validCommandChars.containsChar (d[index]))
  67853. {
  67854. lastCommandChar = d [index++];
  67855. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  67856. }
  67857. switch (lastCommandChar)
  67858. {
  67859. case 'M':
  67860. case 'm':
  67861. case 'L':
  67862. case 'l':
  67863. if (parseCoords (d, x, y, index, false))
  67864. {
  67865. if (isRelative)
  67866. {
  67867. x += lastX;
  67868. y += lastY;
  67869. }
  67870. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  67871. {
  67872. path.startNewSubPath (x, y);
  67873. lastCommandChar = 'l';
  67874. }
  67875. else
  67876. path.lineTo (x, y);
  67877. lastX2 = lastX;
  67878. lastY2 = lastY;
  67879. lastX = x;
  67880. lastY = y;
  67881. }
  67882. else
  67883. {
  67884. ++index;
  67885. }
  67886. break;
  67887. case 'H':
  67888. case 'h':
  67889. if (parseCoord (d, x, index, false, true))
  67890. {
  67891. if (isRelative)
  67892. x += lastX;
  67893. path.lineTo (x, lastY);
  67894. lastX2 = lastX;
  67895. lastX = x;
  67896. }
  67897. else
  67898. {
  67899. ++index;
  67900. }
  67901. break;
  67902. case 'V':
  67903. case 'v':
  67904. if (parseCoord (d, y, index, false, false))
  67905. {
  67906. if (isRelative)
  67907. y += lastY;
  67908. path.lineTo (lastX, y);
  67909. lastY2 = lastY;
  67910. lastY = y;
  67911. }
  67912. else
  67913. {
  67914. ++index;
  67915. }
  67916. break;
  67917. case 'C':
  67918. case 'c':
  67919. if (parseCoords (d, x, y, index, false)
  67920. && parseCoords (d, x2, y2, index, false)
  67921. && parseCoords (d, x3, y3, index, false))
  67922. {
  67923. if (isRelative)
  67924. {
  67925. x += lastX;
  67926. y += lastY;
  67927. x2 += lastX;
  67928. y2 += lastY;
  67929. x3 += lastX;
  67930. y3 += lastY;
  67931. }
  67932. path.cubicTo (x, y, x2, y2, x3, y3);
  67933. lastX2 = x2;
  67934. lastY2 = y2;
  67935. lastX = x3;
  67936. lastY = y3;
  67937. }
  67938. else
  67939. {
  67940. ++index;
  67941. }
  67942. break;
  67943. case 'S':
  67944. case 's':
  67945. if (parseCoords (d, x, y, index, false)
  67946. && parseCoords (d, x3, y3, index, false))
  67947. {
  67948. if (isRelative)
  67949. {
  67950. x += lastX;
  67951. y += lastY;
  67952. x3 += lastX;
  67953. y3 += lastY;
  67954. }
  67955. x2 = lastX + (lastX - lastX2);
  67956. y2 = lastY + (lastY - lastY2);
  67957. path.cubicTo (x2, y2, x, y, x3, y3);
  67958. lastX2 = x;
  67959. lastY2 = y;
  67960. lastX = x3;
  67961. lastY = y3;
  67962. }
  67963. else
  67964. {
  67965. ++index;
  67966. }
  67967. break;
  67968. case 'Q':
  67969. case 'q':
  67970. if (parseCoords (d, x, y, index, false)
  67971. && parseCoords (d, x2, y2, index, false))
  67972. {
  67973. if (isRelative)
  67974. {
  67975. x += lastX;
  67976. y += lastY;
  67977. x2 += lastX;
  67978. y2 += lastY;
  67979. }
  67980. path.quadraticTo (x, y, x2, y2);
  67981. lastX2 = x;
  67982. lastY2 = y;
  67983. lastX = x2;
  67984. lastY = y2;
  67985. }
  67986. else
  67987. {
  67988. ++index;
  67989. }
  67990. break;
  67991. case 'T':
  67992. case 't':
  67993. if (parseCoords (d, x, y, index, false))
  67994. {
  67995. if (isRelative)
  67996. {
  67997. x += lastX;
  67998. y += lastY;
  67999. }
  68000. x2 = lastX + (lastX - lastX2);
  68001. y2 = lastY + (lastY - lastY2);
  68002. path.quadraticTo (x2, y2, x, y);
  68003. lastX2 = x2;
  68004. lastY2 = y2;
  68005. lastX = x;
  68006. lastY = y;
  68007. }
  68008. else
  68009. {
  68010. ++index;
  68011. }
  68012. break;
  68013. case 'A':
  68014. case 'a':
  68015. if (parseCoords (d, x, y, index, false))
  68016. {
  68017. String num;
  68018. if (parseNextNumber (d, num, index, false))
  68019. {
  68020. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  68021. if (parseNextNumber (d, num, index, false))
  68022. {
  68023. const bool largeArc = num.getIntValue() != 0;
  68024. if (parseNextNumber (d, num, index, false))
  68025. {
  68026. const bool sweep = num.getIntValue() != 0;
  68027. if (parseCoords (d, x2, y2, index, false))
  68028. {
  68029. if (isRelative)
  68030. {
  68031. x2 += lastX;
  68032. y2 += lastY;
  68033. }
  68034. if (lastX != x2 || lastY != y2)
  68035. {
  68036. double centreX, centreY, startAngle, deltaAngle;
  68037. double rx = x, ry = y;
  68038. endpointToCentreParameters (lastX, lastY, x2, y2,
  68039. angle, largeArc, sweep,
  68040. rx, ry, centreX, centreY,
  68041. startAngle, deltaAngle);
  68042. path.addCentredArc ((float) centreX, (float) centreY,
  68043. (float) rx, (float) ry,
  68044. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  68045. false);
  68046. path.lineTo (x2, y2);
  68047. }
  68048. lastX2 = lastX;
  68049. lastY2 = lastY;
  68050. lastX = x2;
  68051. lastY = y2;
  68052. }
  68053. }
  68054. }
  68055. }
  68056. }
  68057. else
  68058. {
  68059. ++index;
  68060. }
  68061. break;
  68062. case 'Z':
  68063. case 'z':
  68064. path.closeSubPath();
  68065. while (CharacterFunctions::isWhitespace (d [index]))
  68066. ++index;
  68067. break;
  68068. default:
  68069. carryOn = false;
  68070. break;
  68071. }
  68072. if (! carryOn)
  68073. break;
  68074. }
  68075. return parseShape (xml, path);
  68076. }
  68077. Drawable* parseRect (const XmlElement& xml) const
  68078. {
  68079. Path rect;
  68080. const bool hasRX = xml.hasAttribute ("rx");
  68081. const bool hasRY = xml.hasAttribute ("ry");
  68082. if (hasRX || hasRY)
  68083. {
  68084. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68085. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68086. if (! hasRX)
  68087. rx = ry;
  68088. else if (! hasRY)
  68089. ry = rx;
  68090. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68091. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68092. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68093. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  68094. rx, ry);
  68095. }
  68096. else
  68097. {
  68098. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68099. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68100. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68101. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  68102. }
  68103. return parseShape (xml, rect);
  68104. }
  68105. Drawable* parseCircle (const XmlElement& xml) const
  68106. {
  68107. Path circle;
  68108. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68109. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68110. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  68111. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  68112. return parseShape (xml, circle);
  68113. }
  68114. Drawable* parseEllipse (const XmlElement& xml) const
  68115. {
  68116. Path ellipse;
  68117. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68118. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68119. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68120. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68121. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  68122. return parseShape (xml, ellipse);
  68123. }
  68124. Drawable* parseLine (const XmlElement& xml) const
  68125. {
  68126. Path line;
  68127. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  68128. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  68129. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  68130. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  68131. line.startNewSubPath (x1, y1);
  68132. line.lineTo (x2, y2);
  68133. return parseShape (xml, line);
  68134. }
  68135. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  68136. {
  68137. const String points (xml.getStringAttribute ("points"));
  68138. Path path;
  68139. int index = 0;
  68140. float x, y;
  68141. if (parseCoords (points, x, y, index, true))
  68142. {
  68143. float firstX = x;
  68144. float firstY = y;
  68145. float lastX = 0, lastY = 0;
  68146. path.startNewSubPath (x, y);
  68147. while (parseCoords (points, x, y, index, true))
  68148. {
  68149. lastX = x;
  68150. lastY = y;
  68151. path.lineTo (x, y);
  68152. }
  68153. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  68154. path.closeSubPath();
  68155. }
  68156. return parseShape (xml, path);
  68157. }
  68158. Drawable* parseShape (const XmlElement& xml, Path& path,
  68159. const bool shouldParseTransform = true) const
  68160. {
  68161. if (shouldParseTransform && xml.hasAttribute ("transform"))
  68162. {
  68163. SVGState newState (*this);
  68164. newState.addTransform (xml);
  68165. return newState.parseShape (xml, path, false);
  68166. }
  68167. DrawablePath* dp = new DrawablePath();
  68168. dp->setName (xml.getStringAttribute ("id"));
  68169. dp->setFill (Colours::transparentBlack);
  68170. path.applyTransform (transform);
  68171. dp->setPath (path);
  68172. Path::Iterator iter (path);
  68173. bool containsClosedSubPath = false;
  68174. while (iter.next())
  68175. {
  68176. if (iter.elementType == Path::Iterator::closePath)
  68177. {
  68178. containsClosedSubPath = true;
  68179. break;
  68180. }
  68181. }
  68182. dp->setFill (getPathFillType (path,
  68183. getStyleAttribute (&xml, "fill"),
  68184. getStyleAttribute (&xml, "fill-opacity"),
  68185. getStyleAttribute (&xml, "opacity"),
  68186. containsClosedSubPath ? Colours::black
  68187. : Colours::transparentBlack));
  68188. const String strokeType (getStyleAttribute (&xml, "stroke"));
  68189. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  68190. {
  68191. dp->setStrokeFill (getPathFillType (path, strokeType,
  68192. getStyleAttribute (&xml, "stroke-opacity"),
  68193. getStyleAttribute (&xml, "opacity"),
  68194. Colours::transparentBlack));
  68195. dp->setStrokeType (getStrokeFor (&xml));
  68196. }
  68197. return dp;
  68198. }
  68199. const XmlElement* findLinkedElement (const XmlElement* e) const
  68200. {
  68201. const String id (e->getStringAttribute ("xlink:href"));
  68202. if (! id.startsWithChar ('#'))
  68203. return 0;
  68204. return findElementForId (topLevelXml, id.substring (1));
  68205. }
  68206. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  68207. {
  68208. if (fillXml == 0)
  68209. return;
  68210. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  68211. {
  68212. int index = 0;
  68213. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  68214. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  68215. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  68216. double offset = e->getDoubleAttribute ("offset");
  68217. if (e->getStringAttribute ("offset").containsChar ('%'))
  68218. offset *= 0.01;
  68219. cg.addColour (jlimit (0.0, 1.0, offset), col);
  68220. }
  68221. }
  68222. const FillType getPathFillType (const Path& path,
  68223. const String& fill,
  68224. const String& fillOpacity,
  68225. const String& overallOpacity,
  68226. const Colour& defaultColour) const
  68227. {
  68228. float opacity = 1.0f;
  68229. if (overallOpacity.isNotEmpty())
  68230. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  68231. if (fillOpacity.isNotEmpty())
  68232. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  68233. if (fill.startsWithIgnoreCase ("url"))
  68234. {
  68235. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  68236. .upToLastOccurrenceOf (")", false, false).trim());
  68237. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  68238. if (fillXml != 0
  68239. && (fillXml->hasTagName ("linearGradient")
  68240. || fillXml->hasTagName ("radialGradient")))
  68241. {
  68242. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  68243. ColourGradient gradient;
  68244. addGradientStopsIn (gradient, inheritedFrom);
  68245. addGradientStopsIn (gradient, fillXml);
  68246. if (gradient.getNumColours() > 0)
  68247. {
  68248. gradient.addColour (0.0, gradient.getColour (0));
  68249. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  68250. }
  68251. else
  68252. {
  68253. gradient.addColour (0.0, Colours::black);
  68254. gradient.addColour (1.0, Colours::black);
  68255. }
  68256. if (overallOpacity.isNotEmpty())
  68257. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  68258. jassert (gradient.getNumColours() > 0);
  68259. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  68260. float gradientWidth = viewBoxW;
  68261. float gradientHeight = viewBoxH;
  68262. float dx = 0.0f;
  68263. float dy = 0.0f;
  68264. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  68265. if (! userSpace)
  68266. {
  68267. const Rectangle<float> bounds (path.getBounds());
  68268. dx = bounds.getX();
  68269. dy = bounds.getY();
  68270. gradientWidth = bounds.getWidth();
  68271. gradientHeight = bounds.getHeight();
  68272. }
  68273. if (gradient.isRadial)
  68274. {
  68275. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth);
  68276. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight);
  68277. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  68278. gradient.x2 = gradient.x1 + radius;
  68279. gradient.y2 = gradient.y1;
  68280. //xxx (the fx, fy focal point isn't handled properly here..)
  68281. }
  68282. else
  68283. {
  68284. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth);
  68285. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight);
  68286. gradient.x2 = dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth);
  68287. gradient.y2 = dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight);
  68288. if (gradient.x1 == gradient.x2 && gradient.y1 == gradient.y2)
  68289. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  68290. }
  68291. FillType type (gradient);
  68292. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  68293. .followedBy (transform);
  68294. return type;
  68295. }
  68296. }
  68297. if (fill.equalsIgnoreCase ("none"))
  68298. return Colours::transparentBlack;
  68299. int i = 0;
  68300. const Colour colour (parseColour (fill, i, defaultColour));
  68301. return colour.withMultipliedAlpha (opacity);
  68302. }
  68303. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  68304. {
  68305. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  68306. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  68307. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  68308. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  68309. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  68310. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  68311. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  68312. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  68313. if (join.equalsIgnoreCase ("round"))
  68314. joinStyle = PathStrokeType::curved;
  68315. else if (join.equalsIgnoreCase ("bevel"))
  68316. joinStyle = PathStrokeType::beveled;
  68317. if (cap.equalsIgnoreCase ("round"))
  68318. capStyle = PathStrokeType::rounded;
  68319. else if (cap.equalsIgnoreCase ("square"))
  68320. capStyle = PathStrokeType::square;
  68321. float ox = 0.0f, oy = 0.0f;
  68322. transform.transformPoint (ox, oy);
  68323. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  68324. transform.transformPoint (x, y);
  68325. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  68326. joinStyle, capStyle);
  68327. }
  68328. Drawable* parseText (const XmlElement& xml)
  68329. {
  68330. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  68331. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  68332. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  68333. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  68334. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  68335. //xxx not done text yet!
  68336. forEachXmlChildElement (xml, e)
  68337. {
  68338. if (e->isTextElement())
  68339. {
  68340. const String text (e->getText());
  68341. Path path;
  68342. Drawable* s = parseShape (*e, path);
  68343. delete s;
  68344. }
  68345. else if (e->hasTagName ("tspan"))
  68346. {
  68347. Drawable* s = parseText (*e);
  68348. delete s;
  68349. }
  68350. }
  68351. return 0;
  68352. }
  68353. void addTransform (const XmlElement& xml)
  68354. {
  68355. transform = parseTransform (xml.getStringAttribute ("transform"))
  68356. .followedBy (transform);
  68357. }
  68358. bool parseCoord (const String& s, float& value, int& index,
  68359. const bool allowUnits, const bool isX) const
  68360. {
  68361. String number;
  68362. if (! parseNextNumber (s, number, index, allowUnits))
  68363. {
  68364. value = 0;
  68365. return false;
  68366. }
  68367. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  68368. return true;
  68369. }
  68370. bool parseCoords (const String& s, float& x, float& y,
  68371. int& index, const bool allowUnits) const
  68372. {
  68373. return parseCoord (s, x, index, allowUnits, true)
  68374. && parseCoord (s, y, index, allowUnits, false);
  68375. }
  68376. float getCoordLength (const String& s, const float sizeForProportions) const
  68377. {
  68378. float n = s.getFloatValue();
  68379. const int len = s.length();
  68380. if (len > 2)
  68381. {
  68382. const float dpi = 96.0f;
  68383. const juce_wchar n1 = s [len - 2];
  68384. const juce_wchar n2 = s [len - 1];
  68385. if (n1 == 'i' && n2 == 'n')
  68386. n *= dpi;
  68387. else if (n1 == 'm' && n2 == 'm')
  68388. n *= dpi / 25.4f;
  68389. else if (n1 == 'c' && n2 == 'm')
  68390. n *= dpi / 2.54f;
  68391. else if (n1 == 'p' && n2 == 'c')
  68392. n *= 15.0f;
  68393. else if (n2 == '%')
  68394. n *= 0.01f * sizeForProportions;
  68395. }
  68396. return n;
  68397. }
  68398. void getCoordList (Array <float>& coords, const String& list,
  68399. const bool allowUnits, const bool isX) const
  68400. {
  68401. int index = 0;
  68402. float value;
  68403. while (parseCoord (list, value, index, allowUnits, isX))
  68404. coords.add (value);
  68405. }
  68406. void parseCSSStyle (const XmlElement& xml)
  68407. {
  68408. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  68409. }
  68410. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  68411. const String& defaultValue = String::empty) const
  68412. {
  68413. if (xml->hasAttribute (attributeName))
  68414. return xml->getStringAttribute (attributeName, defaultValue);
  68415. const String styleAtt (xml->getStringAttribute ("style"));
  68416. if (styleAtt.isNotEmpty())
  68417. {
  68418. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  68419. if (value.isNotEmpty())
  68420. return value;
  68421. }
  68422. else if (xml->hasAttribute ("class"))
  68423. {
  68424. const String className ("." + xml->getStringAttribute ("class"));
  68425. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  68426. if (index < 0)
  68427. index = cssStyleText.indexOfIgnoreCase (className + "{");
  68428. if (index >= 0)
  68429. {
  68430. const int openBracket = cssStyleText.indexOfChar (index, '{');
  68431. if (openBracket > index)
  68432. {
  68433. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  68434. if (closeBracket > openBracket)
  68435. {
  68436. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  68437. if (value.isNotEmpty())
  68438. return value;
  68439. }
  68440. }
  68441. }
  68442. }
  68443. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  68444. if (xml != 0)
  68445. return getStyleAttribute (xml, attributeName, defaultValue);
  68446. return defaultValue;
  68447. }
  68448. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  68449. {
  68450. if (xml->hasAttribute (attributeName))
  68451. return xml->getStringAttribute (attributeName);
  68452. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  68453. if (xml != 0)
  68454. return getInheritedAttribute (xml, attributeName);
  68455. return String::empty;
  68456. }
  68457. static bool isIdentifierChar (const juce_wchar c)
  68458. {
  68459. return CharacterFunctions::isLetter (c) || c == '-';
  68460. }
  68461. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  68462. {
  68463. int i = 0;
  68464. for (;;)
  68465. {
  68466. i = list.indexOf (i, attributeName);
  68467. if (i < 0)
  68468. break;
  68469. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  68470. && ! isIdentifierChar (list [i + attributeName.length()]))
  68471. {
  68472. i = list.indexOfChar (i, ':');
  68473. if (i < 0)
  68474. break;
  68475. int end = list.indexOfChar (i, ';');
  68476. if (end < 0)
  68477. end = 0x7ffff;
  68478. return list.substring (i + 1, end).trim();
  68479. }
  68480. ++i;
  68481. }
  68482. return defaultValue;
  68483. }
  68484. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  68485. {
  68486. const juce_wchar* const s = source;
  68487. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  68488. ++index;
  68489. int start = index;
  68490. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  68491. ++index;
  68492. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  68493. ++index;
  68494. if ((s[index] == 'e' || s[index] == 'E')
  68495. && (CharacterFunctions::isDigit (s[index + 1])
  68496. || s[index + 1] == '-'
  68497. || s[index + 1] == '+'))
  68498. {
  68499. index += 2;
  68500. while (CharacterFunctions::isDigit (s[index]))
  68501. ++index;
  68502. }
  68503. if (allowUnits)
  68504. {
  68505. while (CharacterFunctions::isLetter (s[index]))
  68506. ++index;
  68507. }
  68508. if (index == start)
  68509. return false;
  68510. value = String (s + start, index - start);
  68511. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  68512. ++index;
  68513. return true;
  68514. }
  68515. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  68516. {
  68517. if (s [index] == '#')
  68518. {
  68519. uint32 hex [6];
  68520. zeromem (hex, sizeof (hex));
  68521. int numChars = 0;
  68522. for (int i = 6; --i >= 0;)
  68523. {
  68524. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  68525. if (hexValue >= 0)
  68526. hex [numChars++] = hexValue;
  68527. else
  68528. break;
  68529. }
  68530. if (numChars <= 3)
  68531. return Colour ((uint8) (hex [0] * 0x11),
  68532. (uint8) (hex [1] * 0x11),
  68533. (uint8) (hex [2] * 0x11));
  68534. else
  68535. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  68536. (uint8) ((hex [2] << 4) + hex [3]),
  68537. (uint8) ((hex [4] << 4) + hex [5]));
  68538. }
  68539. else if (s [index] == 'r'
  68540. && s [index + 1] == 'g'
  68541. && s [index + 2] == 'b')
  68542. {
  68543. const int openBracket = s.indexOfChar (index, '(');
  68544. const int closeBracket = s.indexOfChar (openBracket, ')');
  68545. if (openBracket >= 3 && closeBracket > openBracket)
  68546. {
  68547. index = closeBracket;
  68548. StringArray tokens;
  68549. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  68550. tokens.trim();
  68551. tokens.removeEmptyStrings();
  68552. if (tokens[0].containsChar ('%'))
  68553. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  68554. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  68555. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  68556. else
  68557. return Colour ((uint8) tokens[0].getIntValue(),
  68558. (uint8) tokens[1].getIntValue(),
  68559. (uint8) tokens[2].getIntValue());
  68560. }
  68561. }
  68562. return Colours::findColourForName (s, defaultColour);
  68563. }
  68564. static const AffineTransform parseTransform (String t)
  68565. {
  68566. AffineTransform result;
  68567. while (t.isNotEmpty())
  68568. {
  68569. StringArray tokens;
  68570. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  68571. .upToFirstOccurrenceOf (")", false, false),
  68572. ", ", String::empty);
  68573. tokens.removeEmptyStrings (true);
  68574. float numbers [6];
  68575. for (int i = 0; i < 6; ++i)
  68576. numbers[i] = tokens[i].getFloatValue();
  68577. AffineTransform trans;
  68578. if (t.startsWithIgnoreCase ("matrix"))
  68579. {
  68580. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  68581. numbers[1], numbers[3], numbers[5]);
  68582. }
  68583. else if (t.startsWithIgnoreCase ("translate"))
  68584. {
  68585. jassert (tokens.size() == 2);
  68586. trans = AffineTransform::translation (numbers[0], numbers[1]);
  68587. }
  68588. else if (t.startsWithIgnoreCase ("scale"))
  68589. {
  68590. if (tokens.size() == 1)
  68591. trans = AffineTransform::scale (numbers[0], numbers[0]);
  68592. else
  68593. trans = AffineTransform::scale (numbers[0], numbers[1]);
  68594. }
  68595. else if (t.startsWithIgnoreCase ("rotate"))
  68596. {
  68597. if (tokens.size() != 3)
  68598. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  68599. else
  68600. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  68601. numbers[1], numbers[2]);
  68602. }
  68603. else if (t.startsWithIgnoreCase ("skewX"))
  68604. {
  68605. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  68606. 0.0f, 1.0f, 0.0f);
  68607. }
  68608. else if (t.startsWithIgnoreCase ("skewY"))
  68609. {
  68610. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  68611. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  68612. }
  68613. result = trans.followedBy (result);
  68614. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  68615. }
  68616. return result;
  68617. }
  68618. static void endpointToCentreParameters (const double x1, const double y1,
  68619. const double x2, const double y2,
  68620. const double angle,
  68621. const bool largeArc, const bool sweep,
  68622. double& rx, double& ry,
  68623. double& centreX, double& centreY,
  68624. double& startAngle, double& deltaAngle)
  68625. {
  68626. const double midX = (x1 - x2) * 0.5;
  68627. const double midY = (y1 - y2) * 0.5;
  68628. const double cosAngle = cos (angle);
  68629. const double sinAngle = sin (angle);
  68630. const double xp = cosAngle * midX + sinAngle * midY;
  68631. const double yp = cosAngle * midY - sinAngle * midX;
  68632. const double xp2 = xp * xp;
  68633. const double yp2 = yp * yp;
  68634. double rx2 = rx * rx;
  68635. double ry2 = ry * ry;
  68636. const double s = (xp2 / rx2) + (yp2 / ry2);
  68637. double c;
  68638. if (s <= 1.0)
  68639. {
  68640. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  68641. / (( rx2 * yp2) + (ry2 * xp2))));
  68642. if (largeArc == sweep)
  68643. c = -c;
  68644. }
  68645. else
  68646. {
  68647. const double s2 = sqrt (s);
  68648. rx *= s2;
  68649. ry *= s2;
  68650. rx2 = rx * rx;
  68651. ry2 = ry * ry;
  68652. c = 0;
  68653. }
  68654. const double cpx = ((rx * yp) / ry) * c;
  68655. const double cpy = ((-ry * xp) / rx) * c;
  68656. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  68657. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  68658. const double ux = (xp - cpx) / rx;
  68659. const double uy = (yp - cpy) / ry;
  68660. const double vx = (-xp - cpx) / rx;
  68661. const double vy = (-yp - cpy) / ry;
  68662. const double length = juce_hypot (ux, uy);
  68663. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  68664. if (uy < 0)
  68665. startAngle = -startAngle;
  68666. startAngle += double_Pi * 0.5;
  68667. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  68668. / (length * juce_hypot (vx, vy))));
  68669. if ((ux * vy) - (uy * vx) < 0)
  68670. deltaAngle = -deltaAngle;
  68671. if (sweep)
  68672. {
  68673. if (deltaAngle < 0)
  68674. deltaAngle += double_Pi * 2.0;
  68675. }
  68676. else
  68677. {
  68678. if (deltaAngle > 0)
  68679. deltaAngle -= double_Pi * 2.0;
  68680. }
  68681. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  68682. }
  68683. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  68684. {
  68685. forEachXmlChildElement (*parent, e)
  68686. {
  68687. if (e->compareAttribute ("id", id))
  68688. return e;
  68689. const XmlElement* const found = findElementForId (e, id);
  68690. if (found != 0)
  68691. return found;
  68692. }
  68693. return 0;
  68694. }
  68695. SVGState& operator= (const SVGState&);
  68696. };
  68697. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  68698. {
  68699. SVGState state (&svgDocument);
  68700. return state.parseSVGElement (svgDocument);
  68701. }
  68702. END_JUCE_NAMESPACE
  68703. /*** End of inlined file: juce_SVGParser.cpp ***/
  68704. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  68705. BEGIN_JUCE_NAMESPACE
  68706. #if JUCE_MSVC
  68707. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  68708. #endif
  68709. DropShadowEffect::DropShadowEffect()
  68710. : offsetX (0),
  68711. offsetY (0),
  68712. radius (4),
  68713. opacity (0.6f)
  68714. {
  68715. }
  68716. DropShadowEffect::~DropShadowEffect()
  68717. {
  68718. }
  68719. void DropShadowEffect::setShadowProperties (const float newRadius,
  68720. const float newOpacity,
  68721. const int newShadowOffsetX,
  68722. const int newShadowOffsetY)
  68723. {
  68724. radius = jmax (1.1f, newRadius);
  68725. offsetX = newShadowOffsetX;
  68726. offsetY = newShadowOffsetY;
  68727. opacity = newOpacity;
  68728. }
  68729. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  68730. {
  68731. const int w = image.getWidth();
  68732. const int h = image.getHeight();
  68733. Image shadowImage (Image::SingleChannel, w, h, false);
  68734. const Image::BitmapData srcData (image, 0, 0, w, h);
  68735. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  68736. const int filter = roundToInt (63.0f / radius);
  68737. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  68738. for (int x = w; --x >= 0;)
  68739. {
  68740. int shadowAlpha = 0;
  68741. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  68742. uint8* shadowPix = destData.data + x;
  68743. for (int y = h; --y >= 0;)
  68744. {
  68745. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  68746. *shadowPix = (uint8) shadowAlpha;
  68747. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  68748. shadowPix += destData.lineStride;
  68749. }
  68750. }
  68751. for (int y = h; --y >= 0;)
  68752. {
  68753. int shadowAlpha = 0;
  68754. uint8* shadowPix = destData.getLinePointer (y);
  68755. for (int x = w; --x >= 0;)
  68756. {
  68757. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  68758. *shadowPix++ = (uint8) shadowAlpha;
  68759. }
  68760. }
  68761. g.setColour (Colours::black.withAlpha (opacity));
  68762. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  68763. g.setOpacity (1.0f);
  68764. g.drawImageAt (&image, 0, 0);
  68765. }
  68766. END_JUCE_NAMESPACE
  68767. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  68768. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  68769. BEGIN_JUCE_NAMESPACE
  68770. GlowEffect::GlowEffect()
  68771. : radius (2.0f),
  68772. colour (Colours::white)
  68773. {
  68774. }
  68775. GlowEffect::~GlowEffect()
  68776. {
  68777. }
  68778. void GlowEffect::setGlowProperties (const float newRadius,
  68779. const Colour& newColour)
  68780. {
  68781. radius = newRadius;
  68782. colour = newColour;
  68783. }
  68784. void GlowEffect::applyEffect (Image& image, Graphics& g)
  68785. {
  68786. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  68787. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  68788. blurKernel.createGaussianBlur (radius);
  68789. blurKernel.rescaleAllValues (radius);
  68790. blurKernel.applyToImage (temp, &image, image.getBounds());
  68791. g.setColour (colour);
  68792. g.drawImageAt (&temp, 0, 0, true);
  68793. g.setOpacity (1.0f);
  68794. g.drawImageAt (&image, 0, 0, false);
  68795. }
  68796. END_JUCE_NAMESPACE
  68797. /*** End of inlined file: juce_GlowEffect.cpp ***/
  68798. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  68799. BEGIN_JUCE_NAMESPACE
  68800. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  68801. : opacity (opacity_)
  68802. {
  68803. }
  68804. ReduceOpacityEffect::~ReduceOpacityEffect()
  68805. {
  68806. }
  68807. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  68808. {
  68809. opacity = jlimit (0.0f, 1.0f, newOpacity);
  68810. }
  68811. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  68812. {
  68813. g.setOpacity (opacity);
  68814. g.drawImageAt (&image, 0, 0);
  68815. }
  68816. END_JUCE_NAMESPACE
  68817. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  68818. /*** Start of inlined file: juce_Font.cpp ***/
  68819. BEGIN_JUCE_NAMESPACE
  68820. namespace FontValues
  68821. {
  68822. static float limitFontHeight (const float height) throw()
  68823. {
  68824. return jlimit (0.1f, 10000.0f, height);
  68825. }
  68826. static const float defaultFontHeight = 14.0f;
  68827. static String fallbackFont;
  68828. }
  68829. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  68830. const float kerning_, const float ascent_, const int styleFlags_,
  68831. Typeface* const typeface_) throw()
  68832. : typefaceName (typefaceName_),
  68833. height (height_),
  68834. horizontalScale (horizontalScale_),
  68835. kerning (kerning_),
  68836. ascent (ascent_),
  68837. styleFlags (styleFlags_),
  68838. typeface (typeface_)
  68839. {
  68840. }
  68841. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  68842. : typefaceName (other.typefaceName),
  68843. height (other.height),
  68844. horizontalScale (other.horizontalScale),
  68845. kerning (other.kerning),
  68846. ascent (other.ascent),
  68847. styleFlags (other.styleFlags),
  68848. typeface (other.typeface)
  68849. {
  68850. }
  68851. Font::Font() throw()
  68852. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  68853. 1.0f, 0, 0, Font::plain, 0))
  68854. {
  68855. }
  68856. Font::Font (const float fontHeight, const int styleFlags_) throw()
  68857. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  68858. 1.0f, 0, 0, styleFlags_, 0))
  68859. {
  68860. }
  68861. Font::Font (const String& typefaceName_,
  68862. const float fontHeight,
  68863. const int styleFlags_) throw()
  68864. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  68865. 1.0f, 0, 0, styleFlags_, 0))
  68866. {
  68867. }
  68868. Font::Font (const Font& other) throw()
  68869. : font (other.font)
  68870. {
  68871. }
  68872. Font& Font::operator= (const Font& other) throw()
  68873. {
  68874. font = other.font;
  68875. return *this;
  68876. }
  68877. Font::~Font() throw()
  68878. {
  68879. }
  68880. Font::Font (const Typeface::Ptr& typeface) throw()
  68881. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  68882. 1.0f, 0, 0, Font::plain, typeface))
  68883. {
  68884. }
  68885. bool Font::operator== (const Font& other) const throw()
  68886. {
  68887. return font == other.font
  68888. || (font->height == other.font->height
  68889. && font->styleFlags == other.font->styleFlags
  68890. && font->horizontalScale == other.font->horizontalScale
  68891. && font->kerning == other.font->kerning
  68892. && font->typefaceName == other.font->typefaceName);
  68893. }
  68894. bool Font::operator!= (const Font& other) const throw()
  68895. {
  68896. return ! operator== (other);
  68897. }
  68898. void Font::dupeInternalIfShared() throw()
  68899. {
  68900. if (font->getReferenceCount() > 1)
  68901. font = new SharedFontInternal (*font);
  68902. }
  68903. const String Font::getDefaultSansSerifFontName() throw()
  68904. {
  68905. static const String name ("<Sans-Serif>");
  68906. return name;
  68907. }
  68908. const String Font::getDefaultSerifFontName() throw()
  68909. {
  68910. static const String name ("<Serif>");
  68911. return name;
  68912. }
  68913. const String Font::getDefaultMonospacedFontName() throw()
  68914. {
  68915. static const String name ("<Monospaced>");
  68916. return name;
  68917. }
  68918. void Font::setTypefaceName (const String& faceName) throw()
  68919. {
  68920. if (faceName != font->typefaceName)
  68921. {
  68922. dupeInternalIfShared();
  68923. font->typefaceName = faceName;
  68924. font->typeface = 0;
  68925. font->ascent = 0;
  68926. }
  68927. }
  68928. const String Font::getFallbackFontName() throw()
  68929. {
  68930. return FontValues::fallbackFont;
  68931. }
  68932. void Font::setFallbackFontName (const String& name) throw()
  68933. {
  68934. FontValues::fallbackFont = name;
  68935. }
  68936. void Font::setHeight (float newHeight) throw()
  68937. {
  68938. newHeight = FontValues::limitFontHeight (newHeight);
  68939. if (font->height != newHeight)
  68940. {
  68941. dupeInternalIfShared();
  68942. font->height = newHeight;
  68943. }
  68944. }
  68945. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  68946. {
  68947. newHeight = FontValues::limitFontHeight (newHeight);
  68948. if (font->height != newHeight)
  68949. {
  68950. dupeInternalIfShared();
  68951. font->horizontalScale *= (font->height / newHeight);
  68952. font->height = newHeight;
  68953. }
  68954. }
  68955. void Font::setStyleFlags (const int newFlags) throw()
  68956. {
  68957. if (font->styleFlags != newFlags)
  68958. {
  68959. dupeInternalIfShared();
  68960. font->styleFlags = newFlags;
  68961. font->typeface = 0;
  68962. font->ascent = 0;
  68963. }
  68964. }
  68965. void Font::setSizeAndStyle (float newHeight,
  68966. const int newStyleFlags,
  68967. const float newHorizontalScale,
  68968. const float newKerningAmount) throw()
  68969. {
  68970. newHeight = FontValues::limitFontHeight (newHeight);
  68971. if (font->height != newHeight
  68972. || font->horizontalScale != newHorizontalScale
  68973. || font->kerning != newKerningAmount)
  68974. {
  68975. dupeInternalIfShared();
  68976. font->height = newHeight;
  68977. font->horizontalScale = newHorizontalScale;
  68978. font->kerning = newKerningAmount;
  68979. }
  68980. setStyleFlags (newStyleFlags);
  68981. }
  68982. void Font::setHorizontalScale (const float scaleFactor) throw()
  68983. {
  68984. dupeInternalIfShared();
  68985. font->horizontalScale = scaleFactor;
  68986. }
  68987. void Font::setExtraKerningFactor (const float extraKerning) throw()
  68988. {
  68989. dupeInternalIfShared();
  68990. font->kerning = extraKerning;
  68991. }
  68992. void Font::setBold (const bool shouldBeBold) throw()
  68993. {
  68994. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  68995. : (font->styleFlags & ~bold));
  68996. }
  68997. bool Font::isBold() const throw()
  68998. {
  68999. return (font->styleFlags & bold) != 0;
  69000. }
  69001. void Font::setItalic (const bool shouldBeItalic) throw()
  69002. {
  69003. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  69004. : (font->styleFlags & ~italic));
  69005. }
  69006. bool Font::isItalic() const throw()
  69007. {
  69008. return (font->styleFlags & italic) != 0;
  69009. }
  69010. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  69011. {
  69012. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  69013. : (font->styleFlags & ~underlined));
  69014. }
  69015. bool Font::isUnderlined() const throw()
  69016. {
  69017. return (font->styleFlags & underlined) != 0;
  69018. }
  69019. float Font::getAscent() const throw()
  69020. {
  69021. if (font->ascent == 0)
  69022. font->ascent = getTypeface()->getAscent();
  69023. return font->height * font->ascent;
  69024. }
  69025. float Font::getDescent() const throw()
  69026. {
  69027. return font->height - getAscent();
  69028. }
  69029. int Font::getStringWidth (const String& text) const throw()
  69030. {
  69031. return roundToInt (getStringWidthFloat (text));
  69032. }
  69033. float Font::getStringWidthFloat (const String& text) const throw()
  69034. {
  69035. float w = getTypeface()->getStringWidth (text);
  69036. if (font->kerning != 0)
  69037. w += font->kerning * text.length();
  69038. return w * font->height * font->horizontalScale;
  69039. }
  69040. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  69041. {
  69042. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  69043. const float scale = font->height * font->horizontalScale;
  69044. const int num = xOffsets.size();
  69045. if (num > 0)
  69046. {
  69047. float* const x = &(xOffsets.getReference(0));
  69048. if (font->kerning != 0)
  69049. {
  69050. for (int i = 0; i < num; ++i)
  69051. x[i] = (x[i] + i * font->kerning) * scale;
  69052. }
  69053. else
  69054. {
  69055. for (int i = 0; i < num; ++i)
  69056. x[i] *= scale;
  69057. }
  69058. }
  69059. }
  69060. void Font::findFonts (Array<Font>& destArray) throw()
  69061. {
  69062. const StringArray names (findAllTypefaceNames());
  69063. for (int i = 0; i < names.size(); ++i)
  69064. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  69065. }
  69066. class TypefaceCache : public DeletedAtShutdown
  69067. {
  69068. public:
  69069. TypefaceCache (int numToCache = 10) throw()
  69070. : counter (1)
  69071. {
  69072. while (--numToCache >= 0)
  69073. faces.add (new CachedFace());
  69074. }
  69075. ~TypefaceCache()
  69076. {
  69077. clearSingletonInstance();
  69078. }
  69079. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  69080. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  69081. {
  69082. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  69083. const String faceName (font.getTypefaceName());
  69084. int i;
  69085. for (i = faces.size(); --i >= 0;)
  69086. {
  69087. CachedFace* const face = faces.getUnchecked(i);
  69088. if (face->flags == flags
  69089. && face->typefaceName == faceName)
  69090. {
  69091. face->lastUsageCount = ++counter;
  69092. return face->typeFace;
  69093. }
  69094. }
  69095. int replaceIndex = 0;
  69096. int bestLastUsageCount = std::numeric_limits<int>::max();
  69097. for (i = faces.size(); --i >= 0;)
  69098. {
  69099. const int lu = faces.getUnchecked(i)->lastUsageCount;
  69100. if (bestLastUsageCount > lu)
  69101. {
  69102. bestLastUsageCount = lu;
  69103. replaceIndex = i;
  69104. }
  69105. }
  69106. CachedFace* const face = faces.getUnchecked (replaceIndex);
  69107. face->typefaceName = faceName;
  69108. face->flags = flags;
  69109. face->lastUsageCount = ++counter;
  69110. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  69111. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  69112. return face->typeFace;
  69113. }
  69114. juce_UseDebuggingNewOperator
  69115. private:
  69116. struct CachedFace
  69117. {
  69118. CachedFace() throw()
  69119. : lastUsageCount (0), flags (-1)
  69120. {
  69121. }
  69122. String typefaceName;
  69123. int lastUsageCount;
  69124. int flags;
  69125. Typeface::Ptr typeFace;
  69126. };
  69127. int counter;
  69128. OwnedArray <CachedFace> faces;
  69129. TypefaceCache (const TypefaceCache&);
  69130. TypefaceCache& operator= (const TypefaceCache&);
  69131. };
  69132. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  69133. Typeface* Font::getTypeface() const throw()
  69134. {
  69135. if (font->typeface == 0)
  69136. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  69137. return font->typeface;
  69138. }
  69139. END_JUCE_NAMESPACE
  69140. /*** End of inlined file: juce_Font.cpp ***/
  69141. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  69142. BEGIN_JUCE_NAMESPACE
  69143. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  69144. const juce_wchar character_, const int glyph_)
  69145. : x (x_),
  69146. y (y_),
  69147. w (w_),
  69148. font (font_),
  69149. character (character_),
  69150. glyph (glyph_)
  69151. {
  69152. }
  69153. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  69154. : x (other.x),
  69155. y (other.y),
  69156. w (other.w),
  69157. font (other.font),
  69158. character (other.character),
  69159. glyph (other.glyph)
  69160. {
  69161. }
  69162. void PositionedGlyph::draw (const Graphics& g) const
  69163. {
  69164. if (! isWhitespace())
  69165. {
  69166. g.getInternalContext()->setFont (font);
  69167. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  69168. }
  69169. }
  69170. void PositionedGlyph::draw (const Graphics& g,
  69171. const AffineTransform& transform) const
  69172. {
  69173. if (! isWhitespace())
  69174. {
  69175. g.getInternalContext()->setFont (font);
  69176. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  69177. .followedBy (transform));
  69178. }
  69179. }
  69180. void PositionedGlyph::createPath (Path& path) const
  69181. {
  69182. if (! isWhitespace())
  69183. {
  69184. Typeface* const t = font.getTypeface();
  69185. if (t != 0)
  69186. {
  69187. Path p;
  69188. t->getOutlineForGlyph (glyph, p);
  69189. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  69190. .translated (x, y));
  69191. }
  69192. }
  69193. }
  69194. bool PositionedGlyph::hitTest (float px, float py) const
  69195. {
  69196. if (getBounds().contains (px, py) && ! isWhitespace())
  69197. {
  69198. Typeface* const t = font.getTypeface();
  69199. if (t != 0)
  69200. {
  69201. Path p;
  69202. t->getOutlineForGlyph (glyph, p);
  69203. AffineTransform::translation (-x, -y)
  69204. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  69205. .transformPoint (px, py);
  69206. return p.contains (px, py);
  69207. }
  69208. }
  69209. return false;
  69210. }
  69211. void PositionedGlyph::moveBy (const float deltaX,
  69212. const float deltaY)
  69213. {
  69214. x += deltaX;
  69215. y += deltaY;
  69216. }
  69217. GlyphArrangement::GlyphArrangement()
  69218. {
  69219. glyphs.ensureStorageAllocated (128);
  69220. }
  69221. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  69222. {
  69223. addGlyphArrangement (other);
  69224. }
  69225. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  69226. {
  69227. if (this != &other)
  69228. {
  69229. clear();
  69230. addGlyphArrangement (other);
  69231. }
  69232. return *this;
  69233. }
  69234. GlyphArrangement::~GlyphArrangement()
  69235. {
  69236. }
  69237. void GlyphArrangement::clear()
  69238. {
  69239. glyphs.clear();
  69240. }
  69241. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  69242. {
  69243. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  69244. return *glyphs [index];
  69245. }
  69246. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  69247. {
  69248. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  69249. for (int i = 0; i < other.glyphs.size(); ++i)
  69250. glyphs.add (new PositionedGlyph (*other.glyphs.getUnchecked (i)));
  69251. }
  69252. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  69253. {
  69254. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  69255. }
  69256. void GlyphArrangement::addLineOfText (const Font& font,
  69257. const String& text,
  69258. const float xOffset,
  69259. const float yOffset)
  69260. {
  69261. addCurtailedLineOfText (font, text,
  69262. xOffset, yOffset,
  69263. 1.0e10f, false);
  69264. }
  69265. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  69266. const String& text,
  69267. float xOffset,
  69268. const float yOffset,
  69269. const float maxWidthPixels,
  69270. const bool useEllipsis)
  69271. {
  69272. if (text.isNotEmpty())
  69273. {
  69274. Array <int> newGlyphs;
  69275. Array <float> xOffsets;
  69276. font.getGlyphPositions (text, newGlyphs, xOffsets);
  69277. const int textLen = newGlyphs.size();
  69278. const juce_wchar* const unicodeText = text;
  69279. for (int i = 0; i < textLen; ++i)
  69280. {
  69281. const float thisX = xOffsets.getUnchecked (i);
  69282. const float nextX = xOffsets.getUnchecked (i + 1);
  69283. if (nextX > maxWidthPixels + 1.0f)
  69284. {
  69285. // curtail the string if it's too wide..
  69286. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  69287. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  69288. break;
  69289. }
  69290. else
  69291. {
  69292. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  69293. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  69294. }
  69295. }
  69296. }
  69297. }
  69298. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  69299. const int startIndex, int endIndex)
  69300. {
  69301. int numDeleted = 0;
  69302. if (glyphs.size() > 0)
  69303. {
  69304. Array<int> dotGlyphs;
  69305. Array<float> dotXs;
  69306. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  69307. const float dx = dotXs[1];
  69308. float xOffset = 0.0f, yOffset = 0.0f;
  69309. while (endIndex > startIndex)
  69310. {
  69311. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  69312. xOffset = pg->x;
  69313. yOffset = pg->y;
  69314. glyphs.remove (endIndex);
  69315. ++numDeleted;
  69316. if (xOffset + dx * 3 <= maxXPos)
  69317. break;
  69318. }
  69319. for (int i = 3; --i >= 0;)
  69320. {
  69321. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  69322. font, '.', dotGlyphs.getFirst()));
  69323. --numDeleted;
  69324. xOffset += dx;
  69325. if (xOffset > maxXPos)
  69326. break;
  69327. }
  69328. }
  69329. return numDeleted;
  69330. }
  69331. void GlyphArrangement::addJustifiedText (const Font& font,
  69332. const String& text,
  69333. float x, float y,
  69334. const float maxLineWidth,
  69335. const Justification& horizontalLayout)
  69336. {
  69337. int lineStartIndex = glyphs.size();
  69338. addLineOfText (font, text, x, y);
  69339. const float originalY = y;
  69340. while (lineStartIndex < glyphs.size())
  69341. {
  69342. int i = lineStartIndex;
  69343. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  69344. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  69345. ++i;
  69346. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  69347. int lastWordBreakIndex = -1;
  69348. while (i < glyphs.size())
  69349. {
  69350. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  69351. const juce_wchar c = pg->getCharacter();
  69352. if (c == '\r' || c == '\n')
  69353. {
  69354. ++i;
  69355. if (c == '\r' && i < glyphs.size()
  69356. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  69357. ++i;
  69358. break;
  69359. }
  69360. else if (pg->isWhitespace())
  69361. {
  69362. lastWordBreakIndex = i + 1;
  69363. }
  69364. else if (pg->getRight() - 0.0001f >= lineMaxX)
  69365. {
  69366. if (lastWordBreakIndex >= 0)
  69367. i = lastWordBreakIndex;
  69368. break;
  69369. }
  69370. ++i;
  69371. }
  69372. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  69373. float currentLineEndX = currentLineStartX;
  69374. for (int j = i; --j >= lineStartIndex;)
  69375. {
  69376. if (! glyphs.getUnchecked (j)->isWhitespace())
  69377. {
  69378. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  69379. break;
  69380. }
  69381. }
  69382. float deltaX = 0.0f;
  69383. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  69384. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  69385. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  69386. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  69387. else if (horizontalLayout.testFlags (Justification::right))
  69388. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  69389. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  69390. x + deltaX - currentLineStartX, y - originalY);
  69391. lineStartIndex = i;
  69392. y += font.getHeight();
  69393. }
  69394. }
  69395. void GlyphArrangement::addFittedText (const Font& f,
  69396. const String& text,
  69397. const float x, const float y,
  69398. const float width, const float height,
  69399. const Justification& layout,
  69400. int maximumLines,
  69401. const float minimumHorizontalScale)
  69402. {
  69403. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  69404. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  69405. if (text.containsAnyOf ("\r\n"))
  69406. {
  69407. GlyphArrangement ga;
  69408. ga.addJustifiedText (f, text, x, y, width, layout);
  69409. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  69410. float dy = y - bb.getY();
  69411. if (layout.testFlags (Justification::verticallyCentred))
  69412. dy += (height - bb.getHeight()) * 0.5f;
  69413. else if (layout.testFlags (Justification::bottom))
  69414. dy += height - bb.getHeight();
  69415. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  69416. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  69417. for (int i = 0; i < ga.glyphs.size(); ++i)
  69418. glyphs.add (ga.glyphs.getUnchecked (i));
  69419. ga.glyphs.clear (false);
  69420. return;
  69421. }
  69422. int startIndex = glyphs.size();
  69423. addLineOfText (f, text.trim(), x, y);
  69424. if (glyphs.size() > startIndex)
  69425. {
  69426. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  69427. - glyphs.getUnchecked (startIndex)->getLeft();
  69428. if (lineWidth <= 0)
  69429. return;
  69430. if (lineWidth * minimumHorizontalScale < width)
  69431. {
  69432. if (lineWidth > width)
  69433. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  69434. width / lineWidth);
  69435. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  69436. x, y, width, height, layout);
  69437. }
  69438. else if (maximumLines <= 1)
  69439. {
  69440. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  69441. x, y, width, height, f, layout, minimumHorizontalScale);
  69442. }
  69443. else
  69444. {
  69445. Font font (f);
  69446. String txt (text.trim());
  69447. const int length = txt.length();
  69448. const int originalStartIndex = startIndex;
  69449. int numLines = 1;
  69450. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  69451. maximumLines = 1;
  69452. maximumLines = jmin (maximumLines, length);
  69453. while (numLines < maximumLines)
  69454. {
  69455. ++numLines;
  69456. const float newFontHeight = height / (float) numLines;
  69457. if (newFontHeight < font.getHeight())
  69458. {
  69459. font.setHeight (jmax (8.0f, newFontHeight));
  69460. removeRangeOfGlyphs (startIndex, -1);
  69461. addLineOfText (font, txt, x, y);
  69462. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  69463. - glyphs.getUnchecked (startIndex)->getLeft();
  69464. }
  69465. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  69466. break;
  69467. }
  69468. if (numLines < 1)
  69469. numLines = 1;
  69470. float lineY = y;
  69471. float widthPerLine = lineWidth / numLines;
  69472. int lastLineStartIndex = 0;
  69473. for (int line = 0; line < numLines; ++line)
  69474. {
  69475. int i = startIndex;
  69476. lastLineStartIndex = i;
  69477. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  69478. if (line == numLines - 1)
  69479. {
  69480. widthPerLine = width;
  69481. i = glyphs.size();
  69482. }
  69483. else
  69484. {
  69485. while (i < glyphs.size())
  69486. {
  69487. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  69488. if (lineWidth > widthPerLine)
  69489. {
  69490. // got to a point where the line's too long, so skip forward to find a
  69491. // good place to break it..
  69492. const int searchStartIndex = i;
  69493. while (i < glyphs.size())
  69494. {
  69495. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  69496. {
  69497. if (glyphs.getUnchecked (i)->isWhitespace()
  69498. || glyphs.getUnchecked (i)->getCharacter() == '-')
  69499. {
  69500. ++i;
  69501. break;
  69502. }
  69503. }
  69504. else
  69505. {
  69506. // can't find a suitable break, so try looking backwards..
  69507. i = searchStartIndex;
  69508. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  69509. {
  69510. if (glyphs.getUnchecked (i - back)->isWhitespace()
  69511. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  69512. {
  69513. i -= back - 1;
  69514. break;
  69515. }
  69516. }
  69517. break;
  69518. }
  69519. ++i;
  69520. }
  69521. break;
  69522. }
  69523. ++i;
  69524. }
  69525. int wsStart = i;
  69526. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  69527. --wsStart;
  69528. int wsEnd = i;
  69529. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  69530. ++wsEnd;
  69531. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  69532. i = jmax (wsStart, startIndex + 1);
  69533. }
  69534. i -= fitLineIntoSpace (startIndex, i - startIndex,
  69535. x, lineY, width, font.getHeight(), font,
  69536. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  69537. minimumHorizontalScale);
  69538. startIndex = i;
  69539. lineY += font.getHeight();
  69540. if (startIndex >= glyphs.size())
  69541. break;
  69542. }
  69543. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  69544. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  69545. }
  69546. }
  69547. }
  69548. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  69549. const float dx, const float dy)
  69550. {
  69551. jassert (startIndex >= 0);
  69552. if (dx != 0.0f || dy != 0.0f)
  69553. {
  69554. if (num < 0 || startIndex + num > glyphs.size())
  69555. num = glyphs.size() - startIndex;
  69556. while (--num >= 0)
  69557. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  69558. }
  69559. }
  69560. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  69561. const Justification& justification, float minimumHorizontalScale)
  69562. {
  69563. int numDeleted = 0;
  69564. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  69565. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  69566. if (lineWidth > w)
  69567. {
  69568. if (minimumHorizontalScale < 1.0f)
  69569. {
  69570. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  69571. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  69572. }
  69573. if (lineWidth > w)
  69574. {
  69575. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  69576. numGlyphs -= numDeleted;
  69577. }
  69578. }
  69579. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  69580. return numDeleted;
  69581. }
  69582. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  69583. const float horizontalScaleFactor)
  69584. {
  69585. jassert (startIndex >= 0);
  69586. if (num < 0 || startIndex + num > glyphs.size())
  69587. num = glyphs.size() - startIndex;
  69588. if (num > 0)
  69589. {
  69590. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  69591. while (--num >= 0)
  69592. {
  69593. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  69594. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  69595. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  69596. pg->w *= horizontalScaleFactor;
  69597. }
  69598. }
  69599. }
  69600. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  69601. {
  69602. jassert (startIndex >= 0);
  69603. if (num < 0 || startIndex + num > glyphs.size())
  69604. num = glyphs.size() - startIndex;
  69605. Rectangle<float> result;
  69606. bool isFirst = true;
  69607. while (--num >= 0)
  69608. {
  69609. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  69610. if (includeWhitespace || ! pg->isWhitespace())
  69611. {
  69612. if (isFirst)
  69613. {
  69614. isFirst = false;
  69615. result = pg->getBounds();
  69616. }
  69617. else
  69618. {
  69619. result = result.getUnion (pg->getBounds());
  69620. }
  69621. }
  69622. }
  69623. return result;
  69624. }
  69625. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  69626. const float x, const float y, const float width, const float height,
  69627. const Justification& justification)
  69628. {
  69629. jassert (num >= 0 && startIndex >= 0);
  69630. if (glyphs.size() > 0 && num > 0)
  69631. {
  69632. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  69633. | Justification::horizontallyCentred)));
  69634. float deltaX = 0.0f;
  69635. if (justification.testFlags (Justification::horizontallyJustified))
  69636. deltaX = x - bb.getX();
  69637. else if (justification.testFlags (Justification::horizontallyCentred))
  69638. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  69639. else if (justification.testFlags (Justification::right))
  69640. deltaX = (x + width) - bb.getRight();
  69641. else
  69642. deltaX = x - bb.getX();
  69643. float deltaY = 0.0f;
  69644. if (justification.testFlags (Justification::top))
  69645. deltaY = y - bb.getY();
  69646. else if (justification.testFlags (Justification::bottom))
  69647. deltaY = (y + height) - bb.getBottom();
  69648. else
  69649. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  69650. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  69651. if (justification.testFlags (Justification::horizontallyJustified))
  69652. {
  69653. int lineStart = 0;
  69654. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  69655. int i;
  69656. for (i = 0; i < num; ++i)
  69657. {
  69658. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  69659. if (glyphY != baseY)
  69660. {
  69661. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  69662. lineStart = i;
  69663. baseY = glyphY;
  69664. }
  69665. }
  69666. if (i > lineStart)
  69667. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  69668. }
  69669. }
  69670. }
  69671. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  69672. {
  69673. if (start + num < glyphs.size()
  69674. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  69675. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  69676. {
  69677. int numSpaces = 0;
  69678. int spacesAtEnd = 0;
  69679. for (int i = 0; i < num; ++i)
  69680. {
  69681. if (glyphs.getUnchecked (start + i)->isWhitespace())
  69682. {
  69683. ++spacesAtEnd;
  69684. ++numSpaces;
  69685. }
  69686. else
  69687. {
  69688. spacesAtEnd = 0;
  69689. }
  69690. }
  69691. numSpaces -= spacesAtEnd;
  69692. if (numSpaces > 0)
  69693. {
  69694. const float startX = glyphs.getUnchecked (start)->getLeft();
  69695. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  69696. const float extraPaddingBetweenWords
  69697. = (targetWidth - (endX - startX)) / (float) numSpaces;
  69698. float deltaX = 0.0f;
  69699. for (int i = 0; i < num; ++i)
  69700. {
  69701. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  69702. if (glyphs.getUnchecked (start + i)->isWhitespace())
  69703. deltaX += extraPaddingBetweenWords;
  69704. }
  69705. }
  69706. }
  69707. }
  69708. void GlyphArrangement::draw (const Graphics& g) const
  69709. {
  69710. for (int i = 0; i < glyphs.size(); ++i)
  69711. {
  69712. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  69713. if (pg->font.isUnderlined())
  69714. {
  69715. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  69716. float nextX = pg->x + pg->w;
  69717. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  69718. nextX = glyphs.getUnchecked (i + 1)->x;
  69719. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  69720. nextX - pg->x, lineThickness);
  69721. }
  69722. pg->draw (g);
  69723. }
  69724. }
  69725. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  69726. {
  69727. for (int i = 0; i < glyphs.size(); ++i)
  69728. {
  69729. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  69730. if (pg->font.isUnderlined())
  69731. {
  69732. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  69733. float nextX = pg->x + pg->w;
  69734. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  69735. nextX = glyphs.getUnchecked (i + 1)->x;
  69736. Path p;
  69737. p.addLineSegment (pg->x, pg->y + lineThickness * 2.0f,
  69738. nextX, pg->y + lineThickness * 2.0f,
  69739. lineThickness);
  69740. g.fillPath (p, transform);
  69741. }
  69742. pg->draw (g, transform);
  69743. }
  69744. }
  69745. void GlyphArrangement::createPath (Path& path) const
  69746. {
  69747. for (int i = 0; i < glyphs.size(); ++i)
  69748. glyphs.getUnchecked (i)->createPath (path);
  69749. }
  69750. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  69751. {
  69752. for (int i = 0; i < glyphs.size(); ++i)
  69753. if (glyphs.getUnchecked (i)->hitTest (x, y))
  69754. return i;
  69755. return -1;
  69756. }
  69757. END_JUCE_NAMESPACE
  69758. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  69759. /*** Start of inlined file: juce_TextLayout.cpp ***/
  69760. BEGIN_JUCE_NAMESPACE
  69761. class TextLayout::Token
  69762. {
  69763. public:
  69764. String text;
  69765. Font font;
  69766. int x, y, w, h;
  69767. int line, lineHeight;
  69768. bool isWhitespace, isNewLine;
  69769. Token (const String& t,
  69770. const Font& f,
  69771. const bool isWhitespace_)
  69772. : text (t),
  69773. font (f),
  69774. x(0),
  69775. y(0),
  69776. isWhitespace (isWhitespace_)
  69777. {
  69778. w = font.getStringWidth (t);
  69779. h = roundToInt (f.getHeight());
  69780. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  69781. }
  69782. Token (const Token& other)
  69783. : text (other.text),
  69784. font (other.font),
  69785. x (other.x),
  69786. y (other.y),
  69787. w (other.w),
  69788. h (other.h),
  69789. line (other.line),
  69790. lineHeight (other.lineHeight),
  69791. isWhitespace (other.isWhitespace),
  69792. isNewLine (other.isNewLine)
  69793. {
  69794. }
  69795. ~Token()
  69796. {
  69797. }
  69798. void draw (Graphics& g,
  69799. const int xOffset,
  69800. const int yOffset)
  69801. {
  69802. if (! isWhitespace)
  69803. {
  69804. g.setFont (font);
  69805. g.drawSingleLineText (text.trimEnd(),
  69806. xOffset + x,
  69807. yOffset + y + (lineHeight - h)
  69808. + roundToInt (font.getAscent()));
  69809. }
  69810. }
  69811. juce_UseDebuggingNewOperator
  69812. };
  69813. TextLayout::TextLayout()
  69814. : totalLines (0)
  69815. {
  69816. tokens.ensureStorageAllocated (64);
  69817. }
  69818. TextLayout::TextLayout (const String& text, const Font& font)
  69819. : totalLines (0)
  69820. {
  69821. tokens.ensureStorageAllocated (64);
  69822. appendText (text, font);
  69823. }
  69824. TextLayout::TextLayout (const TextLayout& other)
  69825. : totalLines (0)
  69826. {
  69827. *this = other;
  69828. }
  69829. TextLayout& TextLayout::operator= (const TextLayout& other)
  69830. {
  69831. if (this != &other)
  69832. {
  69833. clear();
  69834. totalLines = other.totalLines;
  69835. for (int i = 0; i < other.tokens.size(); ++i)
  69836. tokens.add (new Token (*other.tokens.getUnchecked(i)));
  69837. }
  69838. return *this;
  69839. }
  69840. TextLayout::~TextLayout()
  69841. {
  69842. clear();
  69843. }
  69844. void TextLayout::clear()
  69845. {
  69846. tokens.clear();
  69847. totalLines = 0;
  69848. }
  69849. void TextLayout::appendText (const String& text, const Font& font)
  69850. {
  69851. const juce_wchar* t = text;
  69852. String currentString;
  69853. int lastCharType = 0;
  69854. for (;;)
  69855. {
  69856. const juce_wchar c = *t++;
  69857. if (c == 0)
  69858. break;
  69859. int charType;
  69860. if (c == '\r' || c == '\n')
  69861. {
  69862. charType = 0;
  69863. }
  69864. else if (CharacterFunctions::isWhitespace (c))
  69865. {
  69866. charType = 2;
  69867. }
  69868. else
  69869. {
  69870. charType = 1;
  69871. }
  69872. if (charType == 0 || charType != lastCharType)
  69873. {
  69874. if (currentString.isNotEmpty())
  69875. {
  69876. tokens.add (new Token (currentString, font,
  69877. lastCharType == 2 || lastCharType == 0));
  69878. }
  69879. currentString = String::charToString (c);
  69880. if (c == '\r' && *t == '\n')
  69881. currentString += *t++;
  69882. }
  69883. else
  69884. {
  69885. currentString += c;
  69886. }
  69887. lastCharType = charType;
  69888. }
  69889. if (currentString.isNotEmpty())
  69890. tokens.add (new Token (currentString, font, lastCharType == 2));
  69891. }
  69892. void TextLayout::setText (const String& text, const Font& font)
  69893. {
  69894. clear();
  69895. appendText (text, font);
  69896. }
  69897. void TextLayout::layout (int maxWidth,
  69898. const Justification& justification,
  69899. const bool attemptToBalanceLineLengths)
  69900. {
  69901. if (attemptToBalanceLineLengths)
  69902. {
  69903. const int originalW = maxWidth;
  69904. int bestWidth = maxWidth;
  69905. float bestLineProportion = 0.0f;
  69906. while (maxWidth > originalW / 2)
  69907. {
  69908. layout (maxWidth, justification, false);
  69909. if (getNumLines() <= 1)
  69910. return;
  69911. const int lastLineW = getLineWidth (getNumLines() - 1);
  69912. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  69913. const float prop = lastLineW / (float) lastButOneLineW;
  69914. if (prop > 0.9f)
  69915. return;
  69916. if (prop > bestLineProportion)
  69917. {
  69918. bestLineProportion = prop;
  69919. bestWidth = maxWidth;
  69920. }
  69921. maxWidth -= 10;
  69922. }
  69923. layout (bestWidth, justification, false);
  69924. }
  69925. else
  69926. {
  69927. int x = 0;
  69928. int y = 0;
  69929. int h = 0;
  69930. totalLines = 0;
  69931. int i;
  69932. for (i = 0; i < tokens.size(); ++i)
  69933. {
  69934. Token* const t = tokens.getUnchecked(i);
  69935. t->x = x;
  69936. t->y = y;
  69937. t->line = totalLines;
  69938. x += t->w;
  69939. h = jmax (h, t->h);
  69940. const Token* nextTok = tokens [i + 1];
  69941. if (nextTok == 0)
  69942. break;
  69943. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  69944. {
  69945. // finished a line, so go back and update the heights of the things on it
  69946. for (int j = i; j >= 0; --j)
  69947. {
  69948. Token* const tok = tokens.getUnchecked(j);
  69949. if (tok->line == totalLines)
  69950. tok->lineHeight = h;
  69951. else
  69952. break;
  69953. }
  69954. x = 0;
  69955. y += h;
  69956. h = 0;
  69957. ++totalLines;
  69958. }
  69959. }
  69960. // finished a line, so go back and update the heights of the things on it
  69961. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  69962. {
  69963. Token* const t = tokens.getUnchecked(j);
  69964. if (t->line == totalLines)
  69965. t->lineHeight = h;
  69966. else
  69967. break;
  69968. }
  69969. ++totalLines;
  69970. if (! justification.testFlags (Justification::left))
  69971. {
  69972. int totalW = getWidth();
  69973. for (i = totalLines; --i >= 0;)
  69974. {
  69975. const int lineW = getLineWidth (i);
  69976. int dx = 0;
  69977. if (justification.testFlags (Justification::horizontallyCentred))
  69978. dx = (totalW - lineW) / 2;
  69979. else if (justification.testFlags (Justification::right))
  69980. dx = totalW - lineW;
  69981. for (int j = tokens.size(); --j >= 0;)
  69982. {
  69983. Token* const t = tokens.getUnchecked(j);
  69984. if (t->line == i)
  69985. t->x += dx;
  69986. }
  69987. }
  69988. }
  69989. }
  69990. }
  69991. int TextLayout::getLineWidth (const int lineNumber) const
  69992. {
  69993. int maxW = 0;
  69994. for (int i = tokens.size(); --i >= 0;)
  69995. {
  69996. const Token* const t = tokens.getUnchecked(i);
  69997. if (t->line == lineNumber && ! t->isWhitespace)
  69998. maxW = jmax (maxW, t->x + t->w);
  69999. }
  70000. return maxW;
  70001. }
  70002. int TextLayout::getWidth() const
  70003. {
  70004. int maxW = 0;
  70005. for (int i = tokens.size(); --i >= 0;)
  70006. {
  70007. const Token* const t = tokens.getUnchecked(i);
  70008. if (! t->isWhitespace)
  70009. maxW = jmax (maxW, t->x + t->w);
  70010. }
  70011. return maxW;
  70012. }
  70013. int TextLayout::getHeight() const
  70014. {
  70015. int maxH = 0;
  70016. for (int i = tokens.size(); --i >= 0;)
  70017. {
  70018. const Token* const t = tokens.getUnchecked(i);
  70019. if (! t->isWhitespace)
  70020. maxH = jmax (maxH, t->y + t->h);
  70021. }
  70022. return maxH;
  70023. }
  70024. void TextLayout::draw (Graphics& g,
  70025. const int xOffset,
  70026. const int yOffset) const
  70027. {
  70028. for (int i = tokens.size(); --i >= 0;)
  70029. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  70030. }
  70031. void TextLayout::drawWithin (Graphics& g,
  70032. int x, int y, int w, int h,
  70033. const Justification& justification) const
  70034. {
  70035. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  70036. x, y, w, h);
  70037. draw (g, x, y);
  70038. }
  70039. END_JUCE_NAMESPACE
  70040. /*** End of inlined file: juce_TextLayout.cpp ***/
  70041. /*** Start of inlined file: juce_Typeface.cpp ***/
  70042. BEGIN_JUCE_NAMESPACE
  70043. Typeface::Typeface (const String& name_) throw()
  70044. : name (name_)
  70045. {
  70046. }
  70047. Typeface::~Typeface()
  70048. {
  70049. }
  70050. class CustomTypeface::GlyphInfo
  70051. {
  70052. public:
  70053. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  70054. : character (character_), path (path_), width (width_)
  70055. {
  70056. }
  70057. ~GlyphInfo() throw()
  70058. {
  70059. }
  70060. struct KerningPair
  70061. {
  70062. juce_wchar character2;
  70063. float kerningAmount;
  70064. };
  70065. void addKerningPair (const juce_wchar subsequentCharacter,
  70066. const float extraKerningAmount) throw()
  70067. {
  70068. KerningPair kp;
  70069. kp.character2 = subsequentCharacter;
  70070. kp.kerningAmount = extraKerningAmount;
  70071. kerningPairs.add (kp);
  70072. }
  70073. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  70074. {
  70075. if (subsequentCharacter != 0)
  70076. {
  70077. for (int i = kerningPairs.size(); --i >= 0;)
  70078. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  70079. return width + kerningPairs.getReference(i).kerningAmount;
  70080. }
  70081. return width;
  70082. }
  70083. const juce_wchar character;
  70084. const Path path;
  70085. float width;
  70086. Array <KerningPair> kerningPairs;
  70087. juce_UseDebuggingNewOperator
  70088. private:
  70089. GlyphInfo (const GlyphInfo&);
  70090. GlyphInfo& operator= (const GlyphInfo&);
  70091. };
  70092. CustomTypeface::CustomTypeface()
  70093. : Typeface (String::empty)
  70094. {
  70095. clear();
  70096. }
  70097. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  70098. : Typeface (String::empty)
  70099. {
  70100. clear();
  70101. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  70102. BufferedInputStream in (&gzin, 32768, false);
  70103. name = in.readString();
  70104. isBold = in.readBool();
  70105. isItalic = in.readBool();
  70106. ascent = in.readFloat();
  70107. defaultCharacter = (juce_wchar) in.readShort();
  70108. int i, numChars = in.readInt();
  70109. for (i = 0; i < numChars; ++i)
  70110. {
  70111. const juce_wchar c = (juce_wchar) in.readShort();
  70112. const float width = in.readFloat();
  70113. Path p;
  70114. p.loadPathFromStream (in);
  70115. addGlyph (c, p, width);
  70116. }
  70117. const int numKerningPairs = in.readInt();
  70118. for (i = 0; i < numKerningPairs; ++i)
  70119. {
  70120. const juce_wchar char1 = (juce_wchar) in.readShort();
  70121. const juce_wchar char2 = (juce_wchar) in.readShort();
  70122. addKerningPair (char1, char2, in.readFloat());
  70123. }
  70124. }
  70125. CustomTypeface::~CustomTypeface()
  70126. {
  70127. }
  70128. void CustomTypeface::clear()
  70129. {
  70130. defaultCharacter = 0;
  70131. ascent = 1.0f;
  70132. isBold = isItalic = false;
  70133. zeromem (lookupTable, sizeof (lookupTable));
  70134. glyphs.clear();
  70135. }
  70136. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  70137. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  70138. {
  70139. name = name_;
  70140. defaultCharacter = defaultCharacter_;
  70141. ascent = ascent_;
  70142. isBold = isBold_;
  70143. isItalic = isItalic_;
  70144. }
  70145. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  70146. {
  70147. // Check that you're not trying to add the same character twice..
  70148. jassert (findGlyph (character, false) == 0);
  70149. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  70150. lookupTable [character] = (short) glyphs.size();
  70151. glyphs.add (new GlyphInfo (character, path, width));
  70152. }
  70153. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  70154. {
  70155. if (extraAmount != 0)
  70156. {
  70157. GlyphInfo* const g = findGlyph (char1, true);
  70158. jassert (g != 0); // can only add kerning pairs for characters that exist!
  70159. if (g != 0)
  70160. g->addKerningPair (char2, extraAmount);
  70161. }
  70162. }
  70163. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  70164. {
  70165. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  70166. return glyphs [(int) lookupTable [(int) character]];
  70167. for (int i = 0; i < glyphs.size(); ++i)
  70168. {
  70169. GlyphInfo* const g = glyphs.getUnchecked(i);
  70170. if (g->character == character)
  70171. return g;
  70172. }
  70173. if (loadIfNeeded && loadGlyphIfPossible (character))
  70174. return findGlyph (character, false);
  70175. return 0;
  70176. }
  70177. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  70178. {
  70179. GlyphInfo* glyph = findGlyph (character, true);
  70180. if (glyph == 0)
  70181. {
  70182. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  70183. glyph = findGlyph (L' ', true);
  70184. if (glyph == 0)
  70185. {
  70186. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  70187. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  70188. if (fallbackTypeface != 0 && fallbackTypeface != this)
  70189. {
  70190. //xxx
  70191. }
  70192. if (glyph == 0)
  70193. glyph = findGlyph (defaultCharacter, true);
  70194. }
  70195. }
  70196. return glyph;
  70197. }
  70198. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  70199. {
  70200. return false;
  70201. }
  70202. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  70203. {
  70204. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  70205. for (int i = 0; i < numCharacters; ++i)
  70206. {
  70207. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  70208. Array <int> glyphIndexes;
  70209. Array <float> offsets;
  70210. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  70211. const int glyphIndex = glyphIndexes.getFirst();
  70212. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  70213. {
  70214. const float glyphWidth = offsets[1];
  70215. Path p;
  70216. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  70217. addGlyph (c, p, glyphWidth);
  70218. for (int j = glyphs.size() - 1; --j >= 0;)
  70219. {
  70220. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  70221. glyphIndexes.clearQuick();
  70222. offsets.clearQuick();
  70223. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  70224. if (offsets.size() > 1)
  70225. addKerningPair (c, char2, offsets[1] - glyphWidth);
  70226. }
  70227. }
  70228. }
  70229. }
  70230. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  70231. {
  70232. GZIPCompressorOutputStream out (&outputStream);
  70233. out.writeString (name);
  70234. out.writeBool (isBold);
  70235. out.writeBool (isItalic);
  70236. out.writeFloat (ascent);
  70237. out.writeShort ((short) (unsigned short) defaultCharacter);
  70238. out.writeInt (glyphs.size());
  70239. int i, numKerningPairs = 0;
  70240. for (i = 0; i < glyphs.size(); ++i)
  70241. {
  70242. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70243. out.writeShort ((short) (unsigned short) g->character);
  70244. out.writeFloat (g->width);
  70245. g->path.writePathToStream (out);
  70246. numKerningPairs += g->kerningPairs.size();
  70247. }
  70248. out.writeInt (numKerningPairs);
  70249. for (i = 0; i < glyphs.size(); ++i)
  70250. {
  70251. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70252. for (int j = 0; j < g->kerningPairs.size(); ++j)
  70253. {
  70254. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  70255. out.writeShort ((short) (unsigned short) g->character);
  70256. out.writeShort ((short) (unsigned short) p.character2);
  70257. out.writeFloat (p.kerningAmount);
  70258. }
  70259. }
  70260. return true;
  70261. }
  70262. float CustomTypeface::getAscent() const
  70263. {
  70264. return ascent;
  70265. }
  70266. float CustomTypeface::getDescent() const
  70267. {
  70268. return 1.0f - ascent;
  70269. }
  70270. float CustomTypeface::getStringWidth (const String& text)
  70271. {
  70272. float x = 0;
  70273. const juce_wchar* t = text;
  70274. while (*t != 0)
  70275. {
  70276. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  70277. if (glyph != 0)
  70278. x += glyph->getHorizontalSpacing (*t);
  70279. }
  70280. return x;
  70281. }
  70282. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  70283. {
  70284. xOffsets.add (0);
  70285. float x = 0;
  70286. const juce_wchar* t = text;
  70287. while (*t != 0)
  70288. {
  70289. const juce_wchar c = *t++;
  70290. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  70291. if (glyph != 0)
  70292. {
  70293. x += glyph->getHorizontalSpacing (*t);
  70294. resultGlyphs.add ((int) glyph->character);
  70295. xOffsets.add (x);
  70296. }
  70297. }
  70298. }
  70299. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  70300. {
  70301. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  70302. if (glyph != 0)
  70303. {
  70304. path = glyph->path;
  70305. return true;
  70306. }
  70307. return false;
  70308. }
  70309. END_JUCE_NAMESPACE
  70310. /*** End of inlined file: juce_Typeface.cpp ***/
  70311. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  70312. BEGIN_JUCE_NAMESPACE
  70313. AffineTransform::AffineTransform() throw()
  70314. : mat00 (1.0f),
  70315. mat01 (0),
  70316. mat02 (0),
  70317. mat10 (0),
  70318. mat11 (1.0f),
  70319. mat12 (0)
  70320. {
  70321. }
  70322. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  70323. : mat00 (other.mat00),
  70324. mat01 (other.mat01),
  70325. mat02 (other.mat02),
  70326. mat10 (other.mat10),
  70327. mat11 (other.mat11),
  70328. mat12 (other.mat12)
  70329. {
  70330. }
  70331. AffineTransform::AffineTransform (const float mat00_,
  70332. const float mat01_,
  70333. const float mat02_,
  70334. const float mat10_,
  70335. const float mat11_,
  70336. const float mat12_) throw()
  70337. : mat00 (mat00_),
  70338. mat01 (mat01_),
  70339. mat02 (mat02_),
  70340. mat10 (mat10_),
  70341. mat11 (mat11_),
  70342. mat12 (mat12_)
  70343. {
  70344. }
  70345. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  70346. {
  70347. mat00 = other.mat00;
  70348. mat01 = other.mat01;
  70349. mat02 = other.mat02;
  70350. mat10 = other.mat10;
  70351. mat11 = other.mat11;
  70352. mat12 = other.mat12;
  70353. return *this;
  70354. }
  70355. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  70356. {
  70357. return mat00 == other.mat00
  70358. && mat01 == other.mat01
  70359. && mat02 == other.mat02
  70360. && mat10 == other.mat10
  70361. && mat11 == other.mat11
  70362. && mat12 == other.mat12;
  70363. }
  70364. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  70365. {
  70366. return ! operator== (other);
  70367. }
  70368. bool AffineTransform::isIdentity() const throw()
  70369. {
  70370. return (mat01 == 0)
  70371. && (mat02 == 0)
  70372. && (mat10 == 0)
  70373. && (mat12 == 0)
  70374. && (mat00 == 1.0f)
  70375. && (mat11 == 1.0f);
  70376. }
  70377. const AffineTransform AffineTransform::identity;
  70378. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  70379. {
  70380. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  70381. other.mat00 * mat01 + other.mat01 * mat11,
  70382. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  70383. other.mat10 * mat00 + other.mat11 * mat10,
  70384. other.mat10 * mat01 + other.mat11 * mat11,
  70385. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  70386. }
  70387. const AffineTransform AffineTransform::followedBy (const float omat00,
  70388. const float omat01,
  70389. const float omat02,
  70390. const float omat10,
  70391. const float omat11,
  70392. const float omat12) const throw()
  70393. {
  70394. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  70395. omat00 * mat01 + omat01 * mat11,
  70396. omat00 * mat02 + omat01 * mat12 + omat02,
  70397. omat10 * mat00 + omat11 * mat10,
  70398. omat10 * mat01 + omat11 * mat11,
  70399. omat10 * mat02 + omat11 * mat12 + omat12);
  70400. }
  70401. const AffineTransform AffineTransform::translated (const float dx,
  70402. const float dy) const throw()
  70403. {
  70404. return AffineTransform (mat00, mat01, mat02 + dx,
  70405. mat10, mat11, mat12 + dy);
  70406. }
  70407. const AffineTransform AffineTransform::translation (const float dx,
  70408. const float dy) throw()
  70409. {
  70410. return AffineTransform (1.0f, 0, dx,
  70411. 0, 1.0f, dy);
  70412. }
  70413. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  70414. {
  70415. const float cosRad = cosf (rad);
  70416. const float sinRad = sinf (rad);
  70417. return followedBy (cosRad, -sinRad, 0,
  70418. sinRad, cosRad, 0);
  70419. }
  70420. const AffineTransform AffineTransform::rotation (const float rad) throw()
  70421. {
  70422. const float cosRad = cosf (rad);
  70423. const float sinRad = sinf (rad);
  70424. return AffineTransform (cosRad, -sinRad, 0,
  70425. sinRad, cosRad, 0);
  70426. }
  70427. const AffineTransform AffineTransform::rotated (const float angle,
  70428. const float pivotX,
  70429. const float pivotY) const throw()
  70430. {
  70431. return translated (-pivotX, -pivotY)
  70432. .rotated (angle)
  70433. .translated (pivotX, pivotY);
  70434. }
  70435. const AffineTransform AffineTransform::rotation (const float angle,
  70436. const float pivotX,
  70437. const float pivotY) throw()
  70438. {
  70439. return translation (-pivotX, -pivotY)
  70440. .rotated (angle)
  70441. .translated (pivotX, pivotY);
  70442. }
  70443. const AffineTransform AffineTransform::scaled (const float factorX,
  70444. const float factorY) const throw()
  70445. {
  70446. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  70447. factorY * mat10, factorY * mat11, factorY * mat12);
  70448. }
  70449. const AffineTransform AffineTransform::scale (const float factorX,
  70450. const float factorY) throw()
  70451. {
  70452. return AffineTransform (factorX, 0, 0,
  70453. 0, factorY, 0);
  70454. }
  70455. const AffineTransform AffineTransform::sheared (const float shearX,
  70456. const float shearY) const throw()
  70457. {
  70458. return followedBy (1.0f, shearX, 0,
  70459. shearY, 1.0f, 0);
  70460. }
  70461. const AffineTransform AffineTransform::inverted() const throw()
  70462. {
  70463. double determinant = (mat00 * mat11 - mat10 * mat01);
  70464. if (determinant != 0.0)
  70465. {
  70466. determinant = 1.0 / determinant;
  70467. const float dst00 = (float) (mat11 * determinant);
  70468. const float dst10 = (float) (-mat10 * determinant);
  70469. const float dst01 = (float) (-mat01 * determinant);
  70470. const float dst11 = (float) (mat00 * determinant);
  70471. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  70472. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  70473. }
  70474. else
  70475. {
  70476. // singularity..
  70477. return *this;
  70478. }
  70479. }
  70480. bool AffineTransform::isSingularity() const throw()
  70481. {
  70482. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  70483. }
  70484. bool AffineTransform::isOnlyTranslation() const throw()
  70485. {
  70486. return (mat01 == 0)
  70487. && (mat10 == 0)
  70488. && (mat00 == 1.0f)
  70489. && (mat11 == 1.0f);
  70490. }
  70491. void AffineTransform::transformPoint (float& x,
  70492. float& y) const throw()
  70493. {
  70494. const float oldX = x;
  70495. x = mat00 * oldX + mat01 * y + mat02;
  70496. y = mat10 * oldX + mat11 * y + mat12;
  70497. }
  70498. void AffineTransform::transformPoint (double& x,
  70499. double& y) const throw()
  70500. {
  70501. const double oldX = x;
  70502. x = mat00 * oldX + mat01 * y + mat02;
  70503. y = mat10 * oldX + mat11 * y + mat12;
  70504. }
  70505. END_JUCE_NAMESPACE
  70506. /*** End of inlined file: juce_AffineTransform.cpp ***/
  70507. /*** Start of inlined file: juce_BorderSize.cpp ***/
  70508. BEGIN_JUCE_NAMESPACE
  70509. BorderSize::BorderSize() throw()
  70510. : top (0),
  70511. left (0),
  70512. bottom (0),
  70513. right (0)
  70514. {
  70515. }
  70516. BorderSize::BorderSize (const BorderSize& other) throw()
  70517. : top (other.top),
  70518. left (other.left),
  70519. bottom (other.bottom),
  70520. right (other.right)
  70521. {
  70522. }
  70523. BorderSize::BorderSize (const int topGap,
  70524. const int leftGap,
  70525. const int bottomGap,
  70526. const int rightGap) throw()
  70527. : top (topGap),
  70528. left (leftGap),
  70529. bottom (bottomGap),
  70530. right (rightGap)
  70531. {
  70532. }
  70533. BorderSize::BorderSize (const int allGaps) throw()
  70534. : top (allGaps),
  70535. left (allGaps),
  70536. bottom (allGaps),
  70537. right (allGaps)
  70538. {
  70539. }
  70540. BorderSize::~BorderSize() throw()
  70541. {
  70542. }
  70543. void BorderSize::setTop (const int newTopGap) throw()
  70544. {
  70545. top = newTopGap;
  70546. }
  70547. void BorderSize::setLeft (const int newLeftGap) throw()
  70548. {
  70549. left = newLeftGap;
  70550. }
  70551. void BorderSize::setBottom (const int newBottomGap) throw()
  70552. {
  70553. bottom = newBottomGap;
  70554. }
  70555. void BorderSize::setRight (const int newRightGap) throw()
  70556. {
  70557. right = newRightGap;
  70558. }
  70559. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  70560. {
  70561. return Rectangle<int> (r.getX() + left,
  70562. r.getY() + top,
  70563. r.getWidth() - (left + right),
  70564. r.getHeight() - (top + bottom));
  70565. }
  70566. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  70567. {
  70568. r.setBounds (r.getX() + left,
  70569. r.getY() + top,
  70570. r.getWidth() - (left + right),
  70571. r.getHeight() - (top + bottom));
  70572. }
  70573. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  70574. {
  70575. return Rectangle<int> (r.getX() - left,
  70576. r.getY() - top,
  70577. r.getWidth() + (left + right),
  70578. r.getHeight() + (top + bottom));
  70579. }
  70580. void BorderSize::addTo (Rectangle<int>& r) const throw()
  70581. {
  70582. r.setBounds (r.getX() - left,
  70583. r.getY() - top,
  70584. r.getWidth() + (left + right),
  70585. r.getHeight() + (top + bottom));
  70586. }
  70587. bool BorderSize::operator== (const BorderSize& other) const throw()
  70588. {
  70589. return top == other.top
  70590. && left == other.left
  70591. && bottom == other.bottom
  70592. && right == other.right;
  70593. }
  70594. bool BorderSize::operator!= (const BorderSize& other) const throw()
  70595. {
  70596. return ! operator== (other);
  70597. }
  70598. END_JUCE_NAMESPACE
  70599. /*** End of inlined file: juce_BorderSize.cpp ***/
  70600. /*** Start of inlined file: juce_Line.cpp ***/
  70601. BEGIN_JUCE_NAMESPACE
  70602. END_JUCE_NAMESPACE
  70603. /*** End of inlined file: juce_Line.cpp ***/
  70604. /*** Start of inlined file: juce_Path.cpp ***/
  70605. BEGIN_JUCE_NAMESPACE
  70606. // tests that some co-ords aren't NaNs
  70607. #define CHECK_COORDS_ARE_VALID(x, y) \
  70608. jassert (x == x && y == y);
  70609. namespace PathHelpers
  70610. {
  70611. static const float ellipseAngularIncrement = 0.05f;
  70612. static void perpendicularOffset (const float x1, const float y1,
  70613. const float x2, const float y2,
  70614. const float offsetX, const float offsetY,
  70615. float& resultX, float& resultY) throw()
  70616. {
  70617. const float dx = x2 - x1;
  70618. const float dy = y2 - y1;
  70619. const float len = juce_hypotf (dx, dy);
  70620. if (len == 0)
  70621. {
  70622. resultX = x1;
  70623. resultY = y1;
  70624. }
  70625. else
  70626. {
  70627. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  70628. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  70629. }
  70630. }
  70631. static const String nextToken (const juce_wchar*& t)
  70632. {
  70633. while (CharacterFunctions::isWhitespace (*t))
  70634. ++t;
  70635. const juce_wchar* const start = t;
  70636. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  70637. ++t;
  70638. const int length = (int) (t - start);
  70639. while (CharacterFunctions::isWhitespace (*t))
  70640. ++t;
  70641. return String (start, length);
  70642. }
  70643. }
  70644. const float Path::lineMarker = 100001.0f;
  70645. const float Path::moveMarker = 100002.0f;
  70646. const float Path::quadMarker = 100003.0f;
  70647. const float Path::cubicMarker = 100004.0f;
  70648. const float Path::closeSubPathMarker = 100005.0f;
  70649. Path::Path()
  70650. : numElements (0),
  70651. pathXMin (0),
  70652. pathXMax (0),
  70653. pathYMin (0),
  70654. pathYMax (0),
  70655. useNonZeroWinding (true)
  70656. {
  70657. }
  70658. Path::~Path()
  70659. {
  70660. }
  70661. Path::Path (const Path& other)
  70662. : numElements (other.numElements),
  70663. pathXMin (other.pathXMin),
  70664. pathXMax (other.pathXMax),
  70665. pathYMin (other.pathYMin),
  70666. pathYMax (other.pathYMax),
  70667. useNonZeroWinding (other.useNonZeroWinding)
  70668. {
  70669. if (numElements > 0)
  70670. {
  70671. data.setAllocatedSize ((int) numElements);
  70672. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  70673. }
  70674. }
  70675. Path& Path::operator= (const Path& other)
  70676. {
  70677. if (this != &other)
  70678. {
  70679. data.ensureAllocatedSize ((int) other.numElements);
  70680. numElements = other.numElements;
  70681. pathXMin = other.pathXMin;
  70682. pathXMax = other.pathXMax;
  70683. pathYMin = other.pathYMin;
  70684. pathYMax = other.pathYMax;
  70685. useNonZeroWinding = other.useNonZeroWinding;
  70686. if (numElements > 0)
  70687. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  70688. }
  70689. return *this;
  70690. }
  70691. void Path::clear() throw()
  70692. {
  70693. numElements = 0;
  70694. pathXMin = 0;
  70695. pathYMin = 0;
  70696. pathYMax = 0;
  70697. pathXMax = 0;
  70698. }
  70699. void Path::swapWithPath (Path& other)
  70700. {
  70701. data.swapWith (other.data);
  70702. swapVariables <size_t> (numElements, other.numElements);
  70703. swapVariables <float> (pathXMin, other.pathXMin);
  70704. swapVariables <float> (pathXMax, other.pathXMax);
  70705. swapVariables <float> (pathYMin, other.pathYMin);
  70706. swapVariables <float> (pathYMax, other.pathYMax);
  70707. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  70708. }
  70709. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  70710. {
  70711. useNonZeroWinding = isNonZero;
  70712. }
  70713. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  70714. const bool preserveProportions) throw()
  70715. {
  70716. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  70717. }
  70718. bool Path::isEmpty() const throw()
  70719. {
  70720. size_t i = 0;
  70721. while (i < numElements)
  70722. {
  70723. const float type = data.elements [i++];
  70724. if (type == moveMarker)
  70725. {
  70726. i += 2;
  70727. }
  70728. else if (type == lineMarker
  70729. || type == quadMarker
  70730. || type == cubicMarker)
  70731. {
  70732. return false;
  70733. }
  70734. }
  70735. return true;
  70736. }
  70737. const Rectangle<float> Path::getBounds() const throw()
  70738. {
  70739. return Rectangle<float> (pathXMin, pathYMin,
  70740. pathXMax - pathXMin,
  70741. pathYMax - pathYMin);
  70742. }
  70743. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  70744. {
  70745. return getBounds().transformed (transform);
  70746. }
  70747. void Path::startNewSubPath (const float x, const float y)
  70748. {
  70749. CHECK_COORDS_ARE_VALID (x, y);
  70750. if (numElements == 0)
  70751. {
  70752. pathXMin = pathXMax = x;
  70753. pathYMin = pathYMax = y;
  70754. }
  70755. else
  70756. {
  70757. pathXMin = jmin (pathXMin, x);
  70758. pathXMax = jmax (pathXMax, x);
  70759. pathYMin = jmin (pathYMin, y);
  70760. pathYMax = jmax (pathYMax, y);
  70761. }
  70762. data.ensureAllocatedSize ((int) numElements + 3);
  70763. data.elements [numElements++] = moveMarker;
  70764. data.elements [numElements++] = x;
  70765. data.elements [numElements++] = y;
  70766. }
  70767. void Path::lineTo (const float x, const float y)
  70768. {
  70769. CHECK_COORDS_ARE_VALID (x, y);
  70770. if (numElements == 0)
  70771. startNewSubPath (0, 0);
  70772. data.ensureAllocatedSize ((int) numElements + 3);
  70773. data.elements [numElements++] = lineMarker;
  70774. data.elements [numElements++] = x;
  70775. data.elements [numElements++] = y;
  70776. pathXMin = jmin (pathXMin, x);
  70777. pathXMax = jmax (pathXMax, x);
  70778. pathYMin = jmin (pathYMin, y);
  70779. pathYMax = jmax (pathYMax, y);
  70780. }
  70781. void Path::quadraticTo (const float x1, const float y1,
  70782. const float x2, const float y2)
  70783. {
  70784. CHECK_COORDS_ARE_VALID (x1, y1);
  70785. CHECK_COORDS_ARE_VALID (x2, y2);
  70786. if (numElements == 0)
  70787. startNewSubPath (0, 0);
  70788. data.ensureAllocatedSize ((int) numElements + 5);
  70789. data.elements [numElements++] = quadMarker;
  70790. data.elements [numElements++] = x1;
  70791. data.elements [numElements++] = y1;
  70792. data.elements [numElements++] = x2;
  70793. data.elements [numElements++] = y2;
  70794. pathXMin = jmin (pathXMin, x1, x2);
  70795. pathXMax = jmax (pathXMax, x1, x2);
  70796. pathYMin = jmin (pathYMin, y1, y2);
  70797. pathYMax = jmax (pathYMax, y1, y2);
  70798. }
  70799. void Path::cubicTo (const float x1, const float y1,
  70800. const float x2, const float y2,
  70801. const float x3, const float y3)
  70802. {
  70803. CHECK_COORDS_ARE_VALID (x1, y1);
  70804. CHECK_COORDS_ARE_VALID (x2, y2);
  70805. CHECK_COORDS_ARE_VALID (x3, y3);
  70806. if (numElements == 0)
  70807. startNewSubPath (0, 0);
  70808. data.ensureAllocatedSize ((int) numElements + 7);
  70809. data.elements [numElements++] = cubicMarker;
  70810. data.elements [numElements++] = x1;
  70811. data.elements [numElements++] = y1;
  70812. data.elements [numElements++] = x2;
  70813. data.elements [numElements++] = y2;
  70814. data.elements [numElements++] = x3;
  70815. data.elements [numElements++] = y3;
  70816. pathXMin = jmin (pathXMin, x1, x2, x3);
  70817. pathXMax = jmax (pathXMax, x1, x2, x3);
  70818. pathYMin = jmin (pathYMin, y1, y2, y3);
  70819. pathYMax = jmax (pathYMax, y1, y2, y3);
  70820. }
  70821. void Path::closeSubPath()
  70822. {
  70823. if (numElements > 0
  70824. && data.elements [numElements - 1] != closeSubPathMarker)
  70825. {
  70826. data.ensureAllocatedSize ((int) numElements + 1);
  70827. data.elements [numElements++] = closeSubPathMarker;
  70828. }
  70829. }
  70830. const Point<float> Path::getCurrentPosition() const
  70831. {
  70832. size_t i = numElements - 1;
  70833. if (i > 0 && data.elements[i] == closeSubPathMarker)
  70834. {
  70835. while (i >= 0)
  70836. {
  70837. if (data.elements[i] == moveMarker)
  70838. {
  70839. i += 2;
  70840. break;
  70841. }
  70842. --i;
  70843. }
  70844. }
  70845. if (i > 0)
  70846. return Point<float> (data.elements [i - 1], data.elements [i]);
  70847. return Point<float>();
  70848. }
  70849. void Path::addRectangle (const float x, const float y,
  70850. const float w, const float h)
  70851. {
  70852. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  70853. if (w < 0)
  70854. swapVariables (x1, x2);
  70855. if (h < 0)
  70856. swapVariables (y1, y2);
  70857. data.ensureAllocatedSize ((int) numElements + 13);
  70858. if (numElements == 0)
  70859. {
  70860. pathXMin = x1;
  70861. pathXMax = x2;
  70862. pathYMin = y1;
  70863. pathYMax = y2;
  70864. }
  70865. else
  70866. {
  70867. pathXMin = jmin (pathXMin, x1);
  70868. pathXMax = jmax (pathXMax, x2);
  70869. pathYMin = jmin (pathYMin, y1);
  70870. pathYMax = jmax (pathYMax, y2);
  70871. }
  70872. data.elements [numElements++] = moveMarker;
  70873. data.elements [numElements++] = x1;
  70874. data.elements [numElements++] = y2;
  70875. data.elements [numElements++] = lineMarker;
  70876. data.elements [numElements++] = x1;
  70877. data.elements [numElements++] = y1;
  70878. data.elements [numElements++] = lineMarker;
  70879. data.elements [numElements++] = x2;
  70880. data.elements [numElements++] = y1;
  70881. data.elements [numElements++] = lineMarker;
  70882. data.elements [numElements++] = x2;
  70883. data.elements [numElements++] = y2;
  70884. data.elements [numElements++] = closeSubPathMarker;
  70885. }
  70886. void Path::addRectangle (const Rectangle<int>& rectangle)
  70887. {
  70888. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  70889. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  70890. }
  70891. void Path::addRoundedRectangle (const float x, const float y,
  70892. const float w, const float h,
  70893. float csx,
  70894. float csy)
  70895. {
  70896. csx = jmin (csx, w * 0.5f);
  70897. csy = jmin (csy, h * 0.5f);
  70898. const float cs45x = csx * 0.45f;
  70899. const float cs45y = csy * 0.45f;
  70900. const float x2 = x + w;
  70901. const float y2 = y + h;
  70902. startNewSubPath (x + csx, y);
  70903. lineTo (x2 - csx, y);
  70904. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  70905. lineTo (x2, y2 - csy);
  70906. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  70907. lineTo (x + csx, y2);
  70908. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  70909. lineTo (x, y + csy);
  70910. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  70911. closeSubPath();
  70912. }
  70913. void Path::addRoundedRectangle (const float x, const float y,
  70914. const float w, const float h,
  70915. float cs)
  70916. {
  70917. addRoundedRectangle (x, y, w, h, cs, cs);
  70918. }
  70919. void Path::addTriangle (const float x1, const float y1,
  70920. const float x2, const float y2,
  70921. const float x3, const float y3)
  70922. {
  70923. startNewSubPath (x1, y1);
  70924. lineTo (x2, y2);
  70925. lineTo (x3, y3);
  70926. closeSubPath();
  70927. }
  70928. void Path::addQuadrilateral (const float x1, const float y1,
  70929. const float x2, const float y2,
  70930. const float x3, const float y3,
  70931. const float x4, const float y4)
  70932. {
  70933. startNewSubPath (x1, y1);
  70934. lineTo (x2, y2);
  70935. lineTo (x3, y3);
  70936. lineTo (x4, y4);
  70937. closeSubPath();
  70938. }
  70939. void Path::addEllipse (const float x, const float y,
  70940. const float w, const float h)
  70941. {
  70942. const float hw = w * 0.5f;
  70943. const float hw55 = hw * 0.55f;
  70944. const float hh = h * 0.5f;
  70945. const float hh45 = hh * 0.55f;
  70946. const float cx = x + hw;
  70947. const float cy = y + hh;
  70948. startNewSubPath (cx, cy - hh);
  70949. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  70950. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  70951. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  70952. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  70953. closeSubPath();
  70954. }
  70955. void Path::addArc (const float x, const float y,
  70956. const float w, const float h,
  70957. const float fromRadians,
  70958. const float toRadians,
  70959. const bool startAsNewSubPath)
  70960. {
  70961. const float radiusX = w / 2.0f;
  70962. const float radiusY = h / 2.0f;
  70963. addCentredArc (x + radiusX,
  70964. y + radiusY,
  70965. radiusX, radiusY,
  70966. 0.0f,
  70967. fromRadians, toRadians,
  70968. startAsNewSubPath);
  70969. }
  70970. void Path::addCentredArc (const float centreX, const float centreY,
  70971. const float radiusX, const float radiusY,
  70972. const float rotationOfEllipse,
  70973. const float fromRadians,
  70974. const float toRadians,
  70975. const bool startAsNewSubPath)
  70976. {
  70977. if (radiusX > 0.0f && radiusY > 0.0f)
  70978. {
  70979. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  70980. float angle = fromRadians;
  70981. if (startAsNewSubPath)
  70982. {
  70983. float x = centreX + radiusX * sinf (angle);
  70984. float y = centreY - radiusY * cosf (angle);
  70985. if (rotationOfEllipse != 0)
  70986. rotation.transformPoint (x, y);
  70987. startNewSubPath (x, y);
  70988. }
  70989. if (fromRadians < toRadians)
  70990. {
  70991. if (startAsNewSubPath)
  70992. angle += PathHelpers::ellipseAngularIncrement;
  70993. while (angle < toRadians)
  70994. {
  70995. float x = centreX + radiusX * sinf (angle);
  70996. float y = centreY - radiusY * cosf (angle);
  70997. if (rotationOfEllipse != 0)
  70998. rotation.transformPoint (x, y);
  70999. lineTo (x, y);
  71000. angle += PathHelpers::ellipseAngularIncrement;
  71001. }
  71002. }
  71003. else
  71004. {
  71005. if (startAsNewSubPath)
  71006. angle -= PathHelpers::ellipseAngularIncrement;
  71007. while (angle > toRadians)
  71008. {
  71009. float x = centreX + radiusX * sinf (angle);
  71010. float y = centreY - radiusY * cosf (angle);
  71011. if (rotationOfEllipse != 0)
  71012. rotation.transformPoint (x, y);
  71013. lineTo (x, y);
  71014. angle -= PathHelpers::ellipseAngularIncrement;
  71015. }
  71016. }
  71017. float x = centreX + radiusX * sinf (toRadians);
  71018. float y = centreY - radiusY * cosf (toRadians);
  71019. if (rotationOfEllipse != 0)
  71020. rotation.transformPoint (x, y);
  71021. lineTo (x, y);
  71022. }
  71023. }
  71024. void Path::addPieSegment (const float x, const float y,
  71025. const float width, const float height,
  71026. const float fromRadians,
  71027. const float toRadians,
  71028. const float innerCircleProportionalSize)
  71029. {
  71030. float hw = width * 0.5f;
  71031. float hh = height * 0.5f;
  71032. const float centreX = x + hw;
  71033. const float centreY = y + hh;
  71034. startNewSubPath (centreX + hw * sinf (fromRadians),
  71035. centreY - hh * cosf (fromRadians));
  71036. addArc (x, y, width, height, fromRadians, toRadians);
  71037. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  71038. {
  71039. closeSubPath();
  71040. if (innerCircleProportionalSize > 0)
  71041. {
  71042. hw *= innerCircleProportionalSize;
  71043. hh *= innerCircleProportionalSize;
  71044. startNewSubPath (centreX + hw * sinf (toRadians),
  71045. centreY - hh * cosf (toRadians));
  71046. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71047. toRadians, fromRadians);
  71048. }
  71049. }
  71050. else
  71051. {
  71052. if (innerCircleProportionalSize > 0)
  71053. {
  71054. hw *= innerCircleProportionalSize;
  71055. hh *= innerCircleProportionalSize;
  71056. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71057. toRadians, fromRadians);
  71058. }
  71059. else
  71060. {
  71061. lineTo (centreX, centreY);
  71062. }
  71063. }
  71064. closeSubPath();
  71065. }
  71066. void Path::addLineSegment (const float startX, const float startY,
  71067. const float endX, const float endY,
  71068. float lineThickness)
  71069. {
  71070. lineThickness *= 0.5f;
  71071. float x, y;
  71072. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71073. 0, lineThickness, x, y);
  71074. startNewSubPath (x, y);
  71075. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71076. 0, -lineThickness, x, y);
  71077. lineTo (x, y);
  71078. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71079. 0, lineThickness, x, y);
  71080. lineTo (x, y);
  71081. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71082. 0, -lineThickness, x, y);
  71083. lineTo (x, y);
  71084. closeSubPath();
  71085. }
  71086. void Path::addArrow (const float startX, const float startY,
  71087. const float endX, const float endY,
  71088. float lineThickness,
  71089. float arrowheadWidth,
  71090. float arrowheadLength)
  71091. {
  71092. lineThickness *= 0.5f;
  71093. arrowheadWidth *= 0.5f;
  71094. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  71095. startY - endY));
  71096. float x, y;
  71097. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71098. 0, lineThickness, x, y);
  71099. startNewSubPath (x, y);
  71100. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71101. 0, -lineThickness, x, y);
  71102. lineTo (x, y);
  71103. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71104. arrowheadLength, lineThickness, x, y);
  71105. lineTo (x, y);
  71106. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71107. arrowheadLength, arrowheadWidth, x, y);
  71108. lineTo (x, y);
  71109. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71110. 0, 0, x, y);
  71111. lineTo (x, y);
  71112. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71113. arrowheadLength, -arrowheadWidth, x, y);
  71114. lineTo (x, y);
  71115. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71116. arrowheadLength, -lineThickness, x, y);
  71117. lineTo (x, y);
  71118. closeSubPath();
  71119. }
  71120. void Path::addStar (const float centreX,
  71121. const float centreY,
  71122. const int numberOfPoints,
  71123. const float innerRadius,
  71124. const float outerRadius,
  71125. const float startAngle)
  71126. {
  71127. jassert (numberOfPoints > 1); // this would be silly.
  71128. if (numberOfPoints > 1)
  71129. {
  71130. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  71131. for (int i = 0; i < numberOfPoints; ++i)
  71132. {
  71133. float angle = startAngle + i * angleBetweenPoints;
  71134. const float x = centreX + outerRadius * sinf (angle);
  71135. const float y = centreY - outerRadius * cosf (angle);
  71136. if (i == 0)
  71137. startNewSubPath (x, y);
  71138. else
  71139. lineTo (x, y);
  71140. angle += angleBetweenPoints * 0.5f;
  71141. lineTo (centreX + innerRadius * sinf (angle),
  71142. centreY - innerRadius * cosf (angle));
  71143. }
  71144. closeSubPath();
  71145. }
  71146. }
  71147. void Path::addBubble (float x, float y,
  71148. float w, float h,
  71149. float cs,
  71150. float tipX,
  71151. float tipY,
  71152. int whichSide,
  71153. float arrowPos,
  71154. float arrowWidth)
  71155. {
  71156. if (w > 1.0f && h > 1.0f)
  71157. {
  71158. cs = jmin (cs, w * 0.5f, h * 0.5f);
  71159. const float cs2 = 2.0f * cs;
  71160. startNewSubPath (x + cs, y);
  71161. if (whichSide == 0)
  71162. {
  71163. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71164. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71165. lineTo (arrowX1, y);
  71166. lineTo (tipX, tipY);
  71167. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  71168. }
  71169. lineTo (x + w - cs, y);
  71170. if (cs > 0.0f)
  71171. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  71172. if (whichSide == 3)
  71173. {
  71174. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71175. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71176. lineTo (x + w, arrowY1);
  71177. lineTo (tipX, tipY);
  71178. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  71179. }
  71180. lineTo (x + w, y + h - cs);
  71181. if (cs > 0.0f)
  71182. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  71183. if (whichSide == 2)
  71184. {
  71185. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71186. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71187. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  71188. lineTo (tipX, tipY);
  71189. lineTo (arrowX1, y + h);
  71190. }
  71191. lineTo (x + cs, y + h);
  71192. if (cs > 0.0f)
  71193. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  71194. if (whichSide == 1)
  71195. {
  71196. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71197. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71198. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  71199. lineTo (tipX, tipY);
  71200. lineTo (x, arrowY1);
  71201. }
  71202. lineTo (x, y + cs);
  71203. if (cs > 0.0f)
  71204. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  71205. closeSubPath();
  71206. }
  71207. }
  71208. void Path::addPath (const Path& other)
  71209. {
  71210. size_t i = 0;
  71211. while (i < other.numElements)
  71212. {
  71213. const float type = other.data.elements [i++];
  71214. if (type == moveMarker)
  71215. {
  71216. startNewSubPath (other.data.elements [i],
  71217. other.data.elements [i + 1]);
  71218. i += 2;
  71219. }
  71220. else if (type == lineMarker)
  71221. {
  71222. lineTo (other.data.elements [i],
  71223. other.data.elements [i + 1]);
  71224. i += 2;
  71225. }
  71226. else if (type == quadMarker)
  71227. {
  71228. quadraticTo (other.data.elements [i],
  71229. other.data.elements [i + 1],
  71230. other.data.elements [i + 2],
  71231. other.data.elements [i + 3]);
  71232. i += 4;
  71233. }
  71234. else if (type == cubicMarker)
  71235. {
  71236. cubicTo (other.data.elements [i],
  71237. other.data.elements [i + 1],
  71238. other.data.elements [i + 2],
  71239. other.data.elements [i + 3],
  71240. other.data.elements [i + 4],
  71241. other.data.elements [i + 5]);
  71242. i += 6;
  71243. }
  71244. else if (type == closeSubPathMarker)
  71245. {
  71246. closeSubPath();
  71247. }
  71248. else
  71249. {
  71250. // something's gone wrong with the element list!
  71251. jassertfalse
  71252. }
  71253. }
  71254. }
  71255. void Path::addPath (const Path& other,
  71256. const AffineTransform& transformToApply)
  71257. {
  71258. size_t i = 0;
  71259. while (i < other.numElements)
  71260. {
  71261. const float type = other.data.elements [i++];
  71262. if (type == closeSubPathMarker)
  71263. {
  71264. closeSubPath();
  71265. }
  71266. else
  71267. {
  71268. float x = other.data.elements [i++];
  71269. float y = other.data.elements [i++];
  71270. transformToApply.transformPoint (x, y);
  71271. if (type == moveMarker)
  71272. {
  71273. startNewSubPath (x, y);
  71274. }
  71275. else if (type == lineMarker)
  71276. {
  71277. lineTo (x, y);
  71278. }
  71279. else if (type == quadMarker)
  71280. {
  71281. float x2 = other.data.elements [i++];
  71282. float y2 = other.data.elements [i++];
  71283. transformToApply.transformPoint (x2, y2);
  71284. quadraticTo (x, y, x2, y2);
  71285. }
  71286. else if (type == cubicMarker)
  71287. {
  71288. float x2 = other.data.elements [i++];
  71289. float y2 = other.data.elements [i++];
  71290. float x3 = other.data.elements [i++];
  71291. float y3 = other.data.elements [i++];
  71292. transformToApply.transformPoint (x2, y2);
  71293. transformToApply.transformPoint (x3, y3);
  71294. cubicTo (x, y, x2, y2, x3, y3);
  71295. }
  71296. else
  71297. {
  71298. // something's gone wrong with the element list!
  71299. jassertfalse
  71300. }
  71301. }
  71302. }
  71303. }
  71304. void Path::applyTransform (const AffineTransform& transform) throw()
  71305. {
  71306. size_t i = 0;
  71307. pathYMin = pathXMin = 0;
  71308. pathYMax = pathXMax = 0;
  71309. bool setMaxMin = false;
  71310. while (i < numElements)
  71311. {
  71312. const float type = data.elements [i++];
  71313. if (type == moveMarker)
  71314. {
  71315. transform.transformPoint (data.elements [i],
  71316. data.elements [i + 1]);
  71317. if (setMaxMin)
  71318. {
  71319. pathXMin = jmin (pathXMin, data.elements [i]);
  71320. pathXMax = jmax (pathXMax, data.elements [i]);
  71321. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71322. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71323. }
  71324. else
  71325. {
  71326. pathXMin = pathXMax = data.elements [i];
  71327. pathYMin = pathYMax = data.elements [i + 1];
  71328. setMaxMin = true;
  71329. }
  71330. i += 2;
  71331. }
  71332. else if (type == lineMarker)
  71333. {
  71334. transform.transformPoint (data.elements [i],
  71335. data.elements [i + 1]);
  71336. pathXMin = jmin (pathXMin, data.elements [i]);
  71337. pathXMax = jmax (pathXMax, data.elements [i]);
  71338. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71339. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71340. i += 2;
  71341. }
  71342. else if (type == quadMarker)
  71343. {
  71344. transform.transformPoint (data.elements [i],
  71345. data.elements [i + 1]);
  71346. transform.transformPoint (data.elements [i + 2],
  71347. data.elements [i + 3]);
  71348. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  71349. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  71350. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  71351. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  71352. i += 4;
  71353. }
  71354. else if (type == cubicMarker)
  71355. {
  71356. transform.transformPoint (data.elements [i],
  71357. data.elements [i + 1]);
  71358. transform.transformPoint (data.elements [i + 2],
  71359. data.elements [i + 3]);
  71360. transform.transformPoint (data.elements [i + 4],
  71361. data.elements [i + 5]);
  71362. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  71363. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  71364. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  71365. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  71366. i += 6;
  71367. }
  71368. }
  71369. }
  71370. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  71371. const float w, const float h,
  71372. const bool preserveProportions,
  71373. const Justification& justification) const
  71374. {
  71375. Rectangle<float> bounds (getBounds());
  71376. if (preserveProportions)
  71377. {
  71378. if (w <= 0 || h <= 0 || bounds.isEmpty())
  71379. return AffineTransform::identity;
  71380. float newW, newH;
  71381. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  71382. if (srcRatio > h / w)
  71383. {
  71384. newW = h / srcRatio;
  71385. newH = h;
  71386. }
  71387. else
  71388. {
  71389. newW = w;
  71390. newH = w * srcRatio;
  71391. }
  71392. float newXCentre = x;
  71393. float newYCentre = y;
  71394. if (justification.testFlags (Justification::left))
  71395. newXCentre += newW * 0.5f;
  71396. else if (justification.testFlags (Justification::right))
  71397. newXCentre += w - newW * 0.5f;
  71398. else
  71399. newXCentre += w * 0.5f;
  71400. if (justification.testFlags (Justification::top))
  71401. newYCentre += newH * 0.5f;
  71402. else if (justification.testFlags (Justification::bottom))
  71403. newYCentre += h - newH * 0.5f;
  71404. else
  71405. newYCentre += h * 0.5f;
  71406. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  71407. bounds.getHeight() * -0.5f - bounds.getY())
  71408. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  71409. .translated (newXCentre, newYCentre);
  71410. }
  71411. else
  71412. {
  71413. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  71414. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  71415. .translated (x, y);
  71416. }
  71417. }
  71418. bool Path::contains (const float x, const float y, const float tolerence) const
  71419. {
  71420. if (x <= pathXMin || x >= pathXMax
  71421. || y <= pathYMin || y >= pathYMax)
  71422. return false;
  71423. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  71424. int positiveCrossings = 0;
  71425. int negativeCrossings = 0;
  71426. while (i.next())
  71427. {
  71428. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  71429. {
  71430. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  71431. if (intersectX <= x)
  71432. {
  71433. if (i.y1 < i.y2)
  71434. ++positiveCrossings;
  71435. else
  71436. ++negativeCrossings;
  71437. }
  71438. }
  71439. }
  71440. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  71441. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  71442. }
  71443. bool Path::contains (const Point<float>& point, const float tolerence) const
  71444. {
  71445. return contains (point.getX(), point.getY(), tolerence);
  71446. }
  71447. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  71448. {
  71449. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  71450. Point<float> intersection;
  71451. while (i.next())
  71452. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  71453. return true;
  71454. return false;
  71455. }
  71456. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  71457. {
  71458. Line<float> result (line);
  71459. const bool startInside = contains (line.getStart());
  71460. const bool endInside = contains (line.getEnd());
  71461. if (startInside == endInside)
  71462. {
  71463. if (keepSectionOutsidePath == startInside)
  71464. result = Line<float>();
  71465. }
  71466. else
  71467. {
  71468. PathFlatteningIterator i (*this, AffineTransform::identity);
  71469. Point<float> intersection;
  71470. while (i.next())
  71471. {
  71472. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  71473. {
  71474. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  71475. result.setStart (intersection);
  71476. else
  71477. result.setEnd (intersection);
  71478. }
  71479. }
  71480. }
  71481. return result;
  71482. }
  71483. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  71484. {
  71485. if (cornerRadius <= 0.01f)
  71486. return *this;
  71487. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  71488. size_t n = 0;
  71489. bool lastWasLine = false, firstWasLine = false;
  71490. Path p;
  71491. while (n < numElements)
  71492. {
  71493. const float type = data.elements [n++];
  71494. if (type == moveMarker)
  71495. {
  71496. indexOfPathStart = p.numElements;
  71497. indexOfPathStartThis = n - 1;
  71498. const float x = data.elements [n++];
  71499. const float y = data.elements [n++];
  71500. p.startNewSubPath (x, y);
  71501. lastWasLine = false;
  71502. firstWasLine = (data.elements [n] == lineMarker);
  71503. }
  71504. else if (type == lineMarker || type == closeSubPathMarker)
  71505. {
  71506. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  71507. if (type == lineMarker)
  71508. {
  71509. endX = data.elements [n++];
  71510. endY = data.elements [n++];
  71511. if (n > 8)
  71512. {
  71513. startX = data.elements [n - 8];
  71514. startY = data.elements [n - 7];
  71515. joinX = data.elements [n - 5];
  71516. joinY = data.elements [n - 4];
  71517. }
  71518. }
  71519. else
  71520. {
  71521. endX = data.elements [indexOfPathStartThis + 1];
  71522. endY = data.elements [indexOfPathStartThis + 2];
  71523. if (n > 6)
  71524. {
  71525. startX = data.elements [n - 6];
  71526. startY = data.elements [n - 5];
  71527. joinX = data.elements [n - 3];
  71528. joinY = data.elements [n - 2];
  71529. }
  71530. }
  71531. if (lastWasLine)
  71532. {
  71533. const double len1 = juce_hypot (startX - joinX,
  71534. startY - joinY);
  71535. if (len1 > 0)
  71536. {
  71537. const double propNeeded = jmin (0.5, cornerRadius / len1);
  71538. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  71539. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  71540. }
  71541. const double len2 = juce_hypot (endX - joinX,
  71542. endY - joinY);
  71543. if (len2 > 0)
  71544. {
  71545. const double propNeeded = jmin (0.5, cornerRadius / len2);
  71546. p.quadraticTo (joinX, joinY,
  71547. (float) (joinX + (endX - joinX) * propNeeded),
  71548. (float) (joinY + (endY - joinY) * propNeeded));
  71549. }
  71550. p.lineTo (endX, endY);
  71551. }
  71552. else if (type == lineMarker)
  71553. {
  71554. p.lineTo (endX, endY);
  71555. lastWasLine = true;
  71556. }
  71557. if (type == closeSubPathMarker)
  71558. {
  71559. if (firstWasLine)
  71560. {
  71561. startX = data.elements [n - 3];
  71562. startY = data.elements [n - 2];
  71563. joinX = endX;
  71564. joinY = endY;
  71565. endX = data.elements [indexOfPathStartThis + 4];
  71566. endY = data.elements [indexOfPathStartThis + 5];
  71567. const double len1 = juce_hypot (startX - joinX,
  71568. startY - joinY);
  71569. if (len1 > 0)
  71570. {
  71571. const double propNeeded = jmin (0.5, cornerRadius / len1);
  71572. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  71573. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  71574. }
  71575. const double len2 = juce_hypot (endX - joinX,
  71576. endY - joinY);
  71577. if (len2 > 0)
  71578. {
  71579. const double propNeeded = jmin (0.5, cornerRadius / len2);
  71580. endX = (float) (joinX + (endX - joinX) * propNeeded);
  71581. endY = (float) (joinY + (endY - joinY) * propNeeded);
  71582. p.quadraticTo (joinX, joinY, endX, endY);
  71583. p.data.elements [indexOfPathStart + 1] = endX;
  71584. p.data.elements [indexOfPathStart + 2] = endY;
  71585. }
  71586. }
  71587. p.closeSubPath();
  71588. }
  71589. }
  71590. else if (type == quadMarker)
  71591. {
  71592. lastWasLine = false;
  71593. const float x1 = data.elements [n++];
  71594. const float y1 = data.elements [n++];
  71595. const float x2 = data.elements [n++];
  71596. const float y2 = data.elements [n++];
  71597. p.quadraticTo (x1, y1, x2, y2);
  71598. }
  71599. else if (type == cubicMarker)
  71600. {
  71601. lastWasLine = false;
  71602. const float x1 = data.elements [n++];
  71603. const float y1 = data.elements [n++];
  71604. const float x2 = data.elements [n++];
  71605. const float y2 = data.elements [n++];
  71606. const float x3 = data.elements [n++];
  71607. const float y3 = data.elements [n++];
  71608. p.cubicTo (x1, y1, x2, y2, x3, y3);
  71609. }
  71610. }
  71611. return p;
  71612. }
  71613. void Path::loadPathFromStream (InputStream& source)
  71614. {
  71615. while (! source.isExhausted())
  71616. {
  71617. switch (source.readByte())
  71618. {
  71619. case 'm':
  71620. {
  71621. const float x = source.readFloat();
  71622. const float y = source.readFloat();
  71623. startNewSubPath (x, y);
  71624. break;
  71625. }
  71626. case 'l':
  71627. {
  71628. const float x = source.readFloat();
  71629. const float y = source.readFloat();
  71630. lineTo (x, y);
  71631. break;
  71632. }
  71633. case 'q':
  71634. {
  71635. const float x1 = source.readFloat();
  71636. const float y1 = source.readFloat();
  71637. const float x2 = source.readFloat();
  71638. const float y2 = source.readFloat();
  71639. quadraticTo (x1, y1, x2, y2);
  71640. break;
  71641. }
  71642. case 'b':
  71643. {
  71644. const float x1 = source.readFloat();
  71645. const float y1 = source.readFloat();
  71646. const float x2 = source.readFloat();
  71647. const float y2 = source.readFloat();
  71648. const float x3 = source.readFloat();
  71649. const float y3 = source.readFloat();
  71650. cubicTo (x1, y1, x2, y2, x3, y3);
  71651. break;
  71652. }
  71653. case 'c':
  71654. closeSubPath();
  71655. break;
  71656. case 'n':
  71657. useNonZeroWinding = true;
  71658. break;
  71659. case 'z':
  71660. useNonZeroWinding = false;
  71661. break;
  71662. case 'e':
  71663. return; // end of path marker
  71664. default:
  71665. jassertfalse // illegal char in the stream
  71666. break;
  71667. }
  71668. }
  71669. }
  71670. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  71671. {
  71672. MemoryInputStream in (pathData, numberOfBytes, false);
  71673. loadPathFromStream (in);
  71674. }
  71675. void Path::writePathToStream (OutputStream& dest) const
  71676. {
  71677. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  71678. size_t i = 0;
  71679. while (i < numElements)
  71680. {
  71681. const float type = data.elements [i++];
  71682. if (type == moveMarker)
  71683. {
  71684. dest.writeByte ('m');
  71685. dest.writeFloat (data.elements [i++]);
  71686. dest.writeFloat (data.elements [i++]);
  71687. }
  71688. else if (type == lineMarker)
  71689. {
  71690. dest.writeByte ('l');
  71691. dest.writeFloat (data.elements [i++]);
  71692. dest.writeFloat (data.elements [i++]);
  71693. }
  71694. else if (type == quadMarker)
  71695. {
  71696. dest.writeByte ('q');
  71697. dest.writeFloat (data.elements [i++]);
  71698. dest.writeFloat (data.elements [i++]);
  71699. dest.writeFloat (data.elements [i++]);
  71700. dest.writeFloat (data.elements [i++]);
  71701. }
  71702. else if (type == cubicMarker)
  71703. {
  71704. dest.writeByte ('b');
  71705. dest.writeFloat (data.elements [i++]);
  71706. dest.writeFloat (data.elements [i++]);
  71707. dest.writeFloat (data.elements [i++]);
  71708. dest.writeFloat (data.elements [i++]);
  71709. dest.writeFloat (data.elements [i++]);
  71710. dest.writeFloat (data.elements [i++]);
  71711. }
  71712. else if (type == closeSubPathMarker)
  71713. {
  71714. dest.writeByte ('c');
  71715. }
  71716. }
  71717. dest.writeByte ('e'); // marks the end-of-path
  71718. }
  71719. const String Path::toString() const
  71720. {
  71721. MemoryOutputStream s (2048, 2048);
  71722. if (! useNonZeroWinding)
  71723. s << 'a';
  71724. size_t i = 0;
  71725. float lastMarker = 0.0f;
  71726. while (i < numElements)
  71727. {
  71728. const float marker = data.elements [i++];
  71729. char markerChar = 0;
  71730. int numCoords = 0;
  71731. if (marker == moveMarker)
  71732. {
  71733. markerChar = 'm';
  71734. numCoords = 2;
  71735. }
  71736. else if (marker == lineMarker)
  71737. {
  71738. markerChar = 'l';
  71739. numCoords = 2;
  71740. }
  71741. else if (marker == quadMarker)
  71742. {
  71743. markerChar = 'q';
  71744. numCoords = 4;
  71745. }
  71746. else if (marker == cubicMarker)
  71747. {
  71748. markerChar = 'c';
  71749. numCoords = 6;
  71750. }
  71751. else
  71752. {
  71753. jassert (marker == closeSubPathMarker);
  71754. markerChar = 'z';
  71755. }
  71756. if (marker != lastMarker)
  71757. {
  71758. if (s.getDataSize() != 0)
  71759. s << ' ';
  71760. s << markerChar;
  71761. lastMarker = marker;
  71762. }
  71763. while (--numCoords >= 0 && i < numElements)
  71764. {
  71765. String coord (data.elements [i++], 3);
  71766. while (coord.endsWithChar ('0') && coord != "0")
  71767. coord = coord.dropLastCharacters (1);
  71768. if (coord.endsWithChar ('.'))
  71769. coord = coord.dropLastCharacters (1);
  71770. if (s.getDataSize() != 0)
  71771. s << ' ';
  71772. s << coord;
  71773. }
  71774. }
  71775. return s.toUTF8();
  71776. }
  71777. void Path::restoreFromString (const String& stringVersion)
  71778. {
  71779. clear();
  71780. setUsingNonZeroWinding (true);
  71781. const juce_wchar* t = stringVersion;
  71782. juce_wchar marker = 'm';
  71783. int numValues = 2;
  71784. float values [6];
  71785. while (*t != 0)
  71786. {
  71787. const String token (PathHelpers::nextToken (t));
  71788. const juce_wchar firstChar = token[0];
  71789. int startNum = 0;
  71790. if (firstChar == 'm' || firstChar == 'l')
  71791. {
  71792. marker = firstChar;
  71793. numValues = 2;
  71794. }
  71795. else if (firstChar == 'q')
  71796. {
  71797. marker = firstChar;
  71798. numValues = 4;
  71799. }
  71800. else if (firstChar == 'c')
  71801. {
  71802. marker = firstChar;
  71803. numValues = 6;
  71804. }
  71805. else if (firstChar == 'z')
  71806. {
  71807. marker = firstChar;
  71808. numValues = 0;
  71809. }
  71810. else if (firstChar == 'a')
  71811. {
  71812. setUsingNonZeroWinding (false);
  71813. continue;
  71814. }
  71815. else
  71816. {
  71817. ++startNum;
  71818. values [0] = token.getFloatValue();
  71819. }
  71820. for (int i = startNum; i < numValues; ++i)
  71821. values [i] = PathHelpers::nextToken (t).getFloatValue();
  71822. switch (marker)
  71823. {
  71824. case 'm':
  71825. startNewSubPath (values[0], values[1]);
  71826. break;
  71827. case 'l':
  71828. lineTo (values[0], values[1]);
  71829. break;
  71830. case 'q':
  71831. quadraticTo (values[0], values[1],
  71832. values[2], values[3]);
  71833. break;
  71834. case 'c':
  71835. cubicTo (values[0], values[1],
  71836. values[2], values[3],
  71837. values[4], values[5]);
  71838. break;
  71839. case 'z':
  71840. closeSubPath();
  71841. break;
  71842. default:
  71843. jassertfalse // illegal string format?
  71844. break;
  71845. }
  71846. }
  71847. }
  71848. Path::Iterator::Iterator (const Path& path_)
  71849. : path (path_),
  71850. index (0)
  71851. {
  71852. }
  71853. Path::Iterator::~Iterator()
  71854. {
  71855. }
  71856. bool Path::Iterator::next()
  71857. {
  71858. const float* const elements = path.data.elements;
  71859. if (index < path.numElements)
  71860. {
  71861. const float type = elements [index++];
  71862. if (type == moveMarker)
  71863. {
  71864. elementType = startNewSubPath;
  71865. x1 = elements [index++];
  71866. y1 = elements [index++];
  71867. }
  71868. else if (type == lineMarker)
  71869. {
  71870. elementType = lineTo;
  71871. x1 = elements [index++];
  71872. y1 = elements [index++];
  71873. }
  71874. else if (type == quadMarker)
  71875. {
  71876. elementType = quadraticTo;
  71877. x1 = elements [index++];
  71878. y1 = elements [index++];
  71879. x2 = elements [index++];
  71880. y2 = elements [index++];
  71881. }
  71882. else if (type == cubicMarker)
  71883. {
  71884. elementType = cubicTo;
  71885. x1 = elements [index++];
  71886. y1 = elements [index++];
  71887. x2 = elements [index++];
  71888. y2 = elements [index++];
  71889. x3 = elements [index++];
  71890. y3 = elements [index++];
  71891. }
  71892. else if (type == closeSubPathMarker)
  71893. {
  71894. elementType = closePath;
  71895. }
  71896. return true;
  71897. }
  71898. return false;
  71899. }
  71900. END_JUCE_NAMESPACE
  71901. /*** End of inlined file: juce_Path.cpp ***/
  71902. /*** Start of inlined file: juce_PathIterator.cpp ***/
  71903. BEGIN_JUCE_NAMESPACE
  71904. #if JUCE_MSVC
  71905. #pragma optimize ("t", on)
  71906. #endif
  71907. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  71908. const AffineTransform& transform_,
  71909. float tolerence_)
  71910. : x2 (0),
  71911. y2 (0),
  71912. closesSubPath (false),
  71913. subPathIndex (-1),
  71914. path (path_),
  71915. transform (transform_),
  71916. points (path_.data.elements),
  71917. tolerence (tolerence_ * tolerence_),
  71918. subPathCloseX (0),
  71919. subPathCloseY (0),
  71920. isIdentityTransform (transform_.isIdentity()),
  71921. stackBase (32),
  71922. index (0),
  71923. stackSize (32)
  71924. {
  71925. stackPos = stackBase;
  71926. }
  71927. PathFlatteningIterator::~PathFlatteningIterator()
  71928. {
  71929. }
  71930. bool PathFlatteningIterator::next()
  71931. {
  71932. x1 = x2;
  71933. y1 = y2;
  71934. float x3 = 0;
  71935. float y3 = 0;
  71936. float x4 = 0;
  71937. float y4 = 0;
  71938. float type;
  71939. for (;;)
  71940. {
  71941. if (stackPos == stackBase)
  71942. {
  71943. if (index >= path.numElements)
  71944. {
  71945. return false;
  71946. }
  71947. else
  71948. {
  71949. type = points [index++];
  71950. if (type != Path::closeSubPathMarker)
  71951. {
  71952. x2 = points [index++];
  71953. y2 = points [index++];
  71954. if (! isIdentityTransform)
  71955. transform.transformPoint (x2, y2);
  71956. if (type == Path::quadMarker)
  71957. {
  71958. x3 = points [index++];
  71959. y3 = points [index++];
  71960. if (! isIdentityTransform)
  71961. transform.transformPoint (x3, y3);
  71962. }
  71963. else if (type == Path::cubicMarker)
  71964. {
  71965. x3 = points [index++];
  71966. y3 = points [index++];
  71967. x4 = points [index++];
  71968. y4 = points [index++];
  71969. if (! isIdentityTransform)
  71970. {
  71971. transform.transformPoint (x3, y3);
  71972. transform.transformPoint (x4, y4);
  71973. }
  71974. }
  71975. }
  71976. }
  71977. }
  71978. else
  71979. {
  71980. type = *--stackPos;
  71981. if (type != Path::closeSubPathMarker)
  71982. {
  71983. x2 = *--stackPos;
  71984. y2 = *--stackPos;
  71985. if (type == Path::quadMarker)
  71986. {
  71987. x3 = *--stackPos;
  71988. y3 = *--stackPos;
  71989. }
  71990. else if (type == Path::cubicMarker)
  71991. {
  71992. x3 = *--stackPos;
  71993. y3 = *--stackPos;
  71994. x4 = *--stackPos;
  71995. y4 = *--stackPos;
  71996. }
  71997. }
  71998. }
  71999. if (type == Path::lineMarker)
  72000. {
  72001. ++subPathIndex;
  72002. closesSubPath = (stackPos == stackBase)
  72003. && (index < path.numElements)
  72004. && (points [index] == Path::closeSubPathMarker)
  72005. && x2 == subPathCloseX
  72006. && y2 == subPathCloseY;
  72007. return true;
  72008. }
  72009. else if (type == Path::quadMarker)
  72010. {
  72011. const size_t offset = (size_t) (stackPos - stackBase);
  72012. if (offset >= stackSize - 10)
  72013. {
  72014. stackSize <<= 1;
  72015. stackBase.realloc (stackSize);
  72016. stackPos = stackBase + offset;
  72017. }
  72018. const float dx1 = x1 - x2;
  72019. const float dy1 = y1 - y2;
  72020. const float dx2 = x2 - x3;
  72021. const float dy2 = y2 - y3;
  72022. const float m1x = (x1 + x2) * 0.5f;
  72023. const float m1y = (y1 + y2) * 0.5f;
  72024. const float m2x = (x2 + x3) * 0.5f;
  72025. const float m2y = (y2 + y3) * 0.5f;
  72026. const float m3x = (m1x + m2x) * 0.5f;
  72027. const float m3y = (m1y + m2y) * 0.5f;
  72028. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  72029. {
  72030. *stackPos++ = y3;
  72031. *stackPos++ = x3;
  72032. *stackPos++ = m2y;
  72033. *stackPos++ = m2x;
  72034. *stackPos++ = Path::quadMarker;
  72035. *stackPos++ = m3y;
  72036. *stackPos++ = m3x;
  72037. *stackPos++ = m1y;
  72038. *stackPos++ = m1x;
  72039. *stackPos++ = Path::quadMarker;
  72040. }
  72041. else
  72042. {
  72043. *stackPos++ = y3;
  72044. *stackPos++ = x3;
  72045. *stackPos++ = Path::lineMarker;
  72046. *stackPos++ = m3y;
  72047. *stackPos++ = m3x;
  72048. *stackPos++ = Path::lineMarker;
  72049. }
  72050. jassert (stackPos < stackBase + stackSize);
  72051. }
  72052. else if (type == Path::cubicMarker)
  72053. {
  72054. const size_t offset = (size_t) (stackPos - stackBase);
  72055. if (offset >= stackSize - 16)
  72056. {
  72057. stackSize <<= 1;
  72058. stackBase.realloc (stackSize);
  72059. stackPos = stackBase + offset;
  72060. }
  72061. const float dx1 = x1 - x2;
  72062. const float dy1 = y1 - y2;
  72063. const float dx2 = x2 - x3;
  72064. const float dy2 = y2 - y3;
  72065. const float dx3 = x3 - x4;
  72066. const float dy3 = y3 - y4;
  72067. const float m1x = (x1 + x2) * 0.5f;
  72068. const float m1y = (y1 + y2) * 0.5f;
  72069. const float m2x = (x3 + x2) * 0.5f;
  72070. const float m2y = (y3 + y2) * 0.5f;
  72071. const float m3x = (x3 + x4) * 0.5f;
  72072. const float m3y = (y3 + y4) * 0.5f;
  72073. const float m4x = (m1x + m2x) * 0.5f;
  72074. const float m4y = (m1y + m2y) * 0.5f;
  72075. const float m5x = (m3x + m2x) * 0.5f;
  72076. const float m5y = (m3y + m2y) * 0.5f;
  72077. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  72078. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  72079. {
  72080. *stackPos++ = y4;
  72081. *stackPos++ = x4;
  72082. *stackPos++ = m3y;
  72083. *stackPos++ = m3x;
  72084. *stackPos++ = m5y;
  72085. *stackPos++ = m5x;
  72086. *stackPos++ = Path::cubicMarker;
  72087. *stackPos++ = (m4y + m5y) * 0.5f;
  72088. *stackPos++ = (m4x + m5x) * 0.5f;
  72089. *stackPos++ = m4y;
  72090. *stackPos++ = m4x;
  72091. *stackPos++ = m1y;
  72092. *stackPos++ = m1x;
  72093. *stackPos++ = Path::cubicMarker;
  72094. }
  72095. else
  72096. {
  72097. *stackPos++ = y4;
  72098. *stackPos++ = x4;
  72099. *stackPos++ = Path::lineMarker;
  72100. *stackPos++ = m5y;
  72101. *stackPos++ = m5x;
  72102. *stackPos++ = Path::lineMarker;
  72103. *stackPos++ = m4y;
  72104. *stackPos++ = m4x;
  72105. *stackPos++ = Path::lineMarker;
  72106. }
  72107. }
  72108. else if (type == Path::closeSubPathMarker)
  72109. {
  72110. if (x2 != subPathCloseX || y2 != subPathCloseY)
  72111. {
  72112. x1 = x2;
  72113. y1 = y2;
  72114. x2 = subPathCloseX;
  72115. y2 = subPathCloseY;
  72116. closesSubPath = true;
  72117. return true;
  72118. }
  72119. }
  72120. else
  72121. {
  72122. jassert (type == Path::moveMarker);
  72123. subPathIndex = -1;
  72124. subPathCloseX = x1 = x2;
  72125. subPathCloseY = y1 = y2;
  72126. }
  72127. }
  72128. }
  72129. END_JUCE_NAMESPACE
  72130. /*** End of inlined file: juce_PathIterator.cpp ***/
  72131. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  72132. BEGIN_JUCE_NAMESPACE
  72133. PathStrokeType::PathStrokeType (const float strokeThickness,
  72134. const JointStyle jointStyle_,
  72135. const EndCapStyle endStyle_) throw()
  72136. : thickness (strokeThickness),
  72137. jointStyle (jointStyle_),
  72138. endStyle (endStyle_)
  72139. {
  72140. }
  72141. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  72142. : thickness (other.thickness),
  72143. jointStyle (other.jointStyle),
  72144. endStyle (other.endStyle)
  72145. {
  72146. }
  72147. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  72148. {
  72149. thickness = other.thickness;
  72150. jointStyle = other.jointStyle;
  72151. endStyle = other.endStyle;
  72152. return *this;
  72153. }
  72154. PathStrokeType::~PathStrokeType() throw()
  72155. {
  72156. }
  72157. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  72158. {
  72159. return thickness == other.thickness
  72160. && jointStyle == other.jointStyle
  72161. && endStyle == other.endStyle;
  72162. }
  72163. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  72164. {
  72165. return ! operator== (other);
  72166. }
  72167. static bool lineIntersection (const float x1, const float y1,
  72168. const float x2, const float y2,
  72169. const float x3, const float y3,
  72170. const float x4, const float y4,
  72171. float& intersectionX,
  72172. float& intersectionY,
  72173. float& distanceBeyondLine1EndSquared) throw()
  72174. {
  72175. if (x2 != x3 || y2 != y3)
  72176. {
  72177. const float dx1 = x2 - x1;
  72178. const float dy1 = y2 - y1;
  72179. const float dx2 = x4 - x3;
  72180. const float dy2 = y4 - y3;
  72181. const float divisor = dx1 * dy2 - dx2 * dy1;
  72182. if (divisor == 0)
  72183. {
  72184. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  72185. {
  72186. if (dy1 == 0 && dy2 != 0)
  72187. {
  72188. const float along = (y1 - y3) / dy2;
  72189. intersectionX = x3 + along * dx2;
  72190. intersectionY = y1;
  72191. distanceBeyondLine1EndSquared = intersectionX - x2;
  72192. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72193. if ((x2 > x1) == (intersectionX < x2))
  72194. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72195. return along >= 0 && along <= 1.0f;
  72196. }
  72197. else if (dy2 == 0 && dy1 != 0)
  72198. {
  72199. const float along = (y3 - y1) / dy1;
  72200. intersectionX = x1 + along * dx1;
  72201. intersectionY = y3;
  72202. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  72203. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72204. if (along < 1.0f)
  72205. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72206. return along >= 0 && along <= 1.0f;
  72207. }
  72208. else if (dx1 == 0 && dx2 != 0)
  72209. {
  72210. const float along = (x1 - x3) / dx2;
  72211. intersectionX = x1;
  72212. intersectionY = y3 + along * dy2;
  72213. distanceBeyondLine1EndSquared = intersectionY - y2;
  72214. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72215. if ((y2 > y1) == (intersectionY < y2))
  72216. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72217. return along >= 0 && along <= 1.0f;
  72218. }
  72219. else if (dx2 == 0 && dx1 != 0)
  72220. {
  72221. const float along = (x3 - x1) / dx1;
  72222. intersectionX = x3;
  72223. intersectionY = y1 + along * dy1;
  72224. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  72225. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72226. if (along < 1.0f)
  72227. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72228. return along >= 0 && along <= 1.0f;
  72229. }
  72230. }
  72231. intersectionX = 0.5f * (x2 + x3);
  72232. intersectionY = 0.5f * (y2 + y3);
  72233. distanceBeyondLine1EndSquared = 0.0f;
  72234. return false;
  72235. }
  72236. else
  72237. {
  72238. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  72239. intersectionX = x1 + along1 * dx1;
  72240. intersectionY = y1 + along1 * dy1;
  72241. if (along1 >= 0 && along1 <= 1.0f)
  72242. {
  72243. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  72244. if (along2 >= 0 && along2 <= divisor)
  72245. {
  72246. distanceBeyondLine1EndSquared = 0.0f;
  72247. return true;
  72248. }
  72249. }
  72250. distanceBeyondLine1EndSquared = along1 - 1.0f;
  72251. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72252. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  72253. if (along1 < 1.0f)
  72254. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72255. return false;
  72256. }
  72257. }
  72258. intersectionX = x2;
  72259. intersectionY = y2;
  72260. distanceBeyondLine1EndSquared = 0.0f;
  72261. return true;
  72262. }
  72263. namespace PathFunctions
  72264. {
  72265. // part of stroke drawing stuff
  72266. static void addEdgeAndJoint (Path& destPath,
  72267. const PathStrokeType::JointStyle style,
  72268. const float maxMiterExtensionSquared, const float width,
  72269. const float x1, const float y1,
  72270. const float x2, const float y2,
  72271. const float x3, const float y3,
  72272. const float x4, const float y4,
  72273. const float midX, const float midY)
  72274. {
  72275. if (style == PathStrokeType::beveled
  72276. || (x3 == x4 && y3 == y4)
  72277. || (x1 == x2 && y1 == y2))
  72278. {
  72279. destPath.lineTo (x2, y2);
  72280. destPath.lineTo (x3, y3);
  72281. }
  72282. else
  72283. {
  72284. float jx, jy, distanceBeyondLine1EndSquared;
  72285. // if they intersect, use this point..
  72286. if (lineIntersection (x1, y1, x2, y2,
  72287. x3, y3, x4, y4,
  72288. jx, jy, distanceBeyondLine1EndSquared))
  72289. {
  72290. destPath.lineTo (jx, jy);
  72291. }
  72292. else
  72293. {
  72294. if (style == PathStrokeType::mitered)
  72295. {
  72296. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  72297. && distanceBeyondLine1EndSquared > 0.0f)
  72298. {
  72299. destPath.lineTo (jx, jy);
  72300. }
  72301. else
  72302. {
  72303. // the end sticks out too far, so just use a blunt joint
  72304. destPath.lineTo (x2, y2);
  72305. destPath.lineTo (x3, y3);
  72306. }
  72307. }
  72308. else
  72309. {
  72310. // curved joints
  72311. float angle1 = atan2f (x2 - midX, y2 - midY);
  72312. float angle2 = atan2f (x3 - midX, y3 - midY);
  72313. const float angleIncrement = 0.1f;
  72314. destPath.lineTo (x2, y2);
  72315. if (fabs (angle1 - angle2) > angleIncrement)
  72316. {
  72317. if (angle2 > angle1 + float_Pi
  72318. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  72319. {
  72320. if (angle2 > angle1)
  72321. angle2 -= float_Pi * 2.0f;
  72322. jassert (angle1 <= angle2 + float_Pi);
  72323. angle1 -= angleIncrement;
  72324. while (angle1 > angle2)
  72325. {
  72326. destPath.lineTo (midX + width * sinf (angle1),
  72327. midY + width * cosf (angle1));
  72328. angle1 -= angleIncrement;
  72329. }
  72330. }
  72331. else
  72332. {
  72333. if (angle1 > angle2)
  72334. angle1 -= float_Pi * 2.0f;
  72335. jassert (angle1 >= angle2 - float_Pi);
  72336. angle1 += angleIncrement;
  72337. while (angle1 < angle2)
  72338. {
  72339. destPath.lineTo (midX + width * sinf (angle1),
  72340. midY + width * cosf (angle1));
  72341. angle1 += angleIncrement;
  72342. }
  72343. }
  72344. }
  72345. destPath.lineTo (x3, y3);
  72346. }
  72347. }
  72348. }
  72349. }
  72350. static void addLineEnd (Path& destPath,
  72351. const PathStrokeType::EndCapStyle style,
  72352. const float x1, const float y1,
  72353. const float x2, const float y2,
  72354. const float width)
  72355. {
  72356. if (style == PathStrokeType::butt)
  72357. {
  72358. destPath.lineTo (x2, y2);
  72359. }
  72360. else
  72361. {
  72362. float offx1, offy1, offx2, offy2;
  72363. float dx = x2 - x1;
  72364. float dy = y2 - y1;
  72365. const float len = juce_hypotf (dx, dy);
  72366. if (len == 0)
  72367. {
  72368. offx1 = offx2 = x1;
  72369. offy1 = offy2 = y1;
  72370. }
  72371. else
  72372. {
  72373. const float offset = width / len;
  72374. dx *= offset;
  72375. dy *= offset;
  72376. offx1 = x1 + dy;
  72377. offy1 = y1 - dx;
  72378. offx2 = x2 + dy;
  72379. offy2 = y2 - dx;
  72380. }
  72381. if (style == PathStrokeType::square)
  72382. {
  72383. // sqaure ends
  72384. destPath.lineTo (offx1, offy1);
  72385. destPath.lineTo (offx2, offy2);
  72386. destPath.lineTo (x2, y2);
  72387. }
  72388. else
  72389. {
  72390. // rounded ends
  72391. const float midx = (offx1 + offx2) * 0.5f;
  72392. const float midy = (offy1 + offy2) * 0.5f;
  72393. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  72394. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  72395. midx, midy);
  72396. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  72397. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  72398. x2, y2);
  72399. }
  72400. }
  72401. }
  72402. struct LineSection
  72403. {
  72404. LineSection() {}
  72405. LineSection (int) {}
  72406. float x1, y1, x2, y2; // original line
  72407. float lx1, ly1, lx2, ly2; // the left-hand stroke
  72408. float rx1, ry1, rx2, ry2; // the right-hand stroke
  72409. };
  72410. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  72411. const bool isClosed,
  72412. const float width, const float maxMiterExtensionSquared,
  72413. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle)
  72414. {
  72415. jassert (subPath.size() > 0);
  72416. const LineSection& firstLine = subPath.getReference (0);
  72417. float lastX1 = firstLine.lx1;
  72418. float lastY1 = firstLine.ly1;
  72419. float lastX2 = firstLine.lx2;
  72420. float lastY2 = firstLine.ly2;
  72421. if (isClosed)
  72422. {
  72423. destPath.startNewSubPath (lastX1, lastY1);
  72424. }
  72425. else
  72426. {
  72427. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  72428. addLineEnd (destPath, endStyle,
  72429. firstLine.rx2, firstLine.ry2,
  72430. lastX1, lastY1,
  72431. width);
  72432. }
  72433. int i;
  72434. for (i = 1; i < subPath.size(); ++i)
  72435. {
  72436. const LineSection& l = subPath.getReference (i);
  72437. addEdgeAndJoint (destPath, jointStyle,
  72438. maxMiterExtensionSquared, width,
  72439. lastX1, lastY1, lastX2, lastY2,
  72440. l.lx1, l.ly1, l.lx2, l.ly2,
  72441. l.x1, l.y1);
  72442. lastX1 = l.lx1;
  72443. lastY1 = l.ly1;
  72444. lastX2 = l.lx2;
  72445. lastY2 = l.ly2;
  72446. }
  72447. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  72448. if (isClosed)
  72449. {
  72450. const LineSection& l = subPath.getReference (0);
  72451. addEdgeAndJoint (destPath, jointStyle,
  72452. maxMiterExtensionSquared, width,
  72453. lastX1, lastY1, lastX2, lastY2,
  72454. l.lx1, l.ly1, l.lx2, l.ly2,
  72455. l.x1, l.y1);
  72456. destPath.closeSubPath();
  72457. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  72458. }
  72459. else
  72460. {
  72461. destPath.lineTo (lastX2, lastY2);
  72462. addLineEnd (destPath, endStyle,
  72463. lastX2, lastY2,
  72464. lastLine.rx1, lastLine.ry1,
  72465. width);
  72466. }
  72467. lastX1 = lastLine.rx1;
  72468. lastY1 = lastLine.ry1;
  72469. lastX2 = lastLine.rx2;
  72470. lastY2 = lastLine.ry2;
  72471. for (i = subPath.size() - 1; --i >= 0;)
  72472. {
  72473. const LineSection& l = subPath.getReference (i);
  72474. addEdgeAndJoint (destPath, jointStyle,
  72475. maxMiterExtensionSquared, width,
  72476. lastX1, lastY1, lastX2, lastY2,
  72477. l.rx1, l.ry1, l.rx2, l.ry2,
  72478. l.x2, l.y2);
  72479. lastX1 = l.rx1;
  72480. lastY1 = l.ry1;
  72481. lastX2 = l.rx2;
  72482. lastY2 = l.ry2;
  72483. }
  72484. if (isClosed)
  72485. {
  72486. addEdgeAndJoint (destPath, jointStyle,
  72487. maxMiterExtensionSquared, width,
  72488. lastX1, lastY1, lastX2, lastY2,
  72489. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  72490. lastLine.x2, lastLine.y2);
  72491. }
  72492. else
  72493. {
  72494. // do the last line
  72495. destPath.lineTo (lastX2, lastY2);
  72496. }
  72497. destPath.closeSubPath();
  72498. }
  72499. }
  72500. void PathStrokeType::createStrokedPath (Path& destPath,
  72501. const Path& source,
  72502. const AffineTransform& transform,
  72503. const float extraAccuracy) const
  72504. {
  72505. if (thickness <= 0)
  72506. {
  72507. destPath.clear();
  72508. return;
  72509. }
  72510. const Path* sourcePath = &source;
  72511. Path temp;
  72512. if (sourcePath == &destPath)
  72513. {
  72514. destPath.swapWithPath (temp);
  72515. sourcePath = &temp;
  72516. }
  72517. else
  72518. {
  72519. destPath.clear();
  72520. }
  72521. destPath.setUsingNonZeroWinding (true);
  72522. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  72523. const float width = 0.5f * thickness;
  72524. // Iterate the path, creating a list of the
  72525. // left/right-hand lines along either side of it...
  72526. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  72527. using namespace PathFunctions;
  72528. Array <LineSection> subPath;
  72529. LineSection l;
  72530. l.x1 = 0;
  72531. l.y1 = 0;
  72532. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  72533. while (it.next())
  72534. {
  72535. if (it.subPathIndex == 0)
  72536. {
  72537. if (subPath.size() > 0)
  72538. {
  72539. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  72540. subPath.clearQuick();
  72541. }
  72542. l.x1 = it.x1;
  72543. l.y1 = it.y1;
  72544. }
  72545. l.x2 = it.x2;
  72546. l.y2 = it.y2;
  72547. float dx = l.x2 - l.x1;
  72548. float dy = l.y2 - l.y1;
  72549. const float hypotSquared = dx*dx + dy*dy;
  72550. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  72551. {
  72552. const float len = sqrtf (hypotSquared);
  72553. if (len == 0)
  72554. {
  72555. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  72556. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  72557. }
  72558. else
  72559. {
  72560. const float offset = width / len;
  72561. dx *= offset;
  72562. dy *= offset;
  72563. l.rx2 = l.x1 - dy;
  72564. l.ry2 = l.y1 + dx;
  72565. l.lx1 = l.x1 + dy;
  72566. l.ly1 = l.y1 - dx;
  72567. l.lx2 = l.x2 + dy;
  72568. l.ly2 = l.y2 - dx;
  72569. l.rx1 = l.x2 - dy;
  72570. l.ry1 = l.y2 + dx;
  72571. }
  72572. subPath.add (l);
  72573. if (it.closesSubPath)
  72574. {
  72575. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  72576. subPath.clearQuick();
  72577. }
  72578. else
  72579. {
  72580. l.x1 = it.x2;
  72581. l.y1 = it.y2;
  72582. }
  72583. }
  72584. }
  72585. if (subPath.size() > 0)
  72586. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  72587. }
  72588. void PathStrokeType::createDashedStroke (Path& destPath,
  72589. const Path& sourcePath,
  72590. const float* dashLengths,
  72591. int numDashLengths,
  72592. const AffineTransform& transform,
  72593. const float extraAccuracy) const
  72594. {
  72595. if (thickness <= 0)
  72596. return;
  72597. // this should really be an even number..
  72598. jassert ((numDashLengths & 1) == 0);
  72599. Path newDestPath;
  72600. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  72601. bool first = true;
  72602. int dashNum = 0;
  72603. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  72604. float dx = 0.0f, dy = 0.0f;
  72605. for (;;)
  72606. {
  72607. const bool isSolid = ((dashNum & 1) == 0);
  72608. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  72609. jassert (dashLen > 0); // must be a positive increment!
  72610. if (dashLen <= 0)
  72611. break;
  72612. pos += dashLen;
  72613. while (pos > lineEndPos)
  72614. {
  72615. if (! it.next())
  72616. {
  72617. if (isSolid && ! first)
  72618. newDestPath.lineTo (it.x2, it.y2);
  72619. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  72620. return;
  72621. }
  72622. if (isSolid && ! first)
  72623. newDestPath.lineTo (it.x1, it.y1);
  72624. else
  72625. newDestPath.startNewSubPath (it.x1, it.y1);
  72626. dx = it.x2 - it.x1;
  72627. dy = it.y2 - it.y1;
  72628. lineLen = juce_hypotf (dx, dy);
  72629. lineEndPos += lineLen;
  72630. first = it.closesSubPath;
  72631. }
  72632. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  72633. if (isSolid)
  72634. newDestPath.lineTo (it.x1 + dx * alpha,
  72635. it.y1 + dy * alpha);
  72636. else
  72637. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  72638. it.y1 + dy * alpha);
  72639. }
  72640. }
  72641. END_JUCE_NAMESPACE
  72642. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  72643. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  72644. BEGIN_JUCE_NAMESPACE
  72645. PositionedRectangle::PositionedRectangle() throw()
  72646. : x (0.0),
  72647. y (0.0),
  72648. w (0.0),
  72649. h (0.0),
  72650. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  72651. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  72652. wMode (absoluteSize),
  72653. hMode (absoluteSize)
  72654. {
  72655. }
  72656. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  72657. : x (other.x),
  72658. y (other.y),
  72659. w (other.w),
  72660. h (other.h),
  72661. xMode (other.xMode),
  72662. yMode (other.yMode),
  72663. wMode (other.wMode),
  72664. hMode (other.hMode)
  72665. {
  72666. }
  72667. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  72668. {
  72669. x = other.x;
  72670. y = other.y;
  72671. w = other.w;
  72672. h = other.h;
  72673. xMode = other.xMode;
  72674. yMode = other.yMode;
  72675. wMode = other.wMode;
  72676. hMode = other.hMode;
  72677. return *this;
  72678. }
  72679. PositionedRectangle::~PositionedRectangle() throw()
  72680. {
  72681. }
  72682. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  72683. {
  72684. return x == other.x
  72685. && y == other.y
  72686. && w == other.w
  72687. && h == other.h
  72688. && xMode == other.xMode
  72689. && yMode == other.yMode
  72690. && wMode == other.wMode
  72691. && hMode == other.hMode;
  72692. }
  72693. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  72694. {
  72695. return ! operator== (other);
  72696. }
  72697. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  72698. {
  72699. StringArray tokens;
  72700. tokens.addTokens (stringVersion, false);
  72701. decodePosString (tokens [0], xMode, x);
  72702. decodePosString (tokens [1], yMode, y);
  72703. decodeSizeString (tokens [2], wMode, w);
  72704. decodeSizeString (tokens [3], hMode, h);
  72705. }
  72706. const String PositionedRectangle::toString() const throw()
  72707. {
  72708. String s;
  72709. s.preallocateStorage (12);
  72710. addPosDescription (s, xMode, x);
  72711. s << ' ';
  72712. addPosDescription (s, yMode, y);
  72713. s << ' ';
  72714. addSizeDescription (s, wMode, w);
  72715. s << ' ';
  72716. addSizeDescription (s, hMode, h);
  72717. return s;
  72718. }
  72719. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  72720. {
  72721. jassert (! target.isEmpty());
  72722. double x_, y_, w_, h_;
  72723. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  72724. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  72725. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  72726. roundToInt (w_), roundToInt (h_));
  72727. }
  72728. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  72729. double& x_, double& y_,
  72730. double& w_, double& h_) const throw()
  72731. {
  72732. jassert (! target.isEmpty());
  72733. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  72734. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  72735. }
  72736. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  72737. {
  72738. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  72739. }
  72740. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  72741. const Rectangle<int>& target) throw()
  72742. {
  72743. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  72744. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  72745. }
  72746. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  72747. const double newW, const double newH,
  72748. const Rectangle<int>& target) throw()
  72749. {
  72750. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  72751. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  72752. }
  72753. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  72754. {
  72755. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  72756. updateFrom (comp.getBounds(), Rectangle<int>());
  72757. else
  72758. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  72759. }
  72760. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  72761. {
  72762. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  72763. }
  72764. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  72765. {
  72766. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  72767. | absoluteFromParentBottomRight
  72768. | absoluteFromParentCentre
  72769. | proportionOfParentSize));
  72770. }
  72771. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  72772. {
  72773. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  72774. }
  72775. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  72776. {
  72777. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  72778. | absoluteFromParentBottomRight
  72779. | absoluteFromParentCentre
  72780. | proportionOfParentSize));
  72781. }
  72782. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  72783. {
  72784. return (SizeMode) wMode;
  72785. }
  72786. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  72787. {
  72788. return (SizeMode) hMode;
  72789. }
  72790. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  72791. const PositionMode xMode_,
  72792. const AnchorPoint yAnchor,
  72793. const PositionMode yMode_,
  72794. const SizeMode widthMode,
  72795. const SizeMode heightMode,
  72796. const Rectangle<int>& target) throw()
  72797. {
  72798. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  72799. {
  72800. double tx, tw;
  72801. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  72802. xMode = (uint8) (xAnchor | xMode_);
  72803. wMode = (uint8) widthMode;
  72804. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  72805. }
  72806. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  72807. {
  72808. double ty, th;
  72809. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  72810. yMode = (uint8) (yAnchor | yMode_);
  72811. hMode = (uint8) heightMode;
  72812. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  72813. }
  72814. }
  72815. bool PositionedRectangle::isPositionAbsolute() const throw()
  72816. {
  72817. return xMode == absoluteFromParentTopLeft
  72818. && yMode == absoluteFromParentTopLeft
  72819. && wMode == absoluteSize
  72820. && hMode == absoluteSize;
  72821. }
  72822. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  72823. {
  72824. if ((mode & proportionOfParentSize) != 0)
  72825. {
  72826. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  72827. }
  72828. else
  72829. {
  72830. s << (roundToInt (value * 100.0) / 100.0);
  72831. if ((mode & absoluteFromParentBottomRight) != 0)
  72832. s << 'R';
  72833. else if ((mode & absoluteFromParentCentre) != 0)
  72834. s << 'C';
  72835. }
  72836. if ((mode & anchorAtRightOrBottom) != 0)
  72837. s << 'r';
  72838. else if ((mode & anchorAtCentre) != 0)
  72839. s << 'c';
  72840. }
  72841. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  72842. {
  72843. if (mode == proportionalSize)
  72844. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  72845. else if (mode == parentSizeMinusAbsolute)
  72846. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  72847. else
  72848. s << (roundToInt (value * 100.0) / 100.0);
  72849. }
  72850. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  72851. {
  72852. if (s.containsChar ('r'))
  72853. mode = anchorAtRightOrBottom;
  72854. else if (s.containsChar ('c'))
  72855. mode = anchorAtCentre;
  72856. else
  72857. mode = anchorAtLeftOrTop;
  72858. if (s.containsChar ('%'))
  72859. {
  72860. mode |= proportionOfParentSize;
  72861. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  72862. }
  72863. else
  72864. {
  72865. if (s.containsChar ('R'))
  72866. mode |= absoluteFromParentBottomRight;
  72867. else if (s.containsChar ('C'))
  72868. mode |= absoluteFromParentCentre;
  72869. else
  72870. mode |= absoluteFromParentTopLeft;
  72871. value = s.removeCharacters ("rcRC").getDoubleValue();
  72872. }
  72873. }
  72874. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  72875. {
  72876. if (s.containsChar ('%'))
  72877. {
  72878. mode = proportionalSize;
  72879. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  72880. }
  72881. else if (s.containsChar ('M'))
  72882. {
  72883. mode = parentSizeMinusAbsolute;
  72884. value = s.getDoubleValue();
  72885. }
  72886. else
  72887. {
  72888. mode = absoluteSize;
  72889. value = s.getDoubleValue();
  72890. }
  72891. }
  72892. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  72893. const double x_, const double w_,
  72894. const uint8 xMode_, const uint8 wMode_,
  72895. const int parentPos,
  72896. const int parentSize) const throw()
  72897. {
  72898. if (wMode_ == proportionalSize)
  72899. wOut = roundToInt (w_ * parentSize);
  72900. else if (wMode_ == parentSizeMinusAbsolute)
  72901. wOut = jmax (0, parentSize - roundToInt (w_));
  72902. else
  72903. wOut = roundToInt (w_);
  72904. if ((xMode_ & proportionOfParentSize) != 0)
  72905. xOut = parentPos + x_ * parentSize;
  72906. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  72907. xOut = (parentPos + parentSize) - x_;
  72908. else if ((xMode_ & absoluteFromParentCentre) != 0)
  72909. xOut = x_ + (parentPos + parentSize / 2);
  72910. else
  72911. xOut = x_ + parentPos;
  72912. if ((xMode_ & anchorAtRightOrBottom) != 0)
  72913. xOut -= wOut;
  72914. else if ((xMode_ & anchorAtCentre) != 0)
  72915. xOut -= wOut / 2;
  72916. }
  72917. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  72918. double x_, const double w_,
  72919. const uint8 xMode_, const uint8 wMode_,
  72920. const int parentPos,
  72921. const int parentSize) const throw()
  72922. {
  72923. if (wMode_ == proportionalSize)
  72924. {
  72925. if (parentSize > 0)
  72926. wOut = w_ / parentSize;
  72927. }
  72928. else if (wMode_ == parentSizeMinusAbsolute)
  72929. wOut = parentSize - w_;
  72930. else
  72931. wOut = w_;
  72932. if ((xMode_ & anchorAtRightOrBottom) != 0)
  72933. x_ += w_;
  72934. else if ((xMode_ & anchorAtCentre) != 0)
  72935. x_ += w_ / 2;
  72936. if ((xMode_ & proportionOfParentSize) != 0)
  72937. {
  72938. if (parentSize > 0)
  72939. xOut = (x_ - parentPos) / parentSize;
  72940. }
  72941. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  72942. xOut = (parentPos + parentSize) - x_;
  72943. else if ((xMode_ & absoluteFromParentCentre) != 0)
  72944. xOut = x_ - (parentPos + parentSize / 2);
  72945. else
  72946. xOut = x_ - parentPos;
  72947. }
  72948. END_JUCE_NAMESPACE
  72949. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  72950. /*** Start of inlined file: juce_RectangleList.cpp ***/
  72951. BEGIN_JUCE_NAMESPACE
  72952. RectangleList::RectangleList() throw()
  72953. {
  72954. }
  72955. RectangleList::RectangleList (const Rectangle<int>& rect)
  72956. {
  72957. if (! rect.isEmpty())
  72958. rects.add (rect);
  72959. }
  72960. RectangleList::RectangleList (const RectangleList& other)
  72961. : rects (other.rects)
  72962. {
  72963. }
  72964. RectangleList& RectangleList::operator= (const RectangleList& other)
  72965. {
  72966. rects = other.rects;
  72967. return *this;
  72968. }
  72969. RectangleList::~RectangleList()
  72970. {
  72971. }
  72972. void RectangleList::clear()
  72973. {
  72974. rects.clearQuick();
  72975. }
  72976. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  72977. {
  72978. if (((unsigned int) index) < (unsigned int) rects.size())
  72979. return rects.getReference (index);
  72980. return Rectangle<int>();
  72981. }
  72982. bool RectangleList::isEmpty() const throw()
  72983. {
  72984. return rects.size() == 0;
  72985. }
  72986. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  72987. : current (0),
  72988. owner (list),
  72989. index (list.rects.size())
  72990. {
  72991. }
  72992. RectangleList::Iterator::~Iterator()
  72993. {
  72994. }
  72995. bool RectangleList::Iterator::next() throw()
  72996. {
  72997. if (--index >= 0)
  72998. {
  72999. current = & (owner.rects.getReference (index));
  73000. return true;
  73001. }
  73002. return false;
  73003. }
  73004. void RectangleList::add (const Rectangle<int>& rect)
  73005. {
  73006. if (! rect.isEmpty())
  73007. {
  73008. if (rects.size() == 0)
  73009. {
  73010. rects.add (rect);
  73011. }
  73012. else
  73013. {
  73014. bool anyOverlaps = false;
  73015. int i;
  73016. for (i = rects.size(); --i >= 0;)
  73017. {
  73018. Rectangle<int>& ourRect = rects.getReference (i);
  73019. if (rect.intersects (ourRect))
  73020. {
  73021. if (rect.contains (ourRect))
  73022. rects.remove (i);
  73023. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  73024. anyOverlaps = true;
  73025. }
  73026. }
  73027. if (anyOverlaps && rects.size() > 0)
  73028. {
  73029. RectangleList r (rect);
  73030. for (i = rects.size(); --i >= 0;)
  73031. {
  73032. const Rectangle<int>& ourRect = rects.getReference (i);
  73033. if (rect.intersects (ourRect))
  73034. {
  73035. r.subtract (ourRect);
  73036. if (r.rects.size() == 0)
  73037. return;
  73038. }
  73039. }
  73040. for (i = r.getNumRectangles(); --i >= 0;)
  73041. rects.add (r.rects.getReference (i));
  73042. }
  73043. else
  73044. {
  73045. rects.add (rect);
  73046. }
  73047. }
  73048. }
  73049. }
  73050. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  73051. {
  73052. rects.add (rect);
  73053. }
  73054. void RectangleList::add (const int x, const int y, const int w, const int h)
  73055. {
  73056. if (rects.size() == 0)
  73057. {
  73058. if (w > 0 && h > 0)
  73059. rects.add (Rectangle<int> (x, y, w, h));
  73060. }
  73061. else
  73062. {
  73063. add (Rectangle<int> (x, y, w, h));
  73064. }
  73065. }
  73066. void RectangleList::add (const RectangleList& other)
  73067. {
  73068. for (int i = 0; i < other.rects.size(); ++i)
  73069. add (other.rects.getReference (i));
  73070. }
  73071. void RectangleList::subtract (const Rectangle<int>& rect)
  73072. {
  73073. const int originalNumRects = rects.size();
  73074. if (originalNumRects > 0)
  73075. {
  73076. const int x1 = rect.x;
  73077. const int y1 = rect.y;
  73078. const int x2 = x1 + rect.w;
  73079. const int y2 = y1 + rect.h;
  73080. for (int i = getNumRectangles(); --i >= 0;)
  73081. {
  73082. Rectangle<int>& r = rects.getReference (i);
  73083. const int rx1 = r.x;
  73084. const int ry1 = r.y;
  73085. const int rx2 = rx1 + r.w;
  73086. const int ry2 = ry1 + r.h;
  73087. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  73088. {
  73089. if (x1 > rx1 && x1 < rx2)
  73090. {
  73091. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  73092. {
  73093. r.w = x1 - rx1;
  73094. }
  73095. else
  73096. {
  73097. r.x = x1;
  73098. r.w = rx2 - x1;
  73099. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  73100. i += 2;
  73101. }
  73102. }
  73103. else if (x2 > rx1 && x2 < rx2)
  73104. {
  73105. r.x = x2;
  73106. r.w = rx2 - x2;
  73107. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  73108. {
  73109. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  73110. i += 2;
  73111. }
  73112. }
  73113. else if (y1 > ry1 && y1 < ry2)
  73114. {
  73115. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  73116. {
  73117. r.h = y1 - ry1;
  73118. }
  73119. else
  73120. {
  73121. r.y = y1;
  73122. r.h = ry2 - y1;
  73123. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  73124. i += 2;
  73125. }
  73126. }
  73127. else if (y2 > ry1 && y2 < ry2)
  73128. {
  73129. r.y = y2;
  73130. r.h = ry2 - y2;
  73131. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  73132. {
  73133. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  73134. i += 2;
  73135. }
  73136. }
  73137. else
  73138. {
  73139. rects.remove (i);
  73140. }
  73141. }
  73142. }
  73143. if (rects.size() > originalNumRects + 10)
  73144. consolidate();
  73145. }
  73146. }
  73147. void RectangleList::subtract (const RectangleList& otherList)
  73148. {
  73149. for (int i = otherList.rects.size(); --i >= 0;)
  73150. subtract (otherList.rects.getReference (i));
  73151. }
  73152. bool RectangleList::clipTo (const Rectangle<int>& rect)
  73153. {
  73154. bool notEmpty = false;
  73155. if (rect.isEmpty())
  73156. {
  73157. clear();
  73158. }
  73159. else
  73160. {
  73161. for (int i = rects.size(); --i >= 0;)
  73162. {
  73163. Rectangle<int>& r = rects.getReference (i);
  73164. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73165. rects.remove (i);
  73166. else
  73167. notEmpty = true;
  73168. }
  73169. }
  73170. return notEmpty;
  73171. }
  73172. bool RectangleList::clipTo (const RectangleList& other)
  73173. {
  73174. if (rects.size() == 0)
  73175. return false;
  73176. RectangleList result;
  73177. for (int j = 0; j < rects.size(); ++j)
  73178. {
  73179. const Rectangle<int>& rect = rects.getReference (j);
  73180. for (int i = other.rects.size(); --i >= 0;)
  73181. {
  73182. Rectangle<int> r (other.rects.getReference (i));
  73183. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73184. result.rects.add (r);
  73185. }
  73186. }
  73187. swapWith (result);
  73188. return ! isEmpty();
  73189. }
  73190. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  73191. {
  73192. destRegion.clear();
  73193. if (! rect.isEmpty())
  73194. {
  73195. for (int i = rects.size(); --i >= 0;)
  73196. {
  73197. Rectangle<int> r (rects.getReference (i));
  73198. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73199. destRegion.rects.add (r);
  73200. }
  73201. }
  73202. return destRegion.rects.size() > 0;
  73203. }
  73204. void RectangleList::swapWith (RectangleList& otherList) throw()
  73205. {
  73206. rects.swapWithArray (otherList.rects);
  73207. }
  73208. void RectangleList::consolidate()
  73209. {
  73210. int i;
  73211. for (i = 0; i < getNumRectangles() - 1; ++i)
  73212. {
  73213. Rectangle<int>& r = rects.getReference (i);
  73214. const int rx1 = r.x;
  73215. const int ry1 = r.y;
  73216. const int rx2 = rx1 + r.w;
  73217. const int ry2 = ry1 + r.h;
  73218. for (int j = rects.size(); --j > i;)
  73219. {
  73220. Rectangle<int>& r2 = rects.getReference (j);
  73221. const int jrx1 = r2.x;
  73222. const int jry1 = r2.y;
  73223. const int jrx2 = jrx1 + r2.w;
  73224. const int jry2 = jry1 + r2.h;
  73225. // if the vertical edges of any blocks are touching and their horizontals don't
  73226. // line up, split them horizontally..
  73227. if (jrx1 == rx2 || jrx2 == rx1)
  73228. {
  73229. if (jry1 > ry1 && jry1 < ry2)
  73230. {
  73231. r.h = jry1 - ry1;
  73232. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  73233. i = -1;
  73234. break;
  73235. }
  73236. if (jry2 > ry1 && jry2 < ry2)
  73237. {
  73238. r.h = jry2 - ry1;
  73239. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  73240. i = -1;
  73241. break;
  73242. }
  73243. else if (ry1 > jry1 && ry1 < jry2)
  73244. {
  73245. r2.h = ry1 - jry1;
  73246. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  73247. i = -1;
  73248. break;
  73249. }
  73250. else if (ry2 > jry1 && ry2 < jry2)
  73251. {
  73252. r2.h = ry2 - jry1;
  73253. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  73254. i = -1;
  73255. break;
  73256. }
  73257. }
  73258. }
  73259. }
  73260. for (i = 0; i < rects.size() - 1; ++i)
  73261. {
  73262. Rectangle<int>& r = rects.getReference (i);
  73263. for (int j = rects.size(); --j > i;)
  73264. {
  73265. if (r.enlargeIfAdjacent (rects.getReference (j)))
  73266. {
  73267. rects.remove (j);
  73268. i = -1;
  73269. break;
  73270. }
  73271. }
  73272. }
  73273. }
  73274. bool RectangleList::containsPoint (const int x, const int y) const throw()
  73275. {
  73276. for (int i = getNumRectangles(); --i >= 0;)
  73277. if (rects.getReference (i).contains (x, y))
  73278. return true;
  73279. return false;
  73280. }
  73281. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  73282. {
  73283. if (rects.size() > 1)
  73284. {
  73285. RectangleList r (rectangleToCheck);
  73286. for (int i = rects.size(); --i >= 0;)
  73287. {
  73288. r.subtract (rects.getReference (i));
  73289. if (r.rects.size() == 0)
  73290. return true;
  73291. }
  73292. }
  73293. else if (rects.size() > 0)
  73294. {
  73295. return rects.getReference (0).contains (rectangleToCheck);
  73296. }
  73297. return false;
  73298. }
  73299. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  73300. {
  73301. for (int i = rects.size(); --i >= 0;)
  73302. if (rects.getReference (i).intersects (rectangleToCheck))
  73303. return true;
  73304. return false;
  73305. }
  73306. bool RectangleList::intersects (const RectangleList& other) const throw()
  73307. {
  73308. for (int i = rects.size(); --i >= 0;)
  73309. if (other.intersectsRectangle (rects.getReference (i)))
  73310. return true;
  73311. return false;
  73312. }
  73313. const Rectangle<int> RectangleList::getBounds() const throw()
  73314. {
  73315. if (rects.size() <= 1)
  73316. {
  73317. if (rects.size() == 0)
  73318. return Rectangle<int>();
  73319. else
  73320. return rects.getReference (0);
  73321. }
  73322. else
  73323. {
  73324. const Rectangle<int>& r = rects.getReference (0);
  73325. int minX = r.x;
  73326. int minY = r.y;
  73327. int maxX = minX + r.w;
  73328. int maxY = minY + r.h;
  73329. for (int i = rects.size(); --i > 0;)
  73330. {
  73331. const Rectangle<int>& r2 = rects.getReference (i);
  73332. minX = jmin (minX, r2.x);
  73333. minY = jmin (minY, r2.y);
  73334. maxX = jmax (maxX, r2.getRight());
  73335. maxY = jmax (maxY, r2.getBottom());
  73336. }
  73337. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  73338. }
  73339. }
  73340. void RectangleList::offsetAll (const int dx, const int dy) throw()
  73341. {
  73342. for (int i = rects.size(); --i >= 0;)
  73343. {
  73344. Rectangle<int>& r = rects.getReference (i);
  73345. r.x += dx;
  73346. r.y += dy;
  73347. }
  73348. }
  73349. const Path RectangleList::toPath() const
  73350. {
  73351. Path p;
  73352. for (int i = rects.size(); --i >= 0;)
  73353. {
  73354. const Rectangle<int>& r = rects.getReference (i);
  73355. p.addRectangle ((float) r.x,
  73356. (float) r.y,
  73357. (float) r.w,
  73358. (float) r.h);
  73359. }
  73360. return p;
  73361. }
  73362. END_JUCE_NAMESPACE
  73363. /*** End of inlined file: juce_RectangleList.cpp ***/
  73364. /*** Start of inlined file: juce_Image.cpp ***/
  73365. BEGIN_JUCE_NAMESPACE
  73366. static const int fullAlphaThreshold = 253;
  73367. Image::Image (const PixelFormat format_,
  73368. const int imageWidth_,
  73369. const int imageHeight_)
  73370. : format (format_),
  73371. imageWidth (imageWidth_),
  73372. imageHeight (imageHeight_),
  73373. imageData (0)
  73374. {
  73375. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  73376. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  73377. // actual image will be at least 1x1.
  73378. }
  73379. Image::Image (const PixelFormat format_,
  73380. const int imageWidth_,
  73381. const int imageHeight_,
  73382. const bool clearImage)
  73383. : format (format_),
  73384. imageWidth (imageWidth_),
  73385. imageHeight (imageHeight_)
  73386. {
  73387. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  73388. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  73389. // actual image will be at least 1x1.
  73390. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  73391. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  73392. imageDataAllocated.allocate (lineStride * jmax (1, imageHeight_), clearImage);
  73393. imageData = imageDataAllocated;
  73394. }
  73395. Image::Image (const Image& other)
  73396. : format (other.format),
  73397. imageWidth (other.imageWidth),
  73398. imageHeight (other.imageHeight)
  73399. {
  73400. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  73401. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  73402. imageDataAllocated.malloc (lineStride * jmax (1, imageHeight));
  73403. imageData = imageDataAllocated;
  73404. BitmapData srcData (other, 0, 0, imageWidth, imageHeight);
  73405. setPixelData (0, 0, imageWidth, imageHeight, srcData.data, srcData.lineStride);
  73406. }
  73407. Image::~Image()
  73408. {
  73409. }
  73410. LowLevelGraphicsContext* Image::createLowLevelContext()
  73411. {
  73412. return new LowLevelGraphicsSoftwareRenderer (*this);
  73413. }
  73414. Image::BitmapData::BitmapData (Image& image, int x, int y, int w, int h, const bool /*makeWritable*/)
  73415. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  73416. lineStride (image.lineStride),
  73417. pixelStride (image.pixelStride),
  73418. width (w),
  73419. height (h)
  73420. {
  73421. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  73422. }
  73423. Image::BitmapData::BitmapData (const Image& image, int x, int y, int w, int h)
  73424. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  73425. lineStride (image.lineStride),
  73426. pixelStride (image.pixelStride),
  73427. width (w),
  73428. height (h)
  73429. {
  73430. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  73431. }
  73432. Image::BitmapData::~BitmapData()
  73433. {
  73434. }
  73435. void Image::setPixelData (int x, int y, int w, int h,
  73436. const uint8* sourcePixelData, int sourceLineStride)
  73437. {
  73438. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  73439. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  73440. {
  73441. const BitmapData dest (*this, x, y, w, h, true);
  73442. for (int i = 0; i < h; ++i)
  73443. {
  73444. memcpy (dest.getLinePointer(i),
  73445. sourcePixelData + sourceLineStride * i,
  73446. w * dest.pixelStride);
  73447. }
  73448. }
  73449. }
  73450. void Image::clear (int dx, int dy, int dw, int dh, const Colour& colourToClearTo)
  73451. {
  73452. if (Rectangle<int>::intersectRectangles (dx, dy, dw, dh, 0, 0, imageWidth, imageHeight))
  73453. {
  73454. const PixelARGB col (colourToClearTo.getPixelARGB());
  73455. const BitmapData destData (*this, dx, dy, dw, dh, true);
  73456. uint8* dest = destData.data;
  73457. while (--dh >= 0)
  73458. {
  73459. uint8* line = dest;
  73460. dest += destData.lineStride;
  73461. if (isARGB())
  73462. {
  73463. for (int x = dw; --x >= 0;)
  73464. {
  73465. ((PixelARGB*) line)->set (col);
  73466. line += destData.pixelStride;
  73467. }
  73468. }
  73469. else if (isRGB())
  73470. {
  73471. for (int x = dw; --x >= 0;)
  73472. {
  73473. ((PixelRGB*) line)->set (col);
  73474. line += destData.pixelStride;
  73475. }
  73476. }
  73477. else
  73478. {
  73479. for (int x = dw; --x >= 0;)
  73480. {
  73481. *line = col.getAlpha();
  73482. line += destData.pixelStride;
  73483. }
  73484. }
  73485. }
  73486. }
  73487. }
  73488. Image* Image::createCopy (int newWidth, int newHeight,
  73489. const Graphics::ResamplingQuality quality) const
  73490. {
  73491. if (newWidth < 0)
  73492. newWidth = imageWidth;
  73493. if (newHeight < 0)
  73494. newHeight = imageHeight;
  73495. Image* const newImage = Image::createNativeImage (format, newWidth, newHeight, true);
  73496. Graphics g (*newImage);
  73497. g.setImageResamplingQuality (quality);
  73498. g.drawImage (this,
  73499. 0, 0, newWidth, newHeight,
  73500. 0, 0, imageWidth, imageHeight,
  73501. false);
  73502. return newImage;
  73503. }
  73504. Image* Image::createCopyOfAlphaChannel() const
  73505. {
  73506. jassert (format != SingleChannel);
  73507. Image* const newImage = Image::createNativeImage (SingleChannel, imageWidth, imageHeight, false);
  73508. if (! hasAlphaChannel())
  73509. {
  73510. newImage->clear (0, 0, imageWidth, imageHeight, Colours::black);
  73511. }
  73512. else
  73513. {
  73514. const BitmapData destData (*newImage, 0, 0, imageWidth, imageHeight, true);
  73515. const BitmapData srcData (*this, 0, 0, imageWidth, imageHeight);
  73516. for (int y = 0; y < imageHeight; ++y)
  73517. {
  73518. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  73519. uint8* dst = destData.getLinePointer (y);
  73520. for (int x = imageWidth; --x >= 0;)
  73521. {
  73522. *dst++ = src->getAlpha();
  73523. ++src;
  73524. }
  73525. }
  73526. }
  73527. return newImage;
  73528. }
  73529. const Colour Image::getPixelAt (const int x, const int y) const
  73530. {
  73531. Colour c;
  73532. if (((unsigned int) x) < (unsigned int) imageWidth
  73533. && ((unsigned int) y) < (unsigned int) imageHeight)
  73534. {
  73535. const BitmapData srcData (*this, x, y, 1, 1);
  73536. if (isARGB())
  73537. {
  73538. PixelARGB p (*(const PixelARGB*) srcData.data);
  73539. p.unpremultiply();
  73540. c = Colour (p.getARGB());
  73541. }
  73542. else if (isRGB())
  73543. c = Colour (((const PixelRGB*) srcData.data)->getARGB());
  73544. else
  73545. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *(srcData.data));
  73546. }
  73547. return c;
  73548. }
  73549. void Image::setPixelAt (const int x, const int y,
  73550. const Colour& colour)
  73551. {
  73552. if (((unsigned int) x) < (unsigned int) imageWidth
  73553. && ((unsigned int) y) < (unsigned int) imageHeight)
  73554. {
  73555. const BitmapData destData (*this, x, y, 1, 1, true);
  73556. const PixelARGB col (colour.getPixelARGB());
  73557. if (isARGB())
  73558. ((PixelARGB*) destData.data)->set (col);
  73559. else if (isRGB())
  73560. ((PixelRGB*) destData.data)->set (col);
  73561. else
  73562. *(destData.data) = col.getAlpha();
  73563. }
  73564. }
  73565. void Image::multiplyAlphaAt (const int x, const int y,
  73566. const float multiplier)
  73567. {
  73568. if (((unsigned int) x) < (unsigned int) imageWidth
  73569. && ((unsigned int) y) < (unsigned int) imageHeight
  73570. && hasAlphaChannel())
  73571. {
  73572. const BitmapData destData (*this, x, y, 1, 1, true);
  73573. if (isARGB())
  73574. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  73575. else
  73576. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  73577. }
  73578. }
  73579. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  73580. {
  73581. if (hasAlphaChannel())
  73582. {
  73583. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  73584. if (isARGB())
  73585. {
  73586. for (int y = 0; y < imageHeight; ++y)
  73587. {
  73588. uint8* p = destData.getLinePointer (y);
  73589. for (int x = 0; x < imageWidth; ++x)
  73590. {
  73591. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  73592. p += destData.pixelStride;
  73593. }
  73594. }
  73595. }
  73596. else
  73597. {
  73598. for (int y = 0; y < imageHeight; ++y)
  73599. {
  73600. uint8* p = destData.getLinePointer (y);
  73601. for (int x = 0; x < imageWidth; ++x)
  73602. {
  73603. *p = (uint8) (*p * amountToMultiplyBy);
  73604. p += destData.pixelStride;
  73605. }
  73606. }
  73607. }
  73608. }
  73609. else
  73610. {
  73611. jassertfalse // can't do this without an alpha-channel!
  73612. }
  73613. }
  73614. void Image::desaturate()
  73615. {
  73616. if (isARGB() || isRGB())
  73617. {
  73618. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  73619. if (isARGB())
  73620. {
  73621. for (int y = 0; y < imageHeight; ++y)
  73622. {
  73623. uint8* p = destData.getLinePointer (y);
  73624. for (int x = 0; x < imageWidth; ++x)
  73625. {
  73626. ((PixelARGB*) p)->desaturate();
  73627. p += destData.pixelStride;
  73628. }
  73629. }
  73630. }
  73631. else
  73632. {
  73633. for (int y = 0; y < imageHeight; ++y)
  73634. {
  73635. uint8* p = destData.getLinePointer (y);
  73636. for (int x = 0; x < imageWidth; ++x)
  73637. {
  73638. ((PixelRGB*) p)->desaturate();
  73639. p += destData.pixelStride;
  73640. }
  73641. }
  73642. }
  73643. }
  73644. }
  73645. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  73646. {
  73647. if (hasAlphaChannel())
  73648. {
  73649. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  73650. SparseSet<int> pixelsOnRow;
  73651. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  73652. for (int y = 0; y < imageHeight; ++y)
  73653. {
  73654. pixelsOnRow.clear();
  73655. const uint8* lineData = srcData.getLinePointer (y);
  73656. if (isARGB())
  73657. {
  73658. for (int x = 0; x < imageWidth; ++x)
  73659. {
  73660. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  73661. pixelsOnRow.addRange (Range<int> (x, x + 1));
  73662. lineData += srcData.pixelStride;
  73663. }
  73664. }
  73665. else
  73666. {
  73667. for (int x = 0; x < imageWidth; ++x)
  73668. {
  73669. if (*lineData >= threshold)
  73670. pixelsOnRow.addRange (Range<int> (x, x + 1));
  73671. lineData += srcData.pixelStride;
  73672. }
  73673. }
  73674. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  73675. {
  73676. const Range<int> range (pixelsOnRow.getRange (i));
  73677. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  73678. }
  73679. result.consolidate();
  73680. }
  73681. }
  73682. else
  73683. {
  73684. result.add (0, 0, imageWidth, imageHeight);
  73685. }
  73686. }
  73687. void Image::moveImageSection (int dx, int dy,
  73688. int sx, int sy,
  73689. int w, int h)
  73690. {
  73691. if (dx < 0)
  73692. {
  73693. w += dx;
  73694. sx -= dx;
  73695. dx = 0;
  73696. }
  73697. if (dy < 0)
  73698. {
  73699. h += dy;
  73700. sy -= dy;
  73701. dy = 0;
  73702. }
  73703. if (sx < 0)
  73704. {
  73705. w += sx;
  73706. dx -= sx;
  73707. sx = 0;
  73708. }
  73709. if (sy < 0)
  73710. {
  73711. h += sy;
  73712. dy -= sy;
  73713. sy = 0;
  73714. }
  73715. const int minX = jmin (dx, sx);
  73716. const int minY = jmin (dy, sy);
  73717. w = jmin (w, getWidth() - jmax (sx, dx));
  73718. h = jmin (h, getHeight() - jmax (sy, dy));
  73719. if (w > 0 && h > 0)
  73720. {
  73721. const int maxX = jmax (dx, sx) + w;
  73722. const int maxY = jmax (dy, sy) + h;
  73723. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  73724. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  73725. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  73726. const int lineSize = destData.pixelStride * w;
  73727. if (dy > sy)
  73728. {
  73729. while (--h >= 0)
  73730. {
  73731. const int offset = h * destData.lineStride;
  73732. memmove (dst + offset, src + offset, lineSize);
  73733. }
  73734. }
  73735. else if (dst != src)
  73736. {
  73737. while (--h >= 0)
  73738. {
  73739. memmove (dst, src, lineSize);
  73740. dst += destData.lineStride;
  73741. src += destData.lineStride;
  73742. }
  73743. }
  73744. }
  73745. }
  73746. END_JUCE_NAMESPACE
  73747. /*** End of inlined file: juce_Image.cpp ***/
  73748. /*** Start of inlined file: juce_ImageCache.cpp ***/
  73749. BEGIN_JUCE_NAMESPACE
  73750. struct ImageCache::Item
  73751. {
  73752. ScopedPointer <Image> image;
  73753. int64 hashCode;
  73754. int refCount;
  73755. uint32 releaseTime;
  73756. juce_UseDebuggingNewOperator
  73757. };
  73758. ImageCache* ImageCache::instance = 0;
  73759. int ImageCache::cacheTimeout = 5000;
  73760. ImageCache::ImageCache()
  73761. {
  73762. }
  73763. ImageCache::~ImageCache()
  73764. {
  73765. jassert (instance == this);
  73766. instance = 0;
  73767. }
  73768. Image* ImageCache::getFromHashCode (const int64 hashCode)
  73769. {
  73770. if (instance != 0)
  73771. {
  73772. const ScopedLock sl (instance->lock);
  73773. for (int i = instance->images.size(); --i >= 0;)
  73774. {
  73775. Item* const ci = instance->images.getUnchecked(i);
  73776. if (ci->hashCode == hashCode)
  73777. {
  73778. ci->refCount++;
  73779. return ci->image;
  73780. }
  73781. }
  73782. }
  73783. return 0;
  73784. }
  73785. void ImageCache::addImageToCache (Image* const image, const int64 hashCode)
  73786. {
  73787. if (image != 0)
  73788. {
  73789. if (instance == 0)
  73790. instance = new ImageCache();
  73791. Item* const newC = new Item();
  73792. newC->hashCode = hashCode;
  73793. newC->image = image;
  73794. newC->refCount = 1;
  73795. newC->releaseTime = 0;
  73796. const ScopedLock sl (instance->lock);
  73797. instance->images.add (newC);
  73798. }
  73799. }
  73800. void ImageCache::release (Image* const imageToRelease)
  73801. {
  73802. if (imageToRelease != 0 && instance != 0)
  73803. {
  73804. const ScopedLock sl (instance->lock);
  73805. for (int i = instance->images.size(); --i >= 0;)
  73806. {
  73807. Item* const ci = instance->images.getUnchecked(i);
  73808. if (static_cast <Image*> (ci->image) == imageToRelease)
  73809. {
  73810. if (--(ci->refCount) == 0)
  73811. ci->releaseTime = Time::getApproximateMillisecondCounter();
  73812. if (! instance->isTimerRunning())
  73813. instance->startTimer (999);
  73814. break;
  73815. }
  73816. }
  73817. }
  73818. }
  73819. void ImageCache::releaseOrDelete (Image* const imageToRelease)
  73820. {
  73821. if (isImageInCache (imageToRelease))
  73822. release (imageToRelease);
  73823. else
  73824. delete imageToRelease;
  73825. }
  73826. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  73827. {
  73828. if (instance != 0)
  73829. {
  73830. const ScopedLock sl (instance->lock);
  73831. for (int i = instance->images.size(); --i >= 0;)
  73832. if (static_cast <Image*> (instance->images.getUnchecked(i)->image) == imageToLookFor)
  73833. return true;
  73834. }
  73835. return false;
  73836. }
  73837. void ImageCache::incReferenceCount (Image* const image)
  73838. {
  73839. if (instance != 0)
  73840. {
  73841. const ScopedLock sl (instance->lock);
  73842. for (int i = instance->images.size(); --i >= 0;)
  73843. {
  73844. Item* const ci = instance->images.getUnchecked(i);
  73845. if (static_cast <Image*> (ci->image) == image)
  73846. {
  73847. ci->refCount++;
  73848. return;
  73849. }
  73850. }
  73851. }
  73852. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  73853. }
  73854. void ImageCache::timerCallback()
  73855. {
  73856. int numberStillNeedingReleasing = 0;
  73857. const uint32 now = Time::getApproximateMillisecondCounter();
  73858. const ScopedLock sl (lock);
  73859. for (int i = images.size(); --i >= 0;)
  73860. {
  73861. Item* const ci = images.getUnchecked(i);
  73862. if (ci->refCount <= 0)
  73863. {
  73864. if (now > ci->releaseTime + cacheTimeout
  73865. || now < ci->releaseTime - 1000)
  73866. {
  73867. images.remove (i);
  73868. }
  73869. else
  73870. {
  73871. ++numberStillNeedingReleasing;
  73872. }
  73873. }
  73874. }
  73875. if (numberStillNeedingReleasing == 0)
  73876. stopTimer();
  73877. }
  73878. Image* ImageCache::getFromFile (const File& file)
  73879. {
  73880. const int64 hashCode = file.hashCode64();
  73881. Image* image = getFromHashCode (hashCode);
  73882. if (image == 0)
  73883. {
  73884. image = ImageFileFormat::loadFrom (file);
  73885. addImageToCache (image, hashCode);
  73886. }
  73887. return image;
  73888. }
  73889. Image* ImageCache::getFromMemory (const void* imageData, const int dataSize)
  73890. {
  73891. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  73892. Image* image = getFromHashCode (hashCode);
  73893. if (image == 0)
  73894. {
  73895. image = ImageFileFormat::loadFrom (imageData, dataSize);
  73896. addImageToCache (image, hashCode);
  73897. }
  73898. return image;
  73899. }
  73900. void ImageCache::setCacheTimeout (const int millisecs)
  73901. {
  73902. cacheTimeout = millisecs;
  73903. }
  73904. END_JUCE_NAMESPACE
  73905. /*** End of inlined file: juce_ImageCache.cpp ***/
  73906. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  73907. BEGIN_JUCE_NAMESPACE
  73908. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  73909. : values (size_ * size_),
  73910. size (size_)
  73911. {
  73912. clear();
  73913. }
  73914. ImageConvolutionKernel::~ImageConvolutionKernel()
  73915. {
  73916. }
  73917. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  73918. {
  73919. if (((unsigned int) x) < (unsigned int) size
  73920. && ((unsigned int) y) < (unsigned int) size)
  73921. {
  73922. return values [x + y * size];
  73923. }
  73924. else
  73925. {
  73926. jassertfalse;
  73927. return 0;
  73928. }
  73929. }
  73930. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  73931. {
  73932. if (((unsigned int) x) < (unsigned int) size
  73933. && ((unsigned int) y) < (unsigned int) size)
  73934. {
  73935. values [x + y * size] = value;
  73936. }
  73937. else
  73938. {
  73939. jassertfalse;
  73940. }
  73941. }
  73942. void ImageConvolutionKernel::clear()
  73943. {
  73944. for (int i = size * size; --i >= 0;)
  73945. values[i] = 0;
  73946. }
  73947. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  73948. {
  73949. double currentTotal = 0.0;
  73950. for (int i = size * size; --i >= 0;)
  73951. currentTotal += values[i];
  73952. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  73953. }
  73954. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  73955. {
  73956. for (int i = size * size; --i >= 0;)
  73957. values[i] *= multiplier;
  73958. }
  73959. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  73960. {
  73961. const double radiusFactor = -1.0 / (radius * radius * 2);
  73962. const int centre = size >> 1;
  73963. for (int y = size; --y >= 0;)
  73964. {
  73965. for (int x = size; --x >= 0;)
  73966. {
  73967. const int cx = x - centre;
  73968. const int cy = y - centre;
  73969. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  73970. }
  73971. }
  73972. setOverallSum (1.0f);
  73973. }
  73974. void ImageConvolutionKernel::applyToImage (Image& destImage,
  73975. const Image* sourceImage,
  73976. const Rectangle<int>& destinationArea) const
  73977. {
  73978. ScopedPointer <Image> imageCreated;
  73979. if (sourceImage == 0)
  73980. {
  73981. sourceImage = imageCreated = destImage.createCopy();
  73982. }
  73983. else
  73984. {
  73985. jassert (sourceImage->getWidth() == destImage.getWidth()
  73986. && sourceImage->getHeight() == destImage.getHeight()
  73987. && sourceImage->getFormat() == destImage.getFormat());
  73988. if (sourceImage->getWidth() != destImage.getWidth()
  73989. || sourceImage->getHeight() != destImage.getHeight()
  73990. || sourceImage->getFormat() != destImage.getFormat())
  73991. return;
  73992. }
  73993. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  73994. if (area.isEmpty())
  73995. return;
  73996. const int right = area.getRight();
  73997. const int bottom = area.getBottom();
  73998. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  73999. uint8* line = destData.data;
  74000. const Image::BitmapData srcData (*sourceImage, 0, 0, sourceImage->getWidth(), sourceImage->getHeight());
  74001. if (destData.pixelStride == 4)
  74002. {
  74003. for (int y = area.getY(); y < bottom; ++y)
  74004. {
  74005. uint8* dest = line;
  74006. line += destData.lineStride;
  74007. for (int x = area.getX(); x < right; ++x)
  74008. {
  74009. float c1 = 0;
  74010. float c2 = 0;
  74011. float c3 = 0;
  74012. float c4 = 0;
  74013. for (int yy = 0; yy < size; ++yy)
  74014. {
  74015. const int sy = y + yy - (size >> 1);
  74016. if (sy >= srcData.height)
  74017. break;
  74018. if (sy >= 0)
  74019. {
  74020. int sx = x - (size >> 1);
  74021. const uint8* src = srcData.getPixelPointer (sx, sy);
  74022. for (int xx = 0; xx < size; ++xx)
  74023. {
  74024. if (sx >= srcData.width)
  74025. break;
  74026. if (sx >= 0)
  74027. {
  74028. const float kernelMult = values [xx + yy * size];
  74029. c1 += kernelMult * *src++;
  74030. c2 += kernelMult * *src++;
  74031. c3 += kernelMult * *src++;
  74032. c4 += kernelMult * *src++;
  74033. }
  74034. else
  74035. {
  74036. src += 4;
  74037. }
  74038. ++sx;
  74039. }
  74040. }
  74041. }
  74042. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  74043. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  74044. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  74045. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  74046. }
  74047. }
  74048. }
  74049. else if (destData.pixelStride == 3)
  74050. {
  74051. for (int y = area.getY(); y < bottom; ++y)
  74052. {
  74053. uint8* dest = line;
  74054. line += destData.lineStride;
  74055. for (int x = area.getX(); x < right; ++x)
  74056. {
  74057. float c1 = 0;
  74058. float c2 = 0;
  74059. float c3 = 0;
  74060. for (int yy = 0; yy < size; ++yy)
  74061. {
  74062. const int sy = y + yy - (size >> 1);
  74063. if (sy >= srcData.height)
  74064. break;
  74065. if (sy >= 0)
  74066. {
  74067. int sx = x - (size >> 1);
  74068. const uint8* src = srcData.getPixelPointer (sx, sy);
  74069. for (int xx = 0; xx < size; ++xx)
  74070. {
  74071. if (sx >= srcData.width)
  74072. break;
  74073. if (sx >= 0)
  74074. {
  74075. const float kernelMult = values [xx + yy * size];
  74076. c1 += kernelMult * *src++;
  74077. c2 += kernelMult * *src++;
  74078. c3 += kernelMult * *src++;
  74079. }
  74080. else
  74081. {
  74082. src += 3;
  74083. }
  74084. ++sx;
  74085. }
  74086. }
  74087. }
  74088. *dest++ = (uint8) roundToInt (c1);
  74089. *dest++ = (uint8) roundToInt (c2);
  74090. *dest++ = (uint8) roundToInt (c3);
  74091. }
  74092. }
  74093. }
  74094. }
  74095. END_JUCE_NAMESPACE
  74096. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  74097. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  74098. BEGIN_JUCE_NAMESPACE
  74099. /*** Start of inlined file: juce_GIFLoader.h ***/
  74100. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  74101. #define __JUCE_GIFLOADER_JUCEHEADER__
  74102. #ifndef DOXYGEN
  74103. /**
  74104. Used internally by ImageFileFormat - don't use this class directly in your
  74105. application.
  74106. @see ImageFileFormat
  74107. */
  74108. class GIFLoader
  74109. {
  74110. public:
  74111. GIFLoader (InputStream& in);
  74112. ~GIFLoader();
  74113. Image* getImage() const { return image; }
  74114. private:
  74115. Image* image;
  74116. InputStream& input;
  74117. uint8 buffer [300];
  74118. uint8 palette [256][4];
  74119. bool dataBlockIsZero, fresh, finished;
  74120. int currentBit, lastBit, lastByteIndex;
  74121. int codeSize, setCodeSize;
  74122. int maxCode, maxCodeSize;
  74123. int firstcode, oldcode;
  74124. int clearCode, end_code;
  74125. enum { maxGifCode = 1 << 12 };
  74126. int table [2] [maxGifCode];
  74127. int stack [2 * maxGifCode];
  74128. int *sp;
  74129. bool getSizeFromHeader (int& width, int& height);
  74130. bool readPalette (const int numCols);
  74131. int readDataBlock (unsigned char* dest);
  74132. int processExtension (int type, int& transparent);
  74133. int readLZWByte (bool initialise, int input_code_size);
  74134. int getCode (int code_size, bool initialise);
  74135. bool readImage (int width, int height, int interlace, int transparent);
  74136. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  74137. GIFLoader (const GIFLoader&);
  74138. GIFLoader& operator= (const GIFLoader&);
  74139. };
  74140. #endif // DOXYGEN
  74141. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  74142. /*** End of inlined file: juce_GIFLoader.h ***/
  74143. class GIFImageFormat : public ImageFileFormat
  74144. {
  74145. public:
  74146. GIFImageFormat() {}
  74147. ~GIFImageFormat() {}
  74148. const String getFormatName()
  74149. {
  74150. return "GIF";
  74151. }
  74152. bool canUnderstand (InputStream& in)
  74153. {
  74154. const int bytesNeeded = 4;
  74155. char header [bytesNeeded];
  74156. return (in.read (header, bytesNeeded) == bytesNeeded)
  74157. && header[0] == 'G'
  74158. && header[1] == 'I'
  74159. && header[2] == 'F';
  74160. }
  74161. Image* decodeImage (InputStream& in)
  74162. {
  74163. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  74164. return loader->getImage();
  74165. }
  74166. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  74167. {
  74168. return false;
  74169. }
  74170. };
  74171. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  74172. {
  74173. static PNGImageFormat png;
  74174. static JPEGImageFormat jpg;
  74175. static GIFImageFormat gif;
  74176. ImageFileFormat* formats[4];
  74177. int numFormats = 0;
  74178. formats [numFormats++] = &png;
  74179. formats [numFormats++] = &jpg;
  74180. formats [numFormats++] = &gif;
  74181. const int64 streamPos = input.getPosition();
  74182. for (int i = 0; i < numFormats; ++i)
  74183. {
  74184. const bool found = formats[i]->canUnderstand (input);
  74185. input.setPosition (streamPos);
  74186. if (found)
  74187. return formats[i];
  74188. }
  74189. return 0;
  74190. }
  74191. Image* ImageFileFormat::loadFrom (InputStream& input)
  74192. {
  74193. ImageFileFormat* const format = findImageFormatForStream (input);
  74194. if (format != 0)
  74195. return format->decodeImage (input);
  74196. return 0;
  74197. }
  74198. Image* ImageFileFormat::loadFrom (const File& file)
  74199. {
  74200. InputStream* const in = file.createInputStream();
  74201. if (in != 0)
  74202. {
  74203. BufferedInputStream b (in, 8192, true);
  74204. return loadFrom (b);
  74205. }
  74206. return 0;
  74207. }
  74208. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  74209. {
  74210. if (rawData != 0 && numBytes > 4)
  74211. {
  74212. MemoryInputStream stream (rawData, numBytes, false);
  74213. return loadFrom (stream);
  74214. }
  74215. return 0;
  74216. }
  74217. END_JUCE_NAMESPACE
  74218. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  74219. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  74220. BEGIN_JUCE_NAMESPACE
  74221. GIFLoader::GIFLoader (InputStream& in)
  74222. : image (0),
  74223. input (in),
  74224. dataBlockIsZero (false),
  74225. fresh (false),
  74226. finished (false)
  74227. {
  74228. currentBit = lastBit = lastByteIndex = 0;
  74229. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  74230. firstcode = oldcode = 0;
  74231. clearCode = end_code = 0;
  74232. int imageWidth, imageHeight;
  74233. int transparent = -1;
  74234. if (! getSizeFromHeader (imageWidth, imageHeight))
  74235. return;
  74236. if ((imageWidth <= 0) || (imageHeight <= 0))
  74237. return;
  74238. unsigned char buf [16];
  74239. if (in.read (buf, 3) != 3)
  74240. return;
  74241. int numColours = 2 << (buf[0] & 7);
  74242. if ((buf[0] & 0x80) != 0)
  74243. readPalette (numColours);
  74244. for (;;)
  74245. {
  74246. if (input.read (buf, 1) != 1)
  74247. break;
  74248. if (buf[0] == ';')
  74249. break;
  74250. if (buf[0] == '!')
  74251. {
  74252. if (input.read (buf, 1) != 1)
  74253. break;
  74254. if (processExtension (buf[0], transparent) < 0)
  74255. break;
  74256. continue;
  74257. }
  74258. if (buf[0] != ',')
  74259. continue;
  74260. if (input.read (buf, 9) != 9)
  74261. break;
  74262. imageWidth = makeWord (buf[4], buf[5]);
  74263. imageHeight = makeWord (buf[6], buf[7]);
  74264. numColours = 2 << (buf[8] & 7);
  74265. if ((buf[8] & 0x80) != 0)
  74266. if (! readPalette (numColours))
  74267. break;
  74268. image = Image::createNativeImage ((transparent >= 0) ? Image::ARGB : Image::RGB,
  74269. imageWidth, imageHeight, (transparent >= 0));
  74270. readImage (imageWidth, imageHeight,
  74271. (buf[8] & 0x40) != 0,
  74272. transparent);
  74273. break;
  74274. }
  74275. }
  74276. GIFLoader::~GIFLoader()
  74277. {
  74278. }
  74279. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  74280. {
  74281. char b[8];
  74282. if (input.read (b, 6) == 6)
  74283. {
  74284. if ((strncmp ("GIF87a", b, 6) == 0)
  74285. || (strncmp ("GIF89a", b, 6) == 0))
  74286. {
  74287. if (input.read (b, 4) == 4)
  74288. {
  74289. w = makeWord (b[0], b[1]);
  74290. h = makeWord (b[2], b[3]);
  74291. return true;
  74292. }
  74293. }
  74294. }
  74295. return false;
  74296. }
  74297. bool GIFLoader::readPalette (const int numCols)
  74298. {
  74299. unsigned char rgb[4];
  74300. for (int i = 0; i < numCols; ++i)
  74301. {
  74302. input.read (rgb, 3);
  74303. palette [i][0] = rgb[0];
  74304. palette [i][1] = rgb[1];
  74305. palette [i][2] = rgb[2];
  74306. palette [i][3] = 0xff;
  74307. }
  74308. return true;
  74309. }
  74310. int GIFLoader::readDataBlock (unsigned char* const dest)
  74311. {
  74312. unsigned char n;
  74313. if (input.read (&n, 1) == 1)
  74314. {
  74315. dataBlockIsZero = (n == 0);
  74316. if (dataBlockIsZero || (input.read (dest, n) == n))
  74317. return n;
  74318. }
  74319. return -1;
  74320. }
  74321. int GIFLoader::processExtension (const int type, int& transparent)
  74322. {
  74323. unsigned char b [300];
  74324. int n = 0;
  74325. if (type == 0xf9)
  74326. {
  74327. n = readDataBlock (b);
  74328. if (n < 0)
  74329. return 1;
  74330. if ((b[0] & 0x1) != 0)
  74331. transparent = b[3];
  74332. }
  74333. do
  74334. {
  74335. n = readDataBlock (b);
  74336. }
  74337. while (n > 0);
  74338. return n;
  74339. }
  74340. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  74341. {
  74342. if (initialise)
  74343. {
  74344. currentBit = 0;
  74345. lastBit = 0;
  74346. finished = false;
  74347. return 0;
  74348. }
  74349. if ((currentBit + codeSize_) >= lastBit)
  74350. {
  74351. if (finished)
  74352. return -1;
  74353. buffer[0] = buffer [lastByteIndex - 2];
  74354. buffer[1] = buffer [lastByteIndex - 1];
  74355. const int n = readDataBlock (&buffer[2]);
  74356. if (n == 0)
  74357. finished = true;
  74358. lastByteIndex = 2 + n;
  74359. currentBit = (currentBit - lastBit) + 16;
  74360. lastBit = (2 + n) * 8 ;
  74361. }
  74362. int result = 0;
  74363. int i = currentBit;
  74364. for (int j = 0; j < codeSize_; ++j)
  74365. {
  74366. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  74367. ++i;
  74368. }
  74369. currentBit += codeSize_;
  74370. return result;
  74371. }
  74372. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  74373. {
  74374. int code, incode, i;
  74375. if (initialise)
  74376. {
  74377. setCodeSize = inputCodeSize;
  74378. codeSize = setCodeSize + 1;
  74379. clearCode = 1 << setCodeSize;
  74380. end_code = clearCode + 1;
  74381. maxCodeSize = 2 * clearCode;
  74382. maxCode = clearCode + 2;
  74383. getCode (0, true);
  74384. fresh = true;
  74385. for (i = 0; i < clearCode; ++i)
  74386. {
  74387. table[0][i] = 0;
  74388. table[1][i] = i;
  74389. }
  74390. for (; i < maxGifCode; ++i)
  74391. {
  74392. table[0][i] = 0;
  74393. table[1][i] = 0;
  74394. }
  74395. sp = stack;
  74396. return 0;
  74397. }
  74398. else if (fresh)
  74399. {
  74400. fresh = false;
  74401. do
  74402. {
  74403. firstcode = oldcode
  74404. = getCode (codeSize, false);
  74405. }
  74406. while (firstcode == clearCode);
  74407. return firstcode;
  74408. }
  74409. if (sp > stack)
  74410. return *--sp;
  74411. while ((code = getCode (codeSize, false)) >= 0)
  74412. {
  74413. if (code == clearCode)
  74414. {
  74415. for (i = 0; i < clearCode; ++i)
  74416. {
  74417. table[0][i] = 0;
  74418. table[1][i] = i;
  74419. }
  74420. for (; i < maxGifCode; ++i)
  74421. {
  74422. table[0][i] = 0;
  74423. table[1][i] = 0;
  74424. }
  74425. codeSize = setCodeSize + 1;
  74426. maxCodeSize = 2 * clearCode;
  74427. maxCode = clearCode + 2;
  74428. sp = stack;
  74429. firstcode = oldcode = getCode (codeSize, false);
  74430. return firstcode;
  74431. }
  74432. else if (code == end_code)
  74433. {
  74434. if (dataBlockIsZero)
  74435. return -2;
  74436. unsigned char buf [260];
  74437. int n;
  74438. while ((n = readDataBlock (buf)) > 0)
  74439. {}
  74440. if (n != 0)
  74441. return -2;
  74442. }
  74443. incode = code;
  74444. if (code >= maxCode)
  74445. {
  74446. *sp++ = firstcode;
  74447. code = oldcode;
  74448. }
  74449. while (code >= clearCode)
  74450. {
  74451. *sp++ = table[1][code];
  74452. if (code == table[0][code])
  74453. return -2;
  74454. code = table[0][code];
  74455. }
  74456. *sp++ = firstcode = table[1][code];
  74457. if ((code = maxCode) < maxGifCode)
  74458. {
  74459. table[0][code] = oldcode;
  74460. table[1][code] = firstcode;
  74461. ++maxCode;
  74462. if ((maxCode >= maxCodeSize)
  74463. && (maxCodeSize < maxGifCode))
  74464. {
  74465. maxCodeSize <<= 1;
  74466. ++codeSize;
  74467. }
  74468. }
  74469. oldcode = incode;
  74470. if (sp > stack)
  74471. return *--sp;
  74472. }
  74473. return code;
  74474. }
  74475. bool GIFLoader::readImage (const int width, const int height,
  74476. const int interlace, const int transparent)
  74477. {
  74478. unsigned char c;
  74479. if (input.read (&c, 1) != 1
  74480. || readLZWByte (true, c) < 0)
  74481. return false;
  74482. if (transparent >= 0)
  74483. {
  74484. palette [transparent][0] = 0;
  74485. palette [transparent][1] = 0;
  74486. palette [transparent][2] = 0;
  74487. palette [transparent][3] = 0;
  74488. }
  74489. int index;
  74490. int xpos = 0, ypos = 0, pass = 0;
  74491. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  74492. uint8* p = destData.data;
  74493. const bool hasAlpha = image->hasAlphaChannel();
  74494. while ((index = readLZWByte (false, c)) >= 0)
  74495. {
  74496. const uint8* const paletteEntry = palette [index];
  74497. if (hasAlpha)
  74498. {
  74499. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  74500. paletteEntry[0],
  74501. paletteEntry[1],
  74502. paletteEntry[2]);
  74503. ((PixelARGB*) p)->premultiply();
  74504. }
  74505. else
  74506. {
  74507. ((PixelRGB*) p)->setARGB (0,
  74508. paletteEntry[0],
  74509. paletteEntry[1],
  74510. paletteEntry[2]);
  74511. }
  74512. p += destData.pixelStride;
  74513. ++xpos;
  74514. if (xpos == width)
  74515. {
  74516. xpos = 0;
  74517. if (interlace)
  74518. {
  74519. switch (pass)
  74520. {
  74521. case 0:
  74522. case 1: ypos += 8; break;
  74523. case 2: ypos += 4; break;
  74524. case 3: ypos += 2; break;
  74525. }
  74526. while (ypos >= height)
  74527. {
  74528. ++pass;
  74529. switch (pass)
  74530. {
  74531. case 1: ypos = 4; break;
  74532. case 2: ypos = 2; break;
  74533. case 3: ypos = 1; break;
  74534. default: return true;
  74535. }
  74536. }
  74537. }
  74538. else
  74539. {
  74540. ++ypos;
  74541. }
  74542. p = destData.getPixelPointer (xpos, ypos);
  74543. }
  74544. if (ypos >= height)
  74545. break;
  74546. }
  74547. return true;
  74548. }
  74549. END_JUCE_NAMESPACE
  74550. /*** End of inlined file: juce_GIFLoader.cpp ***/
  74551. #endif
  74552. //==============================================================================
  74553. // some files include lots of library code, so leave them to the end to avoid cluttering
  74554. // up the build for the clean files.
  74555. #if JUCE_BUILD_CORE
  74556. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  74557. namespace zlibNamespace
  74558. {
  74559. #if JUCE_INCLUDE_ZLIB_CODE
  74560. #undef OS_CODE
  74561. #undef fdopen
  74562. /*** Start of inlined file: zlib.h ***/
  74563. #ifndef ZLIB_H
  74564. #define ZLIB_H
  74565. /*** Start of inlined file: zconf.h ***/
  74566. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74567. #ifndef ZCONF_H
  74568. #define ZCONF_H
  74569. // *** Just a few hacks here to make it compile nicely with Juce..
  74570. #define Z_PREFIX 1
  74571. #undef __MACTYPES__
  74572. #ifdef _MSC_VER
  74573. #pragma warning (disable : 4131 4127 4244 4267)
  74574. #endif
  74575. /*
  74576. * If you *really* need a unique prefix for all types and library functions,
  74577. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  74578. */
  74579. #ifdef Z_PREFIX
  74580. # define deflateInit_ z_deflateInit_
  74581. # define deflate z_deflate
  74582. # define deflateEnd z_deflateEnd
  74583. # define inflateInit_ z_inflateInit_
  74584. # define inflate z_inflate
  74585. # define inflateEnd z_inflateEnd
  74586. # define inflatePrime z_inflatePrime
  74587. # define inflateGetHeader z_inflateGetHeader
  74588. # define adler32_combine z_adler32_combine
  74589. # define crc32_combine z_crc32_combine
  74590. # define deflateInit2_ z_deflateInit2_
  74591. # define deflateSetDictionary z_deflateSetDictionary
  74592. # define deflateCopy z_deflateCopy
  74593. # define deflateReset z_deflateReset
  74594. # define deflateParams z_deflateParams
  74595. # define deflateBound z_deflateBound
  74596. # define deflatePrime z_deflatePrime
  74597. # define inflateInit2_ z_inflateInit2_
  74598. # define inflateSetDictionary z_inflateSetDictionary
  74599. # define inflateSync z_inflateSync
  74600. # define inflateSyncPoint z_inflateSyncPoint
  74601. # define inflateCopy z_inflateCopy
  74602. # define inflateReset z_inflateReset
  74603. # define inflateBack z_inflateBack
  74604. # define inflateBackEnd z_inflateBackEnd
  74605. # define compress z_compress
  74606. # define compress2 z_compress2
  74607. # define compressBound z_compressBound
  74608. # define uncompress z_uncompress
  74609. # define adler32 z_adler32
  74610. # define crc32 z_crc32
  74611. # define get_crc_table z_get_crc_table
  74612. # define zError z_zError
  74613. # define alloc_func z_alloc_func
  74614. # define free_func z_free_func
  74615. # define in_func z_in_func
  74616. # define out_func z_out_func
  74617. # define Byte z_Byte
  74618. # define uInt z_uInt
  74619. # define uLong z_uLong
  74620. # define Bytef z_Bytef
  74621. # define charf z_charf
  74622. # define intf z_intf
  74623. # define uIntf z_uIntf
  74624. # define uLongf z_uLongf
  74625. # define voidpf z_voidpf
  74626. # define voidp z_voidp
  74627. #endif
  74628. #if defined(__MSDOS__) && !defined(MSDOS)
  74629. # define MSDOS
  74630. #endif
  74631. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  74632. # define OS2
  74633. #endif
  74634. #if defined(_WINDOWS) && !defined(WINDOWS)
  74635. # define WINDOWS
  74636. #endif
  74637. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  74638. # ifndef WIN32
  74639. # define WIN32
  74640. # endif
  74641. #endif
  74642. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  74643. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  74644. # ifndef SYS16BIT
  74645. # define SYS16BIT
  74646. # endif
  74647. # endif
  74648. #endif
  74649. /*
  74650. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  74651. * than 64k bytes at a time (needed on systems with 16-bit int).
  74652. */
  74653. #ifdef SYS16BIT
  74654. # define MAXSEG_64K
  74655. #endif
  74656. #ifdef MSDOS
  74657. # define UNALIGNED_OK
  74658. #endif
  74659. #ifdef __STDC_VERSION__
  74660. # ifndef STDC
  74661. # define STDC
  74662. # endif
  74663. # if __STDC_VERSION__ >= 199901L
  74664. # ifndef STDC99
  74665. # define STDC99
  74666. # endif
  74667. # endif
  74668. #endif
  74669. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  74670. # define STDC
  74671. #endif
  74672. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  74673. # define STDC
  74674. #endif
  74675. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  74676. # define STDC
  74677. #endif
  74678. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  74679. # define STDC
  74680. #endif
  74681. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  74682. # define STDC
  74683. #endif
  74684. #ifndef STDC
  74685. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  74686. # define const /* note: need a more gentle solution here */
  74687. # endif
  74688. #endif
  74689. /* Some Mac compilers merge all .h files incorrectly: */
  74690. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  74691. # define NO_DUMMY_DECL
  74692. #endif
  74693. /* Maximum value for memLevel in deflateInit2 */
  74694. #ifndef MAX_MEM_LEVEL
  74695. # ifdef MAXSEG_64K
  74696. # define MAX_MEM_LEVEL 8
  74697. # else
  74698. # define MAX_MEM_LEVEL 9
  74699. # endif
  74700. #endif
  74701. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  74702. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  74703. * created by gzip. (Files created by minigzip can still be extracted by
  74704. * gzip.)
  74705. */
  74706. #ifndef MAX_WBITS
  74707. # define MAX_WBITS 15 /* 32K LZ77 window */
  74708. #endif
  74709. /* The memory requirements for deflate are (in bytes):
  74710. (1 << (windowBits+2)) + (1 << (memLevel+9))
  74711. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  74712. plus a few kilobytes for small objects. For example, if you want to reduce
  74713. the default memory requirements from 256K to 128K, compile with
  74714. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  74715. Of course this will generally degrade compression (there's no free lunch).
  74716. The memory requirements for inflate are (in bytes) 1 << windowBits
  74717. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  74718. for small objects.
  74719. */
  74720. /* Type declarations */
  74721. #ifndef OF /* function prototypes */
  74722. # ifdef STDC
  74723. # define OF(args) args
  74724. # else
  74725. # define OF(args) ()
  74726. # endif
  74727. #endif
  74728. /* The following definitions for FAR are needed only for MSDOS mixed
  74729. * model programming (small or medium model with some far allocations).
  74730. * This was tested only with MSC; for other MSDOS compilers you may have
  74731. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  74732. * just define FAR to be empty.
  74733. */
  74734. #ifdef SYS16BIT
  74735. # if defined(M_I86SM) || defined(M_I86MM)
  74736. /* MSC small or medium model */
  74737. # define SMALL_MEDIUM
  74738. # ifdef _MSC_VER
  74739. # define FAR _far
  74740. # else
  74741. # define FAR far
  74742. # endif
  74743. # endif
  74744. # if (defined(__SMALL__) || defined(__MEDIUM__))
  74745. /* Turbo C small or medium model */
  74746. # define SMALL_MEDIUM
  74747. # ifdef __BORLANDC__
  74748. # define FAR _far
  74749. # else
  74750. # define FAR far
  74751. # endif
  74752. # endif
  74753. #endif
  74754. #if defined(WINDOWS) || defined(WIN32)
  74755. /* If building or using zlib as a DLL, define ZLIB_DLL.
  74756. * This is not mandatory, but it offers a little performance increase.
  74757. */
  74758. # ifdef ZLIB_DLL
  74759. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  74760. # ifdef ZLIB_INTERNAL
  74761. # define ZEXTERN extern __declspec(dllexport)
  74762. # else
  74763. # define ZEXTERN extern __declspec(dllimport)
  74764. # endif
  74765. # endif
  74766. # endif /* ZLIB_DLL */
  74767. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  74768. * define ZLIB_WINAPI.
  74769. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  74770. */
  74771. # ifdef ZLIB_WINAPI
  74772. # ifdef FAR
  74773. # undef FAR
  74774. # endif
  74775. # include <windows.h>
  74776. /* No need for _export, use ZLIB.DEF instead. */
  74777. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  74778. # define ZEXPORT WINAPI
  74779. # ifdef WIN32
  74780. # define ZEXPORTVA WINAPIV
  74781. # else
  74782. # define ZEXPORTVA FAR CDECL
  74783. # endif
  74784. # endif
  74785. #endif
  74786. #if defined (__BEOS__)
  74787. # ifdef ZLIB_DLL
  74788. # ifdef ZLIB_INTERNAL
  74789. # define ZEXPORT __declspec(dllexport)
  74790. # define ZEXPORTVA __declspec(dllexport)
  74791. # else
  74792. # define ZEXPORT __declspec(dllimport)
  74793. # define ZEXPORTVA __declspec(dllimport)
  74794. # endif
  74795. # endif
  74796. #endif
  74797. #ifndef ZEXTERN
  74798. # define ZEXTERN extern
  74799. #endif
  74800. #ifndef ZEXPORT
  74801. # define ZEXPORT
  74802. #endif
  74803. #ifndef ZEXPORTVA
  74804. # define ZEXPORTVA
  74805. #endif
  74806. #ifndef FAR
  74807. # define FAR
  74808. #endif
  74809. #if !defined(__MACTYPES__)
  74810. typedef unsigned char Byte; /* 8 bits */
  74811. #endif
  74812. typedef unsigned int uInt; /* 16 bits or more */
  74813. typedef unsigned long uLong; /* 32 bits or more */
  74814. #ifdef SMALL_MEDIUM
  74815. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  74816. # define Bytef Byte FAR
  74817. #else
  74818. typedef Byte FAR Bytef;
  74819. #endif
  74820. typedef char FAR charf;
  74821. typedef int FAR intf;
  74822. typedef uInt FAR uIntf;
  74823. typedef uLong FAR uLongf;
  74824. #ifdef STDC
  74825. typedef void const *voidpc;
  74826. typedef void FAR *voidpf;
  74827. typedef void *voidp;
  74828. #else
  74829. typedef Byte const *voidpc;
  74830. typedef Byte FAR *voidpf;
  74831. typedef Byte *voidp;
  74832. #endif
  74833. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  74834. # include <sys/types.h> /* for off_t */
  74835. # include <unistd.h> /* for SEEK_* and off_t */
  74836. # ifdef VMS
  74837. # include <unixio.h> /* for off_t */
  74838. # endif
  74839. # define z_off_t off_t
  74840. #endif
  74841. #ifndef SEEK_SET
  74842. # define SEEK_SET 0 /* Seek from beginning of file. */
  74843. # define SEEK_CUR 1 /* Seek from current position. */
  74844. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  74845. #endif
  74846. #ifndef z_off_t
  74847. # define z_off_t long
  74848. #endif
  74849. #if defined(__OS400__)
  74850. # define NO_vsnprintf
  74851. #endif
  74852. #if defined(__MVS__)
  74853. # define NO_vsnprintf
  74854. # ifdef FAR
  74855. # undef FAR
  74856. # endif
  74857. #endif
  74858. /* MVS linker does not support external names larger than 8 bytes */
  74859. #if defined(__MVS__)
  74860. # pragma map(deflateInit_,"DEIN")
  74861. # pragma map(deflateInit2_,"DEIN2")
  74862. # pragma map(deflateEnd,"DEEND")
  74863. # pragma map(deflateBound,"DEBND")
  74864. # pragma map(inflateInit_,"ININ")
  74865. # pragma map(inflateInit2_,"ININ2")
  74866. # pragma map(inflateEnd,"INEND")
  74867. # pragma map(inflateSync,"INSY")
  74868. # pragma map(inflateSetDictionary,"INSEDI")
  74869. # pragma map(compressBound,"CMBND")
  74870. # pragma map(inflate_table,"INTABL")
  74871. # pragma map(inflate_fast,"INFA")
  74872. # pragma map(inflate_copyright,"INCOPY")
  74873. #endif
  74874. #endif /* ZCONF_H */
  74875. /*** End of inlined file: zconf.h ***/
  74876. #ifdef __cplusplus
  74877. extern "C" {
  74878. #endif
  74879. #define ZLIB_VERSION "1.2.3"
  74880. #define ZLIB_VERNUM 0x1230
  74881. /*
  74882. The 'zlib' compression library provides in-memory compression and
  74883. decompression functions, including integrity checks of the uncompressed
  74884. data. This version of the library supports only one compression method
  74885. (deflation) but other algorithms will be added later and will have the same
  74886. stream interface.
  74887. Compression can be done in a single step if the buffers are large
  74888. enough (for example if an input file is mmap'ed), or can be done by
  74889. repeated calls of the compression function. In the latter case, the
  74890. application must provide more input and/or consume the output
  74891. (providing more output space) before each call.
  74892. The compressed data format used by default by the in-memory functions is
  74893. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  74894. around a deflate stream, which is itself documented in RFC 1951.
  74895. The library also supports reading and writing files in gzip (.gz) format
  74896. with an interface similar to that of stdio using the functions that start
  74897. with "gz". The gzip format is different from the zlib format. gzip is a
  74898. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  74899. This library can optionally read and write gzip streams in memory as well.
  74900. The zlib format was designed to be compact and fast for use in memory
  74901. and on communications channels. The gzip format was designed for single-
  74902. file compression on file systems, has a larger header than zlib to maintain
  74903. directory information, and uses a different, slower check method than zlib.
  74904. The library does not install any signal handler. The decoder checks
  74905. the consistency of the compressed data, so the library should never
  74906. crash even in case of corrupted input.
  74907. */
  74908. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  74909. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  74910. struct internal_state;
  74911. typedef struct z_stream_s {
  74912. Bytef *next_in; /* next input byte */
  74913. uInt avail_in; /* number of bytes available at next_in */
  74914. uLong total_in; /* total nb of input bytes read so far */
  74915. Bytef *next_out; /* next output byte should be put there */
  74916. uInt avail_out; /* remaining free space at next_out */
  74917. uLong total_out; /* total nb of bytes output so far */
  74918. char *msg; /* last error message, NULL if no error */
  74919. struct internal_state FAR *state; /* not visible by applications */
  74920. alloc_func zalloc; /* used to allocate the internal state */
  74921. free_func zfree; /* used to free the internal state */
  74922. voidpf opaque; /* private data object passed to zalloc and zfree */
  74923. int data_type; /* best guess about the data type: binary or text */
  74924. uLong adler; /* adler32 value of the uncompressed data */
  74925. uLong reserved; /* reserved for future use */
  74926. } z_stream;
  74927. typedef z_stream FAR *z_streamp;
  74928. /*
  74929. gzip header information passed to and from zlib routines. See RFC 1952
  74930. for more details on the meanings of these fields.
  74931. */
  74932. typedef struct gz_header_s {
  74933. int text; /* true if compressed data believed to be text */
  74934. uLong time; /* modification time */
  74935. int xflags; /* extra flags (not used when writing a gzip file) */
  74936. int os; /* operating system */
  74937. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  74938. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  74939. uInt extra_max; /* space at extra (only when reading header) */
  74940. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  74941. uInt name_max; /* space at name (only when reading header) */
  74942. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  74943. uInt comm_max; /* space at comment (only when reading header) */
  74944. int hcrc; /* true if there was or will be a header crc */
  74945. int done; /* true when done reading gzip header (not used
  74946. when writing a gzip file) */
  74947. } gz_header;
  74948. typedef gz_header FAR *gz_headerp;
  74949. /*
  74950. The application must update next_in and avail_in when avail_in has
  74951. dropped to zero. It must update next_out and avail_out when avail_out
  74952. has dropped to zero. The application must initialize zalloc, zfree and
  74953. opaque before calling the init function. All other fields are set by the
  74954. compression library and must not be updated by the application.
  74955. The opaque value provided by the application will be passed as the first
  74956. parameter for calls of zalloc and zfree. This can be useful for custom
  74957. memory management. The compression library attaches no meaning to the
  74958. opaque value.
  74959. zalloc must return Z_NULL if there is not enough memory for the object.
  74960. If zlib is used in a multi-threaded application, zalloc and zfree must be
  74961. thread safe.
  74962. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  74963. exactly 65536 bytes, but will not be required to allocate more than this
  74964. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  74965. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  74966. have their offset normalized to zero. The default allocation function
  74967. provided by this library ensures this (see zutil.c). To reduce memory
  74968. requirements and avoid any allocation of 64K objects, at the expense of
  74969. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  74970. The fields total_in and total_out can be used for statistics or
  74971. progress reports. After compression, total_in holds the total size of
  74972. the uncompressed data and may be saved for use in the decompressor
  74973. (particularly if the decompressor wants to decompress everything in
  74974. a single step).
  74975. */
  74976. /* constants */
  74977. #define Z_NO_FLUSH 0
  74978. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  74979. #define Z_SYNC_FLUSH 2
  74980. #define Z_FULL_FLUSH 3
  74981. #define Z_FINISH 4
  74982. #define Z_BLOCK 5
  74983. /* Allowed flush values; see deflate() and inflate() below for details */
  74984. #define Z_OK 0
  74985. #define Z_STREAM_END 1
  74986. #define Z_NEED_DICT 2
  74987. #define Z_ERRNO (-1)
  74988. #define Z_STREAM_ERROR (-2)
  74989. #define Z_DATA_ERROR (-3)
  74990. #define Z_MEM_ERROR (-4)
  74991. #define Z_BUF_ERROR (-5)
  74992. #define Z_VERSION_ERROR (-6)
  74993. /* Return codes for the compression/decompression functions. Negative
  74994. * values are errors, positive values are used for special but normal events.
  74995. */
  74996. #define Z_NO_COMPRESSION 0
  74997. #define Z_BEST_SPEED 1
  74998. #define Z_BEST_COMPRESSION 9
  74999. #define Z_DEFAULT_COMPRESSION (-1)
  75000. /* compression levels */
  75001. #define Z_FILTERED 1
  75002. #define Z_HUFFMAN_ONLY 2
  75003. #define Z_RLE 3
  75004. #define Z_FIXED 4
  75005. #define Z_DEFAULT_STRATEGY 0
  75006. /* compression strategy; see deflateInit2() below for details */
  75007. #define Z_BINARY 0
  75008. #define Z_TEXT 1
  75009. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  75010. #define Z_UNKNOWN 2
  75011. /* Possible values of the data_type field (though see inflate()) */
  75012. #define Z_DEFLATED 8
  75013. /* The deflate compression method (the only one supported in this version) */
  75014. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  75015. #define zlib_version zlibVersion()
  75016. /* for compatibility with versions < 1.0.2 */
  75017. /* basic functions */
  75018. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  75019. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  75020. If the first character differs, the library code actually used is
  75021. not compatible with the zlib.h header file used by the application.
  75022. This check is automatically made by deflateInit and inflateInit.
  75023. */
  75024. /*
  75025. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  75026. Initializes the internal stream state for compression. The fields
  75027. zalloc, zfree and opaque must be initialized before by the caller.
  75028. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  75029. use default allocation functions.
  75030. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  75031. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  75032. all (the input data is simply copied a block at a time).
  75033. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  75034. compression (currently equivalent to level 6).
  75035. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  75036. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  75037. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  75038. with the version assumed by the caller (ZLIB_VERSION).
  75039. msg is set to null if there is no error message. deflateInit does not
  75040. perform any compression: this will be done by deflate().
  75041. */
  75042. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  75043. /*
  75044. deflate compresses as much data as possible, and stops when the input
  75045. buffer becomes empty or the output buffer becomes full. It may introduce some
  75046. output latency (reading input without producing any output) except when
  75047. forced to flush.
  75048. The detailed semantics are as follows. deflate performs one or both of the
  75049. following actions:
  75050. - Compress more input starting at next_in and update next_in and avail_in
  75051. accordingly. If not all input can be processed (because there is not
  75052. enough room in the output buffer), next_in and avail_in are updated and
  75053. processing will resume at this point for the next call of deflate().
  75054. - Provide more output starting at next_out and update next_out and avail_out
  75055. accordingly. This action is forced if the parameter flush is non zero.
  75056. Forcing flush frequently degrades the compression ratio, so this parameter
  75057. should be set only when necessary (in interactive applications).
  75058. Some output may be provided even if flush is not set.
  75059. Before the call of deflate(), the application should ensure that at least
  75060. one of the actions is possible, by providing more input and/or consuming
  75061. more output, and updating avail_in or avail_out accordingly; avail_out
  75062. should never be zero before the call. The application can consume the
  75063. compressed output when it wants, for example when the output buffer is full
  75064. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  75065. and with zero avail_out, it must be called again after making room in the
  75066. output buffer because there might be more output pending.
  75067. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  75068. decide how much data to accumualte before producing output, in order to
  75069. maximize compression.
  75070. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  75071. flushed to the output buffer and the output is aligned on a byte boundary, so
  75072. that the decompressor can get all input data available so far. (In particular
  75073. avail_in is zero after the call if enough output space has been provided
  75074. before the call.) Flushing may degrade compression for some compression
  75075. algorithms and so it should be used only when necessary.
  75076. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  75077. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  75078. restart from this point if previous compressed data has been damaged or if
  75079. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  75080. compression.
  75081. If deflate returns with avail_out == 0, this function must be called again
  75082. with the same value of the flush parameter and more output space (updated
  75083. avail_out), until the flush is complete (deflate returns with non-zero
  75084. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  75085. avail_out is greater than six to avoid repeated flush markers due to
  75086. avail_out == 0 on return.
  75087. If the parameter flush is set to Z_FINISH, pending input is processed,
  75088. pending output is flushed and deflate returns with Z_STREAM_END if there
  75089. was enough output space; if deflate returns with Z_OK, this function must be
  75090. called again with Z_FINISH and more output space (updated avail_out) but no
  75091. more input data, until it returns with Z_STREAM_END or an error. After
  75092. deflate has returned Z_STREAM_END, the only possible operations on the
  75093. stream are deflateReset or deflateEnd.
  75094. Z_FINISH can be used immediately after deflateInit if all the compression
  75095. is to be done in a single step. In this case, avail_out must be at least
  75096. the value returned by deflateBound (see below). If deflate does not return
  75097. Z_STREAM_END, then it must be called again as described above.
  75098. deflate() sets strm->adler to the adler32 checksum of all input read
  75099. so far (that is, total_in bytes).
  75100. deflate() may update strm->data_type if it can make a good guess about
  75101. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  75102. binary. This field is only for information purposes and does not affect
  75103. the compression algorithm in any manner.
  75104. deflate() returns Z_OK if some progress has been made (more input
  75105. processed or more output produced), Z_STREAM_END if all input has been
  75106. consumed and all output has been produced (only when flush is set to
  75107. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  75108. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  75109. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  75110. fatal, and deflate() can be called again with more input and more output
  75111. space to continue compressing.
  75112. */
  75113. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  75114. /*
  75115. All dynamically allocated data structures for this stream are freed.
  75116. This function discards any unprocessed input and does not flush any
  75117. pending output.
  75118. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  75119. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  75120. prematurely (some input or output was discarded). In the error case,
  75121. msg may be set but then points to a static string (which must not be
  75122. deallocated).
  75123. */
  75124. /*
  75125. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  75126. Initializes the internal stream state for decompression. The fields
  75127. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  75128. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  75129. value depends on the compression method), inflateInit determines the
  75130. compression method from the zlib header and allocates all data structures
  75131. accordingly; otherwise the allocation will be deferred to the first call of
  75132. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  75133. use default allocation functions.
  75134. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75135. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  75136. version assumed by the caller. msg is set to null if there is no error
  75137. message. inflateInit does not perform any decompression apart from reading
  75138. the zlib header if present: this will be done by inflate(). (So next_in and
  75139. avail_in may be modified, but next_out and avail_out are unchanged.)
  75140. */
  75141. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  75142. /*
  75143. inflate decompresses as much data as possible, and stops when the input
  75144. buffer becomes empty or the output buffer becomes full. It may introduce
  75145. some output latency (reading input without producing any output) except when
  75146. forced to flush.
  75147. The detailed semantics are as follows. inflate performs one or both of the
  75148. following actions:
  75149. - Decompress more input starting at next_in and update next_in and avail_in
  75150. accordingly. If not all input can be processed (because there is not
  75151. enough room in the output buffer), next_in is updated and processing
  75152. will resume at this point for the next call of inflate().
  75153. - Provide more output starting at next_out and update next_out and avail_out
  75154. accordingly. inflate() provides as much output as possible, until there
  75155. is no more input data or no more space in the output buffer (see below
  75156. about the flush parameter).
  75157. Before the call of inflate(), the application should ensure that at least
  75158. one of the actions is possible, by providing more input and/or consuming
  75159. more output, and updating the next_* and avail_* values accordingly.
  75160. The application can consume the uncompressed output when it wants, for
  75161. example when the output buffer is full (avail_out == 0), or after each
  75162. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  75163. must be called again after making room in the output buffer because there
  75164. might be more output pending.
  75165. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  75166. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  75167. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  75168. if and when it gets to the next deflate block boundary. When decoding the
  75169. zlib or gzip format, this will cause inflate() to return immediately after
  75170. the header and before the first block. When doing a raw inflate, inflate()
  75171. will go ahead and process the first block, and will return when it gets to
  75172. the end of that block, or when it runs out of data.
  75173. The Z_BLOCK option assists in appending to or combining deflate streams.
  75174. Also to assist in this, on return inflate() will set strm->data_type to the
  75175. number of unused bits in the last byte taken from strm->next_in, plus 64
  75176. if inflate() is currently decoding the last block in the deflate stream,
  75177. plus 128 if inflate() returned immediately after decoding an end-of-block
  75178. code or decoding the complete header up to just before the first byte of the
  75179. deflate stream. The end-of-block will not be indicated until all of the
  75180. uncompressed data from that block has been written to strm->next_out. The
  75181. number of unused bits may in general be greater than seven, except when
  75182. bit 7 of data_type is set, in which case the number of unused bits will be
  75183. less than eight.
  75184. inflate() should normally be called until it returns Z_STREAM_END or an
  75185. error. However if all decompression is to be performed in a single step
  75186. (a single call of inflate), the parameter flush should be set to
  75187. Z_FINISH. In this case all pending input is processed and all pending
  75188. output is flushed; avail_out must be large enough to hold all the
  75189. uncompressed data. (The size of the uncompressed data may have been saved
  75190. by the compressor for this purpose.) The next operation on this stream must
  75191. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  75192. is never required, but can be used to inform inflate that a faster approach
  75193. may be used for the single inflate() call.
  75194. In this implementation, inflate() always flushes as much output as
  75195. possible to the output buffer, and always uses the faster approach on the
  75196. first call. So the only effect of the flush parameter in this implementation
  75197. is on the return value of inflate(), as noted below, or when it returns early
  75198. because Z_BLOCK is used.
  75199. If a preset dictionary is needed after this call (see inflateSetDictionary
  75200. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  75201. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  75202. strm->adler to the adler32 checksum of all output produced so far (that is,
  75203. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  75204. below. At the end of the stream, inflate() checks that its computed adler32
  75205. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  75206. only if the checksum is correct.
  75207. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  75208. deflate data. The header type is detected automatically. Any information
  75209. contained in the gzip header is not retained, so applications that need that
  75210. information should instead use raw inflate, see inflateInit2() below, or
  75211. inflateBack() and perform their own processing of the gzip header and
  75212. trailer.
  75213. inflate() returns Z_OK if some progress has been made (more input processed
  75214. or more output produced), Z_STREAM_END if the end of the compressed data has
  75215. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  75216. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  75217. corrupted (input stream not conforming to the zlib format or incorrect check
  75218. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  75219. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  75220. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  75221. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  75222. inflate() can be called again with more input and more output space to
  75223. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  75224. call inflateSync() to look for a good compression block if a partial recovery
  75225. of the data is desired.
  75226. */
  75227. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  75228. /*
  75229. All dynamically allocated data structures for this stream are freed.
  75230. This function discards any unprocessed input and does not flush any
  75231. pending output.
  75232. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  75233. was inconsistent. In the error case, msg may be set but then points to a
  75234. static string (which must not be deallocated).
  75235. */
  75236. /* Advanced functions */
  75237. /*
  75238. The following functions are needed only in some special applications.
  75239. */
  75240. /*
  75241. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  75242. int level,
  75243. int method,
  75244. int windowBits,
  75245. int memLevel,
  75246. int strategy));
  75247. This is another version of deflateInit with more compression options. The
  75248. fields next_in, zalloc, zfree and opaque must be initialized before by
  75249. the caller.
  75250. The method parameter is the compression method. It must be Z_DEFLATED in
  75251. this version of the library.
  75252. The windowBits parameter is the base two logarithm of the window size
  75253. (the size of the history buffer). It should be in the range 8..15 for this
  75254. version of the library. Larger values of this parameter result in better
  75255. compression at the expense of memory usage. The default value is 15 if
  75256. deflateInit is used instead.
  75257. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  75258. determines the window size. deflate() will then generate raw deflate data
  75259. with no zlib header or trailer, and will not compute an adler32 check value.
  75260. windowBits can also be greater than 15 for optional gzip encoding. Add
  75261. 16 to windowBits to write a simple gzip header and trailer around the
  75262. compressed data instead of a zlib wrapper. The gzip header will have no
  75263. file name, no extra data, no comment, no modification time (set to zero),
  75264. no header crc, and the operating system will be set to 255 (unknown). If a
  75265. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  75266. The memLevel parameter specifies how much memory should be allocated
  75267. for the internal compression state. memLevel=1 uses minimum memory but
  75268. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  75269. for optimal speed. The default value is 8. See zconf.h for total memory
  75270. usage as a function of windowBits and memLevel.
  75271. The strategy parameter is used to tune the compression algorithm. Use the
  75272. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  75273. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  75274. string match), or Z_RLE to limit match distances to one (run-length
  75275. encoding). Filtered data consists mostly of small values with a somewhat
  75276. random distribution. In this case, the compression algorithm is tuned to
  75277. compress them better. The effect of Z_FILTERED is to force more Huffman
  75278. coding and less string matching; it is somewhat intermediate between
  75279. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  75280. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  75281. parameter only affects the compression ratio but not the correctness of the
  75282. compressed output even if it is not set appropriately. Z_FIXED prevents the
  75283. use of dynamic Huffman codes, allowing for a simpler decoder for special
  75284. applications.
  75285. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75286. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  75287. method). msg is set to null if there is no error message. deflateInit2 does
  75288. not perform any compression: this will be done by deflate().
  75289. */
  75290. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  75291. const Bytef *dictionary,
  75292. uInt dictLength));
  75293. /*
  75294. Initializes the compression dictionary from the given byte sequence
  75295. without producing any compressed output. This function must be called
  75296. immediately after deflateInit, deflateInit2 or deflateReset, before any
  75297. call of deflate. The compressor and decompressor must use exactly the same
  75298. dictionary (see inflateSetDictionary).
  75299. The dictionary should consist of strings (byte sequences) that are likely
  75300. to be encountered later in the data to be compressed, with the most commonly
  75301. used strings preferably put towards the end of the dictionary. Using a
  75302. dictionary is most useful when the data to be compressed is short and can be
  75303. predicted with good accuracy; the data can then be compressed better than
  75304. with the default empty dictionary.
  75305. Depending on the size of the compression data structures selected by
  75306. deflateInit or deflateInit2, a part of the dictionary may in effect be
  75307. discarded, for example if the dictionary is larger than the window size in
  75308. deflate or deflate2. Thus the strings most likely to be useful should be
  75309. put at the end of the dictionary, not at the front. In addition, the
  75310. current implementation of deflate will use at most the window size minus
  75311. 262 bytes of the provided dictionary.
  75312. Upon return of this function, strm->adler is set to the adler32 value
  75313. of the dictionary; the decompressor may later use this value to determine
  75314. which dictionary has been used by the compressor. (The adler32 value
  75315. applies to the whole dictionary even if only a subset of the dictionary is
  75316. actually used by the compressor.) If a raw deflate was requested, then the
  75317. adler32 value is not computed and strm->adler is not set.
  75318. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  75319. parameter is invalid (such as NULL dictionary) or the stream state is
  75320. inconsistent (for example if deflate has already been called for this stream
  75321. or if the compression method is bsort). deflateSetDictionary does not
  75322. perform any compression: this will be done by deflate().
  75323. */
  75324. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  75325. z_streamp source));
  75326. /*
  75327. Sets the destination stream as a complete copy of the source stream.
  75328. This function can be useful when several compression strategies will be
  75329. tried, for example when there are several ways of pre-processing the input
  75330. data with a filter. The streams that will be discarded should then be freed
  75331. by calling deflateEnd. Note that deflateCopy duplicates the internal
  75332. compression state which can be quite large, so this strategy is slow and
  75333. can consume lots of memory.
  75334. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  75335. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  75336. (such as zalloc being NULL). msg is left unchanged in both source and
  75337. destination.
  75338. */
  75339. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  75340. /*
  75341. This function is equivalent to deflateEnd followed by deflateInit,
  75342. but does not free and reallocate all the internal compression state.
  75343. The stream will keep the same compression level and any other attributes
  75344. that may have been set by deflateInit2.
  75345. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  75346. stream state was inconsistent (such as zalloc or state being NULL).
  75347. */
  75348. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  75349. int level,
  75350. int strategy));
  75351. /*
  75352. Dynamically update the compression level and compression strategy. The
  75353. interpretation of level and strategy is as in deflateInit2. This can be
  75354. used to switch between compression and straight copy of the input data, or
  75355. to switch to a different kind of input data requiring a different
  75356. strategy. If the compression level is changed, the input available so far
  75357. is compressed with the old level (and may be flushed); the new level will
  75358. take effect only at the next call of deflate().
  75359. Before the call of deflateParams, the stream state must be set as for
  75360. a call of deflate(), since the currently available input may have to
  75361. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  75362. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  75363. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  75364. if strm->avail_out was zero.
  75365. */
  75366. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  75367. int good_length,
  75368. int max_lazy,
  75369. int nice_length,
  75370. int max_chain));
  75371. /*
  75372. Fine tune deflate's internal compression parameters. This should only be
  75373. used by someone who understands the algorithm used by zlib's deflate for
  75374. searching for the best matching string, and even then only by the most
  75375. fanatic optimizer trying to squeeze out the last compressed bit for their
  75376. specific input data. Read the deflate.c source code for the meaning of the
  75377. max_lazy, good_length, nice_length, and max_chain parameters.
  75378. deflateTune() can be called after deflateInit() or deflateInit2(), and
  75379. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  75380. */
  75381. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  75382. uLong sourceLen));
  75383. /*
  75384. deflateBound() returns an upper bound on the compressed size after
  75385. deflation of sourceLen bytes. It must be called after deflateInit()
  75386. or deflateInit2(). This would be used to allocate an output buffer
  75387. for deflation in a single pass, and so would be called before deflate().
  75388. */
  75389. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  75390. int bits,
  75391. int value));
  75392. /*
  75393. deflatePrime() inserts bits in the deflate output stream. The intent
  75394. is that this function is used to start off the deflate output with the
  75395. bits leftover from a previous deflate stream when appending to it. As such,
  75396. this function can only be used for raw deflate, and must be used before the
  75397. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  75398. less than or equal to 16, and that many of the least significant bits of
  75399. value will be inserted in the output.
  75400. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  75401. stream state was inconsistent.
  75402. */
  75403. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  75404. gz_headerp head));
  75405. /*
  75406. deflateSetHeader() provides gzip header information for when a gzip
  75407. stream is requested by deflateInit2(). deflateSetHeader() may be called
  75408. after deflateInit2() or deflateReset() and before the first call of
  75409. deflate(). The text, time, os, extra field, name, and comment information
  75410. in the provided gz_header structure are written to the gzip header (xflag is
  75411. ignored -- the extra flags are set according to the compression level). The
  75412. caller must assure that, if not Z_NULL, name and comment are terminated with
  75413. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  75414. available there. If hcrc is true, a gzip header crc is included. Note that
  75415. the current versions of the command-line version of gzip (up through version
  75416. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  75417. gzip file" and give up.
  75418. If deflateSetHeader is not used, the default gzip header has text false,
  75419. the time set to zero, and os set to 255, with no extra, name, or comment
  75420. fields. The gzip header is returned to the default state by deflateReset().
  75421. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  75422. stream state was inconsistent.
  75423. */
  75424. /*
  75425. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  75426. int windowBits));
  75427. This is another version of inflateInit with an extra parameter. The
  75428. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  75429. before by the caller.
  75430. The windowBits parameter is the base two logarithm of the maximum window
  75431. size (the size of the history buffer). It should be in the range 8..15 for
  75432. this version of the library. The default value is 15 if inflateInit is used
  75433. instead. windowBits must be greater than or equal to the windowBits value
  75434. provided to deflateInit2() while compressing, or it must be equal to 15 if
  75435. deflateInit2() was not used. If a compressed stream with a larger window
  75436. size is given as input, inflate() will return with the error code
  75437. Z_DATA_ERROR instead of trying to allocate a larger window.
  75438. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  75439. determines the window size. inflate() will then process raw deflate data,
  75440. not looking for a zlib or gzip header, not generating a check value, and not
  75441. looking for any check values for comparison at the end of the stream. This
  75442. is for use with other formats that use the deflate compressed data format
  75443. such as zip. Those formats provide their own check values. If a custom
  75444. format is developed using the raw deflate format for compressed data, it is
  75445. recommended that a check value such as an adler32 or a crc32 be applied to
  75446. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  75447. most applications, the zlib format should be used as is. Note that comments
  75448. above on the use in deflateInit2() applies to the magnitude of windowBits.
  75449. windowBits can also be greater than 15 for optional gzip decoding. Add
  75450. 32 to windowBits to enable zlib and gzip decoding with automatic header
  75451. detection, or add 16 to decode only the gzip format (the zlib format will
  75452. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  75453. a crc32 instead of an adler32.
  75454. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75455. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  75456. is set to null if there is no error message. inflateInit2 does not perform
  75457. any decompression apart from reading the zlib header if present: this will
  75458. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  75459. and avail_out are unchanged.)
  75460. */
  75461. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  75462. const Bytef *dictionary,
  75463. uInt dictLength));
  75464. /*
  75465. Initializes the decompression dictionary from the given uncompressed byte
  75466. sequence. This function must be called immediately after a call of inflate,
  75467. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  75468. can be determined from the adler32 value returned by that call of inflate.
  75469. The compressor and decompressor must use exactly the same dictionary (see
  75470. deflateSetDictionary). For raw inflate, this function can be called
  75471. immediately after inflateInit2() or inflateReset() and before any call of
  75472. inflate() to set the dictionary. The application must insure that the
  75473. dictionary that was used for compression is provided.
  75474. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  75475. parameter is invalid (such as NULL dictionary) or the stream state is
  75476. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  75477. expected one (incorrect adler32 value). inflateSetDictionary does not
  75478. perform any decompression: this will be done by subsequent calls of
  75479. inflate().
  75480. */
  75481. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  75482. /*
  75483. Skips invalid compressed data until a full flush point (see above the
  75484. description of deflate with Z_FULL_FLUSH) can be found, or until all
  75485. available input is skipped. No output is provided.
  75486. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  75487. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  75488. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  75489. case, the application may save the current current value of total_in which
  75490. indicates where valid compressed data was found. In the error case, the
  75491. application may repeatedly call inflateSync, providing more input each time,
  75492. until success or end of the input data.
  75493. */
  75494. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  75495. z_streamp source));
  75496. /*
  75497. Sets the destination stream as a complete copy of the source stream.
  75498. This function can be useful when randomly accessing a large stream. The
  75499. first pass through the stream can periodically record the inflate state,
  75500. allowing restarting inflate at those points when randomly accessing the
  75501. stream.
  75502. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  75503. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  75504. (such as zalloc being NULL). msg is left unchanged in both source and
  75505. destination.
  75506. */
  75507. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  75508. /*
  75509. This function is equivalent to inflateEnd followed by inflateInit,
  75510. but does not free and reallocate all the internal decompression state.
  75511. The stream will keep attributes that may have been set by inflateInit2.
  75512. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  75513. stream state was inconsistent (such as zalloc or state being NULL).
  75514. */
  75515. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  75516. int bits,
  75517. int value));
  75518. /*
  75519. This function inserts bits in the inflate input stream. The intent is
  75520. that this function is used to start inflating at a bit position in the
  75521. middle of a byte. The provided bits will be used before any bytes are used
  75522. from next_in. This function should only be used with raw inflate, and
  75523. should be used before the first inflate() call after inflateInit2() or
  75524. inflateReset(). bits must be less than or equal to 16, and that many of the
  75525. least significant bits of value will be inserted in the input.
  75526. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  75527. stream state was inconsistent.
  75528. */
  75529. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  75530. gz_headerp head));
  75531. /*
  75532. inflateGetHeader() requests that gzip header information be stored in the
  75533. provided gz_header structure. inflateGetHeader() may be called after
  75534. inflateInit2() or inflateReset(), and before the first call of inflate().
  75535. As inflate() processes the gzip stream, head->done is zero until the header
  75536. is completed, at which time head->done is set to one. If a zlib stream is
  75537. being decoded, then head->done is set to -1 to indicate that there will be
  75538. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  75539. force inflate() to return immediately after header processing is complete
  75540. and before any actual data is decompressed.
  75541. The text, time, xflags, and os fields are filled in with the gzip header
  75542. contents. hcrc is set to true if there is a header CRC. (The header CRC
  75543. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  75544. contains the maximum number of bytes to write to extra. Once done is true,
  75545. extra_len contains the actual extra field length, and extra contains the
  75546. extra field, or that field truncated if extra_max is less than extra_len.
  75547. If name is not Z_NULL, then up to name_max characters are written there,
  75548. terminated with a zero unless the length is greater than name_max. If
  75549. comment is not Z_NULL, then up to comm_max characters are written there,
  75550. terminated with a zero unless the length is greater than comm_max. When
  75551. any of extra, name, or comment are not Z_NULL and the respective field is
  75552. not present in the header, then that field is set to Z_NULL to signal its
  75553. absence. This allows the use of deflateSetHeader() with the returned
  75554. structure to duplicate the header. However if those fields are set to
  75555. allocated memory, then the application will need to save those pointers
  75556. elsewhere so that they can be eventually freed.
  75557. If inflateGetHeader is not used, then the header information is simply
  75558. discarded. The header is always checked for validity, including the header
  75559. CRC if present. inflateReset() will reset the process to discard the header
  75560. information. The application would need to call inflateGetHeader() again to
  75561. retrieve the header from the next gzip stream.
  75562. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  75563. stream state was inconsistent.
  75564. */
  75565. /*
  75566. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  75567. unsigned char FAR *window));
  75568. Initialize the internal stream state for decompression using inflateBack()
  75569. calls. The fields zalloc, zfree and opaque in strm must be initialized
  75570. before the call. If zalloc and zfree are Z_NULL, then the default library-
  75571. derived memory allocation routines are used. windowBits is the base two
  75572. logarithm of the window size, in the range 8..15. window is a caller
  75573. supplied buffer of that size. Except for special applications where it is
  75574. assured that deflate was used with small window sizes, windowBits must be 15
  75575. and a 32K byte window must be supplied to be able to decompress general
  75576. deflate streams.
  75577. See inflateBack() for the usage of these routines.
  75578. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  75579. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  75580. be allocated, or Z_VERSION_ERROR if the version of the library does not
  75581. match the version of the header file.
  75582. */
  75583. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  75584. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  75585. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  75586. in_func in, void FAR *in_desc,
  75587. out_func out, void FAR *out_desc));
  75588. /*
  75589. inflateBack() does a raw inflate with a single call using a call-back
  75590. interface for input and output. This is more efficient than inflate() for
  75591. file i/o applications in that it avoids copying between the output and the
  75592. sliding window by simply making the window itself the output buffer. This
  75593. function trusts the application to not change the output buffer passed by
  75594. the output function, at least until inflateBack() returns.
  75595. inflateBackInit() must be called first to allocate the internal state
  75596. and to initialize the state with the user-provided window buffer.
  75597. inflateBack() may then be used multiple times to inflate a complete, raw
  75598. deflate stream with each call. inflateBackEnd() is then called to free
  75599. the allocated state.
  75600. A raw deflate stream is one with no zlib or gzip header or trailer.
  75601. This routine would normally be used in a utility that reads zip or gzip
  75602. files and writes out uncompressed files. The utility would decode the
  75603. header and process the trailer on its own, hence this routine expects
  75604. only the raw deflate stream to decompress. This is different from the
  75605. normal behavior of inflate(), which expects either a zlib or gzip header and
  75606. trailer around the deflate stream.
  75607. inflateBack() uses two subroutines supplied by the caller that are then
  75608. called by inflateBack() for input and output. inflateBack() calls those
  75609. routines until it reads a complete deflate stream and writes out all of the
  75610. uncompressed data, or until it encounters an error. The function's
  75611. parameters and return types are defined above in the in_func and out_func
  75612. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  75613. number of bytes of provided input, and a pointer to that input in buf. If
  75614. there is no input available, in() must return zero--buf is ignored in that
  75615. case--and inflateBack() will return a buffer error. inflateBack() will call
  75616. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  75617. should return zero on success, or non-zero on failure. If out() returns
  75618. non-zero, inflateBack() will return with an error. Neither in() nor out()
  75619. are permitted to change the contents of the window provided to
  75620. inflateBackInit(), which is also the buffer that out() uses to write from.
  75621. The length written by out() will be at most the window size. Any non-zero
  75622. amount of input may be provided by in().
  75623. For convenience, inflateBack() can be provided input on the first call by
  75624. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  75625. in() will be called. Therefore strm->next_in must be initialized before
  75626. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  75627. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  75628. must also be initialized, and then if strm->avail_in is not zero, input will
  75629. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  75630. The in_desc and out_desc parameters of inflateBack() is passed as the
  75631. first parameter of in() and out() respectively when they are called. These
  75632. descriptors can be optionally used to pass any information that the caller-
  75633. supplied in() and out() functions need to do their job.
  75634. On return, inflateBack() will set strm->next_in and strm->avail_in to
  75635. pass back any unused input that was provided by the last in() call. The
  75636. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  75637. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  75638. error in the deflate stream (in which case strm->msg is set to indicate the
  75639. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  75640. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  75641. distinguished using strm->next_in which will be Z_NULL only if in() returned
  75642. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  75643. out() returning non-zero. (in() will always be called before out(), so
  75644. strm->next_in is assured to be defined if out() returns non-zero.) Note
  75645. that inflateBack() cannot return Z_OK.
  75646. */
  75647. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  75648. /*
  75649. All memory allocated by inflateBackInit() is freed.
  75650. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  75651. state was inconsistent.
  75652. */
  75653. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  75654. /* Return flags indicating compile-time options.
  75655. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  75656. 1.0: size of uInt
  75657. 3.2: size of uLong
  75658. 5.4: size of voidpf (pointer)
  75659. 7.6: size of z_off_t
  75660. Compiler, assembler, and debug options:
  75661. 8: DEBUG
  75662. 9: ASMV or ASMINF -- use ASM code
  75663. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  75664. 11: 0 (reserved)
  75665. One-time table building (smaller code, but not thread-safe if true):
  75666. 12: BUILDFIXED -- build static block decoding tables when needed
  75667. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  75668. 14,15: 0 (reserved)
  75669. Library content (indicates missing functionality):
  75670. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  75671. deflate code when not needed)
  75672. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  75673. and decode gzip streams (to avoid linking crc code)
  75674. 18-19: 0 (reserved)
  75675. Operation variations (changes in library functionality):
  75676. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  75677. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  75678. 22,23: 0 (reserved)
  75679. The sprintf variant used by gzprintf (zero is best):
  75680. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  75681. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  75682. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  75683. Remainder:
  75684. 27-31: 0 (reserved)
  75685. */
  75686. /* utility functions */
  75687. /*
  75688. The following utility functions are implemented on top of the
  75689. basic stream-oriented functions. To simplify the interface, some
  75690. default options are assumed (compression level and memory usage,
  75691. standard memory allocation functions). The source code of these
  75692. utility functions can easily be modified if you need special options.
  75693. */
  75694. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  75695. const Bytef *source, uLong sourceLen));
  75696. /*
  75697. Compresses the source buffer into the destination buffer. sourceLen is
  75698. the byte length of the source buffer. Upon entry, destLen is the total
  75699. size of the destination buffer, which must be at least the value returned
  75700. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  75701. compressed buffer.
  75702. This function can be used to compress a whole file at once if the
  75703. input file is mmap'ed.
  75704. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  75705. enough memory, Z_BUF_ERROR if there was not enough room in the output
  75706. buffer.
  75707. */
  75708. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  75709. const Bytef *source, uLong sourceLen,
  75710. int level));
  75711. /*
  75712. Compresses the source buffer into the destination buffer. The level
  75713. parameter has the same meaning as in deflateInit. sourceLen is the byte
  75714. length of the source buffer. Upon entry, destLen is the total size of the
  75715. destination buffer, which must be at least the value returned by
  75716. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  75717. compressed buffer.
  75718. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75719. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  75720. Z_STREAM_ERROR if the level parameter is invalid.
  75721. */
  75722. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  75723. /*
  75724. compressBound() returns an upper bound on the compressed size after
  75725. compress() or compress2() on sourceLen bytes. It would be used before
  75726. a compress() or compress2() call to allocate the destination buffer.
  75727. */
  75728. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  75729. const Bytef *source, uLong sourceLen));
  75730. /*
  75731. Decompresses the source buffer into the destination buffer. sourceLen is
  75732. the byte length of the source buffer. Upon entry, destLen is the total
  75733. size of the destination buffer, which must be large enough to hold the
  75734. entire uncompressed data. (The size of the uncompressed data must have
  75735. been saved previously by the compressor and transmitted to the decompressor
  75736. by some mechanism outside the scope of this compression library.)
  75737. Upon exit, destLen is the actual size of the compressed buffer.
  75738. This function can be used to decompress a whole file at once if the
  75739. input file is mmap'ed.
  75740. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  75741. enough memory, Z_BUF_ERROR if there was not enough room in the output
  75742. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  75743. */
  75744. typedef voidp gzFile;
  75745. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  75746. /*
  75747. Opens a gzip (.gz) file for reading or writing. The mode parameter
  75748. is as in fopen ("rb" or "wb") but can also include a compression level
  75749. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  75750. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  75751. as in "wb1R". (See the description of deflateInit2 for more information
  75752. about the strategy parameter.)
  75753. gzopen can be used to read a file which is not in gzip format; in this
  75754. case gzread will directly read from the file without decompression.
  75755. gzopen returns NULL if the file could not be opened or if there was
  75756. insufficient memory to allocate the (de)compression state; errno
  75757. can be checked to distinguish the two cases (if errno is zero, the
  75758. zlib error is Z_MEM_ERROR). */
  75759. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  75760. /*
  75761. gzdopen() associates a gzFile with the file descriptor fd. File
  75762. descriptors are obtained from calls like open, dup, creat, pipe or
  75763. fileno (in the file has been previously opened with fopen).
  75764. The mode parameter is as in gzopen.
  75765. The next call of gzclose on the returned gzFile will also close the
  75766. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  75767. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  75768. gzdopen returns NULL if there was insufficient memory to allocate
  75769. the (de)compression state.
  75770. */
  75771. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  75772. /*
  75773. Dynamically update the compression level or strategy. See the description
  75774. of deflateInit2 for the meaning of these parameters.
  75775. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  75776. opened for writing.
  75777. */
  75778. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  75779. /*
  75780. Reads the given number of uncompressed bytes from the compressed file.
  75781. If the input file was not in gzip format, gzread copies the given number
  75782. of bytes into the buffer.
  75783. gzread returns the number of uncompressed bytes actually read (0 for
  75784. end of file, -1 for error). */
  75785. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  75786. voidpc buf, unsigned len));
  75787. /*
  75788. Writes the given number of uncompressed bytes into the compressed file.
  75789. gzwrite returns the number of uncompressed bytes actually written
  75790. (0 in case of error).
  75791. */
  75792. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  75793. /*
  75794. Converts, formats, and writes the args to the compressed file under
  75795. control of the format string, as in fprintf. gzprintf returns the number of
  75796. uncompressed bytes actually written (0 in case of error). The number of
  75797. uncompressed bytes written is limited to 4095. The caller should assure that
  75798. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  75799. return an error (0) with nothing written. In this case, there may also be a
  75800. buffer overflow with unpredictable consequences, which is possible only if
  75801. zlib was compiled with the insecure functions sprintf() or vsprintf()
  75802. because the secure snprintf() or vsnprintf() functions were not available.
  75803. */
  75804. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  75805. /*
  75806. Writes the given null-terminated string to the compressed file, excluding
  75807. the terminating null character.
  75808. gzputs returns the number of characters written, or -1 in case of error.
  75809. */
  75810. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  75811. /*
  75812. Reads bytes from the compressed file until len-1 characters are read, or
  75813. a newline character is read and transferred to buf, or an end-of-file
  75814. condition is encountered. The string is then terminated with a null
  75815. character.
  75816. gzgets returns buf, or Z_NULL in case of error.
  75817. */
  75818. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  75819. /*
  75820. Writes c, converted to an unsigned char, into the compressed file.
  75821. gzputc returns the value that was written, or -1 in case of error.
  75822. */
  75823. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  75824. /*
  75825. Reads one byte from the compressed file. gzgetc returns this byte
  75826. or -1 in case of end of file or error.
  75827. */
  75828. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  75829. /*
  75830. Push one character back onto the stream to be read again later.
  75831. Only one character of push-back is allowed. gzungetc() returns the
  75832. character pushed, or -1 on failure. gzungetc() will fail if a
  75833. character has been pushed but not read yet, or if c is -1. The pushed
  75834. character will be discarded if the stream is repositioned with gzseek()
  75835. or gzrewind().
  75836. */
  75837. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  75838. /*
  75839. Flushes all pending output into the compressed file. The parameter
  75840. flush is as in the deflate() function. The return value is the zlib
  75841. error number (see function gzerror below). gzflush returns Z_OK if
  75842. the flush parameter is Z_FINISH and all output could be flushed.
  75843. gzflush should be called only when strictly necessary because it can
  75844. degrade compression.
  75845. */
  75846. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  75847. z_off_t offset, int whence));
  75848. /*
  75849. Sets the starting position for the next gzread or gzwrite on the
  75850. given compressed file. The offset represents a number of bytes in the
  75851. uncompressed data stream. The whence parameter is defined as in lseek(2);
  75852. the value SEEK_END is not supported.
  75853. If the file is opened for reading, this function is emulated but can be
  75854. extremely slow. If the file is opened for writing, only forward seeks are
  75855. supported; gzseek then compresses a sequence of zeroes up to the new
  75856. starting position.
  75857. gzseek returns the resulting offset location as measured in bytes from
  75858. the beginning of the uncompressed stream, or -1 in case of error, in
  75859. particular if the file is opened for writing and the new starting position
  75860. would be before the current position.
  75861. */
  75862. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  75863. /*
  75864. Rewinds the given file. This function is supported only for reading.
  75865. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  75866. */
  75867. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  75868. /*
  75869. Returns the starting position for the next gzread or gzwrite on the
  75870. given compressed file. This position represents a number of bytes in the
  75871. uncompressed data stream.
  75872. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  75873. */
  75874. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  75875. /*
  75876. Returns 1 when EOF has previously been detected reading the given
  75877. input stream, otherwise zero.
  75878. */
  75879. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  75880. /*
  75881. Returns 1 if file is being read directly without decompression, otherwise
  75882. zero.
  75883. */
  75884. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  75885. /*
  75886. Flushes all pending output if necessary, closes the compressed file
  75887. and deallocates all the (de)compression state. The return value is the zlib
  75888. error number (see function gzerror below).
  75889. */
  75890. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  75891. /*
  75892. Returns the error message for the last error which occurred on the
  75893. given compressed file. errnum is set to zlib error number. If an
  75894. error occurred in the file system and not in the compression library,
  75895. errnum is set to Z_ERRNO and the application may consult errno
  75896. to get the exact error code.
  75897. */
  75898. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  75899. /*
  75900. Clears the error and end-of-file flags for file. This is analogous to the
  75901. clearerr() function in stdio. This is useful for continuing to read a gzip
  75902. file that is being written concurrently.
  75903. */
  75904. /* checksum functions */
  75905. /*
  75906. These functions are not related to compression but are exported
  75907. anyway because they might be useful in applications using the
  75908. compression library.
  75909. */
  75910. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  75911. /*
  75912. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  75913. return the updated checksum. If buf is NULL, this function returns
  75914. the required initial value for the checksum.
  75915. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  75916. much faster. Usage example:
  75917. uLong adler = adler32(0L, Z_NULL, 0);
  75918. while (read_buffer(buffer, length) != EOF) {
  75919. adler = adler32(adler, buffer, length);
  75920. }
  75921. if (adler != original_adler) error();
  75922. */
  75923. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  75924. z_off_t len2));
  75925. /*
  75926. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  75927. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  75928. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  75929. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  75930. */
  75931. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  75932. /*
  75933. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  75934. updated CRC-32. If buf is NULL, this function returns the required initial
  75935. value for the for the crc. Pre- and post-conditioning (one's complement) is
  75936. performed within this function so it shouldn't be done by the application.
  75937. Usage example:
  75938. uLong crc = crc32(0L, Z_NULL, 0);
  75939. while (read_buffer(buffer, length) != EOF) {
  75940. crc = crc32(crc, buffer, length);
  75941. }
  75942. if (crc != original_crc) error();
  75943. */
  75944. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  75945. /*
  75946. Combine two CRC-32 check values into one. For two sequences of bytes,
  75947. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  75948. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  75949. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  75950. len2.
  75951. */
  75952. /* various hacks, don't look :) */
  75953. /* deflateInit and inflateInit are macros to allow checking the zlib version
  75954. * and the compiler's view of z_stream:
  75955. */
  75956. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  75957. const char *version, int stream_size));
  75958. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  75959. const char *version, int stream_size));
  75960. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  75961. int windowBits, int memLevel,
  75962. int strategy, const char *version,
  75963. int stream_size));
  75964. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  75965. const char *version, int stream_size));
  75966. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  75967. unsigned char FAR *window,
  75968. const char *version,
  75969. int stream_size));
  75970. #define deflateInit(strm, level) \
  75971. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  75972. #define inflateInit(strm) \
  75973. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  75974. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  75975. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  75976. (strategy), ZLIB_VERSION, sizeof(z_stream))
  75977. #define inflateInit2(strm, windowBits) \
  75978. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  75979. #define inflateBackInit(strm, windowBits, window) \
  75980. inflateBackInit_((strm), (windowBits), (window), \
  75981. ZLIB_VERSION, sizeof(z_stream))
  75982. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  75983. struct internal_state {int dummy;}; /* hack for buggy compilers */
  75984. #endif
  75985. ZEXTERN const char * ZEXPORT zError OF((int));
  75986. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  75987. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  75988. #ifdef __cplusplus
  75989. }
  75990. #endif
  75991. #endif /* ZLIB_H */
  75992. /*** End of inlined file: zlib.h ***/
  75993. #undef OS_CODE
  75994. #else
  75995. #include <zlib.h>
  75996. #endif
  75997. }
  75998. BEGIN_JUCE_NAMESPACE
  75999. // internal helper object that holds the zlib structures so they don't have to be
  76000. // included publicly.
  76001. class GZIPCompressorHelper
  76002. {
  76003. public:
  76004. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  76005. : data (0),
  76006. dataSize (0),
  76007. compLevel (compressionLevel),
  76008. strategy (0),
  76009. setParams (true),
  76010. streamIsValid (false),
  76011. finished (false),
  76012. shouldFinish (false)
  76013. {
  76014. using namespace zlibNamespace;
  76015. zerostruct (stream);
  76016. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  76017. nowrap ? -MAX_WBITS : MAX_WBITS,
  76018. 8, strategy) == Z_OK);
  76019. }
  76020. ~GZIPCompressorHelper()
  76021. {
  76022. using namespace zlibNamespace;
  76023. if (streamIsValid)
  76024. deflateEnd (&stream);
  76025. }
  76026. bool needsInput() const throw()
  76027. {
  76028. return dataSize <= 0;
  76029. }
  76030. void setInput (const uint8* const newData, const int size) throw()
  76031. {
  76032. data = newData;
  76033. dataSize = size;
  76034. }
  76035. int doNextBlock (uint8* const dest, const int destSize) throw()
  76036. {
  76037. using namespace zlibNamespace;
  76038. if (streamIsValid)
  76039. {
  76040. stream.next_in = const_cast <uint8*> (data);
  76041. stream.next_out = dest;
  76042. stream.avail_in = dataSize;
  76043. stream.avail_out = destSize;
  76044. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  76045. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  76046. setParams = false;
  76047. switch (result)
  76048. {
  76049. case Z_STREAM_END:
  76050. finished = true;
  76051. // Deliberate fall-through..
  76052. case Z_OK:
  76053. data += dataSize - stream.avail_in;
  76054. dataSize = stream.avail_in;
  76055. return destSize - stream.avail_out;
  76056. default:
  76057. break;
  76058. }
  76059. }
  76060. return 0;
  76061. }
  76062. private:
  76063. zlibNamespace::z_stream stream;
  76064. const uint8* data;
  76065. int dataSize, compLevel, strategy;
  76066. bool setParams, streamIsValid;
  76067. public:
  76068. bool finished, shouldFinish;
  76069. };
  76070. const int gzipCompBufferSize = 32768;
  76071. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  76072. int compressionLevel,
  76073. const bool deleteDestStream,
  76074. const bool noWrap)
  76075. : destStream (destStream_),
  76076. streamToDelete (deleteDestStream ? destStream_ : 0),
  76077. buffer (gzipCompBufferSize)
  76078. {
  76079. if (compressionLevel < 1 || compressionLevel > 9)
  76080. compressionLevel = -1;
  76081. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  76082. }
  76083. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  76084. {
  76085. flush();
  76086. }
  76087. void GZIPCompressorOutputStream::flush()
  76088. {
  76089. if (! helper->finished)
  76090. {
  76091. helper->shouldFinish = true;
  76092. while (! helper->finished)
  76093. doNextBlock();
  76094. }
  76095. destStream->flush();
  76096. }
  76097. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  76098. {
  76099. if (! helper->finished)
  76100. {
  76101. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  76102. while (! helper->needsInput())
  76103. {
  76104. if (! doNextBlock())
  76105. return false;
  76106. }
  76107. }
  76108. return true;
  76109. }
  76110. bool GZIPCompressorOutputStream::doNextBlock()
  76111. {
  76112. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  76113. if (len > 0)
  76114. return destStream->write (buffer, len);
  76115. else
  76116. return true;
  76117. }
  76118. int64 GZIPCompressorOutputStream::getPosition()
  76119. {
  76120. return destStream->getPosition();
  76121. }
  76122. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  76123. {
  76124. jassertfalse // can't do it!
  76125. return false;
  76126. }
  76127. END_JUCE_NAMESPACE
  76128. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  76129. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  76130. #if JUCE_MSVC
  76131. #pragma warning (push)
  76132. #pragma warning (disable: 4309 4305)
  76133. #endif
  76134. namespace zlibNamespace
  76135. {
  76136. #if JUCE_INCLUDE_ZLIB_CODE
  76137. extern "C"
  76138. {
  76139. #undef OS_CODE
  76140. #undef fdopen
  76141. #define ZLIB_INTERNAL
  76142. #define NO_DUMMY_DECL
  76143. /*** Start of inlined file: adler32.c ***/
  76144. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76145. #define ZLIB_INTERNAL
  76146. #define BASE 65521UL /* largest prime smaller than 65536 */
  76147. #define NMAX 5552
  76148. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  76149. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  76150. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  76151. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  76152. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  76153. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  76154. /* use NO_DIVIDE if your processor does not do division in hardware */
  76155. #ifdef NO_DIVIDE
  76156. # define MOD(a) \
  76157. do { \
  76158. if (a >= (BASE << 16)) a -= (BASE << 16); \
  76159. if (a >= (BASE << 15)) a -= (BASE << 15); \
  76160. if (a >= (BASE << 14)) a -= (BASE << 14); \
  76161. if (a >= (BASE << 13)) a -= (BASE << 13); \
  76162. if (a >= (BASE << 12)) a -= (BASE << 12); \
  76163. if (a >= (BASE << 11)) a -= (BASE << 11); \
  76164. if (a >= (BASE << 10)) a -= (BASE << 10); \
  76165. if (a >= (BASE << 9)) a -= (BASE << 9); \
  76166. if (a >= (BASE << 8)) a -= (BASE << 8); \
  76167. if (a >= (BASE << 7)) a -= (BASE << 7); \
  76168. if (a >= (BASE << 6)) a -= (BASE << 6); \
  76169. if (a >= (BASE << 5)) a -= (BASE << 5); \
  76170. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76171. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76172. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76173. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76174. if (a >= BASE) a -= BASE; \
  76175. } while (0)
  76176. # define MOD4(a) \
  76177. do { \
  76178. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76179. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76180. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76181. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76182. if (a >= BASE) a -= BASE; \
  76183. } while (0)
  76184. #else
  76185. # define MOD(a) a %= BASE
  76186. # define MOD4(a) a %= BASE
  76187. #endif
  76188. /* ========================================================================= */
  76189. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  76190. {
  76191. unsigned long sum2;
  76192. unsigned n;
  76193. /* split Adler-32 into component sums */
  76194. sum2 = (adler >> 16) & 0xffff;
  76195. adler &= 0xffff;
  76196. /* in case user likes doing a byte at a time, keep it fast */
  76197. if (len == 1) {
  76198. adler += buf[0];
  76199. if (adler >= BASE)
  76200. adler -= BASE;
  76201. sum2 += adler;
  76202. if (sum2 >= BASE)
  76203. sum2 -= BASE;
  76204. return adler | (sum2 << 16);
  76205. }
  76206. /* initial Adler-32 value (deferred check for len == 1 speed) */
  76207. if (buf == Z_NULL)
  76208. return 1L;
  76209. /* in case short lengths are provided, keep it somewhat fast */
  76210. if (len < 16) {
  76211. while (len--) {
  76212. adler += *buf++;
  76213. sum2 += adler;
  76214. }
  76215. if (adler >= BASE)
  76216. adler -= BASE;
  76217. MOD4(sum2); /* only added so many BASE's */
  76218. return adler | (sum2 << 16);
  76219. }
  76220. /* do length NMAX blocks -- requires just one modulo operation */
  76221. while (len >= NMAX) {
  76222. len -= NMAX;
  76223. n = NMAX / 16; /* NMAX is divisible by 16 */
  76224. do {
  76225. DO16(buf); /* 16 sums unrolled */
  76226. buf += 16;
  76227. } while (--n);
  76228. MOD(adler);
  76229. MOD(sum2);
  76230. }
  76231. /* do remaining bytes (less than NMAX, still just one modulo) */
  76232. if (len) { /* avoid modulos if none remaining */
  76233. while (len >= 16) {
  76234. len -= 16;
  76235. DO16(buf);
  76236. buf += 16;
  76237. }
  76238. while (len--) {
  76239. adler += *buf++;
  76240. sum2 += adler;
  76241. }
  76242. MOD(adler);
  76243. MOD(sum2);
  76244. }
  76245. /* return recombined sums */
  76246. return adler | (sum2 << 16);
  76247. }
  76248. /* ========================================================================= */
  76249. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  76250. {
  76251. unsigned long sum1;
  76252. unsigned long sum2;
  76253. unsigned rem;
  76254. /* the derivation of this formula is left as an exercise for the reader */
  76255. rem = (unsigned)(len2 % BASE);
  76256. sum1 = adler1 & 0xffff;
  76257. sum2 = rem * sum1;
  76258. MOD(sum2);
  76259. sum1 += (adler2 & 0xffff) + BASE - 1;
  76260. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  76261. if (sum1 > BASE) sum1 -= BASE;
  76262. if (sum1 > BASE) sum1 -= BASE;
  76263. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  76264. if (sum2 > BASE) sum2 -= BASE;
  76265. return sum1 | (sum2 << 16);
  76266. }
  76267. /*** End of inlined file: adler32.c ***/
  76268. /*** Start of inlined file: compress.c ***/
  76269. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76270. #define ZLIB_INTERNAL
  76271. /* ===========================================================================
  76272. Compresses the source buffer into the destination buffer. The level
  76273. parameter has the same meaning as in deflateInit. sourceLen is the byte
  76274. length of the source buffer. Upon entry, destLen is the total size of the
  76275. destination buffer, which must be at least 0.1% larger than sourceLen plus
  76276. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  76277. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76278. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  76279. Z_STREAM_ERROR if the level parameter is invalid.
  76280. */
  76281. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  76282. uLong sourceLen, int level)
  76283. {
  76284. z_stream stream;
  76285. int err;
  76286. stream.next_in = (Bytef*)source;
  76287. stream.avail_in = (uInt)sourceLen;
  76288. #ifdef MAXSEG_64K
  76289. /* Check for source > 64K on 16-bit machine: */
  76290. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  76291. #endif
  76292. stream.next_out = dest;
  76293. stream.avail_out = (uInt)*destLen;
  76294. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  76295. stream.zalloc = (alloc_func)0;
  76296. stream.zfree = (free_func)0;
  76297. stream.opaque = (voidpf)0;
  76298. err = deflateInit(&stream, level);
  76299. if (err != Z_OK) return err;
  76300. err = deflate(&stream, Z_FINISH);
  76301. if (err != Z_STREAM_END) {
  76302. deflateEnd(&stream);
  76303. return err == Z_OK ? Z_BUF_ERROR : err;
  76304. }
  76305. *destLen = stream.total_out;
  76306. err = deflateEnd(&stream);
  76307. return err;
  76308. }
  76309. /* ===========================================================================
  76310. */
  76311. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  76312. {
  76313. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  76314. }
  76315. /* ===========================================================================
  76316. If the default memLevel or windowBits for deflateInit() is changed, then
  76317. this function needs to be updated.
  76318. */
  76319. uLong ZEXPORT compressBound (uLong sourceLen)
  76320. {
  76321. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  76322. }
  76323. /*** End of inlined file: compress.c ***/
  76324. #undef DO1
  76325. #undef DO8
  76326. /*** Start of inlined file: crc32.c ***/
  76327. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76328. /*
  76329. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  76330. protection on the static variables used to control the first-use generation
  76331. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  76332. first call get_crc_table() to initialize the tables before allowing more than
  76333. one thread to use crc32().
  76334. */
  76335. #ifdef MAKECRCH
  76336. # include <stdio.h>
  76337. # ifndef DYNAMIC_CRC_TABLE
  76338. # define DYNAMIC_CRC_TABLE
  76339. # endif /* !DYNAMIC_CRC_TABLE */
  76340. #endif /* MAKECRCH */
  76341. /*** Start of inlined file: zutil.h ***/
  76342. /* WARNING: this file should *not* be used by applications. It is
  76343. part of the implementation of the compression library and is
  76344. subject to change. Applications should only use zlib.h.
  76345. */
  76346. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76347. #ifndef ZUTIL_H
  76348. #define ZUTIL_H
  76349. #define ZLIB_INTERNAL
  76350. #ifdef STDC
  76351. # ifndef _WIN32_WCE
  76352. # include <stddef.h>
  76353. # endif
  76354. # include <string.h>
  76355. # include <stdlib.h>
  76356. #endif
  76357. #ifdef NO_ERRNO_H
  76358. # ifdef _WIN32_WCE
  76359. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  76360. * errno. We define it as a global variable to simplify porting.
  76361. * Its value is always 0 and should not be used. We rename it to
  76362. * avoid conflict with other libraries that use the same workaround.
  76363. */
  76364. # define errno z_errno
  76365. # endif
  76366. extern int errno;
  76367. #else
  76368. # ifndef _WIN32_WCE
  76369. # include <errno.h>
  76370. # endif
  76371. #endif
  76372. #ifndef local
  76373. # define local static
  76374. #endif
  76375. /* compile with -Dlocal if your debugger can't find static symbols */
  76376. typedef unsigned char uch;
  76377. typedef uch FAR uchf;
  76378. typedef unsigned short ush;
  76379. typedef ush FAR ushf;
  76380. typedef unsigned long ulg;
  76381. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  76382. /* (size given to avoid silly warnings with Visual C++) */
  76383. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  76384. #define ERR_RETURN(strm,err) \
  76385. return (strm->msg = (char*)ERR_MSG(err), (err))
  76386. /* To be used only when the state is known to be valid */
  76387. /* common constants */
  76388. #ifndef DEF_WBITS
  76389. # define DEF_WBITS MAX_WBITS
  76390. #endif
  76391. /* default windowBits for decompression. MAX_WBITS is for compression only */
  76392. #if MAX_MEM_LEVEL >= 8
  76393. # define DEF_MEM_LEVEL 8
  76394. #else
  76395. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  76396. #endif
  76397. /* default memLevel */
  76398. #define STORED_BLOCK 0
  76399. #define STATIC_TREES 1
  76400. #define DYN_TREES 2
  76401. /* The three kinds of block type */
  76402. #define MIN_MATCH 3
  76403. #define MAX_MATCH 258
  76404. /* The minimum and maximum match lengths */
  76405. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  76406. /* target dependencies */
  76407. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  76408. # define OS_CODE 0x00
  76409. # if defined(__TURBOC__) || defined(__BORLANDC__)
  76410. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  76411. /* Allow compilation with ANSI keywords only enabled */
  76412. void _Cdecl farfree( void *block );
  76413. void *_Cdecl farmalloc( unsigned long nbytes );
  76414. # else
  76415. # include <alloc.h>
  76416. # endif
  76417. # else /* MSC or DJGPP */
  76418. # include <malloc.h>
  76419. # endif
  76420. #endif
  76421. #ifdef AMIGA
  76422. # define OS_CODE 0x01
  76423. #endif
  76424. #if defined(VAXC) || defined(VMS)
  76425. # define OS_CODE 0x02
  76426. # define F_OPEN(name, mode) \
  76427. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  76428. #endif
  76429. #if defined(ATARI) || defined(atarist)
  76430. # define OS_CODE 0x05
  76431. #endif
  76432. #ifdef OS2
  76433. # define OS_CODE 0x06
  76434. # ifdef M_I86
  76435. #include <malloc.h>
  76436. # endif
  76437. #endif
  76438. #if defined(MACOS) || TARGET_OS_MAC
  76439. # define OS_CODE 0x07
  76440. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  76441. # include <unix.h> /* for fdopen */
  76442. # else
  76443. # ifndef fdopen
  76444. # define fdopen(fd,mode) NULL /* No fdopen() */
  76445. # endif
  76446. # endif
  76447. #endif
  76448. #ifdef TOPS20
  76449. # define OS_CODE 0x0a
  76450. #endif
  76451. #ifdef WIN32
  76452. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  76453. # define OS_CODE 0x0b
  76454. # endif
  76455. #endif
  76456. #ifdef __50SERIES /* Prime/PRIMOS */
  76457. # define OS_CODE 0x0f
  76458. #endif
  76459. #if defined(_BEOS_) || defined(RISCOS)
  76460. # define fdopen(fd,mode) NULL /* No fdopen() */
  76461. #endif
  76462. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  76463. # if defined(_WIN32_WCE)
  76464. # define fdopen(fd,mode) NULL /* No fdopen() */
  76465. # ifndef _PTRDIFF_T_DEFINED
  76466. typedef int ptrdiff_t;
  76467. # define _PTRDIFF_T_DEFINED
  76468. # endif
  76469. # else
  76470. # define fdopen(fd,type) _fdopen(fd,type)
  76471. # endif
  76472. #endif
  76473. /* common defaults */
  76474. #ifndef OS_CODE
  76475. # define OS_CODE 0x03 /* assume Unix */
  76476. #endif
  76477. #ifndef F_OPEN
  76478. # define F_OPEN(name, mode) fopen((name), (mode))
  76479. #endif
  76480. /* functions */
  76481. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  76482. # ifndef HAVE_VSNPRINTF
  76483. # define HAVE_VSNPRINTF
  76484. # endif
  76485. #endif
  76486. #if defined(__CYGWIN__)
  76487. # ifndef HAVE_VSNPRINTF
  76488. # define HAVE_VSNPRINTF
  76489. # endif
  76490. #endif
  76491. #ifndef HAVE_VSNPRINTF
  76492. # ifdef MSDOS
  76493. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  76494. but for now we just assume it doesn't. */
  76495. # define NO_vsnprintf
  76496. # endif
  76497. # ifdef __TURBOC__
  76498. # define NO_vsnprintf
  76499. # endif
  76500. # ifdef WIN32
  76501. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  76502. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  76503. # define vsnprintf _vsnprintf
  76504. # endif
  76505. # endif
  76506. # ifdef __SASC
  76507. # define NO_vsnprintf
  76508. # endif
  76509. #endif
  76510. #ifdef VMS
  76511. # define NO_vsnprintf
  76512. #endif
  76513. #if defined(pyr)
  76514. # define NO_MEMCPY
  76515. #endif
  76516. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  76517. /* Use our own functions for small and medium model with MSC <= 5.0.
  76518. * You may have to use the same strategy for Borland C (untested).
  76519. * The __SC__ check is for Symantec.
  76520. */
  76521. # define NO_MEMCPY
  76522. #endif
  76523. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  76524. # define HAVE_MEMCPY
  76525. #endif
  76526. #ifdef HAVE_MEMCPY
  76527. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  76528. # define zmemcpy _fmemcpy
  76529. # define zmemcmp _fmemcmp
  76530. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  76531. # else
  76532. # define zmemcpy memcpy
  76533. # define zmemcmp memcmp
  76534. # define zmemzero(dest, len) memset(dest, 0, len)
  76535. # endif
  76536. #else
  76537. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  76538. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  76539. extern void zmemzero OF((Bytef* dest, uInt len));
  76540. #endif
  76541. /* Diagnostic functions */
  76542. #ifdef DEBUG
  76543. # include <stdio.h>
  76544. extern int z_verbose;
  76545. extern void z_error OF((const char *m));
  76546. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  76547. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  76548. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  76549. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  76550. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  76551. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  76552. #else
  76553. # define Assert(cond,msg)
  76554. # define Trace(x)
  76555. # define Tracev(x)
  76556. # define Tracevv(x)
  76557. # define Tracec(c,x)
  76558. # define Tracecv(c,x)
  76559. #endif
  76560. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  76561. void zcfree OF((voidpf opaque, voidpf ptr));
  76562. #define ZALLOC(strm, items, size) \
  76563. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  76564. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  76565. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  76566. #endif /* ZUTIL_H */
  76567. /*** End of inlined file: zutil.h ***/
  76568. /* for STDC and FAR definitions */
  76569. #define local static
  76570. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  76571. #ifndef NOBYFOUR
  76572. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  76573. # include <limits.h>
  76574. # define BYFOUR
  76575. # if (UINT_MAX == 0xffffffffUL)
  76576. typedef unsigned int u4;
  76577. # else
  76578. # if (ULONG_MAX == 0xffffffffUL)
  76579. typedef unsigned long u4;
  76580. # else
  76581. # if (USHRT_MAX == 0xffffffffUL)
  76582. typedef unsigned short u4;
  76583. # else
  76584. # undef BYFOUR /* can't find a four-byte integer type! */
  76585. # endif
  76586. # endif
  76587. # endif
  76588. # endif /* STDC */
  76589. #endif /* !NOBYFOUR */
  76590. /* Definitions for doing the crc four data bytes at a time. */
  76591. #ifdef BYFOUR
  76592. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  76593. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  76594. local unsigned long crc32_little OF((unsigned long,
  76595. const unsigned char FAR *, unsigned));
  76596. local unsigned long crc32_big OF((unsigned long,
  76597. const unsigned char FAR *, unsigned));
  76598. # define TBLS 8
  76599. #else
  76600. # define TBLS 1
  76601. #endif /* BYFOUR */
  76602. /* Local functions for crc concatenation */
  76603. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  76604. unsigned long vec));
  76605. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  76606. #ifdef DYNAMIC_CRC_TABLE
  76607. local volatile int crc_table_empty = 1;
  76608. local unsigned long FAR crc_table[TBLS][256];
  76609. local void make_crc_table OF((void));
  76610. #ifdef MAKECRCH
  76611. local void write_table OF((FILE *, const unsigned long FAR *));
  76612. #endif /* MAKECRCH */
  76613. /*
  76614. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  76615. 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.
  76616. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  76617. with the lowest powers in the most significant bit. Then adding polynomials
  76618. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  76619. one. If we call the above polynomial p, and represent a byte as the
  76620. polynomial q, also with the lowest power in the most significant bit (so the
  76621. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  76622. where a mod b means the remainder after dividing a by b.
  76623. This calculation is done using the shift-register method of multiplying and
  76624. taking the remainder. The register is initialized to zero, and for each
  76625. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  76626. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  76627. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  76628. out is a one). We start with the highest power (least significant bit) of
  76629. q and repeat for all eight bits of q.
  76630. The first table is simply the CRC of all possible eight bit values. This is
  76631. all the information needed to generate CRCs on data a byte at a time for all
  76632. combinations of CRC register values and incoming bytes. The remaining tables
  76633. allow for word-at-a-time CRC calculation for both big-endian and little-
  76634. endian machines, where a word is four bytes.
  76635. */
  76636. local void make_crc_table()
  76637. {
  76638. unsigned long c;
  76639. int n, k;
  76640. unsigned long poly; /* polynomial exclusive-or pattern */
  76641. /* terms of polynomial defining this crc (except x^32): */
  76642. static volatile int first = 1; /* flag to limit concurrent making */
  76643. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  76644. /* See if another task is already doing this (not thread-safe, but better
  76645. than nothing -- significantly reduces duration of vulnerability in
  76646. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  76647. if (first) {
  76648. first = 0;
  76649. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  76650. poly = 0UL;
  76651. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  76652. poly |= 1UL << (31 - p[n]);
  76653. /* generate a crc for every 8-bit value */
  76654. for (n = 0; n < 256; n++) {
  76655. c = (unsigned long)n;
  76656. for (k = 0; k < 8; k++)
  76657. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  76658. crc_table[0][n] = c;
  76659. }
  76660. #ifdef BYFOUR
  76661. /* generate crc for each value followed by one, two, and three zeros,
  76662. and then the byte reversal of those as well as the first table */
  76663. for (n = 0; n < 256; n++) {
  76664. c = crc_table[0][n];
  76665. crc_table[4][n] = REV(c);
  76666. for (k = 1; k < 4; k++) {
  76667. c = crc_table[0][c & 0xff] ^ (c >> 8);
  76668. crc_table[k][n] = c;
  76669. crc_table[k + 4][n] = REV(c);
  76670. }
  76671. }
  76672. #endif /* BYFOUR */
  76673. crc_table_empty = 0;
  76674. }
  76675. else { /* not first */
  76676. /* wait for the other guy to finish (not efficient, but rare) */
  76677. while (crc_table_empty)
  76678. ;
  76679. }
  76680. #ifdef MAKECRCH
  76681. /* write out CRC tables to crc32.h */
  76682. {
  76683. FILE *out;
  76684. out = fopen("crc32.h", "w");
  76685. if (out == NULL) return;
  76686. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  76687. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  76688. fprintf(out, "local const unsigned long FAR ");
  76689. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  76690. write_table(out, crc_table[0]);
  76691. # ifdef BYFOUR
  76692. fprintf(out, "#ifdef BYFOUR\n");
  76693. for (k = 1; k < 8; k++) {
  76694. fprintf(out, " },\n {\n");
  76695. write_table(out, crc_table[k]);
  76696. }
  76697. fprintf(out, "#endif\n");
  76698. # endif /* BYFOUR */
  76699. fprintf(out, " }\n};\n");
  76700. fclose(out);
  76701. }
  76702. #endif /* MAKECRCH */
  76703. }
  76704. #ifdef MAKECRCH
  76705. local void write_table(out, table)
  76706. FILE *out;
  76707. const unsigned long FAR *table;
  76708. {
  76709. int n;
  76710. for (n = 0; n < 256; n++)
  76711. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  76712. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  76713. }
  76714. #endif /* MAKECRCH */
  76715. #else /* !DYNAMIC_CRC_TABLE */
  76716. /* ========================================================================
  76717. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  76718. */
  76719. /*** Start of inlined file: crc32.h ***/
  76720. local const unsigned long FAR crc_table[TBLS][256] =
  76721. {
  76722. {
  76723. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  76724. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  76725. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  76726. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  76727. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  76728. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  76729. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  76730. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  76731. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  76732. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  76733. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  76734. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  76735. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  76736. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  76737. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  76738. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  76739. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  76740. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  76741. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  76742. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  76743. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  76744. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  76745. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  76746. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  76747. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  76748. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  76749. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  76750. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  76751. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  76752. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  76753. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  76754. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  76755. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  76756. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  76757. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  76758. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  76759. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  76760. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  76761. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  76762. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  76763. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  76764. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  76765. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  76766. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  76767. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  76768. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  76769. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  76770. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  76771. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  76772. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  76773. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  76774. 0x2d02ef8dUL
  76775. #ifdef BYFOUR
  76776. },
  76777. {
  76778. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  76779. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  76780. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  76781. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  76782. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  76783. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  76784. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  76785. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  76786. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  76787. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  76788. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  76789. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  76790. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  76791. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  76792. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  76793. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  76794. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  76795. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  76796. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  76797. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  76798. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  76799. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  76800. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  76801. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  76802. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  76803. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  76804. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  76805. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  76806. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  76807. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  76808. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  76809. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  76810. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  76811. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  76812. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  76813. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  76814. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  76815. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  76816. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  76817. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  76818. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  76819. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  76820. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  76821. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  76822. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  76823. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  76824. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  76825. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  76826. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  76827. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  76828. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  76829. 0x9324fd72UL
  76830. },
  76831. {
  76832. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  76833. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  76834. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  76835. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  76836. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  76837. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  76838. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  76839. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  76840. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  76841. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  76842. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  76843. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  76844. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  76845. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  76846. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  76847. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  76848. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  76849. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  76850. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  76851. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  76852. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  76853. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  76854. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  76855. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  76856. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  76857. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  76858. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  76859. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  76860. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  76861. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  76862. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  76863. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  76864. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  76865. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  76866. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  76867. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  76868. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  76869. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  76870. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  76871. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  76872. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  76873. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  76874. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  76875. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  76876. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  76877. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  76878. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  76879. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  76880. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  76881. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  76882. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  76883. 0xbe9834edUL
  76884. },
  76885. {
  76886. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  76887. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  76888. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  76889. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  76890. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  76891. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  76892. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  76893. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  76894. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  76895. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  76896. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  76897. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  76898. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  76899. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  76900. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  76901. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  76902. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  76903. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  76904. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  76905. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  76906. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  76907. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  76908. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  76909. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  76910. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  76911. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  76912. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  76913. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  76914. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  76915. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  76916. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  76917. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  76918. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  76919. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  76920. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  76921. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  76922. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  76923. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  76924. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  76925. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  76926. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  76927. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  76928. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  76929. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  76930. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  76931. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  76932. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  76933. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  76934. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  76935. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  76936. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  76937. 0xde0506f1UL
  76938. },
  76939. {
  76940. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  76941. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  76942. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  76943. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  76944. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  76945. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  76946. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  76947. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  76948. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  76949. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  76950. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  76951. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  76952. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  76953. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  76954. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  76955. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  76956. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  76957. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  76958. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  76959. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  76960. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  76961. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  76962. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  76963. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  76964. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  76965. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  76966. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  76967. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  76968. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  76969. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  76970. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  76971. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  76972. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  76973. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  76974. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  76975. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  76976. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  76977. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  76978. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  76979. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  76980. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  76981. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  76982. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  76983. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  76984. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  76985. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  76986. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  76987. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  76988. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  76989. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  76990. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  76991. 0x8def022dUL
  76992. },
  76993. {
  76994. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  76995. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  76996. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  76997. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  76998. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  76999. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  77000. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  77001. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  77002. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  77003. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  77004. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  77005. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  77006. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  77007. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  77008. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  77009. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  77010. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  77011. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  77012. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  77013. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  77014. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  77015. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  77016. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  77017. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  77018. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  77019. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  77020. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  77021. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  77022. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  77023. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  77024. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  77025. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  77026. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  77027. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  77028. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  77029. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  77030. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  77031. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  77032. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  77033. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  77034. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  77035. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  77036. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  77037. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  77038. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  77039. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  77040. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  77041. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  77042. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  77043. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  77044. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  77045. 0x72fd2493UL
  77046. },
  77047. {
  77048. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  77049. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  77050. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  77051. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  77052. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  77053. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  77054. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  77055. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  77056. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  77057. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  77058. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  77059. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  77060. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  77061. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  77062. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  77063. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  77064. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  77065. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  77066. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  77067. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  77068. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  77069. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  77070. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  77071. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  77072. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  77073. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  77074. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  77075. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  77076. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  77077. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  77078. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  77079. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  77080. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  77081. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  77082. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  77083. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  77084. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  77085. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  77086. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  77087. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  77088. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  77089. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  77090. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  77091. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  77092. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  77093. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  77094. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  77095. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  77096. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  77097. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  77098. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  77099. 0xed3498beUL
  77100. },
  77101. {
  77102. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  77103. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  77104. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  77105. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  77106. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  77107. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  77108. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  77109. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  77110. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  77111. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  77112. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  77113. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  77114. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  77115. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  77116. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  77117. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  77118. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  77119. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  77120. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  77121. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  77122. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  77123. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  77124. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  77125. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  77126. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  77127. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  77128. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  77129. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  77130. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  77131. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  77132. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  77133. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  77134. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  77135. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  77136. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  77137. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  77138. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  77139. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  77140. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  77141. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  77142. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  77143. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  77144. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  77145. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  77146. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  77147. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  77148. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  77149. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  77150. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  77151. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  77152. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  77153. 0xf10605deUL
  77154. #endif
  77155. }
  77156. };
  77157. /*** End of inlined file: crc32.h ***/
  77158. #endif /* DYNAMIC_CRC_TABLE */
  77159. /* =========================================================================
  77160. * This function can be used by asm versions of crc32()
  77161. */
  77162. const unsigned long FAR * ZEXPORT get_crc_table()
  77163. {
  77164. #ifdef DYNAMIC_CRC_TABLE
  77165. if (crc_table_empty)
  77166. make_crc_table();
  77167. #endif /* DYNAMIC_CRC_TABLE */
  77168. return (const unsigned long FAR *)crc_table;
  77169. }
  77170. /* ========================================================================= */
  77171. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  77172. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  77173. /* ========================================================================= */
  77174. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77175. {
  77176. if (buf == Z_NULL) return 0UL;
  77177. #ifdef DYNAMIC_CRC_TABLE
  77178. if (crc_table_empty)
  77179. make_crc_table();
  77180. #endif /* DYNAMIC_CRC_TABLE */
  77181. #ifdef BYFOUR
  77182. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  77183. u4 endian;
  77184. endian = 1;
  77185. if (*((unsigned char *)(&endian)))
  77186. return crc32_little(crc, buf, len);
  77187. else
  77188. return crc32_big(crc, buf, len);
  77189. }
  77190. #endif /* BYFOUR */
  77191. crc = crc ^ 0xffffffffUL;
  77192. while (len >= 8) {
  77193. DO8;
  77194. len -= 8;
  77195. }
  77196. if (len) do {
  77197. DO1;
  77198. } while (--len);
  77199. return crc ^ 0xffffffffUL;
  77200. }
  77201. #ifdef BYFOUR
  77202. /* ========================================================================= */
  77203. #define DOLIT4 c ^= *buf4++; \
  77204. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  77205. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  77206. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  77207. /* ========================================================================= */
  77208. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77209. {
  77210. register u4 c;
  77211. register const u4 FAR *buf4;
  77212. c = (u4)crc;
  77213. c = ~c;
  77214. while (len && ((ptrdiff_t)buf & 3)) {
  77215. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77216. len--;
  77217. }
  77218. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77219. while (len >= 32) {
  77220. DOLIT32;
  77221. len -= 32;
  77222. }
  77223. while (len >= 4) {
  77224. DOLIT4;
  77225. len -= 4;
  77226. }
  77227. buf = (const unsigned char FAR *)buf4;
  77228. if (len) do {
  77229. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77230. } while (--len);
  77231. c = ~c;
  77232. return (unsigned long)c;
  77233. }
  77234. /* ========================================================================= */
  77235. #define DOBIG4 c ^= *++buf4; \
  77236. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  77237. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  77238. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  77239. /* ========================================================================= */
  77240. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77241. {
  77242. register u4 c;
  77243. register const u4 FAR *buf4;
  77244. c = REV((u4)crc);
  77245. c = ~c;
  77246. while (len && ((ptrdiff_t)buf & 3)) {
  77247. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77248. len--;
  77249. }
  77250. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77251. buf4--;
  77252. while (len >= 32) {
  77253. DOBIG32;
  77254. len -= 32;
  77255. }
  77256. while (len >= 4) {
  77257. DOBIG4;
  77258. len -= 4;
  77259. }
  77260. buf4++;
  77261. buf = (const unsigned char FAR *)buf4;
  77262. if (len) do {
  77263. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77264. } while (--len);
  77265. c = ~c;
  77266. return (unsigned long)(REV(c));
  77267. }
  77268. #endif /* BYFOUR */
  77269. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  77270. /* ========================================================================= */
  77271. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  77272. {
  77273. unsigned long sum;
  77274. sum = 0;
  77275. while (vec) {
  77276. if (vec & 1)
  77277. sum ^= *mat;
  77278. vec >>= 1;
  77279. mat++;
  77280. }
  77281. return sum;
  77282. }
  77283. /* ========================================================================= */
  77284. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  77285. {
  77286. int n;
  77287. for (n = 0; n < GF2_DIM; n++)
  77288. square[n] = gf2_matrix_times(mat, mat[n]);
  77289. }
  77290. /* ========================================================================= */
  77291. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  77292. {
  77293. int n;
  77294. unsigned long row;
  77295. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  77296. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  77297. /* degenerate case */
  77298. if (len2 == 0)
  77299. return crc1;
  77300. /* put operator for one zero bit in odd */
  77301. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  77302. row = 1;
  77303. for (n = 1; n < GF2_DIM; n++) {
  77304. odd[n] = row;
  77305. row <<= 1;
  77306. }
  77307. /* put operator for two zero bits in even */
  77308. gf2_matrix_square(even, odd);
  77309. /* put operator for four zero bits in odd */
  77310. gf2_matrix_square(odd, even);
  77311. /* apply len2 zeros to crc1 (first square will put the operator for one
  77312. zero byte, eight zero bits, in even) */
  77313. do {
  77314. /* apply zeros operator for this bit of len2 */
  77315. gf2_matrix_square(even, odd);
  77316. if (len2 & 1)
  77317. crc1 = gf2_matrix_times(even, crc1);
  77318. len2 >>= 1;
  77319. /* if no more bits set, then done */
  77320. if (len2 == 0)
  77321. break;
  77322. /* another iteration of the loop with odd and even swapped */
  77323. gf2_matrix_square(odd, even);
  77324. if (len2 & 1)
  77325. crc1 = gf2_matrix_times(odd, crc1);
  77326. len2 >>= 1;
  77327. /* if no more bits set, then done */
  77328. } while (len2 != 0);
  77329. /* return combined crc */
  77330. crc1 ^= crc2;
  77331. return crc1;
  77332. }
  77333. /*** End of inlined file: crc32.c ***/
  77334. /*** Start of inlined file: deflate.c ***/
  77335. /*
  77336. * ALGORITHM
  77337. *
  77338. * The "deflation" process depends on being able to identify portions
  77339. * of the input text which are identical to earlier input (within a
  77340. * sliding window trailing behind the input currently being processed).
  77341. *
  77342. * The most straightforward technique turns out to be the fastest for
  77343. * most input files: try all possible matches and select the longest.
  77344. * The key feature of this algorithm is that insertions into the string
  77345. * dictionary are very simple and thus fast, and deletions are avoided
  77346. * completely. Insertions are performed at each input character, whereas
  77347. * string matches are performed only when the previous match ends. So it
  77348. * is preferable to spend more time in matches to allow very fast string
  77349. * insertions and avoid deletions. The matching algorithm for small
  77350. * strings is inspired from that of Rabin & Karp. A brute force approach
  77351. * is used to find longer strings when a small match has been found.
  77352. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  77353. * (by Leonid Broukhis).
  77354. * A previous version of this file used a more sophisticated algorithm
  77355. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  77356. * time, but has a larger average cost, uses more memory and is patented.
  77357. * However the F&G algorithm may be faster for some highly redundant
  77358. * files if the parameter max_chain_length (described below) is too large.
  77359. *
  77360. * ACKNOWLEDGEMENTS
  77361. *
  77362. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  77363. * I found it in 'freeze' written by Leonid Broukhis.
  77364. * Thanks to many people for bug reports and testing.
  77365. *
  77366. * REFERENCES
  77367. *
  77368. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  77369. * Available in http://www.ietf.org/rfc/rfc1951.txt
  77370. *
  77371. * A description of the Rabin and Karp algorithm is given in the book
  77372. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  77373. *
  77374. * Fiala,E.R., and Greene,D.H.
  77375. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  77376. *
  77377. */
  77378. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77379. /*** Start of inlined file: deflate.h ***/
  77380. /* WARNING: this file should *not* be used by applications. It is
  77381. part of the implementation of the compression library and is
  77382. subject to change. Applications should only use zlib.h.
  77383. */
  77384. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77385. #ifndef DEFLATE_H
  77386. #define DEFLATE_H
  77387. /* define NO_GZIP when compiling if you want to disable gzip header and
  77388. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  77389. the crc code when it is not needed. For shared libraries, gzip encoding
  77390. should be left enabled. */
  77391. #ifndef NO_GZIP
  77392. # define GZIP
  77393. #endif
  77394. #define NO_DUMMY_DECL
  77395. /* ===========================================================================
  77396. * Internal compression state.
  77397. */
  77398. #define LENGTH_CODES 29
  77399. /* number of length codes, not counting the special END_BLOCK code */
  77400. #define LITERALS 256
  77401. /* number of literal bytes 0..255 */
  77402. #define L_CODES (LITERALS+1+LENGTH_CODES)
  77403. /* number of Literal or Length codes, including the END_BLOCK code */
  77404. #define D_CODES 30
  77405. /* number of distance codes */
  77406. #define BL_CODES 19
  77407. /* number of codes used to transfer the bit lengths */
  77408. #define HEAP_SIZE (2*L_CODES+1)
  77409. /* maximum heap size */
  77410. #define MAX_BITS 15
  77411. /* All codes must not exceed MAX_BITS bits */
  77412. #define INIT_STATE 42
  77413. #define EXTRA_STATE 69
  77414. #define NAME_STATE 73
  77415. #define COMMENT_STATE 91
  77416. #define HCRC_STATE 103
  77417. #define BUSY_STATE 113
  77418. #define FINISH_STATE 666
  77419. /* Stream status */
  77420. /* Data structure describing a single value and its code string. */
  77421. typedef struct ct_data_s {
  77422. union {
  77423. ush freq; /* frequency count */
  77424. ush code; /* bit string */
  77425. } fc;
  77426. union {
  77427. ush dad; /* father node in Huffman tree */
  77428. ush len; /* length of bit string */
  77429. } dl;
  77430. } FAR ct_data;
  77431. #define Freq fc.freq
  77432. #define Code fc.code
  77433. #define Dad dl.dad
  77434. #define Len dl.len
  77435. typedef struct static_tree_desc_s static_tree_desc;
  77436. typedef struct tree_desc_s {
  77437. ct_data *dyn_tree; /* the dynamic tree */
  77438. int max_code; /* largest code with non zero frequency */
  77439. static_tree_desc *stat_desc; /* the corresponding static tree */
  77440. } FAR tree_desc;
  77441. typedef ush Pos;
  77442. typedef Pos FAR Posf;
  77443. typedef unsigned IPos;
  77444. /* A Pos is an index in the character window. We use short instead of int to
  77445. * save space in the various tables. IPos is used only for parameter passing.
  77446. */
  77447. typedef struct internal_state {
  77448. z_streamp strm; /* pointer back to this zlib stream */
  77449. int status; /* as the name implies */
  77450. Bytef *pending_buf; /* output still pending */
  77451. ulg pending_buf_size; /* size of pending_buf */
  77452. Bytef *pending_out; /* next pending byte to output to the stream */
  77453. uInt pending; /* nb of bytes in the pending buffer */
  77454. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  77455. gz_headerp gzhead; /* gzip header information to write */
  77456. uInt gzindex; /* where in extra, name, or comment */
  77457. Byte method; /* STORED (for zip only) or DEFLATED */
  77458. int last_flush; /* value of flush param for previous deflate call */
  77459. /* used by deflate.c: */
  77460. uInt w_size; /* LZ77 window size (32K by default) */
  77461. uInt w_bits; /* log2(w_size) (8..16) */
  77462. uInt w_mask; /* w_size - 1 */
  77463. Bytef *window;
  77464. /* Sliding window. Input bytes are read into the second half of the window,
  77465. * and move to the first half later to keep a dictionary of at least wSize
  77466. * bytes. With this organization, matches are limited to a distance of
  77467. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  77468. * performed with a length multiple of the block size. Also, it limits
  77469. * the window size to 64K, which is quite useful on MSDOS.
  77470. * To do: use the user input buffer as sliding window.
  77471. */
  77472. ulg window_size;
  77473. /* Actual size of window: 2*wSize, except when the user input buffer
  77474. * is directly used as sliding window.
  77475. */
  77476. Posf *prev;
  77477. /* Link to older string with same hash index. To limit the size of this
  77478. * array to 64K, this link is maintained only for the last 32K strings.
  77479. * An index in this array is thus a window index modulo 32K.
  77480. */
  77481. Posf *head; /* Heads of the hash chains or NIL. */
  77482. uInt ins_h; /* hash index of string to be inserted */
  77483. uInt hash_size; /* number of elements in hash table */
  77484. uInt hash_bits; /* log2(hash_size) */
  77485. uInt hash_mask; /* hash_size-1 */
  77486. uInt hash_shift;
  77487. /* Number of bits by which ins_h must be shifted at each input
  77488. * step. It must be such that after MIN_MATCH steps, the oldest
  77489. * byte no longer takes part in the hash key, that is:
  77490. * hash_shift * MIN_MATCH >= hash_bits
  77491. */
  77492. long block_start;
  77493. /* Window position at the beginning of the current output block. Gets
  77494. * negative when the window is moved backwards.
  77495. */
  77496. uInt match_length; /* length of best match */
  77497. IPos prev_match; /* previous match */
  77498. int match_available; /* set if previous match exists */
  77499. uInt strstart; /* start of string to insert */
  77500. uInt match_start; /* start of matching string */
  77501. uInt lookahead; /* number of valid bytes ahead in window */
  77502. uInt prev_length;
  77503. /* Length of the best match at previous step. Matches not greater than this
  77504. * are discarded. This is used in the lazy match evaluation.
  77505. */
  77506. uInt max_chain_length;
  77507. /* To speed up deflation, hash chains are never searched beyond this
  77508. * length. A higher limit improves compression ratio but degrades the
  77509. * speed.
  77510. */
  77511. uInt max_lazy_match;
  77512. /* Attempt to find a better match only when the current match is strictly
  77513. * smaller than this value. This mechanism is used only for compression
  77514. * levels >= 4.
  77515. */
  77516. # define max_insert_length max_lazy_match
  77517. /* Insert new strings in the hash table only if the match length is not
  77518. * greater than this length. This saves time but degrades compression.
  77519. * max_insert_length is used only for compression levels <= 3.
  77520. */
  77521. int level; /* compression level (1..9) */
  77522. int strategy; /* favor or force Huffman coding*/
  77523. uInt good_match;
  77524. /* Use a faster search when the previous match is longer than this */
  77525. int nice_match; /* Stop searching when current match exceeds this */
  77526. /* used by trees.c: */
  77527. /* Didn't use ct_data typedef below to supress compiler warning */
  77528. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  77529. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  77530. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  77531. struct tree_desc_s l_desc; /* desc. for literal tree */
  77532. struct tree_desc_s d_desc; /* desc. for distance tree */
  77533. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  77534. ush bl_count[MAX_BITS+1];
  77535. /* number of codes at each bit length for an optimal tree */
  77536. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  77537. int heap_len; /* number of elements in the heap */
  77538. int heap_max; /* element of largest frequency */
  77539. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  77540. * The same heap array is used to build all trees.
  77541. */
  77542. uch depth[2*L_CODES+1];
  77543. /* Depth of each subtree used as tie breaker for trees of equal frequency
  77544. */
  77545. uchf *l_buf; /* buffer for literals or lengths */
  77546. uInt lit_bufsize;
  77547. /* Size of match buffer for literals/lengths. There are 4 reasons for
  77548. * limiting lit_bufsize to 64K:
  77549. * - frequencies can be kept in 16 bit counters
  77550. * - if compression is not successful for the first block, all input
  77551. * data is still in the window so we can still emit a stored block even
  77552. * when input comes from standard input. (This can also be done for
  77553. * all blocks if lit_bufsize is not greater than 32K.)
  77554. * - if compression is not successful for a file smaller than 64K, we can
  77555. * even emit a stored file instead of a stored block (saving 5 bytes).
  77556. * This is applicable only for zip (not gzip or zlib).
  77557. * - creating new Huffman trees less frequently may not provide fast
  77558. * adaptation to changes in the input data statistics. (Take for
  77559. * example a binary file with poorly compressible code followed by
  77560. * a highly compressible string table.) Smaller buffer sizes give
  77561. * fast adaptation but have of course the overhead of transmitting
  77562. * trees more frequently.
  77563. * - I can't count above 4
  77564. */
  77565. uInt last_lit; /* running index in l_buf */
  77566. ushf *d_buf;
  77567. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  77568. * the same number of elements. To use different lengths, an extra flag
  77569. * array would be necessary.
  77570. */
  77571. ulg opt_len; /* bit length of current block with optimal trees */
  77572. ulg static_len; /* bit length of current block with static trees */
  77573. uInt matches; /* number of string matches in current block */
  77574. int last_eob_len; /* bit length of EOB code for last block */
  77575. #ifdef DEBUG
  77576. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  77577. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  77578. #endif
  77579. ush bi_buf;
  77580. /* Output buffer. bits are inserted starting at the bottom (least
  77581. * significant bits).
  77582. */
  77583. int bi_valid;
  77584. /* Number of valid bits in bi_buf. All bits above the last valid bit
  77585. * are always zero.
  77586. */
  77587. } FAR deflate_state;
  77588. /* Output a byte on the stream.
  77589. * IN assertion: there is enough room in pending_buf.
  77590. */
  77591. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  77592. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  77593. /* Minimum amount of lookahead, except at the end of the input file.
  77594. * See deflate.c for comments about the MIN_MATCH+1.
  77595. */
  77596. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  77597. /* In order to simplify the code, particularly on 16 bit machines, match
  77598. * distances are limited to MAX_DIST instead of WSIZE.
  77599. */
  77600. /* in trees.c */
  77601. void _tr_init OF((deflate_state *s));
  77602. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  77603. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  77604. int eof));
  77605. void _tr_align OF((deflate_state *s));
  77606. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  77607. int eof));
  77608. #define d_code(dist) \
  77609. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  77610. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  77611. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  77612. * used.
  77613. */
  77614. #ifndef DEBUG
  77615. /* Inline versions of _tr_tally for speed: */
  77616. #if defined(GEN_TREES_H) || !defined(STDC)
  77617. extern uch _length_code[];
  77618. extern uch _dist_code[];
  77619. #else
  77620. extern const uch _length_code[];
  77621. extern const uch _dist_code[];
  77622. #endif
  77623. # define _tr_tally_lit(s, c, flush) \
  77624. { uch cc = (c); \
  77625. s->d_buf[s->last_lit] = 0; \
  77626. s->l_buf[s->last_lit++] = cc; \
  77627. s->dyn_ltree[cc].Freq++; \
  77628. flush = (s->last_lit == s->lit_bufsize-1); \
  77629. }
  77630. # define _tr_tally_dist(s, distance, length, flush) \
  77631. { uch len = (length); \
  77632. ush dist = (distance); \
  77633. s->d_buf[s->last_lit] = dist; \
  77634. s->l_buf[s->last_lit++] = len; \
  77635. dist--; \
  77636. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  77637. s->dyn_dtree[d_code(dist)].Freq++; \
  77638. flush = (s->last_lit == s->lit_bufsize-1); \
  77639. }
  77640. #else
  77641. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  77642. # define _tr_tally_dist(s, distance, length, flush) \
  77643. flush = _tr_tally(s, distance, length)
  77644. #endif
  77645. #endif /* DEFLATE_H */
  77646. /*** End of inlined file: deflate.h ***/
  77647. const char deflate_copyright[] =
  77648. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  77649. /*
  77650. If you use the zlib library in a product, an acknowledgment is welcome
  77651. in the documentation of your product. If for some reason you cannot
  77652. include such an acknowledgment, I would appreciate that you keep this
  77653. copyright string in the executable of your product.
  77654. */
  77655. /* ===========================================================================
  77656. * Function prototypes.
  77657. */
  77658. typedef enum {
  77659. need_more, /* block not completed, need more input or more output */
  77660. block_done, /* block flush performed */
  77661. finish_started, /* finish started, need only more output at next deflate */
  77662. finish_done /* finish done, accept no more input or output */
  77663. } block_state;
  77664. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  77665. /* Compression function. Returns the block state after the call. */
  77666. local void fill_window OF((deflate_state *s));
  77667. local block_state deflate_stored OF((deflate_state *s, int flush));
  77668. local block_state deflate_fast OF((deflate_state *s, int flush));
  77669. #ifndef FASTEST
  77670. local block_state deflate_slow OF((deflate_state *s, int flush));
  77671. #endif
  77672. local void lm_init OF((deflate_state *s));
  77673. local void putShortMSB OF((deflate_state *s, uInt b));
  77674. local void flush_pending OF((z_streamp strm));
  77675. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  77676. #ifndef FASTEST
  77677. #ifdef ASMV
  77678. void match_init OF((void)); /* asm code initialization */
  77679. uInt longest_match OF((deflate_state *s, IPos cur_match));
  77680. #else
  77681. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  77682. #endif
  77683. #endif
  77684. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  77685. #ifdef DEBUG
  77686. local void check_match OF((deflate_state *s, IPos start, IPos match,
  77687. int length));
  77688. #endif
  77689. /* ===========================================================================
  77690. * Local data
  77691. */
  77692. #define NIL 0
  77693. /* Tail of hash chains */
  77694. #ifndef TOO_FAR
  77695. # define TOO_FAR 4096
  77696. #endif
  77697. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  77698. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  77699. /* Minimum amount of lookahead, except at the end of the input file.
  77700. * See deflate.c for comments about the MIN_MATCH+1.
  77701. */
  77702. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  77703. * the desired pack level (0..9). The values given below have been tuned to
  77704. * exclude worst case performance for pathological files. Better values may be
  77705. * found for specific files.
  77706. */
  77707. typedef struct config_s {
  77708. ush good_length; /* reduce lazy search above this match length */
  77709. ush max_lazy; /* do not perform lazy search above this match length */
  77710. ush nice_length; /* quit search above this match length */
  77711. ush max_chain;
  77712. compress_func func;
  77713. } config;
  77714. #ifdef FASTEST
  77715. local const config configuration_table[2] = {
  77716. /* good lazy nice chain */
  77717. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  77718. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  77719. #else
  77720. local const config configuration_table[10] = {
  77721. /* good lazy nice chain */
  77722. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  77723. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  77724. /* 2 */ {4, 5, 16, 8, deflate_fast},
  77725. /* 3 */ {4, 6, 32, 32, deflate_fast},
  77726. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  77727. /* 5 */ {8, 16, 32, 32, deflate_slow},
  77728. /* 6 */ {8, 16, 128, 128, deflate_slow},
  77729. /* 7 */ {8, 32, 128, 256, deflate_slow},
  77730. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  77731. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  77732. #endif
  77733. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  77734. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  77735. * meaning.
  77736. */
  77737. #define EQUAL 0
  77738. /* result of memcmp for equal strings */
  77739. #ifndef NO_DUMMY_DECL
  77740. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  77741. #endif
  77742. /* ===========================================================================
  77743. * Update a hash value with the given input byte
  77744. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  77745. * input characters, so that a running hash key can be computed from the
  77746. * previous key instead of complete recalculation each time.
  77747. */
  77748. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  77749. /* ===========================================================================
  77750. * Insert string str in the dictionary and set match_head to the previous head
  77751. * of the hash chain (the most recent string with same hash key). Return
  77752. * the previous length of the hash chain.
  77753. * If this file is compiled with -DFASTEST, the compression level is forced
  77754. * to 1, and no hash chains are maintained.
  77755. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  77756. * input characters and the first MIN_MATCH bytes of str are valid
  77757. * (except for the last MIN_MATCH-1 bytes of the input file).
  77758. */
  77759. #ifdef FASTEST
  77760. #define INSERT_STRING(s, str, match_head) \
  77761. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  77762. match_head = s->head[s->ins_h], \
  77763. s->head[s->ins_h] = (Pos)(str))
  77764. #else
  77765. #define INSERT_STRING(s, str, match_head) \
  77766. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  77767. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  77768. s->head[s->ins_h] = (Pos)(str))
  77769. #endif
  77770. /* ===========================================================================
  77771. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  77772. * prev[] will be initialized on the fly.
  77773. */
  77774. #define CLEAR_HASH(s) \
  77775. s->head[s->hash_size-1] = NIL; \
  77776. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  77777. /* ========================================================================= */
  77778. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  77779. {
  77780. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  77781. Z_DEFAULT_STRATEGY, version, stream_size);
  77782. /* To do: ignore strm->next_in if we use it as window */
  77783. }
  77784. /* ========================================================================= */
  77785. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  77786. {
  77787. deflate_state *s;
  77788. int wrap = 1;
  77789. static const char my_version[] = ZLIB_VERSION;
  77790. ushf *overlay;
  77791. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  77792. * output size for (length,distance) codes is <= 24 bits.
  77793. */
  77794. if (version == Z_NULL || version[0] != my_version[0] ||
  77795. stream_size != sizeof(z_stream)) {
  77796. return Z_VERSION_ERROR;
  77797. }
  77798. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77799. strm->msg = Z_NULL;
  77800. if (strm->zalloc == (alloc_func)0) {
  77801. strm->zalloc = zcalloc;
  77802. strm->opaque = (voidpf)0;
  77803. }
  77804. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77805. #ifdef FASTEST
  77806. if (level != 0) level = 1;
  77807. #else
  77808. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77809. #endif
  77810. if (windowBits < 0) { /* suppress zlib wrapper */
  77811. wrap = 0;
  77812. windowBits = -windowBits;
  77813. }
  77814. #ifdef GZIP
  77815. else if (windowBits > 15) {
  77816. wrap = 2; /* write gzip wrapper instead */
  77817. windowBits -= 16;
  77818. }
  77819. #endif
  77820. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  77821. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  77822. strategy < 0 || strategy > Z_FIXED) {
  77823. return Z_STREAM_ERROR;
  77824. }
  77825. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  77826. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  77827. if (s == Z_NULL) return Z_MEM_ERROR;
  77828. strm->state = (struct internal_state FAR *)s;
  77829. s->strm = strm;
  77830. s->wrap = wrap;
  77831. s->gzhead = Z_NULL;
  77832. s->w_bits = windowBits;
  77833. s->w_size = 1 << s->w_bits;
  77834. s->w_mask = s->w_size - 1;
  77835. s->hash_bits = memLevel + 7;
  77836. s->hash_size = 1 << s->hash_bits;
  77837. s->hash_mask = s->hash_size - 1;
  77838. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  77839. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  77840. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  77841. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  77842. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  77843. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  77844. s->pending_buf = (uchf *) overlay;
  77845. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  77846. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  77847. s->pending_buf == Z_NULL) {
  77848. s->status = FINISH_STATE;
  77849. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  77850. deflateEnd (strm);
  77851. return Z_MEM_ERROR;
  77852. }
  77853. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  77854. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  77855. s->level = level;
  77856. s->strategy = strategy;
  77857. s->method = (Byte)method;
  77858. return deflateReset(strm);
  77859. }
  77860. /* ========================================================================= */
  77861. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  77862. {
  77863. deflate_state *s;
  77864. uInt length = dictLength;
  77865. uInt n;
  77866. IPos hash_head = 0;
  77867. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  77868. strm->state->wrap == 2 ||
  77869. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  77870. return Z_STREAM_ERROR;
  77871. s = strm->state;
  77872. if (s->wrap)
  77873. strm->adler = adler32(strm->adler, dictionary, dictLength);
  77874. if (length < MIN_MATCH) return Z_OK;
  77875. if (length > MAX_DIST(s)) {
  77876. length = MAX_DIST(s);
  77877. dictionary += dictLength - length; /* use the tail of the dictionary */
  77878. }
  77879. zmemcpy(s->window, dictionary, length);
  77880. s->strstart = length;
  77881. s->block_start = (long)length;
  77882. /* Insert all strings in the hash table (except for the last two bytes).
  77883. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  77884. * call of fill_window.
  77885. */
  77886. s->ins_h = s->window[0];
  77887. UPDATE_HASH(s, s->ins_h, s->window[1]);
  77888. for (n = 0; n <= length - MIN_MATCH; n++) {
  77889. INSERT_STRING(s, n, hash_head);
  77890. }
  77891. if (hash_head) hash_head = 0; /* to make compiler happy */
  77892. return Z_OK;
  77893. }
  77894. /* ========================================================================= */
  77895. int ZEXPORT deflateReset (z_streamp strm)
  77896. {
  77897. deflate_state *s;
  77898. if (strm == Z_NULL || strm->state == Z_NULL ||
  77899. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  77900. return Z_STREAM_ERROR;
  77901. }
  77902. strm->total_in = strm->total_out = 0;
  77903. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  77904. strm->data_type = Z_UNKNOWN;
  77905. s = (deflate_state *)strm->state;
  77906. s->pending = 0;
  77907. s->pending_out = s->pending_buf;
  77908. if (s->wrap < 0) {
  77909. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  77910. }
  77911. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  77912. strm->adler =
  77913. #ifdef GZIP
  77914. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  77915. #endif
  77916. adler32(0L, Z_NULL, 0);
  77917. s->last_flush = Z_NO_FLUSH;
  77918. _tr_init(s);
  77919. lm_init(s);
  77920. return Z_OK;
  77921. }
  77922. /* ========================================================================= */
  77923. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  77924. {
  77925. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77926. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  77927. strm->state->gzhead = head;
  77928. return Z_OK;
  77929. }
  77930. /* ========================================================================= */
  77931. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  77932. {
  77933. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77934. strm->state->bi_valid = bits;
  77935. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  77936. return Z_OK;
  77937. }
  77938. /* ========================================================================= */
  77939. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  77940. {
  77941. deflate_state *s;
  77942. compress_func func;
  77943. int err = Z_OK;
  77944. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77945. s = strm->state;
  77946. #ifdef FASTEST
  77947. if (level != 0) level = 1;
  77948. #else
  77949. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77950. #endif
  77951. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  77952. return Z_STREAM_ERROR;
  77953. }
  77954. func = configuration_table[s->level].func;
  77955. if (func != configuration_table[level].func && strm->total_in != 0) {
  77956. /* Flush the last buffer: */
  77957. err = deflate(strm, Z_PARTIAL_FLUSH);
  77958. }
  77959. if (s->level != level) {
  77960. s->level = level;
  77961. s->max_lazy_match = configuration_table[level].max_lazy;
  77962. s->good_match = configuration_table[level].good_length;
  77963. s->nice_match = configuration_table[level].nice_length;
  77964. s->max_chain_length = configuration_table[level].max_chain;
  77965. }
  77966. s->strategy = strategy;
  77967. return err;
  77968. }
  77969. /* ========================================================================= */
  77970. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  77971. {
  77972. deflate_state *s;
  77973. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77974. s = strm->state;
  77975. s->good_match = good_length;
  77976. s->max_lazy_match = max_lazy;
  77977. s->nice_match = nice_length;
  77978. s->max_chain_length = max_chain;
  77979. return Z_OK;
  77980. }
  77981. /* =========================================================================
  77982. * For the default windowBits of 15 and memLevel of 8, this function returns
  77983. * a close to exact, as well as small, upper bound on the compressed size.
  77984. * They are coded as constants here for a reason--if the #define's are
  77985. * changed, then this function needs to be changed as well. The return
  77986. * value for 15 and 8 only works for those exact settings.
  77987. *
  77988. * For any setting other than those defaults for windowBits and memLevel,
  77989. * the value returned is a conservative worst case for the maximum expansion
  77990. * resulting from using fixed blocks instead of stored blocks, which deflate
  77991. * can emit on compressed data for some combinations of the parameters.
  77992. *
  77993. * This function could be more sophisticated to provide closer upper bounds
  77994. * for every combination of windowBits and memLevel, as well as wrap.
  77995. * But even the conservative upper bound of about 14% expansion does not
  77996. * seem onerous for output buffer allocation.
  77997. */
  77998. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  77999. {
  78000. deflate_state *s;
  78001. uLong destLen;
  78002. /* conservative upper bound */
  78003. destLen = sourceLen +
  78004. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  78005. /* if can't get parameters, return conservative bound */
  78006. if (strm == Z_NULL || strm->state == Z_NULL)
  78007. return destLen;
  78008. /* if not default parameters, return conservative bound */
  78009. s = strm->state;
  78010. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  78011. return destLen;
  78012. /* default settings: return tight bound for that case */
  78013. return compressBound(sourceLen);
  78014. }
  78015. /* =========================================================================
  78016. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  78017. * IN assertion: the stream state is correct and there is enough room in
  78018. * pending_buf.
  78019. */
  78020. local void putShortMSB (deflate_state *s, uInt b)
  78021. {
  78022. put_byte(s, (Byte)(b >> 8));
  78023. put_byte(s, (Byte)(b & 0xff));
  78024. }
  78025. /* =========================================================================
  78026. * Flush as much pending output as possible. All deflate() output goes
  78027. * through this function so some applications may wish to modify it
  78028. * to avoid allocating a large strm->next_out buffer and copying into it.
  78029. * (See also read_buf()).
  78030. */
  78031. local void flush_pending (z_streamp strm)
  78032. {
  78033. unsigned len = strm->state->pending;
  78034. if (len > strm->avail_out) len = strm->avail_out;
  78035. if (len == 0) return;
  78036. zmemcpy(strm->next_out, strm->state->pending_out, len);
  78037. strm->next_out += len;
  78038. strm->state->pending_out += len;
  78039. strm->total_out += len;
  78040. strm->avail_out -= len;
  78041. strm->state->pending -= len;
  78042. if (strm->state->pending == 0) {
  78043. strm->state->pending_out = strm->state->pending_buf;
  78044. }
  78045. }
  78046. /* ========================================================================= */
  78047. int ZEXPORT deflate (z_streamp strm, int flush)
  78048. {
  78049. int old_flush; /* value of flush param for previous deflate call */
  78050. deflate_state *s;
  78051. if (strm == Z_NULL || strm->state == Z_NULL ||
  78052. flush > Z_FINISH || flush < 0) {
  78053. return Z_STREAM_ERROR;
  78054. }
  78055. s = strm->state;
  78056. if (strm->next_out == Z_NULL ||
  78057. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  78058. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  78059. ERR_RETURN(strm, Z_STREAM_ERROR);
  78060. }
  78061. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  78062. s->strm = strm; /* just in case */
  78063. old_flush = s->last_flush;
  78064. s->last_flush = flush;
  78065. /* Write the header */
  78066. if (s->status == INIT_STATE) {
  78067. #ifdef GZIP
  78068. if (s->wrap == 2) {
  78069. strm->adler = crc32(0L, Z_NULL, 0);
  78070. put_byte(s, 31);
  78071. put_byte(s, 139);
  78072. put_byte(s, 8);
  78073. if (s->gzhead == NULL) {
  78074. put_byte(s, 0);
  78075. put_byte(s, 0);
  78076. put_byte(s, 0);
  78077. put_byte(s, 0);
  78078. put_byte(s, 0);
  78079. put_byte(s, s->level == 9 ? 2 :
  78080. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78081. 4 : 0));
  78082. put_byte(s, OS_CODE);
  78083. s->status = BUSY_STATE;
  78084. }
  78085. else {
  78086. put_byte(s, (s->gzhead->text ? 1 : 0) +
  78087. (s->gzhead->hcrc ? 2 : 0) +
  78088. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  78089. (s->gzhead->name == Z_NULL ? 0 : 8) +
  78090. (s->gzhead->comment == Z_NULL ? 0 : 16)
  78091. );
  78092. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  78093. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  78094. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  78095. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  78096. put_byte(s, s->level == 9 ? 2 :
  78097. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78098. 4 : 0));
  78099. put_byte(s, s->gzhead->os & 0xff);
  78100. if (s->gzhead->extra != NULL) {
  78101. put_byte(s, s->gzhead->extra_len & 0xff);
  78102. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  78103. }
  78104. if (s->gzhead->hcrc)
  78105. strm->adler = crc32(strm->adler, s->pending_buf,
  78106. s->pending);
  78107. s->gzindex = 0;
  78108. s->status = EXTRA_STATE;
  78109. }
  78110. }
  78111. else
  78112. #endif
  78113. {
  78114. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  78115. uInt level_flags;
  78116. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  78117. level_flags = 0;
  78118. else if (s->level < 6)
  78119. level_flags = 1;
  78120. else if (s->level == 6)
  78121. level_flags = 2;
  78122. else
  78123. level_flags = 3;
  78124. header |= (level_flags << 6);
  78125. if (s->strstart != 0) header |= PRESET_DICT;
  78126. header += 31 - (header % 31);
  78127. s->status = BUSY_STATE;
  78128. putShortMSB(s, header);
  78129. /* Save the adler32 of the preset dictionary: */
  78130. if (s->strstart != 0) {
  78131. putShortMSB(s, (uInt)(strm->adler >> 16));
  78132. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78133. }
  78134. strm->adler = adler32(0L, Z_NULL, 0);
  78135. }
  78136. }
  78137. #ifdef GZIP
  78138. if (s->status == EXTRA_STATE) {
  78139. if (s->gzhead->extra != NULL) {
  78140. uInt beg = s->pending; /* start of bytes to update crc */
  78141. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  78142. if (s->pending == s->pending_buf_size) {
  78143. if (s->gzhead->hcrc && s->pending > beg)
  78144. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78145. s->pending - beg);
  78146. flush_pending(strm);
  78147. beg = s->pending;
  78148. if (s->pending == s->pending_buf_size)
  78149. break;
  78150. }
  78151. put_byte(s, s->gzhead->extra[s->gzindex]);
  78152. s->gzindex++;
  78153. }
  78154. if (s->gzhead->hcrc && s->pending > beg)
  78155. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78156. s->pending - beg);
  78157. if (s->gzindex == s->gzhead->extra_len) {
  78158. s->gzindex = 0;
  78159. s->status = NAME_STATE;
  78160. }
  78161. }
  78162. else
  78163. s->status = NAME_STATE;
  78164. }
  78165. if (s->status == NAME_STATE) {
  78166. if (s->gzhead->name != NULL) {
  78167. uInt beg = s->pending; /* start of bytes to update crc */
  78168. int val;
  78169. do {
  78170. if (s->pending == s->pending_buf_size) {
  78171. if (s->gzhead->hcrc && s->pending > beg)
  78172. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78173. s->pending - beg);
  78174. flush_pending(strm);
  78175. beg = s->pending;
  78176. if (s->pending == s->pending_buf_size) {
  78177. val = 1;
  78178. break;
  78179. }
  78180. }
  78181. val = s->gzhead->name[s->gzindex++];
  78182. put_byte(s, val);
  78183. } while (val != 0);
  78184. if (s->gzhead->hcrc && s->pending > beg)
  78185. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78186. s->pending - beg);
  78187. if (val == 0) {
  78188. s->gzindex = 0;
  78189. s->status = COMMENT_STATE;
  78190. }
  78191. }
  78192. else
  78193. s->status = COMMENT_STATE;
  78194. }
  78195. if (s->status == COMMENT_STATE) {
  78196. if (s->gzhead->comment != NULL) {
  78197. uInt beg = s->pending; /* start of bytes to update crc */
  78198. int val;
  78199. do {
  78200. if (s->pending == s->pending_buf_size) {
  78201. if (s->gzhead->hcrc && s->pending > beg)
  78202. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78203. s->pending - beg);
  78204. flush_pending(strm);
  78205. beg = s->pending;
  78206. if (s->pending == s->pending_buf_size) {
  78207. val = 1;
  78208. break;
  78209. }
  78210. }
  78211. val = s->gzhead->comment[s->gzindex++];
  78212. put_byte(s, val);
  78213. } while (val != 0);
  78214. if (s->gzhead->hcrc && s->pending > beg)
  78215. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78216. s->pending - beg);
  78217. if (val == 0)
  78218. s->status = HCRC_STATE;
  78219. }
  78220. else
  78221. s->status = HCRC_STATE;
  78222. }
  78223. if (s->status == HCRC_STATE) {
  78224. if (s->gzhead->hcrc) {
  78225. if (s->pending + 2 > s->pending_buf_size)
  78226. flush_pending(strm);
  78227. if (s->pending + 2 <= s->pending_buf_size) {
  78228. put_byte(s, (Byte)(strm->adler & 0xff));
  78229. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78230. strm->adler = crc32(0L, Z_NULL, 0);
  78231. s->status = BUSY_STATE;
  78232. }
  78233. }
  78234. else
  78235. s->status = BUSY_STATE;
  78236. }
  78237. #endif
  78238. /* Flush as much pending output as possible */
  78239. if (s->pending != 0) {
  78240. flush_pending(strm);
  78241. if (strm->avail_out == 0) {
  78242. /* Since avail_out is 0, deflate will be called again with
  78243. * more output space, but possibly with both pending and
  78244. * avail_in equal to zero. There won't be anything to do,
  78245. * but this is not an error situation so make sure we
  78246. * return OK instead of BUF_ERROR at next call of deflate:
  78247. */
  78248. s->last_flush = -1;
  78249. return Z_OK;
  78250. }
  78251. /* Make sure there is something to do and avoid duplicate consecutive
  78252. * flushes. For repeated and useless calls with Z_FINISH, we keep
  78253. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  78254. */
  78255. } else if (strm->avail_in == 0 && flush <= old_flush &&
  78256. flush != Z_FINISH) {
  78257. ERR_RETURN(strm, Z_BUF_ERROR);
  78258. }
  78259. /* User must not provide more input after the first FINISH: */
  78260. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  78261. ERR_RETURN(strm, Z_BUF_ERROR);
  78262. }
  78263. /* Start a new block or continue the current one.
  78264. */
  78265. if (strm->avail_in != 0 || s->lookahead != 0 ||
  78266. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  78267. block_state bstate;
  78268. bstate = (*(configuration_table[s->level].func))(s, flush);
  78269. if (bstate == finish_started || bstate == finish_done) {
  78270. s->status = FINISH_STATE;
  78271. }
  78272. if (bstate == need_more || bstate == finish_started) {
  78273. if (strm->avail_out == 0) {
  78274. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  78275. }
  78276. return Z_OK;
  78277. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  78278. * of deflate should use the same flush parameter to make sure
  78279. * that the flush is complete. So we don't have to output an
  78280. * empty block here, this will be done at next call. This also
  78281. * ensures that for a very small output buffer, we emit at most
  78282. * one empty block.
  78283. */
  78284. }
  78285. if (bstate == block_done) {
  78286. if (flush == Z_PARTIAL_FLUSH) {
  78287. _tr_align(s);
  78288. } else { /* FULL_FLUSH or SYNC_FLUSH */
  78289. _tr_stored_block(s, (char*)0, 0L, 0);
  78290. /* For a full flush, this empty block will be recognized
  78291. * as a special marker by inflate_sync().
  78292. */
  78293. if (flush == Z_FULL_FLUSH) {
  78294. CLEAR_HASH(s); /* forget history */
  78295. }
  78296. }
  78297. flush_pending(strm);
  78298. if (strm->avail_out == 0) {
  78299. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  78300. return Z_OK;
  78301. }
  78302. }
  78303. }
  78304. Assert(strm->avail_out > 0, "bug2");
  78305. if (flush != Z_FINISH) return Z_OK;
  78306. if (s->wrap <= 0) return Z_STREAM_END;
  78307. /* Write the trailer */
  78308. #ifdef GZIP
  78309. if (s->wrap == 2) {
  78310. put_byte(s, (Byte)(strm->adler & 0xff));
  78311. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78312. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  78313. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  78314. put_byte(s, (Byte)(strm->total_in & 0xff));
  78315. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  78316. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  78317. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  78318. }
  78319. else
  78320. #endif
  78321. {
  78322. putShortMSB(s, (uInt)(strm->adler >> 16));
  78323. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78324. }
  78325. flush_pending(strm);
  78326. /* If avail_out is zero, the application will call deflate again
  78327. * to flush the rest.
  78328. */
  78329. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  78330. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  78331. }
  78332. /* ========================================================================= */
  78333. int ZEXPORT deflateEnd (z_streamp strm)
  78334. {
  78335. int status;
  78336. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78337. status = strm->state->status;
  78338. if (status != INIT_STATE &&
  78339. status != EXTRA_STATE &&
  78340. status != NAME_STATE &&
  78341. status != COMMENT_STATE &&
  78342. status != HCRC_STATE &&
  78343. status != BUSY_STATE &&
  78344. status != FINISH_STATE) {
  78345. return Z_STREAM_ERROR;
  78346. }
  78347. /* Deallocate in reverse order of allocations: */
  78348. TRY_FREE(strm, strm->state->pending_buf);
  78349. TRY_FREE(strm, strm->state->head);
  78350. TRY_FREE(strm, strm->state->prev);
  78351. TRY_FREE(strm, strm->state->window);
  78352. ZFREE(strm, strm->state);
  78353. strm->state = Z_NULL;
  78354. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  78355. }
  78356. /* =========================================================================
  78357. * Copy the source state to the destination state.
  78358. * To simplify the source, this is not supported for 16-bit MSDOS (which
  78359. * doesn't have enough memory anyway to duplicate compression states).
  78360. */
  78361. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  78362. {
  78363. #ifdef MAXSEG_64K
  78364. return Z_STREAM_ERROR;
  78365. #else
  78366. deflate_state *ds;
  78367. deflate_state *ss;
  78368. ushf *overlay;
  78369. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  78370. return Z_STREAM_ERROR;
  78371. }
  78372. ss = source->state;
  78373. zmemcpy(dest, source, sizeof(z_stream));
  78374. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  78375. if (ds == Z_NULL) return Z_MEM_ERROR;
  78376. dest->state = (struct internal_state FAR *) ds;
  78377. zmemcpy(ds, ss, sizeof(deflate_state));
  78378. ds->strm = dest;
  78379. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  78380. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  78381. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  78382. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  78383. ds->pending_buf = (uchf *) overlay;
  78384. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  78385. ds->pending_buf == Z_NULL) {
  78386. deflateEnd (dest);
  78387. return Z_MEM_ERROR;
  78388. }
  78389. /* following zmemcpy do not work for 16-bit MSDOS */
  78390. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  78391. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  78392. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  78393. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  78394. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  78395. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  78396. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  78397. ds->l_desc.dyn_tree = ds->dyn_ltree;
  78398. ds->d_desc.dyn_tree = ds->dyn_dtree;
  78399. ds->bl_desc.dyn_tree = ds->bl_tree;
  78400. return Z_OK;
  78401. #endif /* MAXSEG_64K */
  78402. }
  78403. /* ===========================================================================
  78404. * Read a new buffer from the current input stream, update the adler32
  78405. * and total number of bytes read. All deflate() input goes through
  78406. * this function so some applications may wish to modify it to avoid
  78407. * allocating a large strm->next_in buffer and copying from it.
  78408. * (See also flush_pending()).
  78409. */
  78410. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  78411. {
  78412. unsigned len = strm->avail_in;
  78413. if (len > size) len = size;
  78414. if (len == 0) return 0;
  78415. strm->avail_in -= len;
  78416. if (strm->state->wrap == 1) {
  78417. strm->adler = adler32(strm->adler, strm->next_in, len);
  78418. }
  78419. #ifdef GZIP
  78420. else if (strm->state->wrap == 2) {
  78421. strm->adler = crc32(strm->adler, strm->next_in, len);
  78422. }
  78423. #endif
  78424. zmemcpy(buf, strm->next_in, len);
  78425. strm->next_in += len;
  78426. strm->total_in += len;
  78427. return (int)len;
  78428. }
  78429. /* ===========================================================================
  78430. * Initialize the "longest match" routines for a new zlib stream
  78431. */
  78432. local void lm_init (deflate_state *s)
  78433. {
  78434. s->window_size = (ulg)2L*s->w_size;
  78435. CLEAR_HASH(s);
  78436. /* Set the default configuration parameters:
  78437. */
  78438. s->max_lazy_match = configuration_table[s->level].max_lazy;
  78439. s->good_match = configuration_table[s->level].good_length;
  78440. s->nice_match = configuration_table[s->level].nice_length;
  78441. s->max_chain_length = configuration_table[s->level].max_chain;
  78442. s->strstart = 0;
  78443. s->block_start = 0L;
  78444. s->lookahead = 0;
  78445. s->match_length = s->prev_length = MIN_MATCH-1;
  78446. s->match_available = 0;
  78447. s->ins_h = 0;
  78448. #ifndef FASTEST
  78449. #ifdef ASMV
  78450. match_init(); /* initialize the asm code */
  78451. #endif
  78452. #endif
  78453. }
  78454. #ifndef FASTEST
  78455. /* ===========================================================================
  78456. * Set match_start to the longest match starting at the given string and
  78457. * return its length. Matches shorter or equal to prev_length are discarded,
  78458. * in which case the result is equal to prev_length and match_start is
  78459. * garbage.
  78460. * IN assertions: cur_match is the head of the hash chain for the current
  78461. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  78462. * OUT assertion: the match length is not greater than s->lookahead.
  78463. */
  78464. #ifndef ASMV
  78465. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  78466. * match.S. The code will be functionally equivalent.
  78467. */
  78468. local uInt longest_match(deflate_state *s, IPos cur_match)
  78469. {
  78470. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  78471. register Bytef *scan = s->window + s->strstart; /* current string */
  78472. register Bytef *match; /* matched string */
  78473. register int len; /* length of current match */
  78474. int best_len = s->prev_length; /* best match length so far */
  78475. int nice_match = s->nice_match; /* stop if match long enough */
  78476. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  78477. s->strstart - (IPos)MAX_DIST(s) : NIL;
  78478. /* Stop when cur_match becomes <= limit. To simplify the code,
  78479. * we prevent matches with the string of window index 0.
  78480. */
  78481. Posf *prev = s->prev;
  78482. uInt wmask = s->w_mask;
  78483. #ifdef UNALIGNED_OK
  78484. /* Compare two bytes at a time. Note: this is not always beneficial.
  78485. * Try with and without -DUNALIGNED_OK to check.
  78486. */
  78487. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  78488. register ush scan_start = *(ushf*)scan;
  78489. register ush scan_end = *(ushf*)(scan+best_len-1);
  78490. #else
  78491. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  78492. register Byte scan_end1 = scan[best_len-1];
  78493. register Byte scan_end = scan[best_len];
  78494. #endif
  78495. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  78496. * It is easy to get rid of this optimization if necessary.
  78497. */
  78498. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  78499. /* Do not waste too much time if we already have a good match: */
  78500. if (s->prev_length >= s->good_match) {
  78501. chain_length >>= 2;
  78502. }
  78503. /* Do not look for matches beyond the end of the input. This is necessary
  78504. * to make deflate deterministic.
  78505. */
  78506. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  78507. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  78508. do {
  78509. Assert(cur_match < s->strstart, "no future");
  78510. match = s->window + cur_match;
  78511. /* Skip to next match if the match length cannot increase
  78512. * or if the match length is less than 2. Note that the checks below
  78513. * for insufficient lookahead only occur occasionally for performance
  78514. * reasons. Therefore uninitialized memory will be accessed, and
  78515. * conditional jumps will be made that depend on those values.
  78516. * However the length of the match is limited to the lookahead, so
  78517. * the output of deflate is not affected by the uninitialized values.
  78518. */
  78519. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  78520. /* This code assumes sizeof(unsigned short) == 2. Do not use
  78521. * UNALIGNED_OK if your compiler uses a different size.
  78522. */
  78523. if (*(ushf*)(match+best_len-1) != scan_end ||
  78524. *(ushf*)match != scan_start) continue;
  78525. /* It is not necessary to compare scan[2] and match[2] since they are
  78526. * always equal when the other bytes match, given that the hash keys
  78527. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  78528. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  78529. * lookahead only every 4th comparison; the 128th check will be made
  78530. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  78531. * necessary to put more guard bytes at the end of the window, or
  78532. * to check more often for insufficient lookahead.
  78533. */
  78534. Assert(scan[2] == match[2], "scan[2]?");
  78535. scan++, match++;
  78536. do {
  78537. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78538. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78539. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78540. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78541. scan < strend);
  78542. /* The funny "do {}" generates better code on most compilers */
  78543. /* Here, scan <= window+strstart+257 */
  78544. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  78545. if (*scan == *match) scan++;
  78546. len = (MAX_MATCH - 1) - (int)(strend-scan);
  78547. scan = strend - (MAX_MATCH-1);
  78548. #else /* UNALIGNED_OK */
  78549. if (match[best_len] != scan_end ||
  78550. match[best_len-1] != scan_end1 ||
  78551. *match != *scan ||
  78552. *++match != scan[1]) continue;
  78553. /* The check at best_len-1 can be removed because it will be made
  78554. * again later. (This heuristic is not always a win.)
  78555. * It is not necessary to compare scan[2] and match[2] since they
  78556. * are always equal when the other bytes match, given that
  78557. * the hash keys are equal and that HASH_BITS >= 8.
  78558. */
  78559. scan += 2, match++;
  78560. Assert(*scan == *match, "match[2]?");
  78561. /* We check for insufficient lookahead only every 8th comparison;
  78562. * the 256th check will be made at strstart+258.
  78563. */
  78564. do {
  78565. } while (*++scan == *++match && *++scan == *++match &&
  78566. *++scan == *++match && *++scan == *++match &&
  78567. *++scan == *++match && *++scan == *++match &&
  78568. *++scan == *++match && *++scan == *++match &&
  78569. scan < strend);
  78570. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  78571. len = MAX_MATCH - (int)(strend - scan);
  78572. scan = strend - MAX_MATCH;
  78573. #endif /* UNALIGNED_OK */
  78574. if (len > best_len) {
  78575. s->match_start = cur_match;
  78576. best_len = len;
  78577. if (len >= nice_match) break;
  78578. #ifdef UNALIGNED_OK
  78579. scan_end = *(ushf*)(scan+best_len-1);
  78580. #else
  78581. scan_end1 = scan[best_len-1];
  78582. scan_end = scan[best_len];
  78583. #endif
  78584. }
  78585. } while ((cur_match = prev[cur_match & wmask]) > limit
  78586. && --chain_length != 0);
  78587. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  78588. return s->lookahead;
  78589. }
  78590. #endif /* ASMV */
  78591. #endif /* FASTEST */
  78592. /* ---------------------------------------------------------------------------
  78593. * Optimized version for level == 1 or strategy == Z_RLE only
  78594. */
  78595. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  78596. {
  78597. register Bytef *scan = s->window + s->strstart; /* current string */
  78598. register Bytef *match; /* matched string */
  78599. register int len; /* length of current match */
  78600. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  78601. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  78602. * It is easy to get rid of this optimization if necessary.
  78603. */
  78604. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  78605. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  78606. Assert(cur_match < s->strstart, "no future");
  78607. match = s->window + cur_match;
  78608. /* Return failure if the match length is less than 2:
  78609. */
  78610. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  78611. /* The check at best_len-1 can be removed because it will be made
  78612. * again later. (This heuristic is not always a win.)
  78613. * It is not necessary to compare scan[2] and match[2] since they
  78614. * are always equal when the other bytes match, given that
  78615. * the hash keys are equal and that HASH_BITS >= 8.
  78616. */
  78617. scan += 2, match += 2;
  78618. Assert(*scan == *match, "match[2]?");
  78619. /* We check for insufficient lookahead only every 8th comparison;
  78620. * the 256th check will be made at strstart+258.
  78621. */
  78622. do {
  78623. } while (*++scan == *++match && *++scan == *++match &&
  78624. *++scan == *++match && *++scan == *++match &&
  78625. *++scan == *++match && *++scan == *++match &&
  78626. *++scan == *++match && *++scan == *++match &&
  78627. scan < strend);
  78628. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  78629. len = MAX_MATCH - (int)(strend - scan);
  78630. if (len < MIN_MATCH) return MIN_MATCH - 1;
  78631. s->match_start = cur_match;
  78632. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  78633. }
  78634. #ifdef DEBUG
  78635. /* ===========================================================================
  78636. * Check that the match at match_start is indeed a match.
  78637. */
  78638. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  78639. {
  78640. /* check that the match is indeed a match */
  78641. if (zmemcmp(s->window + match,
  78642. s->window + start, length) != EQUAL) {
  78643. fprintf(stderr, " start %u, match %u, length %d\n",
  78644. start, match, length);
  78645. do {
  78646. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  78647. } while (--length != 0);
  78648. z_error("invalid match");
  78649. }
  78650. if (z_verbose > 1) {
  78651. fprintf(stderr,"\\[%d,%d]", start-match, length);
  78652. do { putc(s->window[start++], stderr); } while (--length != 0);
  78653. }
  78654. }
  78655. #else
  78656. # define check_match(s, start, match, length)
  78657. #endif /* DEBUG */
  78658. /* ===========================================================================
  78659. * Fill the window when the lookahead becomes insufficient.
  78660. * Updates strstart and lookahead.
  78661. *
  78662. * IN assertion: lookahead < MIN_LOOKAHEAD
  78663. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  78664. * At least one byte has been read, or avail_in == 0; reads are
  78665. * performed for at least two bytes (required for the zip translate_eol
  78666. * option -- not supported here).
  78667. */
  78668. local void fill_window (deflate_state *s)
  78669. {
  78670. register unsigned n, m;
  78671. register Posf *p;
  78672. unsigned more; /* Amount of free space at the end of the window. */
  78673. uInt wsize = s->w_size;
  78674. do {
  78675. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  78676. /* Deal with !@#$% 64K limit: */
  78677. if (sizeof(int) <= 2) {
  78678. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  78679. more = wsize;
  78680. } else if (more == (unsigned)(-1)) {
  78681. /* Very unlikely, but possible on 16 bit machine if
  78682. * strstart == 0 && lookahead == 1 (input done a byte at time)
  78683. */
  78684. more--;
  78685. }
  78686. }
  78687. /* If the window is almost full and there is insufficient lookahead,
  78688. * move the upper half to the lower one to make room in the upper half.
  78689. */
  78690. if (s->strstart >= wsize+MAX_DIST(s)) {
  78691. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  78692. s->match_start -= wsize;
  78693. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  78694. s->block_start -= (long) wsize;
  78695. /* Slide the hash table (could be avoided with 32 bit values
  78696. at the expense of memory usage). We slide even when level == 0
  78697. to keep the hash table consistent if we switch back to level > 0
  78698. later. (Using level 0 permanently is not an optimal usage of
  78699. zlib, so we don't care about this pathological case.)
  78700. */
  78701. /* %%% avoid this when Z_RLE */
  78702. n = s->hash_size;
  78703. p = &s->head[n];
  78704. do {
  78705. m = *--p;
  78706. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  78707. } while (--n);
  78708. n = wsize;
  78709. #ifndef FASTEST
  78710. p = &s->prev[n];
  78711. do {
  78712. m = *--p;
  78713. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  78714. /* If n is not on any hash chain, prev[n] is garbage but
  78715. * its value will never be used.
  78716. */
  78717. } while (--n);
  78718. #endif
  78719. more += wsize;
  78720. }
  78721. if (s->strm->avail_in == 0) return;
  78722. /* If there was no sliding:
  78723. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  78724. * more == window_size - lookahead - strstart
  78725. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  78726. * => more >= window_size - 2*WSIZE + 2
  78727. * In the BIG_MEM or MMAP case (not yet supported),
  78728. * window_size == input_size + MIN_LOOKAHEAD &&
  78729. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  78730. * Otherwise, window_size == 2*WSIZE so more >= 2.
  78731. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  78732. */
  78733. Assert(more >= 2, "more < 2");
  78734. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  78735. s->lookahead += n;
  78736. /* Initialize the hash value now that we have some input: */
  78737. if (s->lookahead >= MIN_MATCH) {
  78738. s->ins_h = s->window[s->strstart];
  78739. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  78740. #if MIN_MATCH != 3
  78741. Call UPDATE_HASH() MIN_MATCH-3 more times
  78742. #endif
  78743. }
  78744. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  78745. * but this is not important since only literal bytes will be emitted.
  78746. */
  78747. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  78748. }
  78749. /* ===========================================================================
  78750. * Flush the current block, with given end-of-file flag.
  78751. * IN assertion: strstart is set to the end of the current match.
  78752. */
  78753. #define FLUSH_BLOCK_ONLY(s, eof) { \
  78754. _tr_flush_block(s, (s->block_start >= 0L ? \
  78755. (charf *)&s->window[(unsigned)s->block_start] : \
  78756. (charf *)Z_NULL), \
  78757. (ulg)((long)s->strstart - s->block_start), \
  78758. (eof)); \
  78759. s->block_start = s->strstart; \
  78760. flush_pending(s->strm); \
  78761. Tracev((stderr,"[FLUSH]")); \
  78762. }
  78763. /* Same but force premature exit if necessary. */
  78764. #define FLUSH_BLOCK(s, eof) { \
  78765. FLUSH_BLOCK_ONLY(s, eof); \
  78766. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  78767. }
  78768. /* ===========================================================================
  78769. * Copy without compression as much as possible from the input stream, return
  78770. * the current block state.
  78771. * This function does not insert new strings in the dictionary since
  78772. * uncompressible data is probably not useful. This function is used
  78773. * only for the level=0 compression option.
  78774. * NOTE: this function should be optimized to avoid extra copying from
  78775. * window to pending_buf.
  78776. */
  78777. local block_state deflate_stored(deflate_state *s, int flush)
  78778. {
  78779. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  78780. * to pending_buf_size, and each stored block has a 5 byte header:
  78781. */
  78782. ulg max_block_size = 0xffff;
  78783. ulg max_start;
  78784. if (max_block_size > s->pending_buf_size - 5) {
  78785. max_block_size = s->pending_buf_size - 5;
  78786. }
  78787. /* Copy as much as possible from input to output: */
  78788. for (;;) {
  78789. /* Fill the window as much as possible: */
  78790. if (s->lookahead <= 1) {
  78791. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  78792. s->block_start >= (long)s->w_size, "slide too late");
  78793. fill_window(s);
  78794. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  78795. if (s->lookahead == 0) break; /* flush the current block */
  78796. }
  78797. Assert(s->block_start >= 0L, "block gone");
  78798. s->strstart += s->lookahead;
  78799. s->lookahead = 0;
  78800. /* Emit a stored block if pending_buf will be full: */
  78801. max_start = s->block_start + max_block_size;
  78802. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  78803. /* strstart == 0 is possible when wraparound on 16-bit machine */
  78804. s->lookahead = (uInt)(s->strstart - max_start);
  78805. s->strstart = (uInt)max_start;
  78806. FLUSH_BLOCK(s, 0);
  78807. }
  78808. /* Flush if we may have to slide, otherwise block_start may become
  78809. * negative and the data will be gone:
  78810. */
  78811. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  78812. FLUSH_BLOCK(s, 0);
  78813. }
  78814. }
  78815. FLUSH_BLOCK(s, flush == Z_FINISH);
  78816. return flush == Z_FINISH ? finish_done : block_done;
  78817. }
  78818. /* ===========================================================================
  78819. * Compress as much as possible from the input stream, return the current
  78820. * block state.
  78821. * This function does not perform lazy evaluation of matches and inserts
  78822. * new strings in the dictionary only for unmatched strings or for short
  78823. * matches. It is used only for the fast compression options.
  78824. */
  78825. local block_state deflate_fast(deflate_state *s, int flush)
  78826. {
  78827. IPos hash_head = NIL; /* head of the hash chain */
  78828. int bflush; /* set if current block must be flushed */
  78829. for (;;) {
  78830. /* Make sure that we always have enough lookahead, except
  78831. * at the end of the input file. We need MAX_MATCH bytes
  78832. * for the next match, plus MIN_MATCH bytes to insert the
  78833. * string following the next match.
  78834. */
  78835. if (s->lookahead < MIN_LOOKAHEAD) {
  78836. fill_window(s);
  78837. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78838. return need_more;
  78839. }
  78840. if (s->lookahead == 0) break; /* flush the current block */
  78841. }
  78842. /* Insert the string window[strstart .. strstart+2] in the
  78843. * dictionary, and set hash_head to the head of the hash chain:
  78844. */
  78845. if (s->lookahead >= MIN_MATCH) {
  78846. INSERT_STRING(s, s->strstart, hash_head);
  78847. }
  78848. /* Find the longest match, discarding those <= prev_length.
  78849. * At this point we have always match_length < MIN_MATCH
  78850. */
  78851. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  78852. /* To simplify the code, we prevent matches with the string
  78853. * of window index 0 (in particular we have to avoid a match
  78854. * of the string with itself at the start of the input file).
  78855. */
  78856. #ifdef FASTEST
  78857. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  78858. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  78859. s->match_length = longest_match_fast (s, hash_head);
  78860. }
  78861. #else
  78862. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78863. s->match_length = longest_match (s, hash_head);
  78864. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78865. s->match_length = longest_match_fast (s, hash_head);
  78866. }
  78867. #endif
  78868. /* longest_match() or longest_match_fast() sets match_start */
  78869. }
  78870. if (s->match_length >= MIN_MATCH) {
  78871. check_match(s, s->strstart, s->match_start, s->match_length);
  78872. _tr_tally_dist(s, s->strstart - s->match_start,
  78873. s->match_length - MIN_MATCH, bflush);
  78874. s->lookahead -= s->match_length;
  78875. /* Insert new strings in the hash table only if the match length
  78876. * is not too large. This saves time but degrades compression.
  78877. */
  78878. #ifndef FASTEST
  78879. if (s->match_length <= s->max_insert_length &&
  78880. s->lookahead >= MIN_MATCH) {
  78881. s->match_length--; /* string at strstart already in table */
  78882. do {
  78883. s->strstart++;
  78884. INSERT_STRING(s, s->strstart, hash_head);
  78885. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  78886. * always MIN_MATCH bytes ahead.
  78887. */
  78888. } while (--s->match_length != 0);
  78889. s->strstart++;
  78890. } else
  78891. #endif
  78892. {
  78893. s->strstart += s->match_length;
  78894. s->match_length = 0;
  78895. s->ins_h = s->window[s->strstart];
  78896. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  78897. #if MIN_MATCH != 3
  78898. Call UPDATE_HASH() MIN_MATCH-3 more times
  78899. #endif
  78900. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  78901. * matter since it will be recomputed at next deflate call.
  78902. */
  78903. }
  78904. } else {
  78905. /* No match, output a literal byte */
  78906. Tracevv((stderr,"%c", s->window[s->strstart]));
  78907. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78908. s->lookahead--;
  78909. s->strstart++;
  78910. }
  78911. if (bflush) FLUSH_BLOCK(s, 0);
  78912. }
  78913. FLUSH_BLOCK(s, flush == Z_FINISH);
  78914. return flush == Z_FINISH ? finish_done : block_done;
  78915. }
  78916. #ifndef FASTEST
  78917. /* ===========================================================================
  78918. * Same as above, but achieves better compression. We use a lazy
  78919. * evaluation for matches: a match is finally adopted only if there is
  78920. * no better match at the next window position.
  78921. */
  78922. local block_state deflate_slow(deflate_state *s, int flush)
  78923. {
  78924. IPos hash_head = NIL; /* head of hash chain */
  78925. int bflush; /* set if current block must be flushed */
  78926. /* Process the input block. */
  78927. for (;;) {
  78928. /* Make sure that we always have enough lookahead, except
  78929. * at the end of the input file. We need MAX_MATCH bytes
  78930. * for the next match, plus MIN_MATCH bytes to insert the
  78931. * string following the next match.
  78932. */
  78933. if (s->lookahead < MIN_LOOKAHEAD) {
  78934. fill_window(s);
  78935. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78936. return need_more;
  78937. }
  78938. if (s->lookahead == 0) break; /* flush the current block */
  78939. }
  78940. /* Insert the string window[strstart .. strstart+2] in the
  78941. * dictionary, and set hash_head to the head of the hash chain:
  78942. */
  78943. if (s->lookahead >= MIN_MATCH) {
  78944. INSERT_STRING(s, s->strstart, hash_head);
  78945. }
  78946. /* Find the longest match, discarding those <= prev_length.
  78947. */
  78948. s->prev_length = s->match_length, s->prev_match = s->match_start;
  78949. s->match_length = MIN_MATCH-1;
  78950. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  78951. s->strstart - hash_head <= MAX_DIST(s)) {
  78952. /* To simplify the code, we prevent matches with the string
  78953. * of window index 0 (in particular we have to avoid a match
  78954. * of the string with itself at the start of the input file).
  78955. */
  78956. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78957. s->match_length = longest_match (s, hash_head);
  78958. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78959. s->match_length = longest_match_fast (s, hash_head);
  78960. }
  78961. /* longest_match() or longest_match_fast() sets match_start */
  78962. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  78963. #if TOO_FAR <= 32767
  78964. || (s->match_length == MIN_MATCH &&
  78965. s->strstart - s->match_start > TOO_FAR)
  78966. #endif
  78967. )) {
  78968. /* If prev_match is also MIN_MATCH, match_start is garbage
  78969. * but we will ignore the current match anyway.
  78970. */
  78971. s->match_length = MIN_MATCH-1;
  78972. }
  78973. }
  78974. /* If there was a match at the previous step and the current
  78975. * match is not better, output the previous match:
  78976. */
  78977. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  78978. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  78979. /* Do not insert strings in hash table beyond this. */
  78980. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  78981. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  78982. s->prev_length - MIN_MATCH, bflush);
  78983. /* Insert in hash table all strings up to the end of the match.
  78984. * strstart-1 and strstart are already inserted. If there is not
  78985. * enough lookahead, the last two strings are not inserted in
  78986. * the hash table.
  78987. */
  78988. s->lookahead -= s->prev_length-1;
  78989. s->prev_length -= 2;
  78990. do {
  78991. if (++s->strstart <= max_insert) {
  78992. INSERT_STRING(s, s->strstart, hash_head);
  78993. }
  78994. } while (--s->prev_length != 0);
  78995. s->match_available = 0;
  78996. s->match_length = MIN_MATCH-1;
  78997. s->strstart++;
  78998. if (bflush) FLUSH_BLOCK(s, 0);
  78999. } else if (s->match_available) {
  79000. /* If there was no match at the previous position, output a
  79001. * single literal. If there was a match but the current match
  79002. * is longer, truncate the previous match to a single literal.
  79003. */
  79004. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79005. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79006. if (bflush) {
  79007. FLUSH_BLOCK_ONLY(s, 0);
  79008. }
  79009. s->strstart++;
  79010. s->lookahead--;
  79011. if (s->strm->avail_out == 0) return need_more;
  79012. } else {
  79013. /* There is no previous match to compare with, wait for
  79014. * the next step to decide.
  79015. */
  79016. s->match_available = 1;
  79017. s->strstart++;
  79018. s->lookahead--;
  79019. }
  79020. }
  79021. Assert (flush != Z_NO_FLUSH, "no flush?");
  79022. if (s->match_available) {
  79023. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79024. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79025. s->match_available = 0;
  79026. }
  79027. FLUSH_BLOCK(s, flush == Z_FINISH);
  79028. return flush == Z_FINISH ? finish_done : block_done;
  79029. }
  79030. #endif /* FASTEST */
  79031. #if 0
  79032. /* ===========================================================================
  79033. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  79034. * one. Do not maintain a hash table. (It will be regenerated if this run of
  79035. * deflate switches away from Z_RLE.)
  79036. */
  79037. local block_state deflate_rle(s, flush)
  79038. deflate_state *s;
  79039. int flush;
  79040. {
  79041. int bflush; /* set if current block must be flushed */
  79042. uInt run; /* length of run */
  79043. uInt max; /* maximum length of run */
  79044. uInt prev; /* byte at distance one to match */
  79045. Bytef *scan; /* scan for end of run */
  79046. for (;;) {
  79047. /* Make sure that we always have enough lookahead, except
  79048. * at the end of the input file. We need MAX_MATCH bytes
  79049. * for the longest encodable run.
  79050. */
  79051. if (s->lookahead < MAX_MATCH) {
  79052. fill_window(s);
  79053. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  79054. return need_more;
  79055. }
  79056. if (s->lookahead == 0) break; /* flush the current block */
  79057. }
  79058. /* See how many times the previous byte repeats */
  79059. run = 0;
  79060. if (s->strstart > 0) { /* if there is a previous byte, that is */
  79061. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  79062. scan = s->window + s->strstart - 1;
  79063. prev = *scan++;
  79064. do {
  79065. if (*scan++ != prev)
  79066. break;
  79067. } while (++run < max);
  79068. }
  79069. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  79070. if (run >= MIN_MATCH) {
  79071. check_match(s, s->strstart, s->strstart - 1, run);
  79072. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  79073. s->lookahead -= run;
  79074. s->strstart += run;
  79075. } else {
  79076. /* No match, output a literal byte */
  79077. Tracevv((stderr,"%c", s->window[s->strstart]));
  79078. _tr_tally_lit (s, s->window[s->strstart], bflush);
  79079. s->lookahead--;
  79080. s->strstart++;
  79081. }
  79082. if (bflush) FLUSH_BLOCK(s, 0);
  79083. }
  79084. FLUSH_BLOCK(s, flush == Z_FINISH);
  79085. return flush == Z_FINISH ? finish_done : block_done;
  79086. }
  79087. #endif
  79088. /*** End of inlined file: deflate.c ***/
  79089. /*** Start of inlined file: inffast.c ***/
  79090. /*** Start of inlined file: inftrees.h ***/
  79091. /* WARNING: this file should *not* be used by applications. It is
  79092. part of the implementation of the compression library and is
  79093. subject to change. Applications should only use zlib.h.
  79094. */
  79095. #ifndef _INFTREES_H_
  79096. #define _INFTREES_H_
  79097. /* Structure for decoding tables. Each entry provides either the
  79098. information needed to do the operation requested by the code that
  79099. indexed that table entry, or it provides a pointer to another
  79100. table that indexes more bits of the code. op indicates whether
  79101. the entry is a pointer to another table, a literal, a length or
  79102. distance, an end-of-block, or an invalid code. For a table
  79103. pointer, the low four bits of op is the number of index bits of
  79104. that table. For a length or distance, the low four bits of op
  79105. is the number of extra bits to get after the code. bits is
  79106. the number of bits in this code or part of the code to drop off
  79107. of the bit buffer. val is the actual byte to output in the case
  79108. of a literal, the base length or distance, or the offset from
  79109. the current table to the next table. Each entry is four bytes. */
  79110. typedef struct {
  79111. unsigned char op; /* operation, extra bits, table bits */
  79112. unsigned char bits; /* bits in this part of the code */
  79113. unsigned short val; /* offset in table or code value */
  79114. } code;
  79115. /* op values as set by inflate_table():
  79116. 00000000 - literal
  79117. 0000tttt - table link, tttt != 0 is the number of table index bits
  79118. 0001eeee - length or distance, eeee is the number of extra bits
  79119. 01100000 - end of block
  79120. 01000000 - invalid code
  79121. */
  79122. /* Maximum size of dynamic tree. The maximum found in a long but non-
  79123. exhaustive search was 1444 code structures (852 for length/literals
  79124. and 592 for distances, the latter actually the result of an
  79125. exhaustive search). The true maximum is not known, but the value
  79126. below is more than safe. */
  79127. #define ENOUGH 2048
  79128. #define MAXD 592
  79129. /* Type of code to build for inftable() */
  79130. typedef enum {
  79131. CODES,
  79132. LENS,
  79133. DISTS
  79134. } codetype;
  79135. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  79136. unsigned codes, code FAR * FAR *table,
  79137. unsigned FAR *bits, unsigned short FAR *work));
  79138. #endif
  79139. /*** End of inlined file: inftrees.h ***/
  79140. /*** Start of inlined file: inflate.h ***/
  79141. /* WARNING: this file should *not* be used by applications. It is
  79142. part of the implementation of the compression library and is
  79143. subject to change. Applications should only use zlib.h.
  79144. */
  79145. #ifndef _INFLATE_H_
  79146. #define _INFLATE_H_
  79147. /* define NO_GZIP when compiling if you want to disable gzip header and
  79148. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  79149. the crc code when it is not needed. For shared libraries, gzip decoding
  79150. should be left enabled. */
  79151. #ifndef NO_GZIP
  79152. # define GUNZIP
  79153. #endif
  79154. /* Possible inflate modes between inflate() calls */
  79155. typedef enum {
  79156. HEAD, /* i: waiting for magic header */
  79157. FLAGS, /* i: waiting for method and flags (gzip) */
  79158. TIME, /* i: waiting for modification time (gzip) */
  79159. OS, /* i: waiting for extra flags and operating system (gzip) */
  79160. EXLEN, /* i: waiting for extra length (gzip) */
  79161. EXTRA, /* i: waiting for extra bytes (gzip) */
  79162. NAME, /* i: waiting for end of file name (gzip) */
  79163. COMMENT, /* i: waiting for end of comment (gzip) */
  79164. HCRC, /* i: waiting for header crc (gzip) */
  79165. DICTID, /* i: waiting for dictionary check value */
  79166. DICT, /* waiting for inflateSetDictionary() call */
  79167. TYPE, /* i: waiting for type bits, including last-flag bit */
  79168. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  79169. STORED, /* i: waiting for stored size (length and complement) */
  79170. COPY, /* i/o: waiting for input or output to copy stored block */
  79171. TABLE, /* i: waiting for dynamic block table lengths */
  79172. LENLENS, /* i: waiting for code length code lengths */
  79173. CODELENS, /* i: waiting for length/lit and distance code lengths */
  79174. LEN, /* i: waiting for length/lit code */
  79175. LENEXT, /* i: waiting for length extra bits */
  79176. DIST, /* i: waiting for distance code */
  79177. DISTEXT, /* i: waiting for distance extra bits */
  79178. MATCH, /* o: waiting for output space to copy string */
  79179. LIT, /* o: waiting for output space to write literal */
  79180. CHECK, /* i: waiting for 32-bit check value */
  79181. LENGTH, /* i: waiting for 32-bit length (gzip) */
  79182. DONE, /* finished check, done -- remain here until reset */
  79183. BAD, /* got a data error -- remain here until reset */
  79184. MEM, /* got an inflate() memory error -- remain here until reset */
  79185. SYNC /* looking for synchronization bytes to restart inflate() */
  79186. } inflate_mode;
  79187. /*
  79188. State transitions between above modes -
  79189. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  79190. Process header:
  79191. HEAD -> (gzip) or (zlib)
  79192. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  79193. NAME -> COMMENT -> HCRC -> TYPE
  79194. (zlib) -> DICTID or TYPE
  79195. DICTID -> DICT -> TYPE
  79196. Read deflate blocks:
  79197. TYPE -> STORED or TABLE or LEN or CHECK
  79198. STORED -> COPY -> TYPE
  79199. TABLE -> LENLENS -> CODELENS -> LEN
  79200. Read deflate codes:
  79201. LEN -> LENEXT or LIT or TYPE
  79202. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  79203. LIT -> LEN
  79204. Process trailer:
  79205. CHECK -> LENGTH -> DONE
  79206. */
  79207. /* state maintained between inflate() calls. Approximately 7K bytes. */
  79208. struct inflate_state {
  79209. inflate_mode mode; /* current inflate mode */
  79210. int last; /* true if processing last block */
  79211. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  79212. int havedict; /* true if dictionary provided */
  79213. int flags; /* gzip header method and flags (0 if zlib) */
  79214. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  79215. unsigned long check; /* protected copy of check value */
  79216. unsigned long total; /* protected copy of output count */
  79217. gz_headerp head; /* where to save gzip header information */
  79218. /* sliding window */
  79219. unsigned wbits; /* log base 2 of requested window size */
  79220. unsigned wsize; /* window size or zero if not using window */
  79221. unsigned whave; /* valid bytes in the window */
  79222. unsigned write; /* window write index */
  79223. unsigned char FAR *window; /* allocated sliding window, if needed */
  79224. /* bit accumulator */
  79225. unsigned long hold; /* input bit accumulator */
  79226. unsigned bits; /* number of bits in "in" */
  79227. /* for string and stored block copying */
  79228. unsigned length; /* literal or length of data to copy */
  79229. unsigned offset; /* distance back to copy string from */
  79230. /* for table and code decoding */
  79231. unsigned extra; /* extra bits needed */
  79232. /* fixed and dynamic code tables */
  79233. code const FAR *lencode; /* starting table for length/literal codes */
  79234. code const FAR *distcode; /* starting table for distance codes */
  79235. unsigned lenbits; /* index bits for lencode */
  79236. unsigned distbits; /* index bits for distcode */
  79237. /* dynamic table building */
  79238. unsigned ncode; /* number of code length code lengths */
  79239. unsigned nlen; /* number of length code lengths */
  79240. unsigned ndist; /* number of distance code lengths */
  79241. unsigned have; /* number of code lengths in lens[] */
  79242. code FAR *next; /* next available space in codes[] */
  79243. unsigned short lens[320]; /* temporary storage for code lengths */
  79244. unsigned short work[288]; /* work area for code table building */
  79245. code codes[ENOUGH]; /* space for code tables */
  79246. };
  79247. #endif
  79248. /*** End of inlined file: inflate.h ***/
  79249. /*** Start of inlined file: inffast.h ***/
  79250. /* WARNING: this file should *not* be used by applications. It is
  79251. part of the implementation of the compression library and is
  79252. subject to change. Applications should only use zlib.h.
  79253. */
  79254. void inflate_fast OF((z_streamp strm, unsigned start));
  79255. /*** End of inlined file: inffast.h ***/
  79256. #ifndef ASMINF
  79257. /* Allow machine dependent optimization for post-increment or pre-increment.
  79258. Based on testing to date,
  79259. Pre-increment preferred for:
  79260. - PowerPC G3 (Adler)
  79261. - MIPS R5000 (Randers-Pehrson)
  79262. Post-increment preferred for:
  79263. - none
  79264. No measurable difference:
  79265. - Pentium III (Anderson)
  79266. - M68060 (Nikl)
  79267. */
  79268. #ifdef POSTINC
  79269. # define OFF 0
  79270. # define PUP(a) *(a)++
  79271. #else
  79272. # define OFF 1
  79273. # define PUP(a) *++(a)
  79274. #endif
  79275. /*
  79276. Decode literal, length, and distance codes and write out the resulting
  79277. literal and match bytes until either not enough input or output is
  79278. available, an end-of-block is encountered, or a data error is encountered.
  79279. When large enough input and output buffers are supplied to inflate(), for
  79280. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  79281. inflate execution time is spent in this routine.
  79282. Entry assumptions:
  79283. state->mode == LEN
  79284. strm->avail_in >= 6
  79285. strm->avail_out >= 258
  79286. start >= strm->avail_out
  79287. state->bits < 8
  79288. On return, state->mode is one of:
  79289. LEN -- ran out of enough output space or enough available input
  79290. TYPE -- reached end of block code, inflate() to interpret next block
  79291. BAD -- error in block data
  79292. Notes:
  79293. - The maximum input bits used by a length/distance pair is 15 bits for the
  79294. length code, 5 bits for the length extra, 15 bits for the distance code,
  79295. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  79296. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  79297. checking for available input while decoding.
  79298. - The maximum bytes that a single length/distance pair can output is 258
  79299. bytes, which is the maximum length that can be coded. inflate_fast()
  79300. requires strm->avail_out >= 258 for each loop to avoid checking for
  79301. output space.
  79302. */
  79303. void inflate_fast (z_streamp strm, unsigned start)
  79304. {
  79305. struct inflate_state FAR *state;
  79306. unsigned char FAR *in; /* local strm->next_in */
  79307. unsigned char FAR *last; /* while in < last, enough input available */
  79308. unsigned char FAR *out; /* local strm->next_out */
  79309. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  79310. unsigned char FAR *end; /* while out < end, enough space available */
  79311. #ifdef INFLATE_STRICT
  79312. unsigned dmax; /* maximum distance from zlib header */
  79313. #endif
  79314. unsigned wsize; /* window size or zero if not using window */
  79315. unsigned whave; /* valid bytes in the window */
  79316. unsigned write; /* window write index */
  79317. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  79318. unsigned long hold; /* local strm->hold */
  79319. unsigned bits; /* local strm->bits */
  79320. code const FAR *lcode; /* local strm->lencode */
  79321. code const FAR *dcode; /* local strm->distcode */
  79322. unsigned lmask; /* mask for first level of length codes */
  79323. unsigned dmask; /* mask for first level of distance codes */
  79324. code thisx; /* retrieved table entry */
  79325. unsigned op; /* code bits, operation, extra bits, or */
  79326. /* window position, window bytes to copy */
  79327. unsigned len; /* match length, unused bytes */
  79328. unsigned dist; /* match distance */
  79329. unsigned char FAR *from; /* where to copy match from */
  79330. /* copy state to local variables */
  79331. state = (struct inflate_state FAR *)strm->state;
  79332. in = strm->next_in - OFF;
  79333. last = in + (strm->avail_in - 5);
  79334. out = strm->next_out - OFF;
  79335. beg = out - (start - strm->avail_out);
  79336. end = out + (strm->avail_out - 257);
  79337. #ifdef INFLATE_STRICT
  79338. dmax = state->dmax;
  79339. #endif
  79340. wsize = state->wsize;
  79341. whave = state->whave;
  79342. write = state->write;
  79343. window = state->window;
  79344. hold = state->hold;
  79345. bits = state->bits;
  79346. lcode = state->lencode;
  79347. dcode = state->distcode;
  79348. lmask = (1U << state->lenbits) - 1;
  79349. dmask = (1U << state->distbits) - 1;
  79350. /* decode literals and length/distances until end-of-block or not enough
  79351. input data or output space */
  79352. do {
  79353. if (bits < 15) {
  79354. hold += (unsigned long)(PUP(in)) << bits;
  79355. bits += 8;
  79356. hold += (unsigned long)(PUP(in)) << bits;
  79357. bits += 8;
  79358. }
  79359. thisx = lcode[hold & lmask];
  79360. dolen:
  79361. op = (unsigned)(thisx.bits);
  79362. hold >>= op;
  79363. bits -= op;
  79364. op = (unsigned)(thisx.op);
  79365. if (op == 0) { /* literal */
  79366. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79367. "inflate: literal '%c'\n" :
  79368. "inflate: literal 0x%02x\n", thisx.val));
  79369. PUP(out) = (unsigned char)(thisx.val);
  79370. }
  79371. else if (op & 16) { /* length base */
  79372. len = (unsigned)(thisx.val);
  79373. op &= 15; /* number of extra bits */
  79374. if (op) {
  79375. if (bits < op) {
  79376. hold += (unsigned long)(PUP(in)) << bits;
  79377. bits += 8;
  79378. }
  79379. len += (unsigned)hold & ((1U << op) - 1);
  79380. hold >>= op;
  79381. bits -= op;
  79382. }
  79383. Tracevv((stderr, "inflate: length %u\n", len));
  79384. if (bits < 15) {
  79385. hold += (unsigned long)(PUP(in)) << bits;
  79386. bits += 8;
  79387. hold += (unsigned long)(PUP(in)) << bits;
  79388. bits += 8;
  79389. }
  79390. thisx = dcode[hold & dmask];
  79391. dodist:
  79392. op = (unsigned)(thisx.bits);
  79393. hold >>= op;
  79394. bits -= op;
  79395. op = (unsigned)(thisx.op);
  79396. if (op & 16) { /* distance base */
  79397. dist = (unsigned)(thisx.val);
  79398. op &= 15; /* number of extra bits */
  79399. if (bits < op) {
  79400. hold += (unsigned long)(PUP(in)) << bits;
  79401. bits += 8;
  79402. if (bits < op) {
  79403. hold += (unsigned long)(PUP(in)) << bits;
  79404. bits += 8;
  79405. }
  79406. }
  79407. dist += (unsigned)hold & ((1U << op) - 1);
  79408. #ifdef INFLATE_STRICT
  79409. if (dist > dmax) {
  79410. strm->msg = (char *)"invalid distance too far back";
  79411. state->mode = BAD;
  79412. break;
  79413. }
  79414. #endif
  79415. hold >>= op;
  79416. bits -= op;
  79417. Tracevv((stderr, "inflate: distance %u\n", dist));
  79418. op = (unsigned)(out - beg); /* max distance in output */
  79419. if (dist > op) { /* see if copy from window */
  79420. op = dist - op; /* distance back in window */
  79421. if (op > whave) {
  79422. strm->msg = (char *)"invalid distance too far back";
  79423. state->mode = BAD;
  79424. break;
  79425. }
  79426. from = window - OFF;
  79427. if (write == 0) { /* very common case */
  79428. from += wsize - op;
  79429. if (op < len) { /* some from window */
  79430. len -= op;
  79431. do {
  79432. PUP(out) = PUP(from);
  79433. } while (--op);
  79434. from = out - dist; /* rest from output */
  79435. }
  79436. }
  79437. else if (write < op) { /* wrap around window */
  79438. from += wsize + write - op;
  79439. op -= write;
  79440. if (op < len) { /* some from end of window */
  79441. len -= op;
  79442. do {
  79443. PUP(out) = PUP(from);
  79444. } while (--op);
  79445. from = window - OFF;
  79446. if (write < len) { /* some from start of window */
  79447. op = write;
  79448. len -= op;
  79449. do {
  79450. PUP(out) = PUP(from);
  79451. } while (--op);
  79452. from = out - dist; /* rest from output */
  79453. }
  79454. }
  79455. }
  79456. else { /* contiguous in window */
  79457. from += write - op;
  79458. if (op < len) { /* some from window */
  79459. len -= op;
  79460. do {
  79461. PUP(out) = PUP(from);
  79462. } while (--op);
  79463. from = out - dist; /* rest from output */
  79464. }
  79465. }
  79466. while (len > 2) {
  79467. PUP(out) = PUP(from);
  79468. PUP(out) = PUP(from);
  79469. PUP(out) = PUP(from);
  79470. len -= 3;
  79471. }
  79472. if (len) {
  79473. PUP(out) = PUP(from);
  79474. if (len > 1)
  79475. PUP(out) = PUP(from);
  79476. }
  79477. }
  79478. else {
  79479. from = out - dist; /* copy direct from output */
  79480. do { /* minimum length is three */
  79481. PUP(out) = PUP(from);
  79482. PUP(out) = PUP(from);
  79483. PUP(out) = PUP(from);
  79484. len -= 3;
  79485. } while (len > 2);
  79486. if (len) {
  79487. PUP(out) = PUP(from);
  79488. if (len > 1)
  79489. PUP(out) = PUP(from);
  79490. }
  79491. }
  79492. }
  79493. else if ((op & 64) == 0) { /* 2nd level distance code */
  79494. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  79495. goto dodist;
  79496. }
  79497. else {
  79498. strm->msg = (char *)"invalid distance code";
  79499. state->mode = BAD;
  79500. break;
  79501. }
  79502. }
  79503. else if ((op & 64) == 0) { /* 2nd level length code */
  79504. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  79505. goto dolen;
  79506. }
  79507. else if (op & 32) { /* end-of-block */
  79508. Tracevv((stderr, "inflate: end of block\n"));
  79509. state->mode = TYPE;
  79510. break;
  79511. }
  79512. else {
  79513. strm->msg = (char *)"invalid literal/length code";
  79514. state->mode = BAD;
  79515. break;
  79516. }
  79517. } while (in < last && out < end);
  79518. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  79519. len = bits >> 3;
  79520. in -= len;
  79521. bits -= len << 3;
  79522. hold &= (1U << bits) - 1;
  79523. /* update state and return */
  79524. strm->next_in = in + OFF;
  79525. strm->next_out = out + OFF;
  79526. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  79527. strm->avail_out = (unsigned)(out < end ?
  79528. 257 + (end - out) : 257 - (out - end));
  79529. state->hold = hold;
  79530. state->bits = bits;
  79531. return;
  79532. }
  79533. /*
  79534. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  79535. - Using bit fields for code structure
  79536. - Different op definition to avoid & for extra bits (do & for table bits)
  79537. - Three separate decoding do-loops for direct, window, and write == 0
  79538. - Special case for distance > 1 copies to do overlapped load and store copy
  79539. - Explicit branch predictions (based on measured branch probabilities)
  79540. - Deferring match copy and interspersed it with decoding subsequent codes
  79541. - Swapping literal/length else
  79542. - Swapping window/direct else
  79543. - Larger unrolled copy loops (three is about right)
  79544. - Moving len -= 3 statement into middle of loop
  79545. */
  79546. #endif /* !ASMINF */
  79547. /*** End of inlined file: inffast.c ***/
  79548. #undef PULLBYTE
  79549. #undef LOAD
  79550. #undef RESTORE
  79551. #undef INITBITS
  79552. #undef NEEDBITS
  79553. #undef DROPBITS
  79554. #undef BYTEBITS
  79555. /*** Start of inlined file: inflate.c ***/
  79556. /*
  79557. * Change history:
  79558. *
  79559. * 1.2.beta0 24 Nov 2002
  79560. * - First version -- complete rewrite of inflate to simplify code, avoid
  79561. * creation of window when not needed, minimize use of window when it is
  79562. * needed, make inffast.c even faster, implement gzip decoding, and to
  79563. * improve code readability and style over the previous zlib inflate code
  79564. *
  79565. * 1.2.beta1 25 Nov 2002
  79566. * - Use pointers for available input and output checking in inffast.c
  79567. * - Remove input and output counters in inffast.c
  79568. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  79569. * - Remove unnecessary second byte pull from length extra in inffast.c
  79570. * - Unroll direct copy to three copies per loop in inffast.c
  79571. *
  79572. * 1.2.beta2 4 Dec 2002
  79573. * - Change external routine names to reduce potential conflicts
  79574. * - Correct filename to inffixed.h for fixed tables in inflate.c
  79575. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  79576. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  79577. * to avoid negation problem on Alphas (64 bit) in inflate.c
  79578. *
  79579. * 1.2.beta3 22 Dec 2002
  79580. * - Add comments on state->bits assertion in inffast.c
  79581. * - Add comments on op field in inftrees.h
  79582. * - Fix bug in reuse of allocated window after inflateReset()
  79583. * - Remove bit fields--back to byte structure for speed
  79584. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  79585. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  79586. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  79587. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  79588. * - Use local copies of stream next and avail values, as well as local bit
  79589. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  79590. *
  79591. * 1.2.beta4 1 Jan 2003
  79592. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  79593. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  79594. * - Add comments in inffast.c to introduce the inflate_fast() routine
  79595. * - Rearrange window copies in inflate_fast() for speed and simplification
  79596. * - Unroll last copy for window match in inflate_fast()
  79597. * - Use local copies of window variables in inflate_fast() for speed
  79598. * - Pull out common write == 0 case for speed in inflate_fast()
  79599. * - Make op and len in inflate_fast() unsigned for consistency
  79600. * - Add FAR to lcode and dcode declarations in inflate_fast()
  79601. * - Simplified bad distance check in inflate_fast()
  79602. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  79603. * source file infback.c to provide a call-back interface to inflate for
  79604. * programs like gzip and unzip -- uses window as output buffer to avoid
  79605. * window copying
  79606. *
  79607. * 1.2.beta5 1 Jan 2003
  79608. * - Improved inflateBack() interface to allow the caller to provide initial
  79609. * input in strm.
  79610. * - Fixed stored blocks bug in inflateBack()
  79611. *
  79612. * 1.2.beta6 4 Jan 2003
  79613. * - Added comments in inffast.c on effectiveness of POSTINC
  79614. * - Typecasting all around to reduce compiler warnings
  79615. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  79616. * make compilers happy
  79617. * - Changed type of window in inflateBackInit() to unsigned char *
  79618. *
  79619. * 1.2.beta7 27 Jan 2003
  79620. * - Changed many types to unsigned or unsigned short to avoid warnings
  79621. * - Added inflateCopy() function
  79622. *
  79623. * 1.2.0 9 Mar 2003
  79624. * - Changed inflateBack() interface to provide separate opaque descriptors
  79625. * for the in() and out() functions
  79626. * - Changed inflateBack() argument and in_func typedef to swap the length
  79627. * and buffer address return values for the input function
  79628. * - Check next_in and next_out for Z_NULL on entry to inflate()
  79629. *
  79630. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  79631. */
  79632. /*** Start of inlined file: inffast.h ***/
  79633. /* WARNING: this file should *not* be used by applications. It is
  79634. part of the implementation of the compression library and is
  79635. subject to change. Applications should only use zlib.h.
  79636. */
  79637. void inflate_fast OF((z_streamp strm, unsigned start));
  79638. /*** End of inlined file: inffast.h ***/
  79639. #ifdef MAKEFIXED
  79640. # ifndef BUILDFIXED
  79641. # define BUILDFIXED
  79642. # endif
  79643. #endif
  79644. /* function prototypes */
  79645. local void fixedtables OF((struct inflate_state FAR *state));
  79646. local int updatewindow OF((z_streamp strm, unsigned out));
  79647. #ifdef BUILDFIXED
  79648. void makefixed OF((void));
  79649. #endif
  79650. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  79651. unsigned len));
  79652. int ZEXPORT inflateReset (z_streamp strm)
  79653. {
  79654. struct inflate_state FAR *state;
  79655. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79656. state = (struct inflate_state FAR *)strm->state;
  79657. strm->total_in = strm->total_out = state->total = 0;
  79658. strm->msg = Z_NULL;
  79659. strm->adler = 1; /* to support ill-conceived Java test suite */
  79660. state->mode = HEAD;
  79661. state->last = 0;
  79662. state->havedict = 0;
  79663. state->dmax = 32768U;
  79664. state->head = Z_NULL;
  79665. state->wsize = 0;
  79666. state->whave = 0;
  79667. state->write = 0;
  79668. state->hold = 0;
  79669. state->bits = 0;
  79670. state->lencode = state->distcode = state->next = state->codes;
  79671. Tracev((stderr, "inflate: reset\n"));
  79672. return Z_OK;
  79673. }
  79674. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  79675. {
  79676. struct inflate_state FAR *state;
  79677. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79678. state = (struct inflate_state FAR *)strm->state;
  79679. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  79680. value &= (1L << bits) - 1;
  79681. state->hold += value << state->bits;
  79682. state->bits += bits;
  79683. return Z_OK;
  79684. }
  79685. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  79686. {
  79687. struct inflate_state FAR *state;
  79688. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  79689. stream_size != (int)(sizeof(z_stream)))
  79690. return Z_VERSION_ERROR;
  79691. if (strm == Z_NULL) return Z_STREAM_ERROR;
  79692. strm->msg = Z_NULL; /* in case we return an error */
  79693. if (strm->zalloc == (alloc_func)0) {
  79694. strm->zalloc = zcalloc;
  79695. strm->opaque = (voidpf)0;
  79696. }
  79697. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  79698. state = (struct inflate_state FAR *)
  79699. ZALLOC(strm, 1, sizeof(struct inflate_state));
  79700. if (state == Z_NULL) return Z_MEM_ERROR;
  79701. Tracev((stderr, "inflate: allocated\n"));
  79702. strm->state = (struct internal_state FAR *)state;
  79703. if (windowBits < 0) {
  79704. state->wrap = 0;
  79705. windowBits = -windowBits;
  79706. }
  79707. else {
  79708. state->wrap = (windowBits >> 4) + 1;
  79709. #ifdef GUNZIP
  79710. if (windowBits < 48) windowBits &= 15;
  79711. #endif
  79712. }
  79713. if (windowBits < 8 || windowBits > 15) {
  79714. ZFREE(strm, state);
  79715. strm->state = Z_NULL;
  79716. return Z_STREAM_ERROR;
  79717. }
  79718. state->wbits = (unsigned)windowBits;
  79719. state->window = Z_NULL;
  79720. return inflateReset(strm);
  79721. }
  79722. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  79723. {
  79724. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  79725. }
  79726. /*
  79727. Return state with length and distance decoding tables and index sizes set to
  79728. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  79729. If BUILDFIXED is defined, then instead this routine builds the tables the
  79730. first time it's called, and returns those tables the first time and
  79731. thereafter. This reduces the size of the code by about 2K bytes, in
  79732. exchange for a little execution time. However, BUILDFIXED should not be
  79733. used for threaded applications, since the rewriting of the tables and virgin
  79734. may not be thread-safe.
  79735. */
  79736. local void fixedtables (struct inflate_state FAR *state)
  79737. {
  79738. #ifdef BUILDFIXED
  79739. static int virgin = 1;
  79740. static code *lenfix, *distfix;
  79741. static code fixed[544];
  79742. /* build fixed huffman tables if first call (may not be thread safe) */
  79743. if (virgin) {
  79744. unsigned sym, bits;
  79745. static code *next;
  79746. /* literal/length table */
  79747. sym = 0;
  79748. while (sym < 144) state->lens[sym++] = 8;
  79749. while (sym < 256) state->lens[sym++] = 9;
  79750. while (sym < 280) state->lens[sym++] = 7;
  79751. while (sym < 288) state->lens[sym++] = 8;
  79752. next = fixed;
  79753. lenfix = next;
  79754. bits = 9;
  79755. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  79756. /* distance table */
  79757. sym = 0;
  79758. while (sym < 32) state->lens[sym++] = 5;
  79759. distfix = next;
  79760. bits = 5;
  79761. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  79762. /* do this just once */
  79763. virgin = 0;
  79764. }
  79765. #else /* !BUILDFIXED */
  79766. /*** Start of inlined file: inffixed.h ***/
  79767. /* WARNING: this file should *not* be used by applications. It
  79768. is part of the implementation of the compression library and
  79769. is subject to change. Applications should only use zlib.h.
  79770. */
  79771. static const code lenfix[512] = {
  79772. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  79773. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  79774. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  79775. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  79776. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  79777. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  79778. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  79779. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  79780. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  79781. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  79782. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  79783. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  79784. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  79785. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  79786. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  79787. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  79788. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  79789. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  79790. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  79791. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  79792. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  79793. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  79794. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  79795. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  79796. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  79797. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  79798. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  79799. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  79800. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  79801. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  79802. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  79803. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  79804. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  79805. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  79806. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  79807. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  79808. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  79809. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  79810. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  79811. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  79812. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  79813. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  79814. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  79815. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  79816. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  79817. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  79818. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  79819. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  79820. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  79821. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  79822. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  79823. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  79824. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  79825. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  79826. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  79827. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  79828. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  79829. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  79830. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  79831. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  79832. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  79833. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  79834. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  79835. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  79836. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  79837. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  79838. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  79839. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  79840. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  79841. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  79842. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  79843. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  79844. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  79845. {0,9,255}
  79846. };
  79847. static const code distfix[32] = {
  79848. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  79849. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  79850. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  79851. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  79852. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  79853. {22,5,193},{64,5,0}
  79854. };
  79855. /*** End of inlined file: inffixed.h ***/
  79856. #endif /* BUILDFIXED */
  79857. state->lencode = lenfix;
  79858. state->lenbits = 9;
  79859. state->distcode = distfix;
  79860. state->distbits = 5;
  79861. }
  79862. #ifdef MAKEFIXED
  79863. #include <stdio.h>
  79864. /*
  79865. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  79866. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  79867. those tables to stdout, which would be piped to inffixed.h. A small program
  79868. can simply call makefixed to do this:
  79869. void makefixed(void);
  79870. int main(void)
  79871. {
  79872. makefixed();
  79873. return 0;
  79874. }
  79875. Then that can be linked with zlib built with MAKEFIXED defined and run:
  79876. a.out > inffixed.h
  79877. */
  79878. void makefixed()
  79879. {
  79880. unsigned low, size;
  79881. struct inflate_state state;
  79882. fixedtables(&state);
  79883. puts(" /* inffixed.h -- table for decoding fixed codes");
  79884. puts(" * Generated automatically by makefixed().");
  79885. puts(" */");
  79886. puts("");
  79887. puts(" /* WARNING: this file should *not* be used by applications.");
  79888. puts(" It is part of the implementation of this library and is");
  79889. puts(" subject to change. Applications should only use zlib.h.");
  79890. puts(" */");
  79891. puts("");
  79892. size = 1U << 9;
  79893. printf(" static const code lenfix[%u] = {", size);
  79894. low = 0;
  79895. for (;;) {
  79896. if ((low % 7) == 0) printf("\n ");
  79897. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  79898. state.lencode[low].val);
  79899. if (++low == size) break;
  79900. putchar(',');
  79901. }
  79902. puts("\n };");
  79903. size = 1U << 5;
  79904. printf("\n static const code distfix[%u] = {", size);
  79905. low = 0;
  79906. for (;;) {
  79907. if ((low % 6) == 0) printf("\n ");
  79908. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  79909. state.distcode[low].val);
  79910. if (++low == size) break;
  79911. putchar(',');
  79912. }
  79913. puts("\n };");
  79914. }
  79915. #endif /* MAKEFIXED */
  79916. /*
  79917. Update the window with the last wsize (normally 32K) bytes written before
  79918. returning. If window does not exist yet, create it. This is only called
  79919. when a window is already in use, or when output has been written during this
  79920. inflate call, but the end of the deflate stream has not been reached yet.
  79921. It is also called to create a window for dictionary data when a dictionary
  79922. is loaded.
  79923. Providing output buffers larger than 32K to inflate() should provide a speed
  79924. advantage, since only the last 32K of output is copied to the sliding window
  79925. upon return from inflate(), and since all distances after the first 32K of
  79926. output will fall in the output data, making match copies simpler and faster.
  79927. The advantage may be dependent on the size of the processor's data caches.
  79928. */
  79929. local int updatewindow (z_streamp strm, unsigned out)
  79930. {
  79931. struct inflate_state FAR *state;
  79932. unsigned copy, dist;
  79933. state = (struct inflate_state FAR *)strm->state;
  79934. /* if it hasn't been done already, allocate space for the window */
  79935. if (state->window == Z_NULL) {
  79936. state->window = (unsigned char FAR *)
  79937. ZALLOC(strm, 1U << state->wbits,
  79938. sizeof(unsigned char));
  79939. if (state->window == Z_NULL) return 1;
  79940. }
  79941. /* if window not in use yet, initialize */
  79942. if (state->wsize == 0) {
  79943. state->wsize = 1U << state->wbits;
  79944. state->write = 0;
  79945. state->whave = 0;
  79946. }
  79947. /* copy state->wsize or less output bytes into the circular window */
  79948. copy = out - strm->avail_out;
  79949. if (copy >= state->wsize) {
  79950. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  79951. state->write = 0;
  79952. state->whave = state->wsize;
  79953. }
  79954. else {
  79955. dist = state->wsize - state->write;
  79956. if (dist > copy) dist = copy;
  79957. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  79958. copy -= dist;
  79959. if (copy) {
  79960. zmemcpy(state->window, strm->next_out - copy, copy);
  79961. state->write = copy;
  79962. state->whave = state->wsize;
  79963. }
  79964. else {
  79965. state->write += dist;
  79966. if (state->write == state->wsize) state->write = 0;
  79967. if (state->whave < state->wsize) state->whave += dist;
  79968. }
  79969. }
  79970. return 0;
  79971. }
  79972. /* Macros for inflate(): */
  79973. /* check function to use adler32() for zlib or crc32() for gzip */
  79974. #ifdef GUNZIP
  79975. # define UPDATE(check, buf, len) \
  79976. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  79977. #else
  79978. # define UPDATE(check, buf, len) adler32(check, buf, len)
  79979. #endif
  79980. /* check macros for header crc */
  79981. #ifdef GUNZIP
  79982. # define CRC2(check, word) \
  79983. do { \
  79984. hbuf[0] = (unsigned char)(word); \
  79985. hbuf[1] = (unsigned char)((word) >> 8); \
  79986. check = crc32(check, hbuf, 2); \
  79987. } while (0)
  79988. # define CRC4(check, word) \
  79989. do { \
  79990. hbuf[0] = (unsigned char)(word); \
  79991. hbuf[1] = (unsigned char)((word) >> 8); \
  79992. hbuf[2] = (unsigned char)((word) >> 16); \
  79993. hbuf[3] = (unsigned char)((word) >> 24); \
  79994. check = crc32(check, hbuf, 4); \
  79995. } while (0)
  79996. #endif
  79997. /* Load registers with state in inflate() for speed */
  79998. #define LOAD() \
  79999. do { \
  80000. put = strm->next_out; \
  80001. left = strm->avail_out; \
  80002. next = strm->next_in; \
  80003. have = strm->avail_in; \
  80004. hold = state->hold; \
  80005. bits = state->bits; \
  80006. } while (0)
  80007. /* Restore state from registers in inflate() */
  80008. #define RESTORE() \
  80009. do { \
  80010. strm->next_out = put; \
  80011. strm->avail_out = left; \
  80012. strm->next_in = next; \
  80013. strm->avail_in = have; \
  80014. state->hold = hold; \
  80015. state->bits = bits; \
  80016. } while (0)
  80017. /* Clear the input bit accumulator */
  80018. #define INITBITS() \
  80019. do { \
  80020. hold = 0; \
  80021. bits = 0; \
  80022. } while (0)
  80023. /* Get a byte of input into the bit accumulator, or return from inflate()
  80024. if there is no input available. */
  80025. #define PULLBYTE() \
  80026. do { \
  80027. if (have == 0) goto inf_leave; \
  80028. have--; \
  80029. hold += (unsigned long)(*next++) << bits; \
  80030. bits += 8; \
  80031. } while (0)
  80032. /* Assure that there are at least n bits in the bit accumulator. If there is
  80033. not enough available input to do that, then return from inflate(). */
  80034. #define NEEDBITS(n) \
  80035. do { \
  80036. while (bits < (unsigned)(n)) \
  80037. PULLBYTE(); \
  80038. } while (0)
  80039. /* Return the low n bits of the bit accumulator (n < 16) */
  80040. #define BITS(n) \
  80041. ((unsigned)hold & ((1U << (n)) - 1))
  80042. /* Remove n bits from the bit accumulator */
  80043. #define DROPBITS(n) \
  80044. do { \
  80045. hold >>= (n); \
  80046. bits -= (unsigned)(n); \
  80047. } while (0)
  80048. /* Remove zero to seven bits as needed to go to a byte boundary */
  80049. #define BYTEBITS() \
  80050. do { \
  80051. hold >>= bits & 7; \
  80052. bits -= bits & 7; \
  80053. } while (0)
  80054. /* Reverse the bytes in a 32-bit value */
  80055. #define REVERSE(q) \
  80056. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  80057. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  80058. /*
  80059. inflate() uses a state machine to process as much input data and generate as
  80060. much output data as possible before returning. The state machine is
  80061. structured roughly as follows:
  80062. for (;;) switch (state) {
  80063. ...
  80064. case STATEn:
  80065. if (not enough input data or output space to make progress)
  80066. return;
  80067. ... make progress ...
  80068. state = STATEm;
  80069. break;
  80070. ...
  80071. }
  80072. so when inflate() is called again, the same case is attempted again, and
  80073. if the appropriate resources are provided, the machine proceeds to the
  80074. next state. The NEEDBITS() macro is usually the way the state evaluates
  80075. whether it can proceed or should return. NEEDBITS() does the return if
  80076. the requested bits are not available. The typical use of the BITS macros
  80077. is:
  80078. NEEDBITS(n);
  80079. ... do something with BITS(n) ...
  80080. DROPBITS(n);
  80081. where NEEDBITS(n) either returns from inflate() if there isn't enough
  80082. input left to load n bits into the accumulator, or it continues. BITS(n)
  80083. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  80084. the low n bits off the accumulator. INITBITS() clears the accumulator
  80085. and sets the number of available bits to zero. BYTEBITS() discards just
  80086. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  80087. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  80088. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  80089. if there is no input available. The decoding of variable length codes uses
  80090. PULLBYTE() directly in order to pull just enough bytes to decode the next
  80091. code, and no more.
  80092. Some states loop until they get enough input, making sure that enough
  80093. state information is maintained to continue the loop where it left off
  80094. if NEEDBITS() returns in the loop. For example, want, need, and keep
  80095. would all have to actually be part of the saved state in case NEEDBITS()
  80096. returns:
  80097. case STATEw:
  80098. while (want < need) {
  80099. NEEDBITS(n);
  80100. keep[want++] = BITS(n);
  80101. DROPBITS(n);
  80102. }
  80103. state = STATEx;
  80104. case STATEx:
  80105. As shown above, if the next state is also the next case, then the break
  80106. is omitted.
  80107. A state may also return if there is not enough output space available to
  80108. complete that state. Those states are copying stored data, writing a
  80109. literal byte, and copying a matching string.
  80110. When returning, a "goto inf_leave" is used to update the total counters,
  80111. update the check value, and determine whether any progress has been made
  80112. during that inflate() call in order to return the proper return code.
  80113. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  80114. When there is a window, goto inf_leave will update the window with the last
  80115. output written. If a goto inf_leave occurs in the middle of decompression
  80116. and there is no window currently, goto inf_leave will create one and copy
  80117. output to the window for the next call of inflate().
  80118. In this implementation, the flush parameter of inflate() only affects the
  80119. return code (per zlib.h). inflate() always writes as much as possible to
  80120. strm->next_out, given the space available and the provided input--the effect
  80121. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  80122. the allocation of and copying into a sliding window until necessary, which
  80123. provides the effect documented in zlib.h for Z_FINISH when the entire input
  80124. stream available. So the only thing the flush parameter actually does is:
  80125. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  80126. will return Z_BUF_ERROR if it has not reached the end of the stream.
  80127. */
  80128. int ZEXPORT inflate (z_streamp strm, int flush)
  80129. {
  80130. struct inflate_state FAR *state;
  80131. unsigned char FAR *next; /* next input */
  80132. unsigned char FAR *put; /* next output */
  80133. unsigned have, left; /* available input and output */
  80134. unsigned long hold; /* bit buffer */
  80135. unsigned bits; /* bits in bit buffer */
  80136. unsigned in, out; /* save starting available input and output */
  80137. unsigned copy; /* number of stored or match bytes to copy */
  80138. unsigned char FAR *from; /* where to copy match bytes from */
  80139. code thisx; /* current decoding table entry */
  80140. code last; /* parent table entry */
  80141. unsigned len; /* length to copy for repeats, bits to drop */
  80142. int ret; /* return code */
  80143. #ifdef GUNZIP
  80144. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  80145. #endif
  80146. static const unsigned short order[19] = /* permutation of code lengths */
  80147. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  80148. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  80149. (strm->next_in == Z_NULL && strm->avail_in != 0))
  80150. return Z_STREAM_ERROR;
  80151. state = (struct inflate_state FAR *)strm->state;
  80152. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  80153. LOAD();
  80154. in = have;
  80155. out = left;
  80156. ret = Z_OK;
  80157. for (;;)
  80158. switch (state->mode) {
  80159. case HEAD:
  80160. if (state->wrap == 0) {
  80161. state->mode = TYPEDO;
  80162. break;
  80163. }
  80164. NEEDBITS(16);
  80165. #ifdef GUNZIP
  80166. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  80167. state->check = crc32(0L, Z_NULL, 0);
  80168. CRC2(state->check, hold);
  80169. INITBITS();
  80170. state->mode = FLAGS;
  80171. break;
  80172. }
  80173. state->flags = 0; /* expect zlib header */
  80174. if (state->head != Z_NULL)
  80175. state->head->done = -1;
  80176. if (!(state->wrap & 1) || /* check if zlib header allowed */
  80177. #else
  80178. if (
  80179. #endif
  80180. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  80181. strm->msg = (char *)"incorrect header check";
  80182. state->mode = BAD;
  80183. break;
  80184. }
  80185. if (BITS(4) != Z_DEFLATED) {
  80186. strm->msg = (char *)"unknown compression method";
  80187. state->mode = BAD;
  80188. break;
  80189. }
  80190. DROPBITS(4);
  80191. len = BITS(4) + 8;
  80192. if (len > state->wbits) {
  80193. strm->msg = (char *)"invalid window size";
  80194. state->mode = BAD;
  80195. break;
  80196. }
  80197. state->dmax = 1U << len;
  80198. Tracev((stderr, "inflate: zlib header ok\n"));
  80199. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80200. state->mode = hold & 0x200 ? DICTID : TYPE;
  80201. INITBITS();
  80202. break;
  80203. #ifdef GUNZIP
  80204. case FLAGS:
  80205. NEEDBITS(16);
  80206. state->flags = (int)(hold);
  80207. if ((state->flags & 0xff) != Z_DEFLATED) {
  80208. strm->msg = (char *)"unknown compression method";
  80209. state->mode = BAD;
  80210. break;
  80211. }
  80212. if (state->flags & 0xe000) {
  80213. strm->msg = (char *)"unknown header flags set";
  80214. state->mode = BAD;
  80215. break;
  80216. }
  80217. if (state->head != Z_NULL)
  80218. state->head->text = (int)((hold >> 8) & 1);
  80219. if (state->flags & 0x0200) CRC2(state->check, hold);
  80220. INITBITS();
  80221. state->mode = TIME;
  80222. case TIME:
  80223. NEEDBITS(32);
  80224. if (state->head != Z_NULL)
  80225. state->head->time = hold;
  80226. if (state->flags & 0x0200) CRC4(state->check, hold);
  80227. INITBITS();
  80228. state->mode = OS;
  80229. case OS:
  80230. NEEDBITS(16);
  80231. if (state->head != Z_NULL) {
  80232. state->head->xflags = (int)(hold & 0xff);
  80233. state->head->os = (int)(hold >> 8);
  80234. }
  80235. if (state->flags & 0x0200) CRC2(state->check, hold);
  80236. INITBITS();
  80237. state->mode = EXLEN;
  80238. case EXLEN:
  80239. if (state->flags & 0x0400) {
  80240. NEEDBITS(16);
  80241. state->length = (unsigned)(hold);
  80242. if (state->head != Z_NULL)
  80243. state->head->extra_len = (unsigned)hold;
  80244. if (state->flags & 0x0200) CRC2(state->check, hold);
  80245. INITBITS();
  80246. }
  80247. else if (state->head != Z_NULL)
  80248. state->head->extra = Z_NULL;
  80249. state->mode = EXTRA;
  80250. case EXTRA:
  80251. if (state->flags & 0x0400) {
  80252. copy = state->length;
  80253. if (copy > have) copy = have;
  80254. if (copy) {
  80255. if (state->head != Z_NULL &&
  80256. state->head->extra != Z_NULL) {
  80257. len = state->head->extra_len - state->length;
  80258. zmemcpy(state->head->extra + len, next,
  80259. len + copy > state->head->extra_max ?
  80260. state->head->extra_max - len : copy);
  80261. }
  80262. if (state->flags & 0x0200)
  80263. state->check = crc32(state->check, next, copy);
  80264. have -= copy;
  80265. next += copy;
  80266. state->length -= copy;
  80267. }
  80268. if (state->length) goto inf_leave;
  80269. }
  80270. state->length = 0;
  80271. state->mode = NAME;
  80272. case NAME:
  80273. if (state->flags & 0x0800) {
  80274. if (have == 0) goto inf_leave;
  80275. copy = 0;
  80276. do {
  80277. len = (unsigned)(next[copy++]);
  80278. if (state->head != Z_NULL &&
  80279. state->head->name != Z_NULL &&
  80280. state->length < state->head->name_max)
  80281. state->head->name[state->length++] = len;
  80282. } while (len && copy < have);
  80283. if (state->flags & 0x0200)
  80284. state->check = crc32(state->check, next, copy);
  80285. have -= copy;
  80286. next += copy;
  80287. if (len) goto inf_leave;
  80288. }
  80289. else if (state->head != Z_NULL)
  80290. state->head->name = Z_NULL;
  80291. state->length = 0;
  80292. state->mode = COMMENT;
  80293. case COMMENT:
  80294. if (state->flags & 0x1000) {
  80295. if (have == 0) goto inf_leave;
  80296. copy = 0;
  80297. do {
  80298. len = (unsigned)(next[copy++]);
  80299. if (state->head != Z_NULL &&
  80300. state->head->comment != Z_NULL &&
  80301. state->length < state->head->comm_max)
  80302. state->head->comment[state->length++] = len;
  80303. } while (len && copy < have);
  80304. if (state->flags & 0x0200)
  80305. state->check = crc32(state->check, next, copy);
  80306. have -= copy;
  80307. next += copy;
  80308. if (len) goto inf_leave;
  80309. }
  80310. else if (state->head != Z_NULL)
  80311. state->head->comment = Z_NULL;
  80312. state->mode = HCRC;
  80313. case HCRC:
  80314. if (state->flags & 0x0200) {
  80315. NEEDBITS(16);
  80316. if (hold != (state->check & 0xffff)) {
  80317. strm->msg = (char *)"header crc mismatch";
  80318. state->mode = BAD;
  80319. break;
  80320. }
  80321. INITBITS();
  80322. }
  80323. if (state->head != Z_NULL) {
  80324. state->head->hcrc = (int)((state->flags >> 9) & 1);
  80325. state->head->done = 1;
  80326. }
  80327. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  80328. state->mode = TYPE;
  80329. break;
  80330. #endif
  80331. case DICTID:
  80332. NEEDBITS(32);
  80333. strm->adler = state->check = REVERSE(hold);
  80334. INITBITS();
  80335. state->mode = DICT;
  80336. case DICT:
  80337. if (state->havedict == 0) {
  80338. RESTORE();
  80339. return Z_NEED_DICT;
  80340. }
  80341. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80342. state->mode = TYPE;
  80343. case TYPE:
  80344. if (flush == Z_BLOCK) goto inf_leave;
  80345. case TYPEDO:
  80346. if (state->last) {
  80347. BYTEBITS();
  80348. state->mode = CHECK;
  80349. break;
  80350. }
  80351. NEEDBITS(3);
  80352. state->last = BITS(1);
  80353. DROPBITS(1);
  80354. switch (BITS(2)) {
  80355. case 0: /* stored block */
  80356. Tracev((stderr, "inflate: stored block%s\n",
  80357. state->last ? " (last)" : ""));
  80358. state->mode = STORED;
  80359. break;
  80360. case 1: /* fixed block */
  80361. fixedtables(state);
  80362. Tracev((stderr, "inflate: fixed codes block%s\n",
  80363. state->last ? " (last)" : ""));
  80364. state->mode = LEN; /* decode codes */
  80365. break;
  80366. case 2: /* dynamic block */
  80367. Tracev((stderr, "inflate: dynamic codes block%s\n",
  80368. state->last ? " (last)" : ""));
  80369. state->mode = TABLE;
  80370. break;
  80371. case 3:
  80372. strm->msg = (char *)"invalid block type";
  80373. state->mode = BAD;
  80374. }
  80375. DROPBITS(2);
  80376. break;
  80377. case STORED:
  80378. BYTEBITS(); /* go to byte boundary */
  80379. NEEDBITS(32);
  80380. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  80381. strm->msg = (char *)"invalid stored block lengths";
  80382. state->mode = BAD;
  80383. break;
  80384. }
  80385. state->length = (unsigned)hold & 0xffff;
  80386. Tracev((stderr, "inflate: stored length %u\n",
  80387. state->length));
  80388. INITBITS();
  80389. state->mode = COPY;
  80390. case COPY:
  80391. copy = state->length;
  80392. if (copy) {
  80393. if (copy > have) copy = have;
  80394. if (copy > left) copy = left;
  80395. if (copy == 0) goto inf_leave;
  80396. zmemcpy(put, next, copy);
  80397. have -= copy;
  80398. next += copy;
  80399. left -= copy;
  80400. put += copy;
  80401. state->length -= copy;
  80402. break;
  80403. }
  80404. Tracev((stderr, "inflate: stored end\n"));
  80405. state->mode = TYPE;
  80406. break;
  80407. case TABLE:
  80408. NEEDBITS(14);
  80409. state->nlen = BITS(5) + 257;
  80410. DROPBITS(5);
  80411. state->ndist = BITS(5) + 1;
  80412. DROPBITS(5);
  80413. state->ncode = BITS(4) + 4;
  80414. DROPBITS(4);
  80415. #ifndef PKZIP_BUG_WORKAROUND
  80416. if (state->nlen > 286 || state->ndist > 30) {
  80417. strm->msg = (char *)"too many length or distance symbols";
  80418. state->mode = BAD;
  80419. break;
  80420. }
  80421. #endif
  80422. Tracev((stderr, "inflate: table sizes ok\n"));
  80423. state->have = 0;
  80424. state->mode = LENLENS;
  80425. case LENLENS:
  80426. while (state->have < state->ncode) {
  80427. NEEDBITS(3);
  80428. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  80429. DROPBITS(3);
  80430. }
  80431. while (state->have < 19)
  80432. state->lens[order[state->have++]] = 0;
  80433. state->next = state->codes;
  80434. state->lencode = (code const FAR *)(state->next);
  80435. state->lenbits = 7;
  80436. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  80437. &(state->lenbits), state->work);
  80438. if (ret) {
  80439. strm->msg = (char *)"invalid code lengths set";
  80440. state->mode = BAD;
  80441. break;
  80442. }
  80443. Tracev((stderr, "inflate: code lengths ok\n"));
  80444. state->have = 0;
  80445. state->mode = CODELENS;
  80446. case CODELENS:
  80447. while (state->have < state->nlen + state->ndist) {
  80448. for (;;) {
  80449. thisx = state->lencode[BITS(state->lenbits)];
  80450. if ((unsigned)(thisx.bits) <= bits) break;
  80451. PULLBYTE();
  80452. }
  80453. if (thisx.val < 16) {
  80454. NEEDBITS(thisx.bits);
  80455. DROPBITS(thisx.bits);
  80456. state->lens[state->have++] = thisx.val;
  80457. }
  80458. else {
  80459. if (thisx.val == 16) {
  80460. NEEDBITS(thisx.bits + 2);
  80461. DROPBITS(thisx.bits);
  80462. if (state->have == 0) {
  80463. strm->msg = (char *)"invalid bit length repeat";
  80464. state->mode = BAD;
  80465. break;
  80466. }
  80467. len = state->lens[state->have - 1];
  80468. copy = 3 + BITS(2);
  80469. DROPBITS(2);
  80470. }
  80471. else if (thisx.val == 17) {
  80472. NEEDBITS(thisx.bits + 3);
  80473. DROPBITS(thisx.bits);
  80474. len = 0;
  80475. copy = 3 + BITS(3);
  80476. DROPBITS(3);
  80477. }
  80478. else {
  80479. NEEDBITS(thisx.bits + 7);
  80480. DROPBITS(thisx.bits);
  80481. len = 0;
  80482. copy = 11 + BITS(7);
  80483. DROPBITS(7);
  80484. }
  80485. if (state->have + copy > state->nlen + state->ndist) {
  80486. strm->msg = (char *)"invalid bit length repeat";
  80487. state->mode = BAD;
  80488. break;
  80489. }
  80490. while (copy--)
  80491. state->lens[state->have++] = (unsigned short)len;
  80492. }
  80493. }
  80494. /* handle error breaks in while */
  80495. if (state->mode == BAD) break;
  80496. /* build code tables */
  80497. state->next = state->codes;
  80498. state->lencode = (code const FAR *)(state->next);
  80499. state->lenbits = 9;
  80500. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  80501. &(state->lenbits), state->work);
  80502. if (ret) {
  80503. strm->msg = (char *)"invalid literal/lengths set";
  80504. state->mode = BAD;
  80505. break;
  80506. }
  80507. state->distcode = (code const FAR *)(state->next);
  80508. state->distbits = 6;
  80509. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  80510. &(state->next), &(state->distbits), state->work);
  80511. if (ret) {
  80512. strm->msg = (char *)"invalid distances set";
  80513. state->mode = BAD;
  80514. break;
  80515. }
  80516. Tracev((stderr, "inflate: codes ok\n"));
  80517. state->mode = LEN;
  80518. case LEN:
  80519. if (have >= 6 && left >= 258) {
  80520. RESTORE();
  80521. inflate_fast(strm, out);
  80522. LOAD();
  80523. break;
  80524. }
  80525. for (;;) {
  80526. thisx = state->lencode[BITS(state->lenbits)];
  80527. if ((unsigned)(thisx.bits) <= bits) break;
  80528. PULLBYTE();
  80529. }
  80530. if (thisx.op && (thisx.op & 0xf0) == 0) {
  80531. last = thisx;
  80532. for (;;) {
  80533. thisx = state->lencode[last.val +
  80534. (BITS(last.bits + last.op) >> last.bits)];
  80535. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  80536. PULLBYTE();
  80537. }
  80538. DROPBITS(last.bits);
  80539. }
  80540. DROPBITS(thisx.bits);
  80541. state->length = (unsigned)thisx.val;
  80542. if ((int)(thisx.op) == 0) {
  80543. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  80544. "inflate: literal '%c'\n" :
  80545. "inflate: literal 0x%02x\n", thisx.val));
  80546. state->mode = LIT;
  80547. break;
  80548. }
  80549. if (thisx.op & 32) {
  80550. Tracevv((stderr, "inflate: end of block\n"));
  80551. state->mode = TYPE;
  80552. break;
  80553. }
  80554. if (thisx.op & 64) {
  80555. strm->msg = (char *)"invalid literal/length code";
  80556. state->mode = BAD;
  80557. break;
  80558. }
  80559. state->extra = (unsigned)(thisx.op) & 15;
  80560. state->mode = LENEXT;
  80561. case LENEXT:
  80562. if (state->extra) {
  80563. NEEDBITS(state->extra);
  80564. state->length += BITS(state->extra);
  80565. DROPBITS(state->extra);
  80566. }
  80567. Tracevv((stderr, "inflate: length %u\n", state->length));
  80568. state->mode = DIST;
  80569. case DIST:
  80570. for (;;) {
  80571. thisx = state->distcode[BITS(state->distbits)];
  80572. if ((unsigned)(thisx.bits) <= bits) break;
  80573. PULLBYTE();
  80574. }
  80575. if ((thisx.op & 0xf0) == 0) {
  80576. last = thisx;
  80577. for (;;) {
  80578. thisx = state->distcode[last.val +
  80579. (BITS(last.bits + last.op) >> last.bits)];
  80580. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  80581. PULLBYTE();
  80582. }
  80583. DROPBITS(last.bits);
  80584. }
  80585. DROPBITS(thisx.bits);
  80586. if (thisx.op & 64) {
  80587. strm->msg = (char *)"invalid distance code";
  80588. state->mode = BAD;
  80589. break;
  80590. }
  80591. state->offset = (unsigned)thisx.val;
  80592. state->extra = (unsigned)(thisx.op) & 15;
  80593. state->mode = DISTEXT;
  80594. case DISTEXT:
  80595. if (state->extra) {
  80596. NEEDBITS(state->extra);
  80597. state->offset += BITS(state->extra);
  80598. DROPBITS(state->extra);
  80599. }
  80600. #ifdef INFLATE_STRICT
  80601. if (state->offset > state->dmax) {
  80602. strm->msg = (char *)"invalid distance too far back";
  80603. state->mode = BAD;
  80604. break;
  80605. }
  80606. #endif
  80607. if (state->offset > state->whave + out - left) {
  80608. strm->msg = (char *)"invalid distance too far back";
  80609. state->mode = BAD;
  80610. break;
  80611. }
  80612. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  80613. state->mode = MATCH;
  80614. case MATCH:
  80615. if (left == 0) goto inf_leave;
  80616. copy = out - left;
  80617. if (state->offset > copy) { /* copy from window */
  80618. copy = state->offset - copy;
  80619. if (copy > state->write) {
  80620. copy -= state->write;
  80621. from = state->window + (state->wsize - copy);
  80622. }
  80623. else
  80624. from = state->window + (state->write - copy);
  80625. if (copy > state->length) copy = state->length;
  80626. }
  80627. else { /* copy from output */
  80628. from = put - state->offset;
  80629. copy = state->length;
  80630. }
  80631. if (copy > left) copy = left;
  80632. left -= copy;
  80633. state->length -= copy;
  80634. do {
  80635. *put++ = *from++;
  80636. } while (--copy);
  80637. if (state->length == 0) state->mode = LEN;
  80638. break;
  80639. case LIT:
  80640. if (left == 0) goto inf_leave;
  80641. *put++ = (unsigned char)(state->length);
  80642. left--;
  80643. state->mode = LEN;
  80644. break;
  80645. case CHECK:
  80646. if (state->wrap) {
  80647. NEEDBITS(32);
  80648. out -= left;
  80649. strm->total_out += out;
  80650. state->total += out;
  80651. if (out)
  80652. strm->adler = state->check =
  80653. UPDATE(state->check, put - out, out);
  80654. out = left;
  80655. if ((
  80656. #ifdef GUNZIP
  80657. state->flags ? hold :
  80658. #endif
  80659. REVERSE(hold)) != state->check) {
  80660. strm->msg = (char *)"incorrect data check";
  80661. state->mode = BAD;
  80662. break;
  80663. }
  80664. INITBITS();
  80665. Tracev((stderr, "inflate: check matches trailer\n"));
  80666. }
  80667. #ifdef GUNZIP
  80668. state->mode = LENGTH;
  80669. case LENGTH:
  80670. if (state->wrap && state->flags) {
  80671. NEEDBITS(32);
  80672. if (hold != (state->total & 0xffffffffUL)) {
  80673. strm->msg = (char *)"incorrect length check";
  80674. state->mode = BAD;
  80675. break;
  80676. }
  80677. INITBITS();
  80678. Tracev((stderr, "inflate: length matches trailer\n"));
  80679. }
  80680. #endif
  80681. state->mode = DONE;
  80682. case DONE:
  80683. ret = Z_STREAM_END;
  80684. goto inf_leave;
  80685. case BAD:
  80686. ret = Z_DATA_ERROR;
  80687. goto inf_leave;
  80688. case MEM:
  80689. return Z_MEM_ERROR;
  80690. case SYNC:
  80691. default:
  80692. return Z_STREAM_ERROR;
  80693. }
  80694. /*
  80695. Return from inflate(), updating the total counts and the check value.
  80696. If there was no progress during the inflate() call, return a buffer
  80697. error. Call updatewindow() to create and/or update the window state.
  80698. Note: a memory error from inflate() is non-recoverable.
  80699. */
  80700. inf_leave:
  80701. RESTORE();
  80702. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  80703. if (updatewindow(strm, out)) {
  80704. state->mode = MEM;
  80705. return Z_MEM_ERROR;
  80706. }
  80707. in -= strm->avail_in;
  80708. out -= strm->avail_out;
  80709. strm->total_in += in;
  80710. strm->total_out += out;
  80711. state->total += out;
  80712. if (state->wrap && out)
  80713. strm->adler = state->check =
  80714. UPDATE(state->check, strm->next_out - out, out);
  80715. strm->data_type = state->bits + (state->last ? 64 : 0) +
  80716. (state->mode == TYPE ? 128 : 0);
  80717. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  80718. ret = Z_BUF_ERROR;
  80719. return ret;
  80720. }
  80721. int ZEXPORT inflateEnd (z_streamp strm)
  80722. {
  80723. struct inflate_state FAR *state;
  80724. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  80725. return Z_STREAM_ERROR;
  80726. state = (struct inflate_state FAR *)strm->state;
  80727. if (state->window != Z_NULL) ZFREE(strm, state->window);
  80728. ZFREE(strm, strm->state);
  80729. strm->state = Z_NULL;
  80730. Tracev((stderr, "inflate: end\n"));
  80731. return Z_OK;
  80732. }
  80733. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80734. {
  80735. struct inflate_state FAR *state;
  80736. unsigned long id_;
  80737. /* check state */
  80738. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80739. state = (struct inflate_state FAR *)strm->state;
  80740. if (state->wrap != 0 && state->mode != DICT)
  80741. return Z_STREAM_ERROR;
  80742. /* check for correct dictionary id */
  80743. if (state->mode == DICT) {
  80744. id_ = adler32(0L, Z_NULL, 0);
  80745. id_ = adler32(id_, dictionary, dictLength);
  80746. if (id_ != state->check)
  80747. return Z_DATA_ERROR;
  80748. }
  80749. /* copy dictionary to window */
  80750. if (updatewindow(strm, strm->avail_out)) {
  80751. state->mode = MEM;
  80752. return Z_MEM_ERROR;
  80753. }
  80754. if (dictLength > state->wsize) {
  80755. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  80756. state->wsize);
  80757. state->whave = state->wsize;
  80758. }
  80759. else {
  80760. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  80761. dictLength);
  80762. state->whave = dictLength;
  80763. }
  80764. state->havedict = 1;
  80765. Tracev((stderr, "inflate: dictionary set\n"));
  80766. return Z_OK;
  80767. }
  80768. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  80769. {
  80770. struct inflate_state FAR *state;
  80771. /* check state */
  80772. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80773. state = (struct inflate_state FAR *)strm->state;
  80774. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  80775. /* save header structure */
  80776. state->head = head;
  80777. head->done = 0;
  80778. return Z_OK;
  80779. }
  80780. /*
  80781. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  80782. or when out of input. When called, *have is the number of pattern bytes
  80783. found in order so far, in 0..3. On return *have is updated to the new
  80784. state. If on return *have equals four, then the pattern was found and the
  80785. return value is how many bytes were read including the last byte of the
  80786. pattern. If *have is less than four, then the pattern has not been found
  80787. yet and the return value is len. In the latter case, syncsearch() can be
  80788. called again with more data and the *have state. *have is initialized to
  80789. zero for the first call.
  80790. */
  80791. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  80792. {
  80793. unsigned got;
  80794. unsigned next;
  80795. got = *have;
  80796. next = 0;
  80797. while (next < len && got < 4) {
  80798. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  80799. got++;
  80800. else if (buf[next])
  80801. got = 0;
  80802. else
  80803. got = 4 - got;
  80804. next++;
  80805. }
  80806. *have = got;
  80807. return next;
  80808. }
  80809. int ZEXPORT inflateSync (z_streamp strm)
  80810. {
  80811. unsigned len; /* number of bytes to look at or looked at */
  80812. unsigned long in, out; /* temporary to save total_in and total_out */
  80813. unsigned char buf[4]; /* to restore bit buffer to byte string */
  80814. struct inflate_state FAR *state;
  80815. /* check parameters */
  80816. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80817. state = (struct inflate_state FAR *)strm->state;
  80818. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  80819. /* if first time, start search in bit buffer */
  80820. if (state->mode != SYNC) {
  80821. state->mode = SYNC;
  80822. state->hold <<= state->bits & 7;
  80823. state->bits -= state->bits & 7;
  80824. len = 0;
  80825. while (state->bits >= 8) {
  80826. buf[len++] = (unsigned char)(state->hold);
  80827. state->hold >>= 8;
  80828. state->bits -= 8;
  80829. }
  80830. state->have = 0;
  80831. syncsearch(&(state->have), buf, len);
  80832. }
  80833. /* search available input */
  80834. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  80835. strm->avail_in -= len;
  80836. strm->next_in += len;
  80837. strm->total_in += len;
  80838. /* return no joy or set up to restart inflate() on a new block */
  80839. if (state->have != 4) return Z_DATA_ERROR;
  80840. in = strm->total_in; out = strm->total_out;
  80841. inflateReset(strm);
  80842. strm->total_in = in; strm->total_out = out;
  80843. state->mode = TYPE;
  80844. return Z_OK;
  80845. }
  80846. /*
  80847. Returns true if inflate is currently at the end of a block generated by
  80848. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  80849. implementation to provide an additional safety check. PPP uses
  80850. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  80851. block. When decompressing, PPP checks that at the end of input packet,
  80852. inflate is waiting for these length bytes.
  80853. */
  80854. int ZEXPORT inflateSyncPoint (z_streamp strm)
  80855. {
  80856. struct inflate_state FAR *state;
  80857. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80858. state = (struct inflate_state FAR *)strm->state;
  80859. return state->mode == STORED && state->bits == 0;
  80860. }
  80861. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  80862. {
  80863. struct inflate_state FAR *state;
  80864. struct inflate_state FAR *copy;
  80865. unsigned char FAR *window;
  80866. unsigned wsize;
  80867. /* check input */
  80868. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  80869. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  80870. return Z_STREAM_ERROR;
  80871. state = (struct inflate_state FAR *)source->state;
  80872. /* allocate space */
  80873. copy = (struct inflate_state FAR *)
  80874. ZALLOC(source, 1, sizeof(struct inflate_state));
  80875. if (copy == Z_NULL) return Z_MEM_ERROR;
  80876. window = Z_NULL;
  80877. if (state->window != Z_NULL) {
  80878. window = (unsigned char FAR *)
  80879. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  80880. if (window == Z_NULL) {
  80881. ZFREE(source, copy);
  80882. return Z_MEM_ERROR;
  80883. }
  80884. }
  80885. /* copy state */
  80886. zmemcpy(dest, source, sizeof(z_stream));
  80887. zmemcpy(copy, state, sizeof(struct inflate_state));
  80888. if (state->lencode >= state->codes &&
  80889. state->lencode <= state->codes + ENOUGH - 1) {
  80890. copy->lencode = copy->codes + (state->lencode - state->codes);
  80891. copy->distcode = copy->codes + (state->distcode - state->codes);
  80892. }
  80893. copy->next = copy->codes + (state->next - state->codes);
  80894. if (window != Z_NULL) {
  80895. wsize = 1U << state->wbits;
  80896. zmemcpy(window, state->window, wsize);
  80897. }
  80898. copy->window = window;
  80899. dest->state = (struct internal_state FAR *)copy;
  80900. return Z_OK;
  80901. }
  80902. /*** End of inlined file: inflate.c ***/
  80903. /*** Start of inlined file: inftrees.c ***/
  80904. #define MAXBITS 15
  80905. const char inflate_copyright[] =
  80906. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  80907. /*
  80908. If you use the zlib library in a product, an acknowledgment is welcome
  80909. in the documentation of your product. If for some reason you cannot
  80910. include such an acknowledgment, I would appreciate that you keep this
  80911. copyright string in the executable of your product.
  80912. */
  80913. /*
  80914. Build a set of tables to decode the provided canonical Huffman code.
  80915. The code lengths are lens[0..codes-1]. The result starts at *table,
  80916. whose indices are 0..2^bits-1. work is a writable array of at least
  80917. lens shorts, which is used as a work area. type is the type of code
  80918. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  80919. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  80920. on return points to the next available entry's address. bits is the
  80921. requested root table index bits, and on return it is the actual root
  80922. table index bits. It will differ if the request is greater than the
  80923. longest code or if it is less than the shortest code.
  80924. */
  80925. int inflate_table (codetype type,
  80926. unsigned short FAR *lens,
  80927. unsigned codes,
  80928. code FAR * FAR *table,
  80929. unsigned FAR *bits,
  80930. unsigned short FAR *work)
  80931. {
  80932. unsigned len; /* a code's length in bits */
  80933. unsigned sym; /* index of code symbols */
  80934. unsigned min, max; /* minimum and maximum code lengths */
  80935. unsigned root; /* number of index bits for root table */
  80936. unsigned curr; /* number of index bits for current table */
  80937. unsigned drop; /* code bits to drop for sub-table */
  80938. int left; /* number of prefix codes available */
  80939. unsigned used; /* code entries in table used */
  80940. unsigned huff; /* Huffman code */
  80941. unsigned incr; /* for incrementing code, index */
  80942. unsigned fill; /* index for replicating entries */
  80943. unsigned low; /* low bits for current root entry */
  80944. unsigned mask; /* mask for low root bits */
  80945. code thisx; /* table entry for duplication */
  80946. code FAR *next; /* next available space in table */
  80947. const unsigned short FAR *base; /* base value table to use */
  80948. const unsigned short FAR *extra; /* extra bits table to use */
  80949. int end; /* use base and extra for symbol > end */
  80950. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  80951. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  80952. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  80953. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  80954. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  80955. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  80956. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  80957. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  80958. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  80959. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  80960. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  80961. 8193, 12289, 16385, 24577, 0, 0};
  80962. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  80963. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  80964. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  80965. 28, 28, 29, 29, 64, 64};
  80966. /*
  80967. Process a set of code lengths to create a canonical Huffman code. The
  80968. code lengths are lens[0..codes-1]. Each length corresponds to the
  80969. symbols 0..codes-1. The Huffman code is generated by first sorting the
  80970. symbols by length from short to long, and retaining the symbol order
  80971. for codes with equal lengths. Then the code starts with all zero bits
  80972. for the first code of the shortest length, and the codes are integer
  80973. increments for the same length, and zeros are appended as the length
  80974. increases. For the deflate format, these bits are stored backwards
  80975. from their more natural integer increment ordering, and so when the
  80976. decoding tables are built in the large loop below, the integer codes
  80977. are incremented backwards.
  80978. This routine assumes, but does not check, that all of the entries in
  80979. lens[] are in the range 0..MAXBITS. The caller must assure this.
  80980. 1..MAXBITS is interpreted as that code length. zero means that that
  80981. symbol does not occur in this code.
  80982. The codes are sorted by computing a count of codes for each length,
  80983. creating from that a table of starting indices for each length in the
  80984. sorted table, and then entering the symbols in order in the sorted
  80985. table. The sorted table is work[], with that space being provided by
  80986. the caller.
  80987. The length counts are used for other purposes as well, i.e. finding
  80988. the minimum and maximum length codes, determining if there are any
  80989. codes at all, checking for a valid set of lengths, and looking ahead
  80990. at length counts to determine sub-table sizes when building the
  80991. decoding tables.
  80992. */
  80993. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  80994. for (len = 0; len <= MAXBITS; len++)
  80995. count[len] = 0;
  80996. for (sym = 0; sym < codes; sym++)
  80997. count[lens[sym]]++;
  80998. /* bound code lengths, force root to be within code lengths */
  80999. root = *bits;
  81000. for (max = MAXBITS; max >= 1; max--)
  81001. if (count[max] != 0) break;
  81002. if (root > max) root = max;
  81003. if (max == 0) { /* no symbols to code at all */
  81004. thisx.op = (unsigned char)64; /* invalid code marker */
  81005. thisx.bits = (unsigned char)1;
  81006. thisx.val = (unsigned short)0;
  81007. *(*table)++ = thisx; /* make a table to force an error */
  81008. *(*table)++ = thisx;
  81009. *bits = 1;
  81010. return 0; /* no symbols, but wait for decoding to report error */
  81011. }
  81012. for (min = 1; min <= MAXBITS; min++)
  81013. if (count[min] != 0) break;
  81014. if (root < min) root = min;
  81015. /* check for an over-subscribed or incomplete set of lengths */
  81016. left = 1;
  81017. for (len = 1; len <= MAXBITS; len++) {
  81018. left <<= 1;
  81019. left -= count[len];
  81020. if (left < 0) return -1; /* over-subscribed */
  81021. }
  81022. if (left > 0 && (type == CODES || max != 1))
  81023. return -1; /* incomplete set */
  81024. /* generate offsets into symbol table for each length for sorting */
  81025. offs[1] = 0;
  81026. for (len = 1; len < MAXBITS; len++)
  81027. offs[len + 1] = offs[len] + count[len];
  81028. /* sort symbols by length, by symbol order within each length */
  81029. for (sym = 0; sym < codes; sym++)
  81030. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  81031. /*
  81032. Create and fill in decoding tables. In this loop, the table being
  81033. filled is at next and has curr index bits. The code being used is huff
  81034. with length len. That code is converted to an index by dropping drop
  81035. bits off of the bottom. For codes where len is less than drop + curr,
  81036. those top drop + curr - len bits are incremented through all values to
  81037. fill the table with replicated entries.
  81038. root is the number of index bits for the root table. When len exceeds
  81039. root, sub-tables are created pointed to by the root entry with an index
  81040. of the low root bits of huff. This is saved in low to check for when a
  81041. new sub-table should be started. drop is zero when the root table is
  81042. being filled, and drop is root when sub-tables are being filled.
  81043. When a new sub-table is needed, it is necessary to look ahead in the
  81044. code lengths to determine what size sub-table is needed. The length
  81045. counts are used for this, and so count[] is decremented as codes are
  81046. entered in the tables.
  81047. used keeps track of how many table entries have been allocated from the
  81048. provided *table space. It is checked when a LENS table is being made
  81049. against the space in *table, ENOUGH, minus the maximum space needed by
  81050. the worst case distance code, MAXD. This should never happen, but the
  81051. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  81052. This assumes that when type == LENS, bits == 9.
  81053. sym increments through all symbols, and the loop terminates when
  81054. all codes of length max, i.e. all codes, have been processed. This
  81055. routine permits incomplete codes, so another loop after this one fills
  81056. in the rest of the decoding tables with invalid code markers.
  81057. */
  81058. /* set up for code type */
  81059. switch (type) {
  81060. case CODES:
  81061. base = extra = work; /* dummy value--not used */
  81062. end = 19;
  81063. break;
  81064. case LENS:
  81065. base = lbase;
  81066. base -= 257;
  81067. extra = lext;
  81068. extra -= 257;
  81069. end = 256;
  81070. break;
  81071. default: /* DISTS */
  81072. base = dbase;
  81073. extra = dext;
  81074. end = -1;
  81075. }
  81076. /* initialize state for loop */
  81077. huff = 0; /* starting code */
  81078. sym = 0; /* starting code symbol */
  81079. len = min; /* starting code length */
  81080. next = *table; /* current table to fill in */
  81081. curr = root; /* current table index bits */
  81082. drop = 0; /* current bits to drop from code for index */
  81083. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  81084. used = 1U << root; /* use root table entries */
  81085. mask = used - 1; /* mask for comparing low */
  81086. /* check available table space */
  81087. if (type == LENS && used >= ENOUGH - MAXD)
  81088. return 1;
  81089. /* process all codes and make table entries */
  81090. for (;;) {
  81091. /* create table entry */
  81092. thisx.bits = (unsigned char)(len - drop);
  81093. if ((int)(work[sym]) < end) {
  81094. thisx.op = (unsigned char)0;
  81095. thisx.val = work[sym];
  81096. }
  81097. else if ((int)(work[sym]) > end) {
  81098. thisx.op = (unsigned char)(extra[work[sym]]);
  81099. thisx.val = base[work[sym]];
  81100. }
  81101. else {
  81102. thisx.op = (unsigned char)(32 + 64); /* end of block */
  81103. thisx.val = 0;
  81104. }
  81105. /* replicate for those indices with low len bits equal to huff */
  81106. incr = 1U << (len - drop);
  81107. fill = 1U << curr;
  81108. min = fill; /* save offset to next table */
  81109. do {
  81110. fill -= incr;
  81111. next[(huff >> drop) + fill] = thisx;
  81112. } while (fill != 0);
  81113. /* backwards increment the len-bit code huff */
  81114. incr = 1U << (len - 1);
  81115. while (huff & incr)
  81116. incr >>= 1;
  81117. if (incr != 0) {
  81118. huff &= incr - 1;
  81119. huff += incr;
  81120. }
  81121. else
  81122. huff = 0;
  81123. /* go to next symbol, update count, len */
  81124. sym++;
  81125. if (--(count[len]) == 0) {
  81126. if (len == max) break;
  81127. len = lens[work[sym]];
  81128. }
  81129. /* create new sub-table if needed */
  81130. if (len > root && (huff & mask) != low) {
  81131. /* if first time, transition to sub-tables */
  81132. if (drop == 0)
  81133. drop = root;
  81134. /* increment past last table */
  81135. next += min; /* here min is 1 << curr */
  81136. /* determine length of next table */
  81137. curr = len - drop;
  81138. left = (int)(1 << curr);
  81139. while (curr + drop < max) {
  81140. left -= count[curr + drop];
  81141. if (left <= 0) break;
  81142. curr++;
  81143. left <<= 1;
  81144. }
  81145. /* check for enough space */
  81146. used += 1U << curr;
  81147. if (type == LENS && used >= ENOUGH - MAXD)
  81148. return 1;
  81149. /* point entry in root table to sub-table */
  81150. low = huff & mask;
  81151. (*table)[low].op = (unsigned char)curr;
  81152. (*table)[low].bits = (unsigned char)root;
  81153. (*table)[low].val = (unsigned short)(next - *table);
  81154. }
  81155. }
  81156. /*
  81157. Fill in rest of table for incomplete codes. This loop is similar to the
  81158. loop above in incrementing huff for table indices. It is assumed that
  81159. len is equal to curr + drop, so there is no loop needed to increment
  81160. through high index bits. When the current sub-table is filled, the loop
  81161. drops back to the root table to fill in any remaining entries there.
  81162. */
  81163. thisx.op = (unsigned char)64; /* invalid code marker */
  81164. thisx.bits = (unsigned char)(len - drop);
  81165. thisx.val = (unsigned short)0;
  81166. while (huff != 0) {
  81167. /* when done with sub-table, drop back to root table */
  81168. if (drop != 0 && (huff & mask) != low) {
  81169. drop = 0;
  81170. len = root;
  81171. next = *table;
  81172. thisx.bits = (unsigned char)len;
  81173. }
  81174. /* put invalid code marker in table */
  81175. next[huff >> drop] = thisx;
  81176. /* backwards increment the len-bit code huff */
  81177. incr = 1U << (len - 1);
  81178. while (huff & incr)
  81179. incr >>= 1;
  81180. if (incr != 0) {
  81181. huff &= incr - 1;
  81182. huff += incr;
  81183. }
  81184. else
  81185. huff = 0;
  81186. }
  81187. /* set return parameters */
  81188. *table += used;
  81189. *bits = root;
  81190. return 0;
  81191. }
  81192. /*** End of inlined file: inftrees.c ***/
  81193. /*** Start of inlined file: trees.c ***/
  81194. /*
  81195. * ALGORITHM
  81196. *
  81197. * The "deflation" process uses several Huffman trees. The more
  81198. * common source values are represented by shorter bit sequences.
  81199. *
  81200. * Each code tree is stored in a compressed form which is itself
  81201. * a Huffman encoding of the lengths of all the code strings (in
  81202. * ascending order by source values). The actual code strings are
  81203. * reconstructed from the lengths in the inflate process, as described
  81204. * in the deflate specification.
  81205. *
  81206. * REFERENCES
  81207. *
  81208. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  81209. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  81210. *
  81211. * Storer, James A.
  81212. * Data Compression: Methods and Theory, pp. 49-50.
  81213. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  81214. *
  81215. * Sedgewick, R.
  81216. * Algorithms, p290.
  81217. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  81218. */
  81219. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81220. /* #define GEN_TREES_H */
  81221. #ifdef DEBUG
  81222. # include <ctype.h>
  81223. #endif
  81224. /* ===========================================================================
  81225. * Constants
  81226. */
  81227. #define MAX_BL_BITS 7
  81228. /* Bit length codes must not exceed MAX_BL_BITS bits */
  81229. #define END_BLOCK 256
  81230. /* end of block literal code */
  81231. #define REP_3_6 16
  81232. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  81233. #define REPZ_3_10 17
  81234. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  81235. #define REPZ_11_138 18
  81236. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  81237. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  81238. = {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};
  81239. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  81240. = {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};
  81241. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  81242. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  81243. local const uch bl_order[BL_CODES]
  81244. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  81245. /* The lengths of the bit length codes are sent in order of decreasing
  81246. * probability, to avoid transmitting the lengths for unused bit length codes.
  81247. */
  81248. #define Buf_size (8 * 2*sizeof(char))
  81249. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  81250. * more than 16 bits on some systems.)
  81251. */
  81252. /* ===========================================================================
  81253. * Local data. These are initialized only once.
  81254. */
  81255. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  81256. #if defined(GEN_TREES_H) || !defined(STDC)
  81257. /* non ANSI compilers may not accept trees.h */
  81258. local ct_data static_ltree[L_CODES+2];
  81259. /* The static literal tree. Since the bit lengths are imposed, there is no
  81260. * need for the L_CODES extra codes used during heap construction. However
  81261. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  81262. * below).
  81263. */
  81264. local ct_data static_dtree[D_CODES];
  81265. /* The static distance tree. (Actually a trivial tree since all codes use
  81266. * 5 bits.)
  81267. */
  81268. uch _dist_code[DIST_CODE_LEN];
  81269. /* Distance codes. The first 256 values correspond to the distances
  81270. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  81271. * the 15 bit distances.
  81272. */
  81273. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  81274. /* length code for each normalized match length (0 == MIN_MATCH) */
  81275. local int base_length[LENGTH_CODES];
  81276. /* First normalized length for each code (0 = MIN_MATCH) */
  81277. local int base_dist[D_CODES];
  81278. /* First normalized distance for each code (0 = distance of 1) */
  81279. #else
  81280. /*** Start of inlined file: trees.h ***/
  81281. local const ct_data static_ltree[L_CODES+2] = {
  81282. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  81283. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  81284. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  81285. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  81286. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  81287. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  81288. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  81289. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  81290. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  81291. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  81292. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  81293. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  81294. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  81295. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  81296. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  81297. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  81298. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  81299. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  81300. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  81301. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  81302. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  81303. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  81304. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  81305. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  81306. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  81307. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  81308. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  81309. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  81310. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  81311. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  81312. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  81313. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  81314. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  81315. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  81316. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  81317. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  81318. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  81319. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  81320. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  81321. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  81322. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  81323. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  81324. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  81325. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  81326. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  81327. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  81328. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  81329. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  81330. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  81331. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  81332. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  81333. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  81334. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  81335. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  81336. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  81337. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  81338. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  81339. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  81340. };
  81341. local const ct_data static_dtree[D_CODES] = {
  81342. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  81343. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  81344. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  81345. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  81346. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  81347. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  81348. };
  81349. const uch _dist_code[DIST_CODE_LEN] = {
  81350. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  81351. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  81352. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  81353. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  81354. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  81355. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  81356. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81357. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81358. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81359. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  81360. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  81361. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  81362. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  81363. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  81364. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81365. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  81366. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  81367. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  81368. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  81369. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81370. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81371. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81372. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81373. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81374. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81375. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  81376. };
  81377. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  81378. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  81379. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  81380. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  81381. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  81382. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  81383. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  81384. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81385. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81386. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  81387. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  81388. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  81389. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  81390. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  81391. };
  81392. local const int base_length[LENGTH_CODES] = {
  81393. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  81394. 64, 80, 96, 112, 128, 160, 192, 224, 0
  81395. };
  81396. local const int base_dist[D_CODES] = {
  81397. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  81398. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  81399. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  81400. };
  81401. /*** End of inlined file: trees.h ***/
  81402. #endif /* GEN_TREES_H */
  81403. struct static_tree_desc_s {
  81404. const ct_data *static_tree; /* static tree or NULL */
  81405. const intf *extra_bits; /* extra bits for each code or NULL */
  81406. int extra_base; /* base index for extra_bits */
  81407. int elems; /* max number of elements in the tree */
  81408. int max_length; /* max bit length for the codes */
  81409. };
  81410. local static_tree_desc static_l_desc =
  81411. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  81412. local static_tree_desc static_d_desc =
  81413. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  81414. local static_tree_desc static_bl_desc =
  81415. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  81416. /* ===========================================================================
  81417. * Local (static) routines in this file.
  81418. */
  81419. local void tr_static_init OF((void));
  81420. local void init_block OF((deflate_state *s));
  81421. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  81422. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  81423. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  81424. local void build_tree OF((deflate_state *s, tree_desc *desc));
  81425. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  81426. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  81427. local int build_bl_tree OF((deflate_state *s));
  81428. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  81429. int blcodes));
  81430. local void compress_block OF((deflate_state *s, ct_data *ltree,
  81431. ct_data *dtree));
  81432. local void set_data_type OF((deflate_state *s));
  81433. local unsigned bi_reverse OF((unsigned value, int length));
  81434. local void bi_windup OF((deflate_state *s));
  81435. local void bi_flush OF((deflate_state *s));
  81436. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  81437. int header));
  81438. #ifdef GEN_TREES_H
  81439. local void gen_trees_header OF((void));
  81440. #endif
  81441. #ifndef DEBUG
  81442. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  81443. /* Send a code of the given tree. c and tree must not have side effects */
  81444. #else /* DEBUG */
  81445. # define send_code(s, c, tree) \
  81446. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  81447. send_bits(s, tree[c].Code, tree[c].Len); }
  81448. #endif
  81449. /* ===========================================================================
  81450. * Output a short LSB first on the stream.
  81451. * IN assertion: there is enough room in pendingBuf.
  81452. */
  81453. #define put_short(s, w) { \
  81454. put_byte(s, (uch)((w) & 0xff)); \
  81455. put_byte(s, (uch)((ush)(w) >> 8)); \
  81456. }
  81457. /* ===========================================================================
  81458. * Send a value on a given number of bits.
  81459. * IN assertion: length <= 16 and value fits in length bits.
  81460. */
  81461. #ifdef DEBUG
  81462. local void send_bits OF((deflate_state *s, int value, int length));
  81463. local void send_bits (deflate_state *s, int value, int length)
  81464. {
  81465. Tracevv((stderr," l %2d v %4x ", length, value));
  81466. Assert(length > 0 && length <= 15, "invalid length");
  81467. s->bits_sent += (ulg)length;
  81468. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  81469. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  81470. * unused bits in value.
  81471. */
  81472. if (s->bi_valid > (int)Buf_size - length) {
  81473. s->bi_buf |= (value << s->bi_valid);
  81474. put_short(s, s->bi_buf);
  81475. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  81476. s->bi_valid += length - Buf_size;
  81477. } else {
  81478. s->bi_buf |= value << s->bi_valid;
  81479. s->bi_valid += length;
  81480. }
  81481. }
  81482. #else /* !DEBUG */
  81483. #define send_bits(s, value, length) \
  81484. { int len = length;\
  81485. if (s->bi_valid > (int)Buf_size - len) {\
  81486. int val = value;\
  81487. s->bi_buf |= (val << s->bi_valid);\
  81488. put_short(s, s->bi_buf);\
  81489. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  81490. s->bi_valid += len - Buf_size;\
  81491. } else {\
  81492. s->bi_buf |= (value) << s->bi_valid;\
  81493. s->bi_valid += len;\
  81494. }\
  81495. }
  81496. #endif /* DEBUG */
  81497. /* the arguments must not have side effects */
  81498. /* ===========================================================================
  81499. * Initialize the various 'constant' tables.
  81500. */
  81501. local void tr_static_init()
  81502. {
  81503. #if defined(GEN_TREES_H) || !defined(STDC)
  81504. static int static_init_done = 0;
  81505. int n; /* iterates over tree elements */
  81506. int bits; /* bit counter */
  81507. int length; /* length value */
  81508. int code; /* code value */
  81509. int dist; /* distance index */
  81510. ush bl_count[MAX_BITS+1];
  81511. /* number of codes at each bit length for an optimal tree */
  81512. if (static_init_done) return;
  81513. /* For some embedded targets, global variables are not initialized: */
  81514. static_l_desc.static_tree = static_ltree;
  81515. static_l_desc.extra_bits = extra_lbits;
  81516. static_d_desc.static_tree = static_dtree;
  81517. static_d_desc.extra_bits = extra_dbits;
  81518. static_bl_desc.extra_bits = extra_blbits;
  81519. /* Initialize the mapping length (0..255) -> length code (0..28) */
  81520. length = 0;
  81521. for (code = 0; code < LENGTH_CODES-1; code++) {
  81522. base_length[code] = length;
  81523. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  81524. _length_code[length++] = (uch)code;
  81525. }
  81526. }
  81527. Assert (length == 256, "tr_static_init: length != 256");
  81528. /* Note that the length 255 (match length 258) can be represented
  81529. * in two different ways: code 284 + 5 bits or code 285, so we
  81530. * overwrite length_code[255] to use the best encoding:
  81531. */
  81532. _length_code[length-1] = (uch)code;
  81533. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  81534. dist = 0;
  81535. for (code = 0 ; code < 16; code++) {
  81536. base_dist[code] = dist;
  81537. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  81538. _dist_code[dist++] = (uch)code;
  81539. }
  81540. }
  81541. Assert (dist == 256, "tr_static_init: dist != 256");
  81542. dist >>= 7; /* from now on, all distances are divided by 128 */
  81543. for ( ; code < D_CODES; code++) {
  81544. base_dist[code] = dist << 7;
  81545. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  81546. _dist_code[256 + dist++] = (uch)code;
  81547. }
  81548. }
  81549. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  81550. /* Construct the codes of the static literal tree */
  81551. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  81552. n = 0;
  81553. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  81554. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  81555. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  81556. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  81557. /* Codes 286 and 287 do not exist, but we must include them in the
  81558. * tree construction to get a canonical Huffman tree (longest code
  81559. * all ones)
  81560. */
  81561. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  81562. /* The static distance tree is trivial: */
  81563. for (n = 0; n < D_CODES; n++) {
  81564. static_dtree[n].Len = 5;
  81565. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  81566. }
  81567. static_init_done = 1;
  81568. # ifdef GEN_TREES_H
  81569. gen_trees_header();
  81570. # endif
  81571. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  81572. }
  81573. /* ===========================================================================
  81574. * Genererate the file trees.h describing the static trees.
  81575. */
  81576. #ifdef GEN_TREES_H
  81577. # ifndef DEBUG
  81578. # include <stdio.h>
  81579. # endif
  81580. # define SEPARATOR(i, last, width) \
  81581. ((i) == (last)? "\n};\n\n" : \
  81582. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  81583. void gen_trees_header()
  81584. {
  81585. FILE *header = fopen("trees.h", "w");
  81586. int i;
  81587. Assert (header != NULL, "Can't open trees.h");
  81588. fprintf(header,
  81589. "/* header created automatically with -DGEN_TREES_H */\n\n");
  81590. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  81591. for (i = 0; i < L_CODES+2; i++) {
  81592. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  81593. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  81594. }
  81595. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  81596. for (i = 0; i < D_CODES; i++) {
  81597. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  81598. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  81599. }
  81600. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  81601. for (i = 0; i < DIST_CODE_LEN; i++) {
  81602. fprintf(header, "%2u%s", _dist_code[i],
  81603. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  81604. }
  81605. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  81606. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  81607. fprintf(header, "%2u%s", _length_code[i],
  81608. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  81609. }
  81610. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  81611. for (i = 0; i < LENGTH_CODES; i++) {
  81612. fprintf(header, "%1u%s", base_length[i],
  81613. SEPARATOR(i, LENGTH_CODES-1, 20));
  81614. }
  81615. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  81616. for (i = 0; i < D_CODES; i++) {
  81617. fprintf(header, "%5u%s", base_dist[i],
  81618. SEPARATOR(i, D_CODES-1, 10));
  81619. }
  81620. fclose(header);
  81621. }
  81622. #endif /* GEN_TREES_H */
  81623. /* ===========================================================================
  81624. * Initialize the tree data structures for a new zlib stream.
  81625. */
  81626. void _tr_init(deflate_state *s)
  81627. {
  81628. tr_static_init();
  81629. s->l_desc.dyn_tree = s->dyn_ltree;
  81630. s->l_desc.stat_desc = &static_l_desc;
  81631. s->d_desc.dyn_tree = s->dyn_dtree;
  81632. s->d_desc.stat_desc = &static_d_desc;
  81633. s->bl_desc.dyn_tree = s->bl_tree;
  81634. s->bl_desc.stat_desc = &static_bl_desc;
  81635. s->bi_buf = 0;
  81636. s->bi_valid = 0;
  81637. s->last_eob_len = 8; /* enough lookahead for inflate */
  81638. #ifdef DEBUG
  81639. s->compressed_len = 0L;
  81640. s->bits_sent = 0L;
  81641. #endif
  81642. /* Initialize the first block of the first file: */
  81643. init_block(s);
  81644. }
  81645. /* ===========================================================================
  81646. * Initialize a new block.
  81647. */
  81648. local void init_block (deflate_state *s)
  81649. {
  81650. int n; /* iterates over tree elements */
  81651. /* Initialize the trees. */
  81652. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  81653. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  81654. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  81655. s->dyn_ltree[END_BLOCK].Freq = 1;
  81656. s->opt_len = s->static_len = 0L;
  81657. s->last_lit = s->matches = 0;
  81658. }
  81659. #define SMALLEST 1
  81660. /* Index within the heap array of least frequent node in the Huffman tree */
  81661. /* ===========================================================================
  81662. * Remove the smallest element from the heap and recreate the heap with
  81663. * one less element. Updates heap and heap_len.
  81664. */
  81665. #define pqremove(s, tree, top) \
  81666. {\
  81667. top = s->heap[SMALLEST]; \
  81668. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  81669. pqdownheap(s, tree, SMALLEST); \
  81670. }
  81671. /* ===========================================================================
  81672. * Compares to subtrees, using the tree depth as tie breaker when
  81673. * the subtrees have equal frequency. This minimizes the worst case length.
  81674. */
  81675. #define smaller(tree, n, m, depth) \
  81676. (tree[n].Freq < tree[m].Freq || \
  81677. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  81678. /* ===========================================================================
  81679. * Restore the heap property by moving down the tree starting at node k,
  81680. * exchanging a node with the smallest of its two sons if necessary, stopping
  81681. * when the heap property is re-established (each father smaller than its
  81682. * two sons).
  81683. */
  81684. local void pqdownheap (deflate_state *s,
  81685. ct_data *tree, /* the tree to restore */
  81686. int k) /* node to move down */
  81687. {
  81688. int v = s->heap[k];
  81689. int j = k << 1; /* left son of k */
  81690. while (j <= s->heap_len) {
  81691. /* Set j to the smallest of the two sons: */
  81692. if (j < s->heap_len &&
  81693. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  81694. j++;
  81695. }
  81696. /* Exit if v is smaller than both sons */
  81697. if (smaller(tree, v, s->heap[j], s->depth)) break;
  81698. /* Exchange v with the smallest son */
  81699. s->heap[k] = s->heap[j]; k = j;
  81700. /* And continue down the tree, setting j to the left son of k */
  81701. j <<= 1;
  81702. }
  81703. s->heap[k] = v;
  81704. }
  81705. /* ===========================================================================
  81706. * Compute the optimal bit lengths for a tree and update the total bit length
  81707. * for the current block.
  81708. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  81709. * above are the tree nodes sorted by increasing frequency.
  81710. * OUT assertions: the field len is set to the optimal bit length, the
  81711. * array bl_count contains the frequencies for each bit length.
  81712. * The length opt_len is updated; static_len is also updated if stree is
  81713. * not null.
  81714. */
  81715. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  81716. {
  81717. ct_data *tree = desc->dyn_tree;
  81718. int max_code = desc->max_code;
  81719. const ct_data *stree = desc->stat_desc->static_tree;
  81720. const intf *extra = desc->stat_desc->extra_bits;
  81721. int base = desc->stat_desc->extra_base;
  81722. int max_length = desc->stat_desc->max_length;
  81723. int h; /* heap index */
  81724. int n, m; /* iterate over the tree elements */
  81725. int bits; /* bit length */
  81726. int xbits; /* extra bits */
  81727. ush f; /* frequency */
  81728. int overflow = 0; /* number of elements with bit length too large */
  81729. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  81730. /* In a first pass, compute the optimal bit lengths (which may
  81731. * overflow in the case of the bit length tree).
  81732. */
  81733. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  81734. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  81735. n = s->heap[h];
  81736. bits = tree[tree[n].Dad].Len + 1;
  81737. if (bits > max_length) bits = max_length, overflow++;
  81738. tree[n].Len = (ush)bits;
  81739. /* We overwrite tree[n].Dad which is no longer needed */
  81740. if (n > max_code) continue; /* not a leaf node */
  81741. s->bl_count[bits]++;
  81742. xbits = 0;
  81743. if (n >= base) xbits = extra[n-base];
  81744. f = tree[n].Freq;
  81745. s->opt_len += (ulg)f * (bits + xbits);
  81746. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  81747. }
  81748. if (overflow == 0) return;
  81749. Trace((stderr,"\nbit length overflow\n"));
  81750. /* This happens for example on obj2 and pic of the Calgary corpus */
  81751. /* Find the first bit length which could increase: */
  81752. do {
  81753. bits = max_length-1;
  81754. while (s->bl_count[bits] == 0) bits--;
  81755. s->bl_count[bits]--; /* move one leaf down the tree */
  81756. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  81757. s->bl_count[max_length]--;
  81758. /* The brother of the overflow item also moves one step up,
  81759. * but this does not affect bl_count[max_length]
  81760. */
  81761. overflow -= 2;
  81762. } while (overflow > 0);
  81763. /* Now recompute all bit lengths, scanning in increasing frequency.
  81764. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  81765. * lengths instead of fixing only the wrong ones. This idea is taken
  81766. * from 'ar' written by Haruhiko Okumura.)
  81767. */
  81768. for (bits = max_length; bits != 0; bits--) {
  81769. n = s->bl_count[bits];
  81770. while (n != 0) {
  81771. m = s->heap[--h];
  81772. if (m > max_code) continue;
  81773. if ((unsigned) tree[m].Len != (unsigned) bits) {
  81774. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  81775. s->opt_len += ((long)bits - (long)tree[m].Len)
  81776. *(long)tree[m].Freq;
  81777. tree[m].Len = (ush)bits;
  81778. }
  81779. n--;
  81780. }
  81781. }
  81782. }
  81783. /* ===========================================================================
  81784. * Generate the codes for a given tree and bit counts (which need not be
  81785. * optimal).
  81786. * IN assertion: the array bl_count contains the bit length statistics for
  81787. * the given tree and the field len is set for all tree elements.
  81788. * OUT assertion: the field code is set for all tree elements of non
  81789. * zero code length.
  81790. */
  81791. local void gen_codes (ct_data *tree, /* the tree to decorate */
  81792. int max_code, /* largest code with non zero frequency */
  81793. ushf *bl_count) /* number of codes at each bit length */
  81794. {
  81795. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  81796. ush code = 0; /* running code value */
  81797. int bits; /* bit index */
  81798. int n; /* code index */
  81799. /* The distribution counts are first used to generate the code values
  81800. * without bit reversal.
  81801. */
  81802. for (bits = 1; bits <= MAX_BITS; bits++) {
  81803. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  81804. }
  81805. /* Check that the bit counts in bl_count are consistent. The last code
  81806. * must be all ones.
  81807. */
  81808. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  81809. "inconsistent bit counts");
  81810. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  81811. for (n = 0; n <= max_code; n++) {
  81812. int len = tree[n].Len;
  81813. if (len == 0) continue;
  81814. /* Now reverse the bits */
  81815. tree[n].Code = bi_reverse(next_code[len]++, len);
  81816. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  81817. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  81818. }
  81819. }
  81820. /* ===========================================================================
  81821. * Construct one Huffman tree and assigns the code bit strings and lengths.
  81822. * Update the total bit length for the current block.
  81823. * IN assertion: the field freq is set for all tree elements.
  81824. * OUT assertions: the fields len and code are set to the optimal bit length
  81825. * and corresponding code. The length opt_len is updated; static_len is
  81826. * also updated if stree is not null. The field max_code is set.
  81827. */
  81828. local void build_tree (deflate_state *s,
  81829. tree_desc *desc) /* the tree descriptor */
  81830. {
  81831. ct_data *tree = desc->dyn_tree;
  81832. const ct_data *stree = desc->stat_desc->static_tree;
  81833. int elems = desc->stat_desc->elems;
  81834. int n, m; /* iterate over heap elements */
  81835. int max_code = -1; /* largest code with non zero frequency */
  81836. int node; /* new node being created */
  81837. /* Construct the initial heap, with least frequent element in
  81838. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  81839. * heap[0] is not used.
  81840. */
  81841. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  81842. for (n = 0; n < elems; n++) {
  81843. if (tree[n].Freq != 0) {
  81844. s->heap[++(s->heap_len)] = max_code = n;
  81845. s->depth[n] = 0;
  81846. } else {
  81847. tree[n].Len = 0;
  81848. }
  81849. }
  81850. /* The pkzip format requires that at least one distance code exists,
  81851. * and that at least one bit should be sent even if there is only one
  81852. * possible code. So to avoid special checks later on we force at least
  81853. * two codes of non zero frequency.
  81854. */
  81855. while (s->heap_len < 2) {
  81856. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  81857. tree[node].Freq = 1;
  81858. s->depth[node] = 0;
  81859. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  81860. /* node is 0 or 1 so it does not have extra bits */
  81861. }
  81862. desc->max_code = max_code;
  81863. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  81864. * establish sub-heaps of increasing lengths:
  81865. */
  81866. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  81867. /* Construct the Huffman tree by repeatedly combining the least two
  81868. * frequent nodes.
  81869. */
  81870. node = elems; /* next internal node of the tree */
  81871. do {
  81872. pqremove(s, tree, n); /* n = node of least frequency */
  81873. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  81874. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  81875. s->heap[--(s->heap_max)] = m;
  81876. /* Create a new node father of n and m */
  81877. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  81878. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  81879. s->depth[n] : s->depth[m]) + 1);
  81880. tree[n].Dad = tree[m].Dad = (ush)node;
  81881. #ifdef DUMP_BL_TREE
  81882. if (tree == s->bl_tree) {
  81883. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  81884. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  81885. }
  81886. #endif
  81887. /* and insert the new node in the heap */
  81888. s->heap[SMALLEST] = node++;
  81889. pqdownheap(s, tree, SMALLEST);
  81890. } while (s->heap_len >= 2);
  81891. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  81892. /* At this point, the fields freq and dad are set. We can now
  81893. * generate the bit lengths.
  81894. */
  81895. gen_bitlen(s, (tree_desc *)desc);
  81896. /* The field len is now set, we can generate the bit codes */
  81897. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  81898. }
  81899. /* ===========================================================================
  81900. * Scan a literal or distance tree to determine the frequencies of the codes
  81901. * in the bit length tree.
  81902. */
  81903. local void scan_tree (deflate_state *s,
  81904. ct_data *tree, /* the tree to be scanned */
  81905. int max_code) /* and its largest code of non zero frequency */
  81906. {
  81907. int n; /* iterates over all tree elements */
  81908. int prevlen = -1; /* last emitted length */
  81909. int curlen; /* length of current code */
  81910. int nextlen = tree[0].Len; /* length of next code */
  81911. int count = 0; /* repeat count of the current code */
  81912. int max_count = 7; /* max repeat count */
  81913. int min_count = 4; /* min repeat count */
  81914. if (nextlen == 0) max_count = 138, min_count = 3;
  81915. tree[max_code+1].Len = (ush)0xffff; /* guard */
  81916. for (n = 0; n <= max_code; n++) {
  81917. curlen = nextlen; nextlen = tree[n+1].Len;
  81918. if (++count < max_count && curlen == nextlen) {
  81919. continue;
  81920. } else if (count < min_count) {
  81921. s->bl_tree[curlen].Freq += count;
  81922. } else if (curlen != 0) {
  81923. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  81924. s->bl_tree[REP_3_6].Freq++;
  81925. } else if (count <= 10) {
  81926. s->bl_tree[REPZ_3_10].Freq++;
  81927. } else {
  81928. s->bl_tree[REPZ_11_138].Freq++;
  81929. }
  81930. count = 0; prevlen = curlen;
  81931. if (nextlen == 0) {
  81932. max_count = 138, min_count = 3;
  81933. } else if (curlen == nextlen) {
  81934. max_count = 6, min_count = 3;
  81935. } else {
  81936. max_count = 7, min_count = 4;
  81937. }
  81938. }
  81939. }
  81940. /* ===========================================================================
  81941. * Send a literal or distance tree in compressed form, using the codes in
  81942. * bl_tree.
  81943. */
  81944. local void send_tree (deflate_state *s,
  81945. ct_data *tree, /* the tree to be scanned */
  81946. int max_code) /* and its largest code of non zero frequency */
  81947. {
  81948. int n; /* iterates over all tree elements */
  81949. int prevlen = -1; /* last emitted length */
  81950. int curlen; /* length of current code */
  81951. int nextlen = tree[0].Len; /* length of next code */
  81952. int count = 0; /* repeat count of the current code */
  81953. int max_count = 7; /* max repeat count */
  81954. int min_count = 4; /* min repeat count */
  81955. /* tree[max_code+1].Len = -1; */ /* guard already set */
  81956. if (nextlen == 0) max_count = 138, min_count = 3;
  81957. for (n = 0; n <= max_code; n++) {
  81958. curlen = nextlen; nextlen = tree[n+1].Len;
  81959. if (++count < max_count && curlen == nextlen) {
  81960. continue;
  81961. } else if (count < min_count) {
  81962. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  81963. } else if (curlen != 0) {
  81964. if (curlen != prevlen) {
  81965. send_code(s, curlen, s->bl_tree); count--;
  81966. }
  81967. Assert(count >= 3 && count <= 6, " 3_6?");
  81968. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  81969. } else if (count <= 10) {
  81970. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  81971. } else {
  81972. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  81973. }
  81974. count = 0; prevlen = curlen;
  81975. if (nextlen == 0) {
  81976. max_count = 138, min_count = 3;
  81977. } else if (curlen == nextlen) {
  81978. max_count = 6, min_count = 3;
  81979. } else {
  81980. max_count = 7, min_count = 4;
  81981. }
  81982. }
  81983. }
  81984. /* ===========================================================================
  81985. * Construct the Huffman tree for the bit lengths and return the index in
  81986. * bl_order of the last bit length code to send.
  81987. */
  81988. local int build_bl_tree (deflate_state *s)
  81989. {
  81990. int max_blindex; /* index of last bit length code of non zero freq */
  81991. /* Determine the bit length frequencies for literal and distance trees */
  81992. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  81993. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  81994. /* Build the bit length tree: */
  81995. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  81996. /* opt_len now includes the length of the tree representations, except
  81997. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  81998. */
  81999. /* Determine the number of bit length codes to send. The pkzip format
  82000. * requires that at least 4 bit length codes be sent. (appnote.txt says
  82001. * 3 but the actual value used is 4.)
  82002. */
  82003. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  82004. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  82005. }
  82006. /* Update opt_len to include the bit length tree and counts */
  82007. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  82008. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  82009. s->opt_len, s->static_len));
  82010. return max_blindex;
  82011. }
  82012. /* ===========================================================================
  82013. * Send the header for a block using dynamic Huffman trees: the counts, the
  82014. * lengths of the bit length codes, the literal tree and the distance tree.
  82015. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  82016. */
  82017. local void send_all_trees (deflate_state *s,
  82018. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  82019. {
  82020. int rank; /* index in bl_order */
  82021. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  82022. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  82023. "too many codes");
  82024. Tracev((stderr, "\nbl counts: "));
  82025. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  82026. send_bits(s, dcodes-1, 5);
  82027. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  82028. for (rank = 0; rank < blcodes; rank++) {
  82029. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  82030. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  82031. }
  82032. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  82033. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  82034. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  82035. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  82036. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  82037. }
  82038. /* ===========================================================================
  82039. * Send a stored block
  82040. */
  82041. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  82042. {
  82043. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  82044. #ifdef DEBUG
  82045. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  82046. s->compressed_len += (stored_len + 4) << 3;
  82047. #endif
  82048. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  82049. }
  82050. /* ===========================================================================
  82051. * Send one empty static block to give enough lookahead for inflate.
  82052. * This takes 10 bits, of which 7 may remain in the bit buffer.
  82053. * The current inflate code requires 9 bits of lookahead. If the
  82054. * last two codes for the previous block (real code plus EOB) were coded
  82055. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  82056. * the last real code. In this case we send two empty static blocks instead
  82057. * of one. (There are no problems if the previous block is stored or fixed.)
  82058. * To simplify the code, we assume the worst case of last real code encoded
  82059. * on one bit only.
  82060. */
  82061. void _tr_align (deflate_state *s)
  82062. {
  82063. send_bits(s, STATIC_TREES<<1, 3);
  82064. send_code(s, END_BLOCK, static_ltree);
  82065. #ifdef DEBUG
  82066. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  82067. #endif
  82068. bi_flush(s);
  82069. /* Of the 10 bits for the empty block, we have already sent
  82070. * (10 - bi_valid) bits. The lookahead for the last real code (before
  82071. * the EOB of the previous block) was thus at least one plus the length
  82072. * of the EOB plus what we have just sent of the empty static block.
  82073. */
  82074. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  82075. send_bits(s, STATIC_TREES<<1, 3);
  82076. send_code(s, END_BLOCK, static_ltree);
  82077. #ifdef DEBUG
  82078. s->compressed_len += 10L;
  82079. #endif
  82080. bi_flush(s);
  82081. }
  82082. s->last_eob_len = 7;
  82083. }
  82084. /* ===========================================================================
  82085. * Determine the best encoding for the current block: dynamic trees, static
  82086. * trees or store, and output the encoded block to the zip file.
  82087. */
  82088. void _tr_flush_block (deflate_state *s,
  82089. charf *buf, /* input block, or NULL if too old */
  82090. ulg stored_len, /* length of input block */
  82091. int eof) /* true if this is the last block for a file */
  82092. {
  82093. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  82094. int max_blindex = 0; /* index of last bit length code of non zero freq */
  82095. /* Build the Huffman trees unless a stored block is forced */
  82096. if (s->level > 0) {
  82097. /* Check if the file is binary or text */
  82098. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  82099. set_data_type(s);
  82100. /* Construct the literal and distance trees */
  82101. build_tree(s, (tree_desc *)(&(s->l_desc)));
  82102. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  82103. s->static_len));
  82104. build_tree(s, (tree_desc *)(&(s->d_desc)));
  82105. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  82106. s->static_len));
  82107. /* At this point, opt_len and static_len are the total bit lengths of
  82108. * the compressed block data, excluding the tree representations.
  82109. */
  82110. /* Build the bit length tree for the above two trees, and get the index
  82111. * in bl_order of the last bit length code to send.
  82112. */
  82113. max_blindex = build_bl_tree(s);
  82114. /* Determine the best encoding. Compute the block lengths in bytes. */
  82115. opt_lenb = (s->opt_len+3+7)>>3;
  82116. static_lenb = (s->static_len+3+7)>>3;
  82117. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  82118. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  82119. s->last_lit));
  82120. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  82121. } else {
  82122. Assert(buf != (char*)0, "lost buf");
  82123. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  82124. }
  82125. #ifdef FORCE_STORED
  82126. if (buf != (char*)0) { /* force stored block */
  82127. #else
  82128. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  82129. /* 4: two words for the lengths */
  82130. #endif
  82131. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  82132. * Otherwise we can't have processed more than WSIZE input bytes since
  82133. * the last block flush, because compression would have been
  82134. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  82135. * transform a block into a stored block.
  82136. */
  82137. _tr_stored_block(s, buf, stored_len, eof);
  82138. #ifdef FORCE_STATIC
  82139. } else if (static_lenb >= 0) { /* force static trees */
  82140. #else
  82141. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  82142. #endif
  82143. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  82144. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  82145. #ifdef DEBUG
  82146. s->compressed_len += 3 + s->static_len;
  82147. #endif
  82148. } else {
  82149. send_bits(s, (DYN_TREES<<1)+eof, 3);
  82150. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  82151. max_blindex+1);
  82152. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  82153. #ifdef DEBUG
  82154. s->compressed_len += 3 + s->opt_len;
  82155. #endif
  82156. }
  82157. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  82158. /* The above check is made mod 2^32, for files larger than 512 MB
  82159. * and uLong implemented on 32 bits.
  82160. */
  82161. init_block(s);
  82162. if (eof) {
  82163. bi_windup(s);
  82164. #ifdef DEBUG
  82165. s->compressed_len += 7; /* align on byte boundary */
  82166. #endif
  82167. }
  82168. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  82169. s->compressed_len-7*eof));
  82170. }
  82171. /* ===========================================================================
  82172. * Save the match info and tally the frequency counts. Return true if
  82173. * the current block must be flushed.
  82174. */
  82175. int _tr_tally (deflate_state *s,
  82176. unsigned dist, /* distance of matched string */
  82177. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  82178. {
  82179. s->d_buf[s->last_lit] = (ush)dist;
  82180. s->l_buf[s->last_lit++] = (uch)lc;
  82181. if (dist == 0) {
  82182. /* lc is the unmatched char */
  82183. s->dyn_ltree[lc].Freq++;
  82184. } else {
  82185. s->matches++;
  82186. /* Here, lc is the match length - MIN_MATCH */
  82187. dist--; /* dist = match distance - 1 */
  82188. Assert((ush)dist < (ush)MAX_DIST(s) &&
  82189. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  82190. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  82191. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  82192. s->dyn_dtree[d_code(dist)].Freq++;
  82193. }
  82194. #ifdef TRUNCATE_BLOCK
  82195. /* Try to guess if it is profitable to stop the current block here */
  82196. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  82197. /* Compute an upper bound for the compressed length */
  82198. ulg out_length = (ulg)s->last_lit*8L;
  82199. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  82200. int dcode;
  82201. for (dcode = 0; dcode < D_CODES; dcode++) {
  82202. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  82203. (5L+extra_dbits[dcode]);
  82204. }
  82205. out_length >>= 3;
  82206. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  82207. s->last_lit, in_length, out_length,
  82208. 100L - out_length*100L/in_length));
  82209. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  82210. }
  82211. #endif
  82212. return (s->last_lit == s->lit_bufsize-1);
  82213. /* We avoid equality with lit_bufsize because of wraparound at 64K
  82214. * on 16 bit machines and because stored blocks are restricted to
  82215. * 64K-1 bytes.
  82216. */
  82217. }
  82218. /* ===========================================================================
  82219. * Send the block data compressed using the given Huffman trees
  82220. */
  82221. local void compress_block (deflate_state *s,
  82222. ct_data *ltree, /* literal tree */
  82223. ct_data *dtree) /* distance tree */
  82224. {
  82225. unsigned dist; /* distance of matched string */
  82226. int lc; /* match length or unmatched char (if dist == 0) */
  82227. unsigned lx = 0; /* running index in l_buf */
  82228. unsigned code; /* the code to send */
  82229. int extra; /* number of extra bits to send */
  82230. if (s->last_lit != 0) do {
  82231. dist = s->d_buf[lx];
  82232. lc = s->l_buf[lx++];
  82233. if (dist == 0) {
  82234. send_code(s, lc, ltree); /* send a literal byte */
  82235. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  82236. } else {
  82237. /* Here, lc is the match length - MIN_MATCH */
  82238. code = _length_code[lc];
  82239. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  82240. extra = extra_lbits[code];
  82241. if (extra != 0) {
  82242. lc -= base_length[code];
  82243. send_bits(s, lc, extra); /* send the extra length bits */
  82244. }
  82245. dist--; /* dist is now the match distance - 1 */
  82246. code = d_code(dist);
  82247. Assert (code < D_CODES, "bad d_code");
  82248. send_code(s, code, dtree); /* send the distance code */
  82249. extra = extra_dbits[code];
  82250. if (extra != 0) {
  82251. dist -= base_dist[code];
  82252. send_bits(s, dist, extra); /* send the extra distance bits */
  82253. }
  82254. } /* literal or match pair ? */
  82255. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  82256. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  82257. "pendingBuf overflow");
  82258. } while (lx < s->last_lit);
  82259. send_code(s, END_BLOCK, ltree);
  82260. s->last_eob_len = ltree[END_BLOCK].Len;
  82261. }
  82262. /* ===========================================================================
  82263. * Set the data type to BINARY or TEXT, using a crude approximation:
  82264. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  82265. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  82266. * IN assertion: the fields Freq of dyn_ltree are set.
  82267. */
  82268. local void set_data_type (deflate_state *s)
  82269. {
  82270. int n;
  82271. for (n = 0; n < 9; n++)
  82272. if (s->dyn_ltree[n].Freq != 0)
  82273. break;
  82274. if (n == 9)
  82275. for (n = 14; n < 32; n++)
  82276. if (s->dyn_ltree[n].Freq != 0)
  82277. break;
  82278. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  82279. }
  82280. /* ===========================================================================
  82281. * Reverse the first len bits of a code, using straightforward code (a faster
  82282. * method would use a table)
  82283. * IN assertion: 1 <= len <= 15
  82284. */
  82285. local unsigned bi_reverse (unsigned code, int len)
  82286. {
  82287. register unsigned res = 0;
  82288. do {
  82289. res |= code & 1;
  82290. code >>= 1, res <<= 1;
  82291. } while (--len > 0);
  82292. return res >> 1;
  82293. }
  82294. /* ===========================================================================
  82295. * Flush the bit buffer, keeping at most 7 bits in it.
  82296. */
  82297. local void bi_flush (deflate_state *s)
  82298. {
  82299. if (s->bi_valid == 16) {
  82300. put_short(s, s->bi_buf);
  82301. s->bi_buf = 0;
  82302. s->bi_valid = 0;
  82303. } else if (s->bi_valid >= 8) {
  82304. put_byte(s, (Byte)s->bi_buf);
  82305. s->bi_buf >>= 8;
  82306. s->bi_valid -= 8;
  82307. }
  82308. }
  82309. /* ===========================================================================
  82310. * Flush the bit buffer and align the output on a byte boundary
  82311. */
  82312. local void bi_windup (deflate_state *s)
  82313. {
  82314. if (s->bi_valid > 8) {
  82315. put_short(s, s->bi_buf);
  82316. } else if (s->bi_valid > 0) {
  82317. put_byte(s, (Byte)s->bi_buf);
  82318. }
  82319. s->bi_buf = 0;
  82320. s->bi_valid = 0;
  82321. #ifdef DEBUG
  82322. s->bits_sent = (s->bits_sent+7) & ~7;
  82323. #endif
  82324. }
  82325. /* ===========================================================================
  82326. * Copy a stored block, storing first the length and its
  82327. * one's complement if requested.
  82328. */
  82329. local void copy_block(deflate_state *s,
  82330. charf *buf, /* the input data */
  82331. unsigned len, /* its length */
  82332. int header) /* true if block header must be written */
  82333. {
  82334. bi_windup(s); /* align on byte boundary */
  82335. s->last_eob_len = 8; /* enough lookahead for inflate */
  82336. if (header) {
  82337. put_short(s, (ush)len);
  82338. put_short(s, (ush)~len);
  82339. #ifdef DEBUG
  82340. s->bits_sent += 2*16;
  82341. #endif
  82342. }
  82343. #ifdef DEBUG
  82344. s->bits_sent += (ulg)len<<3;
  82345. #endif
  82346. while (len--) {
  82347. put_byte(s, *buf++);
  82348. }
  82349. }
  82350. /*** End of inlined file: trees.c ***/
  82351. /*** Start of inlined file: zutil.c ***/
  82352. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  82353. #ifndef NO_DUMMY_DECL
  82354. struct internal_state {int dummy;}; /* for buggy compilers */
  82355. #endif
  82356. const char * const z_errmsg[10] = {
  82357. "need dictionary", /* Z_NEED_DICT 2 */
  82358. "stream end", /* Z_STREAM_END 1 */
  82359. "", /* Z_OK 0 */
  82360. "file error", /* Z_ERRNO (-1) */
  82361. "stream error", /* Z_STREAM_ERROR (-2) */
  82362. "data error", /* Z_DATA_ERROR (-3) */
  82363. "insufficient memory", /* Z_MEM_ERROR (-4) */
  82364. "buffer error", /* Z_BUF_ERROR (-5) */
  82365. "incompatible version",/* Z_VERSION_ERROR (-6) */
  82366. ""};
  82367. /*const char * ZEXPORT zlibVersion()
  82368. {
  82369. return ZLIB_VERSION;
  82370. }
  82371. uLong ZEXPORT zlibCompileFlags()
  82372. {
  82373. uLong flags;
  82374. flags = 0;
  82375. switch (sizeof(uInt)) {
  82376. case 2: break;
  82377. case 4: flags += 1; break;
  82378. case 8: flags += 2; break;
  82379. default: flags += 3;
  82380. }
  82381. switch (sizeof(uLong)) {
  82382. case 2: break;
  82383. case 4: flags += 1 << 2; break;
  82384. case 8: flags += 2 << 2; break;
  82385. default: flags += 3 << 2;
  82386. }
  82387. switch (sizeof(voidpf)) {
  82388. case 2: break;
  82389. case 4: flags += 1 << 4; break;
  82390. case 8: flags += 2 << 4; break;
  82391. default: flags += 3 << 4;
  82392. }
  82393. switch (sizeof(z_off_t)) {
  82394. case 2: break;
  82395. case 4: flags += 1 << 6; break;
  82396. case 8: flags += 2 << 6; break;
  82397. default: flags += 3 << 6;
  82398. }
  82399. #ifdef DEBUG
  82400. flags += 1 << 8;
  82401. #endif
  82402. #if defined(ASMV) || defined(ASMINF)
  82403. flags += 1 << 9;
  82404. #endif
  82405. #ifdef ZLIB_WINAPI
  82406. flags += 1 << 10;
  82407. #endif
  82408. #ifdef BUILDFIXED
  82409. flags += 1 << 12;
  82410. #endif
  82411. #ifdef DYNAMIC_CRC_TABLE
  82412. flags += 1 << 13;
  82413. #endif
  82414. #ifdef NO_GZCOMPRESS
  82415. flags += 1L << 16;
  82416. #endif
  82417. #ifdef NO_GZIP
  82418. flags += 1L << 17;
  82419. #endif
  82420. #ifdef PKZIP_BUG_WORKAROUND
  82421. flags += 1L << 20;
  82422. #endif
  82423. #ifdef FASTEST
  82424. flags += 1L << 21;
  82425. #endif
  82426. #ifdef STDC
  82427. # ifdef NO_vsnprintf
  82428. flags += 1L << 25;
  82429. # ifdef HAS_vsprintf_void
  82430. flags += 1L << 26;
  82431. # endif
  82432. # else
  82433. # ifdef HAS_vsnprintf_void
  82434. flags += 1L << 26;
  82435. # endif
  82436. # endif
  82437. #else
  82438. flags += 1L << 24;
  82439. # ifdef NO_snprintf
  82440. flags += 1L << 25;
  82441. # ifdef HAS_sprintf_void
  82442. flags += 1L << 26;
  82443. # endif
  82444. # else
  82445. # ifdef HAS_snprintf_void
  82446. flags += 1L << 26;
  82447. # endif
  82448. # endif
  82449. #endif
  82450. return flags;
  82451. }*/
  82452. #ifdef DEBUG
  82453. # ifndef verbose
  82454. # define verbose 0
  82455. # endif
  82456. int z_verbose = verbose;
  82457. void z_error (const char *m)
  82458. {
  82459. fprintf(stderr, "%s\n", m);
  82460. exit(1);
  82461. }
  82462. #endif
  82463. /* exported to allow conversion of error code to string for compress() and
  82464. * uncompress()
  82465. */
  82466. const char * ZEXPORT zError(int err)
  82467. {
  82468. return ERR_MSG(err);
  82469. }
  82470. #if defined(_WIN32_WCE)
  82471. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  82472. * errno. We define it as a global variable to simplify porting.
  82473. * Its value is always 0 and should not be used.
  82474. */
  82475. int errno = 0;
  82476. #endif
  82477. #ifndef HAVE_MEMCPY
  82478. void zmemcpy(dest, source, len)
  82479. Bytef* dest;
  82480. const Bytef* source;
  82481. uInt len;
  82482. {
  82483. if (len == 0) return;
  82484. do {
  82485. *dest++ = *source++; /* ??? to be unrolled */
  82486. } while (--len != 0);
  82487. }
  82488. int zmemcmp(s1, s2, len)
  82489. const Bytef* s1;
  82490. const Bytef* s2;
  82491. uInt len;
  82492. {
  82493. uInt j;
  82494. for (j = 0; j < len; j++) {
  82495. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  82496. }
  82497. return 0;
  82498. }
  82499. void zmemzero(dest, len)
  82500. Bytef* dest;
  82501. uInt len;
  82502. {
  82503. if (len == 0) return;
  82504. do {
  82505. *dest++ = 0; /* ??? to be unrolled */
  82506. } while (--len != 0);
  82507. }
  82508. #endif
  82509. #ifdef SYS16BIT
  82510. #ifdef __TURBOC__
  82511. /* Turbo C in 16-bit mode */
  82512. # define MY_ZCALLOC
  82513. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  82514. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  82515. * must fix the pointer. Warning: the pointer must be put back to its
  82516. * original form in order to free it, use zcfree().
  82517. */
  82518. #define MAX_PTR 10
  82519. /* 10*64K = 640K */
  82520. local int next_ptr = 0;
  82521. typedef struct ptr_table_s {
  82522. voidpf org_ptr;
  82523. voidpf new_ptr;
  82524. } ptr_table;
  82525. local ptr_table table[MAX_PTR];
  82526. /* This table is used to remember the original form of pointers
  82527. * to large buffers (64K). Such pointers are normalized with a zero offset.
  82528. * Since MSDOS is not a preemptive multitasking OS, this table is not
  82529. * protected from concurrent access. This hack doesn't work anyway on
  82530. * a protected system like OS/2. Use Microsoft C instead.
  82531. */
  82532. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  82533. {
  82534. voidpf buf = opaque; /* just to make some compilers happy */
  82535. ulg bsize = (ulg)items*size;
  82536. /* If we allocate less than 65520 bytes, we assume that farmalloc
  82537. * will return a usable pointer which doesn't have to be normalized.
  82538. */
  82539. if (bsize < 65520L) {
  82540. buf = farmalloc(bsize);
  82541. if (*(ush*)&buf != 0) return buf;
  82542. } else {
  82543. buf = farmalloc(bsize + 16L);
  82544. }
  82545. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  82546. table[next_ptr].org_ptr = buf;
  82547. /* Normalize the pointer to seg:0 */
  82548. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  82549. *(ush*)&buf = 0;
  82550. table[next_ptr++].new_ptr = buf;
  82551. return buf;
  82552. }
  82553. void zcfree (voidpf opaque, voidpf ptr)
  82554. {
  82555. int n;
  82556. if (*(ush*)&ptr != 0) { /* object < 64K */
  82557. farfree(ptr);
  82558. return;
  82559. }
  82560. /* Find the original pointer */
  82561. for (n = 0; n < next_ptr; n++) {
  82562. if (ptr != table[n].new_ptr) continue;
  82563. farfree(table[n].org_ptr);
  82564. while (++n < next_ptr) {
  82565. table[n-1] = table[n];
  82566. }
  82567. next_ptr--;
  82568. return;
  82569. }
  82570. ptr = opaque; /* just to make some compilers happy */
  82571. Assert(0, "zcfree: ptr not found");
  82572. }
  82573. #endif /* __TURBOC__ */
  82574. #ifdef M_I86
  82575. /* Microsoft C in 16-bit mode */
  82576. # define MY_ZCALLOC
  82577. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  82578. # define _halloc halloc
  82579. # define _hfree hfree
  82580. #endif
  82581. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  82582. {
  82583. if (opaque) opaque = 0; /* to make compiler happy */
  82584. return _halloc((long)items, size);
  82585. }
  82586. void zcfree (voidpf opaque, voidpf ptr)
  82587. {
  82588. if (opaque) opaque = 0; /* to make compiler happy */
  82589. _hfree(ptr);
  82590. }
  82591. #endif /* M_I86 */
  82592. #endif /* SYS16BIT */
  82593. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  82594. #ifndef STDC
  82595. extern voidp malloc OF((uInt size));
  82596. extern voidp calloc OF((uInt items, uInt size));
  82597. extern void free OF((voidpf ptr));
  82598. #endif
  82599. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  82600. {
  82601. if (opaque) items += size - size; /* make compiler happy */
  82602. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  82603. (voidpf)calloc(items, size);
  82604. }
  82605. void zcfree (voidpf opaque, voidpf ptr)
  82606. {
  82607. free(ptr);
  82608. if (opaque) return; /* make compiler happy */
  82609. }
  82610. #endif /* MY_ZCALLOC */
  82611. /*** End of inlined file: zutil.c ***/
  82612. #undef Byte
  82613. }
  82614. #else
  82615. #include <zlib.h>
  82616. #endif
  82617. }
  82618. #if JUCE_MSVC
  82619. #pragma warning (pop)
  82620. #endif
  82621. BEGIN_JUCE_NAMESPACE
  82622. // internal helper object that holds the zlib structures so they don't have to be
  82623. // included publicly.
  82624. class GZIPDecompressHelper
  82625. {
  82626. public:
  82627. GZIPDecompressHelper (const bool noWrap)
  82628. : finished (true),
  82629. needsDictionary (false),
  82630. error (true),
  82631. streamIsValid (false),
  82632. data (0),
  82633. dataSize (0)
  82634. {
  82635. using namespace zlibNamespace;
  82636. zerostruct (stream);
  82637. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  82638. finished = error = ! streamIsValid;
  82639. }
  82640. ~GZIPDecompressHelper()
  82641. {
  82642. using namespace zlibNamespace;
  82643. if (streamIsValid)
  82644. inflateEnd (&stream);
  82645. }
  82646. bool needsInput() const throw() { return dataSize <= 0; }
  82647. void setInput (uint8* const data_, const int size) throw()
  82648. {
  82649. data = data_;
  82650. dataSize = size;
  82651. }
  82652. int doNextBlock (uint8* const dest, const int destSize)
  82653. {
  82654. using namespace zlibNamespace;
  82655. if (streamIsValid && data != 0 && ! finished)
  82656. {
  82657. stream.next_in = data;
  82658. stream.next_out = dest;
  82659. stream.avail_in = dataSize;
  82660. stream.avail_out = destSize;
  82661. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  82662. {
  82663. case Z_STREAM_END:
  82664. finished = true;
  82665. // deliberate fall-through
  82666. case Z_OK:
  82667. data += dataSize - stream.avail_in;
  82668. dataSize = stream.avail_in;
  82669. return destSize - stream.avail_out;
  82670. case Z_NEED_DICT:
  82671. needsDictionary = true;
  82672. data += dataSize - stream.avail_in;
  82673. dataSize = stream.avail_in;
  82674. break;
  82675. case Z_DATA_ERROR:
  82676. case Z_MEM_ERROR:
  82677. error = true;
  82678. default:
  82679. break;
  82680. }
  82681. }
  82682. return 0;
  82683. }
  82684. bool finished, needsDictionary, error, streamIsValid;
  82685. private:
  82686. zlibNamespace::z_stream stream;
  82687. uint8* data;
  82688. int dataSize;
  82689. GZIPDecompressHelper (const GZIPDecompressHelper&);
  82690. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  82691. };
  82692. const int gzipDecompBufferSize = 32768;
  82693. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  82694. const bool deleteSourceWhenDestroyed,
  82695. const bool noWrap_,
  82696. const int64 uncompressedStreamLength_)
  82697. : sourceStream (sourceStream_),
  82698. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  82699. uncompressedStreamLength (uncompressedStreamLength_),
  82700. noWrap (noWrap_),
  82701. isEof (false),
  82702. activeBufferSize (0),
  82703. originalSourcePos (sourceStream_->getPosition()),
  82704. currentPos (0),
  82705. buffer (gzipDecompBufferSize),
  82706. helper (new GZIPDecompressHelper (noWrap_))
  82707. {
  82708. }
  82709. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  82710. {
  82711. }
  82712. int64 GZIPDecompressorInputStream::getTotalLength()
  82713. {
  82714. return uncompressedStreamLength;
  82715. }
  82716. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  82717. {
  82718. if ((howMany > 0) && ! isEof)
  82719. {
  82720. jassert (destBuffer != 0);
  82721. if (destBuffer != 0)
  82722. {
  82723. int numRead = 0;
  82724. uint8* d = static_cast <uint8*> (destBuffer);
  82725. while (! helper->error)
  82726. {
  82727. const int n = helper->doNextBlock (d, howMany);
  82728. currentPos += n;
  82729. if (n == 0)
  82730. {
  82731. if (helper->finished || helper->needsDictionary)
  82732. {
  82733. isEof = true;
  82734. return numRead;
  82735. }
  82736. if (helper->needsInput())
  82737. {
  82738. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  82739. if (activeBufferSize > 0)
  82740. {
  82741. helper->setInput (buffer, activeBufferSize);
  82742. }
  82743. else
  82744. {
  82745. isEof = true;
  82746. return numRead;
  82747. }
  82748. }
  82749. }
  82750. else
  82751. {
  82752. numRead += n;
  82753. howMany -= n;
  82754. d += n;
  82755. if (howMany <= 0)
  82756. return numRead;
  82757. }
  82758. }
  82759. }
  82760. }
  82761. return 0;
  82762. }
  82763. bool GZIPDecompressorInputStream::isExhausted()
  82764. {
  82765. return helper->error || isEof;
  82766. }
  82767. int64 GZIPDecompressorInputStream::getPosition()
  82768. {
  82769. return currentPos;
  82770. }
  82771. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  82772. {
  82773. if (newPos < currentPos)
  82774. {
  82775. // to go backwards, reset the stream and start again..
  82776. isEof = false;
  82777. activeBufferSize = 0;
  82778. currentPos = 0;
  82779. helper = new GZIPDecompressHelper (noWrap);
  82780. sourceStream->setPosition (originalSourcePos);
  82781. }
  82782. skipNextBytes (newPos - currentPos);
  82783. return true;
  82784. }
  82785. END_JUCE_NAMESPACE
  82786. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  82787. #endif
  82788. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  82789. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  82790. #if JUCE_USE_FLAC
  82791. #if JUCE_WINDOWS
  82792. #include <windows.h>
  82793. #endif
  82794. #ifdef _MSC_VER
  82795. #pragma warning (disable : 4505)
  82796. #pragma warning (push)
  82797. #endif
  82798. namespace FlacNamespace
  82799. {
  82800. #if JUCE_INCLUDE_FLAC_CODE
  82801. #define FLAC__NO_DLL 1
  82802. #if ! defined (SIZE_MAX)
  82803. #define SIZE_MAX 0xffffffff
  82804. #endif
  82805. #define __STDC_LIMIT_MACROS 1
  82806. /*** Start of inlined file: all.h ***/
  82807. #ifndef FLAC__ALL_H
  82808. #define FLAC__ALL_H
  82809. /*** Start of inlined file: export.h ***/
  82810. #ifndef FLAC__EXPORT_H
  82811. #define FLAC__EXPORT_H
  82812. /** \file include/FLAC/export.h
  82813. *
  82814. * \brief
  82815. * This module contains #defines and symbols for exporting function
  82816. * calls, and providing version information and compiled-in features.
  82817. *
  82818. * See the \link flac_export export \endlink module.
  82819. */
  82820. /** \defgroup flac_export FLAC/export.h: export symbols
  82821. * \ingroup flac
  82822. *
  82823. * \brief
  82824. * This module contains #defines and symbols for exporting function
  82825. * calls, and providing version information and compiled-in features.
  82826. *
  82827. * If you are compiling with MSVC and will link to the static library
  82828. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  82829. * make sure the symbols are exported properly.
  82830. *
  82831. * \{
  82832. */
  82833. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  82834. #define FLAC_API
  82835. #else
  82836. #ifdef FLAC_API_EXPORTS
  82837. #define FLAC_API _declspec(dllexport)
  82838. #else
  82839. #define FLAC_API _declspec(dllimport)
  82840. #endif
  82841. #endif
  82842. /** These #defines will mirror the libtool-based library version number, see
  82843. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  82844. */
  82845. #define FLAC_API_VERSION_CURRENT 10
  82846. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  82847. #define FLAC_API_VERSION_AGE 2 /**< see above */
  82848. #ifdef __cplusplus
  82849. extern "C" {
  82850. #endif
  82851. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  82852. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  82853. #ifdef __cplusplus
  82854. }
  82855. #endif
  82856. /* \} */
  82857. #endif
  82858. /*** End of inlined file: export.h ***/
  82859. /*** Start of inlined file: assert.h ***/
  82860. #ifndef FLAC__ASSERT_H
  82861. #define FLAC__ASSERT_H
  82862. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  82863. #ifdef DEBUG
  82864. #include <assert.h>
  82865. #define FLAC__ASSERT(x) assert(x)
  82866. #define FLAC__ASSERT_DECLARATION(x) x
  82867. #else
  82868. #define FLAC__ASSERT(x)
  82869. #define FLAC__ASSERT_DECLARATION(x)
  82870. #endif
  82871. #endif
  82872. /*** End of inlined file: assert.h ***/
  82873. /*** Start of inlined file: callback.h ***/
  82874. #ifndef FLAC__CALLBACK_H
  82875. #define FLAC__CALLBACK_H
  82876. /*** Start of inlined file: ordinals.h ***/
  82877. #ifndef FLAC__ORDINALS_H
  82878. #define FLAC__ORDINALS_H
  82879. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  82880. #include <inttypes.h>
  82881. #endif
  82882. typedef signed char FLAC__int8;
  82883. typedef unsigned char FLAC__uint8;
  82884. #if defined(_MSC_VER) || defined(__BORLANDC__)
  82885. typedef __int16 FLAC__int16;
  82886. typedef __int32 FLAC__int32;
  82887. typedef __int64 FLAC__int64;
  82888. typedef unsigned __int16 FLAC__uint16;
  82889. typedef unsigned __int32 FLAC__uint32;
  82890. typedef unsigned __int64 FLAC__uint64;
  82891. #elif defined(__EMX__)
  82892. typedef short FLAC__int16;
  82893. typedef long FLAC__int32;
  82894. typedef long long FLAC__int64;
  82895. typedef unsigned short FLAC__uint16;
  82896. typedef unsigned long FLAC__uint32;
  82897. typedef unsigned long long FLAC__uint64;
  82898. #else
  82899. typedef int16_t FLAC__int16;
  82900. typedef int32_t FLAC__int32;
  82901. typedef int64_t FLAC__int64;
  82902. typedef uint16_t FLAC__uint16;
  82903. typedef uint32_t FLAC__uint32;
  82904. typedef uint64_t FLAC__uint64;
  82905. #endif
  82906. typedef int FLAC__bool;
  82907. typedef FLAC__uint8 FLAC__byte;
  82908. #ifdef true
  82909. #undef true
  82910. #endif
  82911. #ifdef false
  82912. #undef false
  82913. #endif
  82914. #ifndef __cplusplus
  82915. #define true 1
  82916. #define false 0
  82917. #endif
  82918. #endif
  82919. /*** End of inlined file: ordinals.h ***/
  82920. #include <stdlib.h> /* for size_t */
  82921. /** \file include/FLAC/callback.h
  82922. *
  82923. * \brief
  82924. * This module defines the structures for describing I/O callbacks
  82925. * to the other FLAC interfaces.
  82926. *
  82927. * See the detailed documentation for callbacks in the
  82928. * \link flac_callbacks callbacks \endlink module.
  82929. */
  82930. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  82931. * \ingroup flac
  82932. *
  82933. * \brief
  82934. * This module defines the structures for describing I/O callbacks
  82935. * to the other FLAC interfaces.
  82936. *
  82937. * The purpose of the I/O callback functions is to create a common way
  82938. * for the metadata interfaces to handle I/O.
  82939. *
  82940. * Originally the metadata interfaces required filenames as the way of
  82941. * specifying FLAC files to operate on. This is problematic in some
  82942. * environments so there is an additional option to specify a set of
  82943. * callbacks for doing I/O on the FLAC file, instead of the filename.
  82944. *
  82945. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  82946. * opaque structure for a data source.
  82947. *
  82948. * The callback function prototypes are similar (but not identical) to the
  82949. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  82950. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  82951. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  82952. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  82953. * is required. \warning You generally CANNOT directly use fseek or ftell
  82954. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  82955. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  82956. * large files. You will have to find an equivalent function (e.g. ftello),
  82957. * or write a wrapper. The same is true for feof() since this is usually
  82958. * implemented as a macro, not as a function whose address can be taken.
  82959. *
  82960. * \{
  82961. */
  82962. #ifdef __cplusplus
  82963. extern "C" {
  82964. #endif
  82965. /** This is the opaque handle type used by the callbacks. Typically
  82966. * this is a \c FILE* or address of a file descriptor.
  82967. */
  82968. typedef void* FLAC__IOHandle;
  82969. /** Signature for the read callback.
  82970. * The signature and semantics match POSIX fread() implementations
  82971. * and can generally be used interchangeably.
  82972. *
  82973. * \param ptr The address of the read buffer.
  82974. * \param size The size of the records to be read.
  82975. * \param nmemb The number of records to be read.
  82976. * \param handle The handle to the data source.
  82977. * \retval size_t
  82978. * The number of records read.
  82979. */
  82980. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82981. /** Signature for the write callback.
  82982. * The signature and semantics match POSIX fwrite() implementations
  82983. * and can generally be used interchangeably.
  82984. *
  82985. * \param ptr The address of the write buffer.
  82986. * \param size The size of the records to be written.
  82987. * \param nmemb The number of records to be written.
  82988. * \param handle The handle to the data source.
  82989. * \retval size_t
  82990. * The number of records written.
  82991. */
  82992. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82993. /** Signature for the seek callback.
  82994. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  82995. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  82996. * and 32-bits wide.
  82997. *
  82998. * \param handle The handle to the data source.
  82999. * \param offset The new position, relative to \a whence
  83000. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  83001. * \retval int
  83002. * \c 0 on success, \c -1 on error.
  83003. */
  83004. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  83005. /** Signature for the tell callback.
  83006. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  83007. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  83008. * and 32-bits wide.
  83009. *
  83010. * \param handle The handle to the data source.
  83011. * \retval FLAC__int64
  83012. * The current position on success, \c -1 on error.
  83013. */
  83014. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  83015. /** Signature for the EOF callback.
  83016. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  83017. * on many systems, feof() is a macro, so in this case a wrapper function
  83018. * must be provided instead.
  83019. *
  83020. * \param handle The handle to the data source.
  83021. * \retval int
  83022. * \c 0 if not at end of file, nonzero if at end of file.
  83023. */
  83024. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  83025. /** Signature for the close callback.
  83026. * The signature and semantics match POSIX fclose() implementations
  83027. * and can generally be used interchangeably.
  83028. *
  83029. * \param handle The handle to the data source.
  83030. * \retval int
  83031. * \c 0 on success, \c EOF on error.
  83032. */
  83033. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  83034. /** A structure for holding a set of callbacks.
  83035. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  83036. * describe which of the callbacks are required. The ones that are not
  83037. * required may be set to NULL.
  83038. *
  83039. * If the seek requirement for an interface is optional, you can signify that
  83040. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  83041. */
  83042. typedef struct {
  83043. FLAC__IOCallback_Read read;
  83044. FLAC__IOCallback_Write write;
  83045. FLAC__IOCallback_Seek seek;
  83046. FLAC__IOCallback_Tell tell;
  83047. FLAC__IOCallback_Eof eof;
  83048. FLAC__IOCallback_Close close;
  83049. } FLAC__IOCallbacks;
  83050. /* \} */
  83051. #ifdef __cplusplus
  83052. }
  83053. #endif
  83054. #endif
  83055. /*** End of inlined file: callback.h ***/
  83056. /*** Start of inlined file: format.h ***/
  83057. #ifndef FLAC__FORMAT_H
  83058. #define FLAC__FORMAT_H
  83059. #ifdef __cplusplus
  83060. extern "C" {
  83061. #endif
  83062. /** \file include/FLAC/format.h
  83063. *
  83064. * \brief
  83065. * This module contains structure definitions for the representation
  83066. * of FLAC format components in memory. These are the basic
  83067. * structures used by the rest of the interfaces.
  83068. *
  83069. * See the detailed documentation in the
  83070. * \link flac_format format \endlink module.
  83071. */
  83072. /** \defgroup flac_format FLAC/format.h: format components
  83073. * \ingroup flac
  83074. *
  83075. * \brief
  83076. * This module contains structure definitions for the representation
  83077. * of FLAC format components in memory. These are the basic
  83078. * structures used by the rest of the interfaces.
  83079. *
  83080. * First, you should be familiar with the
  83081. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  83082. * follow directly from the specification. As a user of libFLAC, the
  83083. * interesting parts really are the structures that describe the frame
  83084. * header and metadata blocks.
  83085. *
  83086. * The format structures here are very primitive, designed to store
  83087. * information in an efficient way. Reading information from the
  83088. * structures is easy but creating or modifying them directly is
  83089. * more complex. For the most part, as a user of a library, editing
  83090. * is not necessary; however, for metadata blocks it is, so there are
  83091. * convenience functions provided in the \link flac_metadata metadata
  83092. * module \endlink to simplify the manipulation of metadata blocks.
  83093. *
  83094. * \note
  83095. * It's not the best convention, but symbols ending in _LEN are in bits
  83096. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  83097. * global variables because they are usually used when declaring byte
  83098. * arrays and some compilers require compile-time knowledge of array
  83099. * sizes when declared on the stack.
  83100. *
  83101. * \{
  83102. */
  83103. /*
  83104. Most of the values described in this file are defined by the FLAC
  83105. format specification. There is nothing to tune here.
  83106. */
  83107. /** The largest legal metadata type code. */
  83108. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  83109. /** The minimum block size, in samples, permitted by the format. */
  83110. #define FLAC__MIN_BLOCK_SIZE (16u)
  83111. /** The maximum block size, in samples, permitted by the format. */
  83112. #define FLAC__MAX_BLOCK_SIZE (65535u)
  83113. /** The maximum block size, in samples, permitted by the FLAC subset for
  83114. * sample rates up to 48kHz. */
  83115. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  83116. /** The maximum number of channels permitted by the format. */
  83117. #define FLAC__MAX_CHANNELS (8u)
  83118. /** The minimum sample resolution permitted by the format. */
  83119. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  83120. /** The maximum sample resolution permitted by the format. */
  83121. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  83122. /** The maximum sample resolution permitted by libFLAC.
  83123. *
  83124. * \warning
  83125. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  83126. * the reference encoder/decoder is currently limited to 24 bits because
  83127. * of prevalent 32-bit math, so make sure and use this value when
  83128. * appropriate.
  83129. */
  83130. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  83131. /** The maximum sample rate permitted by the format. The value is
  83132. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  83133. * as to why.
  83134. */
  83135. #define FLAC__MAX_SAMPLE_RATE (655350u)
  83136. /** The maximum LPC order permitted by the format. */
  83137. #define FLAC__MAX_LPC_ORDER (32u)
  83138. /** The maximum LPC order permitted by the FLAC subset for sample rates
  83139. * up to 48kHz. */
  83140. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  83141. /** The minimum quantized linear predictor coefficient precision
  83142. * permitted by the format.
  83143. */
  83144. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  83145. /** The maximum quantized linear predictor coefficient precision
  83146. * permitted by the format.
  83147. */
  83148. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  83149. /** The maximum order of the fixed predictors permitted by the format. */
  83150. #define FLAC__MAX_FIXED_ORDER (4u)
  83151. /** The maximum Rice partition order permitted by the format. */
  83152. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  83153. /** The maximum Rice partition order permitted by the FLAC Subset. */
  83154. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  83155. /** The version string of the release, stamped onto the libraries and binaries.
  83156. *
  83157. * \note
  83158. * This does not correspond to the shared library version number, which
  83159. * is used to determine binary compatibility.
  83160. */
  83161. extern FLAC_API const char *FLAC__VERSION_STRING;
  83162. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  83163. * This is a NUL-terminated ASCII string; when inserted into the
  83164. * VORBIS_COMMENT the trailing null is stripped.
  83165. */
  83166. extern FLAC_API const char *FLAC__VENDOR_STRING;
  83167. /** The byte string representation of the beginning of a FLAC stream. */
  83168. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  83169. /** The 32-bit integer big-endian representation of the beginning of
  83170. * a FLAC stream.
  83171. */
  83172. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  83173. /** The length of the FLAC signature in bits. */
  83174. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  83175. /** The length of the FLAC signature in bytes. */
  83176. #define FLAC__STREAM_SYNC_LENGTH (4u)
  83177. /*****************************************************************************
  83178. *
  83179. * Subframe structures
  83180. *
  83181. *****************************************************************************/
  83182. /*****************************************************************************/
  83183. /** An enumeration of the available entropy coding methods. */
  83184. typedef enum {
  83185. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  83186. /**< Residual is coded by partitioning into contexts, each with it's own
  83187. * 4-bit Rice parameter. */
  83188. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  83189. /**< Residual is coded by partitioning into contexts, each with it's own
  83190. * 5-bit Rice parameter. */
  83191. } FLAC__EntropyCodingMethodType;
  83192. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  83193. *
  83194. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  83195. * give the string equivalent. The contents should not be modified.
  83196. */
  83197. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  83198. /** Contents of a Rice partitioned residual
  83199. */
  83200. typedef struct {
  83201. unsigned *parameters;
  83202. /**< The Rice parameters for each context. */
  83203. unsigned *raw_bits;
  83204. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  83205. * partitions and zero for unescaped partitions.
  83206. */
  83207. unsigned capacity_by_order;
  83208. /**< The capacity of the \a parameters and \a raw_bits arrays
  83209. * specified as an order, i.e. the number of array elements
  83210. * allocated is 2 ^ \a capacity_by_order.
  83211. */
  83212. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  83213. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  83214. */
  83215. typedef struct {
  83216. unsigned order;
  83217. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  83218. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  83219. /**< The context's Rice parameters and/or raw bits. */
  83220. } FLAC__EntropyCodingMethod_PartitionedRice;
  83221. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  83222. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  83223. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  83224. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  83225. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  83226. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  83227. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  83228. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  83229. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  83230. */
  83231. typedef struct {
  83232. FLAC__EntropyCodingMethodType type;
  83233. union {
  83234. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  83235. } data;
  83236. } FLAC__EntropyCodingMethod;
  83237. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  83238. /*****************************************************************************/
  83239. /** An enumeration of the available subframe types. */
  83240. typedef enum {
  83241. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  83242. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  83243. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  83244. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  83245. } FLAC__SubframeType;
  83246. /** Maps a FLAC__SubframeType to a C string.
  83247. *
  83248. * Using a FLAC__SubframeType as the index to this array will
  83249. * give the string equivalent. The contents should not be modified.
  83250. */
  83251. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  83252. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  83253. */
  83254. typedef struct {
  83255. FLAC__int32 value; /**< The constant signal value. */
  83256. } FLAC__Subframe_Constant;
  83257. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  83258. */
  83259. typedef struct {
  83260. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  83261. } FLAC__Subframe_Verbatim;
  83262. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  83263. */
  83264. typedef struct {
  83265. FLAC__EntropyCodingMethod entropy_coding_method;
  83266. /**< The residual coding method. */
  83267. unsigned order;
  83268. /**< The polynomial order. */
  83269. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  83270. /**< Warmup samples to prime the predictor, length == order. */
  83271. const FLAC__int32 *residual;
  83272. /**< The residual signal, length == (blocksize minus order) samples. */
  83273. } FLAC__Subframe_Fixed;
  83274. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  83275. */
  83276. typedef struct {
  83277. FLAC__EntropyCodingMethod entropy_coding_method;
  83278. /**< The residual coding method. */
  83279. unsigned order;
  83280. /**< The FIR order. */
  83281. unsigned qlp_coeff_precision;
  83282. /**< Quantized FIR filter coefficient precision in bits. */
  83283. int quantization_level;
  83284. /**< The qlp coeff shift needed. */
  83285. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  83286. /**< FIR filter coefficients. */
  83287. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  83288. /**< Warmup samples to prime the predictor, length == order. */
  83289. const FLAC__int32 *residual;
  83290. /**< The residual signal, length == (blocksize minus order) samples. */
  83291. } FLAC__Subframe_LPC;
  83292. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  83293. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  83294. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  83295. */
  83296. typedef struct {
  83297. FLAC__SubframeType type;
  83298. union {
  83299. FLAC__Subframe_Constant constant;
  83300. FLAC__Subframe_Fixed fixed;
  83301. FLAC__Subframe_LPC lpc;
  83302. FLAC__Subframe_Verbatim verbatim;
  83303. } data;
  83304. unsigned wasted_bits;
  83305. } FLAC__Subframe;
  83306. /** == 1 (bit)
  83307. *
  83308. * This used to be a zero-padding bit (hence the name
  83309. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  83310. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  83311. * to mean something else.
  83312. */
  83313. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  83314. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  83315. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  83316. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  83317. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  83318. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  83319. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  83320. /*****************************************************************************/
  83321. /*****************************************************************************
  83322. *
  83323. * Frame structures
  83324. *
  83325. *****************************************************************************/
  83326. /** An enumeration of the available channel assignments. */
  83327. typedef enum {
  83328. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  83329. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  83330. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  83331. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  83332. } FLAC__ChannelAssignment;
  83333. /** Maps a FLAC__ChannelAssignment to a C string.
  83334. *
  83335. * Using a FLAC__ChannelAssignment as the index to this array will
  83336. * give the string equivalent. The contents should not be modified.
  83337. */
  83338. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  83339. /** An enumeration of the possible frame numbering methods. */
  83340. typedef enum {
  83341. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  83342. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  83343. } FLAC__FrameNumberType;
  83344. /** Maps a FLAC__FrameNumberType to a C string.
  83345. *
  83346. * Using a FLAC__FrameNumberType as the index to this array will
  83347. * give the string equivalent. The contents should not be modified.
  83348. */
  83349. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  83350. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  83351. */
  83352. typedef struct {
  83353. unsigned blocksize;
  83354. /**< The number of samples per subframe. */
  83355. unsigned sample_rate;
  83356. /**< The sample rate in Hz. */
  83357. unsigned channels;
  83358. /**< The number of channels (== number of subframes). */
  83359. FLAC__ChannelAssignment channel_assignment;
  83360. /**< The channel assignment for the frame. */
  83361. unsigned bits_per_sample;
  83362. /**< The sample resolution. */
  83363. FLAC__FrameNumberType number_type;
  83364. /**< The numbering scheme used for the frame. As a convenience, the
  83365. * decoder will always convert a frame number to a sample number because
  83366. * the rules are complex. */
  83367. union {
  83368. FLAC__uint32 frame_number;
  83369. FLAC__uint64 sample_number;
  83370. } number;
  83371. /**< The frame number or sample number of first sample in frame;
  83372. * use the \a number_type value to determine which to use. */
  83373. FLAC__uint8 crc;
  83374. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  83375. * of the raw frame header bytes, meaning everything before the CRC byte
  83376. * including the sync code.
  83377. */
  83378. } FLAC__FrameHeader;
  83379. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  83380. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  83381. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  83382. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  83383. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  83384. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  83385. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  83386. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  83387. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  83388. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  83389. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  83390. */
  83391. typedef struct {
  83392. FLAC__uint16 crc;
  83393. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  83394. * 0) of the bytes before the crc, back to and including the frame header
  83395. * sync code.
  83396. */
  83397. } FLAC__FrameFooter;
  83398. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  83399. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  83400. */
  83401. typedef struct {
  83402. FLAC__FrameHeader header;
  83403. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  83404. FLAC__FrameFooter footer;
  83405. } FLAC__Frame;
  83406. /*****************************************************************************/
  83407. /*****************************************************************************
  83408. *
  83409. * Meta-data structures
  83410. *
  83411. *****************************************************************************/
  83412. /** An enumeration of the available metadata block types. */
  83413. typedef enum {
  83414. FLAC__METADATA_TYPE_STREAMINFO = 0,
  83415. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  83416. FLAC__METADATA_TYPE_PADDING = 1,
  83417. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  83418. FLAC__METADATA_TYPE_APPLICATION = 2,
  83419. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  83420. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  83421. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  83422. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  83423. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  83424. FLAC__METADATA_TYPE_CUESHEET = 5,
  83425. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  83426. FLAC__METADATA_TYPE_PICTURE = 6,
  83427. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  83428. FLAC__METADATA_TYPE_UNDEFINED = 7
  83429. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  83430. } FLAC__MetadataType;
  83431. /** Maps a FLAC__MetadataType to a C string.
  83432. *
  83433. * Using a FLAC__MetadataType as the index to this array will
  83434. * give the string equivalent. The contents should not be modified.
  83435. */
  83436. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  83437. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  83438. */
  83439. typedef struct {
  83440. unsigned min_blocksize, max_blocksize;
  83441. unsigned min_framesize, max_framesize;
  83442. unsigned sample_rate;
  83443. unsigned channels;
  83444. unsigned bits_per_sample;
  83445. FLAC__uint64 total_samples;
  83446. FLAC__byte md5sum[16];
  83447. } FLAC__StreamMetadata_StreamInfo;
  83448. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  83449. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  83450. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  83451. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  83452. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  83453. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  83454. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  83455. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  83456. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  83457. /** The total stream length of the STREAMINFO block in bytes. */
  83458. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  83459. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  83460. */
  83461. typedef struct {
  83462. int dummy;
  83463. /**< Conceptually this is an empty struct since we don't store the
  83464. * padding bytes. Empty structs are not allowed by some C compilers,
  83465. * hence the dummy.
  83466. */
  83467. } FLAC__StreamMetadata_Padding;
  83468. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  83469. */
  83470. typedef struct {
  83471. FLAC__byte id[4];
  83472. FLAC__byte *data;
  83473. } FLAC__StreamMetadata_Application;
  83474. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  83475. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  83476. */
  83477. typedef struct {
  83478. FLAC__uint64 sample_number;
  83479. /**< The sample number of the target frame. */
  83480. FLAC__uint64 stream_offset;
  83481. /**< The offset, in bytes, of the target frame with respect to
  83482. * beginning of the first frame. */
  83483. unsigned frame_samples;
  83484. /**< The number of samples in the target frame. */
  83485. } FLAC__StreamMetadata_SeekPoint;
  83486. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  83487. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  83488. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  83489. /** The total stream length of a seek point in bytes. */
  83490. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  83491. /** The value used in the \a sample_number field of
  83492. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  83493. * point (== 0xffffffffffffffff).
  83494. */
  83495. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  83496. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  83497. *
  83498. * \note From the format specification:
  83499. * - The seek points must be sorted by ascending sample number.
  83500. * - Each seek point's sample number must be the first sample of the
  83501. * target frame.
  83502. * - Each seek point's sample number must be unique within the table.
  83503. * - Existence of a SEEKTABLE block implies a correct setting of
  83504. * total_samples in the stream_info block.
  83505. * - Behavior is undefined when more than one SEEKTABLE block is
  83506. * present in a stream.
  83507. */
  83508. typedef struct {
  83509. unsigned num_points;
  83510. FLAC__StreamMetadata_SeekPoint *points;
  83511. } FLAC__StreamMetadata_SeekTable;
  83512. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  83513. *
  83514. * For convenience, the APIs maintain a trailing NUL character at the end of
  83515. * \a entry which is not counted toward \a length, i.e.
  83516. * \code strlen(entry) == length \endcode
  83517. */
  83518. typedef struct {
  83519. FLAC__uint32 length;
  83520. FLAC__byte *entry;
  83521. } FLAC__StreamMetadata_VorbisComment_Entry;
  83522. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  83523. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  83524. */
  83525. typedef struct {
  83526. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  83527. FLAC__uint32 num_comments;
  83528. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  83529. } FLAC__StreamMetadata_VorbisComment;
  83530. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  83531. /** FLAC CUESHEET track index structure. (See the
  83532. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  83533. * the full description of each field.)
  83534. */
  83535. typedef struct {
  83536. FLAC__uint64 offset;
  83537. /**< Offset in samples, relative to the track offset, of the index
  83538. * point.
  83539. */
  83540. FLAC__byte number;
  83541. /**< The index point number. */
  83542. } FLAC__StreamMetadata_CueSheet_Index;
  83543. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  83544. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  83545. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  83546. /** FLAC CUESHEET track structure. (See the
  83547. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  83548. * the full description of each field.)
  83549. */
  83550. typedef struct {
  83551. FLAC__uint64 offset;
  83552. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  83553. FLAC__byte number;
  83554. /**< The track number. */
  83555. char isrc[13];
  83556. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  83557. unsigned type:1;
  83558. /**< The track type: 0 for audio, 1 for non-audio. */
  83559. unsigned pre_emphasis:1;
  83560. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  83561. FLAC__byte num_indices;
  83562. /**< The number of track index points. */
  83563. FLAC__StreamMetadata_CueSheet_Index *indices;
  83564. /**< NULL if num_indices == 0, else pointer to array of index points. */
  83565. } FLAC__StreamMetadata_CueSheet_Track;
  83566. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  83567. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  83568. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  83569. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  83570. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  83571. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  83572. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  83573. /** FLAC CUESHEET structure. (See the
  83574. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  83575. * for the full description of each field.)
  83576. */
  83577. typedef struct {
  83578. char media_catalog_number[129];
  83579. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  83580. * general, the media catalog number may be 0 to 128 bytes long; any
  83581. * unused characters should be right-padded with NUL characters.
  83582. */
  83583. FLAC__uint64 lead_in;
  83584. /**< The number of lead-in samples. */
  83585. FLAC__bool is_cd;
  83586. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  83587. unsigned num_tracks;
  83588. /**< The number of tracks. */
  83589. FLAC__StreamMetadata_CueSheet_Track *tracks;
  83590. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  83591. } FLAC__StreamMetadata_CueSheet;
  83592. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  83593. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  83594. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  83595. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  83596. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  83597. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  83598. typedef enum {
  83599. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  83600. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  83601. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  83602. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  83603. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  83604. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  83605. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  83606. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  83607. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  83608. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  83609. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  83610. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  83611. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  83612. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  83613. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  83614. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  83615. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  83616. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  83617. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  83618. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  83619. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  83620. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  83621. } FLAC__StreamMetadata_Picture_Type;
  83622. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  83623. *
  83624. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  83625. * will give the string equivalent. The contents should not be
  83626. * modified.
  83627. */
  83628. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  83629. /** FLAC PICTURE structure. (See the
  83630. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  83631. * for the full description of each field.)
  83632. */
  83633. typedef struct {
  83634. FLAC__StreamMetadata_Picture_Type type;
  83635. /**< The kind of picture stored. */
  83636. char *mime_type;
  83637. /**< Picture data's MIME type, in ASCII printable characters
  83638. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  83639. * use picture data of MIME type \c image/jpeg or \c image/png. A
  83640. * MIME type of '-->' is also allowed, in which case the picture
  83641. * data should be a complete URL. In file storage, the MIME type is
  83642. * stored as a 32-bit length followed by the ASCII string with no NUL
  83643. * terminator, but is converted to a plain C string in this structure
  83644. * for convenience.
  83645. */
  83646. FLAC__byte *description;
  83647. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  83648. * the description is stored as a 32-bit length followed by the UTF-8
  83649. * string with no NUL terminator, but is converted to a plain C string
  83650. * in this structure for convenience.
  83651. */
  83652. FLAC__uint32 width;
  83653. /**< Picture's width in pixels. */
  83654. FLAC__uint32 height;
  83655. /**< Picture's height in pixels. */
  83656. FLAC__uint32 depth;
  83657. /**< Picture's color depth in bits-per-pixel. */
  83658. FLAC__uint32 colors;
  83659. /**< For indexed palettes (like GIF), picture's number of colors (the
  83660. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  83661. */
  83662. FLAC__uint32 data_length;
  83663. /**< Length of binary picture data in bytes. */
  83664. FLAC__byte *data;
  83665. /**< Binary picture data. */
  83666. } FLAC__StreamMetadata_Picture;
  83667. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  83668. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  83669. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  83670. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  83671. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  83672. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  83673. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  83674. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  83675. /** Structure that is used when a metadata block of unknown type is loaded.
  83676. * The contents are opaque. The structure is used only internally to
  83677. * correctly handle unknown metadata.
  83678. */
  83679. typedef struct {
  83680. FLAC__byte *data;
  83681. } FLAC__StreamMetadata_Unknown;
  83682. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  83683. */
  83684. typedef struct {
  83685. FLAC__MetadataType type;
  83686. /**< The type of the metadata block; used determine which member of the
  83687. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  83688. * then \a data.unknown must be used. */
  83689. FLAC__bool is_last;
  83690. /**< \c true if this metadata block is the last, else \a false */
  83691. unsigned length;
  83692. /**< Length, in bytes, of the block data as it appears in the stream. */
  83693. union {
  83694. FLAC__StreamMetadata_StreamInfo stream_info;
  83695. FLAC__StreamMetadata_Padding padding;
  83696. FLAC__StreamMetadata_Application application;
  83697. FLAC__StreamMetadata_SeekTable seek_table;
  83698. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  83699. FLAC__StreamMetadata_CueSheet cue_sheet;
  83700. FLAC__StreamMetadata_Picture picture;
  83701. FLAC__StreamMetadata_Unknown unknown;
  83702. } data;
  83703. /**< Polymorphic block data; use the \a type value to determine which
  83704. * to use. */
  83705. } FLAC__StreamMetadata;
  83706. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  83707. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  83708. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  83709. /** The total stream length of a metadata block header in bytes. */
  83710. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  83711. /*****************************************************************************/
  83712. /*****************************************************************************
  83713. *
  83714. * Utility functions
  83715. *
  83716. *****************************************************************************/
  83717. /** Tests that a sample rate is valid for FLAC.
  83718. *
  83719. * \param sample_rate The sample rate to test for compliance.
  83720. * \retval FLAC__bool
  83721. * \c true if the given sample rate conforms to the specification, else
  83722. * \c false.
  83723. */
  83724. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  83725. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  83726. * for valid sample rates are slightly more complex since the rate has to
  83727. * be expressible completely in the frame header.
  83728. *
  83729. * \param sample_rate The sample rate to test for compliance.
  83730. * \retval FLAC__bool
  83731. * \c true if the given sample rate conforms to the specification for the
  83732. * subset, else \c false.
  83733. */
  83734. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  83735. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  83736. * comment specification.
  83737. *
  83738. * Vorbis comment names must be composed only of characters from
  83739. * [0x20-0x3C,0x3E-0x7D].
  83740. *
  83741. * \param name A NUL-terminated string to be checked.
  83742. * \assert
  83743. * \code name != NULL \endcode
  83744. * \retval FLAC__bool
  83745. * \c false if entry name is illegal, else \c true.
  83746. */
  83747. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  83748. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  83749. * comment specification.
  83750. *
  83751. * Vorbis comment values must be valid UTF-8 sequences.
  83752. *
  83753. * \param value A string to be checked.
  83754. * \param length A the length of \a value in bytes. May be
  83755. * \c (unsigned)(-1) to indicate that \a value is a plain
  83756. * UTF-8 NUL-terminated string.
  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_value_is_legal(const FLAC__byte *value, unsigned length);
  83763. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  83764. * comment specification.
  83765. *
  83766. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  83767. * 'value' must be legal according to
  83768. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  83769. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  83770. *
  83771. * \param entry An entry to be checked.
  83772. * \param length The length of \a entry in bytes.
  83773. * \assert
  83774. * \code value != NULL \endcode
  83775. * \retval FLAC__bool
  83776. * \c false if entry name is illegal, else \c true.
  83777. */
  83778. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  83779. /** Check a seek table to see if it conforms to the FLAC specification.
  83780. * See the format specification for limits on the contents of the
  83781. * seek table.
  83782. *
  83783. * \param seek_table A pointer to a seek table to be checked.
  83784. * \assert
  83785. * \code seek_table != NULL \endcode
  83786. * \retval FLAC__bool
  83787. * \c false if seek table is illegal, else \c true.
  83788. */
  83789. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  83790. /** Sort a seek table's seek points according to the format specification.
  83791. * This includes a "unique-ification" step to remove duplicates, i.e.
  83792. * seek points with identical \a sample_number values. Duplicate seek
  83793. * points are converted into placeholder points and sorted to the end of
  83794. * the table.
  83795. *
  83796. * \param seek_table A pointer to a seek table to be sorted.
  83797. * \assert
  83798. * \code seek_table != NULL \endcode
  83799. * \retval unsigned
  83800. * The number of duplicate seek points converted into placeholders.
  83801. */
  83802. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  83803. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83804. * See the format specification for limits on the contents of the
  83805. * cue sheet.
  83806. *
  83807. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  83808. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83809. * stringent requirements for a CD-DA (audio) disc.
  83810. * \param violation Address of a pointer to a string. If there is a
  83811. * violation, a pointer to a string explanation of the
  83812. * violation will be returned here. \a violation may be
  83813. * \c NULL if you don't need the returned string. Do not
  83814. * free the returned string; it will always point to static
  83815. * data.
  83816. * \assert
  83817. * \code cue_sheet != NULL \endcode
  83818. * \retval FLAC__bool
  83819. * \c false if cue sheet is illegal, else \c true.
  83820. */
  83821. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  83822. /** Check picture data to see if it conforms to the FLAC specification.
  83823. * See the format specification for limits on the contents of the
  83824. * PICTURE block.
  83825. *
  83826. * \param picture A pointer to existing picture data to be checked.
  83827. * \param violation Address of a pointer to a string. If there is a
  83828. * violation, a pointer to a string explanation of the
  83829. * violation will be returned here. \a violation may be
  83830. * \c NULL if you don't need the returned string. Do not
  83831. * free the returned string; it will always point to static
  83832. * data.
  83833. * \assert
  83834. * \code picture != NULL \endcode
  83835. * \retval FLAC__bool
  83836. * \c false if picture data is illegal, else \c true.
  83837. */
  83838. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  83839. /* \} */
  83840. #ifdef __cplusplus
  83841. }
  83842. #endif
  83843. #endif
  83844. /*** End of inlined file: format.h ***/
  83845. /*** Start of inlined file: metadata.h ***/
  83846. #ifndef FLAC__METADATA_H
  83847. #define FLAC__METADATA_H
  83848. #include <sys/types.h> /* for off_t */
  83849. /* --------------------------------------------------------------------
  83850. (For an example of how all these routines are used, see the source
  83851. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  83852. metaflac in src/metaflac/)
  83853. ------------------------------------------------------------------*/
  83854. /** \file include/FLAC/metadata.h
  83855. *
  83856. * \brief
  83857. * This module provides functions for creating and manipulating FLAC
  83858. * metadata blocks in memory, and three progressively more powerful
  83859. * interfaces for traversing and editing metadata in FLAC files.
  83860. *
  83861. * See the detailed documentation for each interface in the
  83862. * \link flac_metadata metadata \endlink module.
  83863. */
  83864. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  83865. * \ingroup flac
  83866. *
  83867. * \brief
  83868. * This module provides functions for creating and manipulating FLAC
  83869. * metadata blocks in memory, and three progressively more powerful
  83870. * interfaces for traversing and editing metadata in native FLAC files.
  83871. * Note that currently only the Chain interface (level 2) supports Ogg
  83872. * FLAC files, and it is read-only i.e. no writing back changed
  83873. * metadata to file.
  83874. *
  83875. * There are three metadata interfaces of increasing complexity:
  83876. *
  83877. * Level 0:
  83878. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  83879. * PICTURE blocks.
  83880. *
  83881. * Level 1:
  83882. * Read-write access to all metadata blocks. This level is write-
  83883. * efficient in most cases (more on this below), and uses less memory
  83884. * than level 2.
  83885. *
  83886. * Level 2:
  83887. * Read-write access to all metadata blocks. This level is write-
  83888. * efficient in all cases, but uses more memory since all metadata for
  83889. * the whole file is read into memory and manipulated before writing
  83890. * out again.
  83891. *
  83892. * What do we mean by efficient? Since FLAC metadata appears at the
  83893. * beginning of the file, when writing metadata back to a FLAC file
  83894. * it is possible to grow or shrink the metadata such that the entire
  83895. * file must be rewritten. However, if the size remains the same during
  83896. * changes or PADDING blocks are utilized, only the metadata needs to be
  83897. * overwritten, which is much faster.
  83898. *
  83899. * Efficient means the whole file is rewritten at most one time, and only
  83900. * when necessary. Level 1 is not efficient only in the case that you
  83901. * cause more than one metadata block to grow or shrink beyond what can
  83902. * be accomodated by padding. In this case you should probably use level
  83903. * 2, which allows you to edit all the metadata for a file in memory and
  83904. * write it out all at once.
  83905. *
  83906. * All levels know how to skip over and not disturb an ID3v2 tag at the
  83907. * front of the file.
  83908. *
  83909. * All levels access files via their filenames. In addition, level 2
  83910. * has additional alternative read and write functions that take an I/O
  83911. * handle and callbacks, for situations where access by filename is not
  83912. * possible.
  83913. *
  83914. * In addition to the three interfaces, this module defines functions for
  83915. * creating and manipulating various metadata objects in memory. As we see
  83916. * from the Format module, FLAC metadata blocks in memory are very primitive
  83917. * structures for storing information in an efficient way. Reading
  83918. * information from the structures is easy but creating or modifying them
  83919. * directly is more complex. The metadata object routines here facilitate
  83920. * this by taking care of the consistency and memory management drudgery.
  83921. *
  83922. * Unless you will be using the level 1 or 2 interfaces to modify existing
  83923. * metadata however, you will not probably not need these.
  83924. *
  83925. * From a dependency standpoint, none of the encoders or decoders require
  83926. * the metadata module. This is so that embedded users can strip out the
  83927. * metadata module from libFLAC to reduce the size and complexity.
  83928. */
  83929. #ifdef __cplusplus
  83930. extern "C" {
  83931. #endif
  83932. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  83933. * \ingroup flac_metadata
  83934. *
  83935. * \brief
  83936. * The level 0 interface consists of individual routines to read the
  83937. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  83938. * only a filename.
  83939. *
  83940. * They try to skip any ID3v2 tag at the head of the file.
  83941. *
  83942. * \{
  83943. */
  83944. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  83945. * will try to skip any ID3v2 tag at the head of the file.
  83946. *
  83947. * \param filename The path to the FLAC file to read.
  83948. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  83949. * FLAC__StreamMetadata is a simple structure with no
  83950. * memory allocation involved, you pass the address of
  83951. * an existing structure. It need not be initialized.
  83952. * \assert
  83953. * \code filename != NULL \endcode
  83954. * \code streaminfo != NULL \endcode
  83955. * \retval FLAC__bool
  83956. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  83957. * \c false if there was a memory allocation error, a file decoder error,
  83958. * or the file contained no STREAMINFO block. (A memory allocation error
  83959. * is possible because this function must set up a file decoder.)
  83960. */
  83961. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  83962. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  83963. * function will try to skip any ID3v2 tag at the head of the file.
  83964. *
  83965. * \param filename The path to the FLAC file to read.
  83966. * \param tags The address where the returned pointer will be
  83967. * stored. The \a tags object must be deleted by
  83968. * the caller using FLAC__metadata_object_delete().
  83969. * \assert
  83970. * \code filename != NULL \endcode
  83971. * \code tags != NULL \endcode
  83972. * \retval FLAC__bool
  83973. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  83974. * and \a *tags will be set to the address of the metadata structure.
  83975. * Returns \c false if there was a memory allocation error, a file
  83976. * decoder error, or the file contained no VORBIS_COMMENT block, and
  83977. * \a *tags will be set to \c NULL.
  83978. */
  83979. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  83980. /** Read the CUESHEET metadata block of the given FLAC file. This
  83981. * function will try to skip any ID3v2 tag at the head of the file.
  83982. *
  83983. * \param filename The path to the FLAC file to read.
  83984. * \param cuesheet The address where the returned pointer will be
  83985. * stored. The \a cuesheet object must be deleted by
  83986. * the caller using FLAC__metadata_object_delete().
  83987. * \assert
  83988. * \code filename != NULL \endcode
  83989. * \code cuesheet != NULL \endcode
  83990. * \retval FLAC__bool
  83991. * \c true if a valid CUESHEET block was read from \a filename,
  83992. * and \a *cuesheet will be set to the address of the metadata
  83993. * structure. Returns \c false if there was a memory allocation
  83994. * error, a file decoder error, or the file contained no CUESHEET
  83995. * block, and \a *cuesheet will be set to \c NULL.
  83996. */
  83997. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  83998. /** Read a PICTURE metadata block of the given FLAC file. This
  83999. * function will try to skip any ID3v2 tag at the head of the file.
  84000. * Since there can be more than one PICTURE block in a file, this
  84001. * function takes a number of parameters that act as constraints to
  84002. * the search. The PICTURE block with the largest area matching all
  84003. * the constraints will be returned, or \a *picture will be set to
  84004. * \c NULL if there was no such block.
  84005. *
  84006. * \param filename The path to the FLAC file to read.
  84007. * \param picture The address where the returned pointer will be
  84008. * stored. The \a picture object must be deleted by
  84009. * the caller using FLAC__metadata_object_delete().
  84010. * \param type The desired picture type. Use \c -1 to mean
  84011. * "any type".
  84012. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  84013. * string will be matched exactly. Use \c NULL to
  84014. * mean "any MIME type".
  84015. * \param description The desired description. The string will be
  84016. * matched exactly. Use \c NULL to mean "any
  84017. * description".
  84018. * \param max_width The maximum width in pixels desired. Use
  84019. * \c (unsigned)(-1) to mean "any width".
  84020. * \param max_height The maximum height in pixels desired. Use
  84021. * \c (unsigned)(-1) to mean "any height".
  84022. * \param max_depth The maximum color depth in bits-per-pixel desired.
  84023. * Use \c (unsigned)(-1) to mean "any depth".
  84024. * \param max_colors The maximum number of colors desired. Use
  84025. * \c (unsigned)(-1) to mean "any number of colors".
  84026. * \assert
  84027. * \code filename != NULL \endcode
  84028. * \code picture != NULL \endcode
  84029. * \retval FLAC__bool
  84030. * \c true if a valid PICTURE block was read from \a filename,
  84031. * and \a *picture will be set to the address of the metadata
  84032. * structure. Returns \c false if there was a memory allocation
  84033. * error, a file decoder error, or the file contained no PICTURE
  84034. * block, and \a *picture will be set to \c NULL.
  84035. */
  84036. 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);
  84037. /* \} */
  84038. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  84039. * \ingroup flac_metadata
  84040. *
  84041. * \brief
  84042. * The level 1 interface provides read-write access to FLAC file metadata and
  84043. * operates directly on the FLAC file.
  84044. *
  84045. * The general usage of this interface is:
  84046. *
  84047. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  84048. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  84049. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  84050. * see if the file is writable, or only read access is allowed.
  84051. * - Use FLAC__metadata_simple_iterator_next() and
  84052. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  84053. * This is does not read the actual blocks themselves.
  84054. * FLAC__metadata_simple_iterator_next() is relatively fast.
  84055. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  84056. * forward from the front of the file.
  84057. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  84058. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  84059. * the current iterator position. The returned object is yours to modify
  84060. * and free.
  84061. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  84062. * back. You must have write permission to the original file. Make sure to
  84063. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  84064. * below.
  84065. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  84066. * Use the object creation functions from
  84067. * \link flac_metadata_object here \endlink to generate new objects.
  84068. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  84069. * currently referred to by the iterator, or replace it with padding.
  84070. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  84071. * finished.
  84072. *
  84073. * \note
  84074. * The FLAC file remains open the whole time between
  84075. * FLAC__metadata_simple_iterator_init() and
  84076. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  84077. * the file during this time.
  84078. *
  84079. * \note
  84080. * Do not modify the \a is_last, \a length, or \a type fields of returned
  84081. * FLAC__StreamMetadata objects. These are managed automatically.
  84082. *
  84083. * \note
  84084. * If any of the modification functions
  84085. * (FLAC__metadata_simple_iterator_set_block(),
  84086. * FLAC__metadata_simple_iterator_delete_block(),
  84087. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  84088. * you should delete the iterator as it may no longer be valid.
  84089. *
  84090. * \{
  84091. */
  84092. struct FLAC__Metadata_SimpleIterator;
  84093. /** The opaque structure definition for the level 1 iterator type.
  84094. * See the
  84095. * \link flac_metadata_level1 metadata level 1 module \endlink
  84096. * for a detailed description.
  84097. */
  84098. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  84099. /** Status type for FLAC__Metadata_SimpleIterator.
  84100. *
  84101. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  84102. */
  84103. typedef enum {
  84104. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  84105. /**< The iterator is in the normal OK state */
  84106. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  84107. /**< The data passed into a function violated the function's usage criteria */
  84108. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  84109. /**< The iterator could not open the target file */
  84110. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  84111. /**< The iterator could not find the FLAC signature at the start of the file */
  84112. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  84113. /**< The iterator tried to write to a file that was not writable */
  84114. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  84115. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  84116. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  84117. /**< The iterator encountered an error while reading the FLAC file */
  84118. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  84119. /**< The iterator encountered an error while seeking in the FLAC file */
  84120. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  84121. /**< The iterator encountered an error while writing the FLAC file */
  84122. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  84123. /**< The iterator encountered an error renaming the FLAC file */
  84124. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  84125. /**< The iterator encountered an error removing the temporary file */
  84126. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  84127. /**< Memory allocation failed */
  84128. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  84129. /**< The caller violated an assertion or an unexpected error occurred */
  84130. } FLAC__Metadata_SimpleIteratorStatus;
  84131. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  84132. *
  84133. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  84134. * will give the string equivalent. The contents should not be modified.
  84135. */
  84136. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  84137. /** Create a new iterator instance.
  84138. *
  84139. * \retval FLAC__Metadata_SimpleIterator*
  84140. * \c NULL if there was an error allocating memory, else the new instance.
  84141. */
  84142. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  84143. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84144. *
  84145. * \param iterator A pointer to an existing iterator.
  84146. * \assert
  84147. * \code iterator != NULL \endcode
  84148. */
  84149. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  84150. /** Get the current status of the iterator. Call this after a function
  84151. * returns \c false to get the reason for the error. Also resets the status
  84152. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  84153. *
  84154. * \param iterator A pointer to an existing iterator.
  84155. * \assert
  84156. * \code iterator != NULL \endcode
  84157. * \retval FLAC__Metadata_SimpleIteratorStatus
  84158. * The current status of the iterator.
  84159. */
  84160. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  84161. /** Initialize the iterator to point to the first metadata block in the
  84162. * given FLAC file.
  84163. *
  84164. * \param iterator A pointer to an existing iterator.
  84165. * \param filename The path to the FLAC file.
  84166. * \param read_only If \c true, the FLAC file will be opened
  84167. * in read-only mode; if \c false, the FLAC
  84168. * file will be opened for edit even if no
  84169. * edits are performed.
  84170. * \param preserve_file_stats If \c true, the owner and modification
  84171. * time will be preserved even if the FLAC
  84172. * file is written to.
  84173. * \assert
  84174. * \code iterator != NULL \endcode
  84175. * \code filename != NULL \endcode
  84176. * \retval FLAC__bool
  84177. * \c false if a memory allocation error occurs, the file can't be
  84178. * opened, or another error occurs, else \c true.
  84179. */
  84180. 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);
  84181. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  84182. * FLAC__metadata_simple_iterator_set_block() and
  84183. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  84184. *
  84185. * \param iterator A pointer to an existing iterator.
  84186. * \assert
  84187. * \code iterator != NULL \endcode
  84188. * \retval FLAC__bool
  84189. * See above.
  84190. */
  84191. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  84192. /** Moves the iterator forward one metadata block, returning \c false if
  84193. * already at the end.
  84194. *
  84195. * \param iterator A pointer to an existing initialized iterator.
  84196. * \assert
  84197. * \code iterator != NULL \endcode
  84198. * \a iterator has been successfully initialized with
  84199. * FLAC__metadata_simple_iterator_init()
  84200. * \retval FLAC__bool
  84201. * \c false if already at the last metadata block of the chain, else
  84202. * \c true.
  84203. */
  84204. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  84205. /** Moves the iterator backward one metadata block, returning \c false if
  84206. * already at the beginning.
  84207. *
  84208. * \param iterator A pointer to an existing initialized iterator.
  84209. * \assert
  84210. * \code iterator != NULL \endcode
  84211. * \a iterator has been successfully initialized with
  84212. * FLAC__metadata_simple_iterator_init()
  84213. * \retval FLAC__bool
  84214. * \c false if already at the first metadata block of the chain, else
  84215. * \c true.
  84216. */
  84217. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  84218. /** Returns a flag telling if the current metadata block is the last.
  84219. *
  84220. * \param iterator A pointer to an existing initialized iterator.
  84221. * \assert
  84222. * \code iterator != NULL \endcode
  84223. * \a iterator has been successfully initialized with
  84224. * FLAC__metadata_simple_iterator_init()
  84225. * \retval FLAC__bool
  84226. * \c true if the current metadata block is the last in the file,
  84227. * else \c false.
  84228. */
  84229. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  84230. /** Get the offset of the metadata block at the current position. This
  84231. * avoids reading the actual block data which can save time for large
  84232. * blocks.
  84233. *
  84234. * \param iterator A pointer to an existing initialized iterator.
  84235. * \assert
  84236. * \code iterator != NULL \endcode
  84237. * \a iterator has been successfully initialized with
  84238. * FLAC__metadata_simple_iterator_init()
  84239. * \retval off_t
  84240. * The offset of the metadata block at the current iterator position.
  84241. * This is the byte offset relative to the beginning of the file of
  84242. * the current metadata block's header.
  84243. */
  84244. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  84245. /** Get the type of the metadata block at the current position. This
  84246. * avoids reading the actual block data which can save time for large
  84247. * blocks.
  84248. *
  84249. * \param iterator A pointer to an existing initialized iterator.
  84250. * \assert
  84251. * \code iterator != NULL \endcode
  84252. * \a iterator has been successfully initialized with
  84253. * FLAC__metadata_simple_iterator_init()
  84254. * \retval FLAC__MetadataType
  84255. * The type of the metadata block at the current iterator position.
  84256. */
  84257. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  84258. /** Get the length of the metadata block at the current position. This
  84259. * avoids reading the actual block data which can save time for large
  84260. * blocks.
  84261. *
  84262. * \param iterator A pointer to an existing initialized iterator.
  84263. * \assert
  84264. * \code iterator != NULL \endcode
  84265. * \a iterator has been successfully initialized with
  84266. * FLAC__metadata_simple_iterator_init()
  84267. * \retval unsigned
  84268. * The length of the metadata block at the current iterator position.
  84269. * The is same length as that in the
  84270. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  84271. * i.e. the length of the metadata body that follows the header.
  84272. */
  84273. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  84274. /** Get the application ID of the \c APPLICATION block at the current
  84275. * position. This avoids reading the actual block data which can save
  84276. * time for large blocks.
  84277. *
  84278. * \param iterator A pointer to an existing initialized iterator.
  84279. * \param id A pointer to a buffer of at least \c 4 bytes where
  84280. * the ID will be stored.
  84281. * \assert
  84282. * \code iterator != NULL \endcode
  84283. * \code id != NULL \endcode
  84284. * \a iterator has been successfully initialized with
  84285. * FLAC__metadata_simple_iterator_init()
  84286. * \retval FLAC__bool
  84287. * \c true if the ID was successfully read, else \c false, in which
  84288. * case you should check FLAC__metadata_simple_iterator_status() to
  84289. * find out why. If the status is
  84290. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  84291. * current metadata block is not an \c APPLICATION block. Otherwise
  84292. * if the status is
  84293. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  84294. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  84295. * occurred and the iterator can no longer be used.
  84296. */
  84297. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  84298. /** Get the metadata block at the current position. You can modify the
  84299. * block but must use FLAC__metadata_simple_iterator_set_block() to
  84300. * write it back to the FLAC file.
  84301. *
  84302. * You must call FLAC__metadata_object_delete() on the returned object
  84303. * when you are finished with it.
  84304. *
  84305. * \param iterator A pointer to an existing initialized iterator.
  84306. * \assert
  84307. * \code iterator != NULL \endcode
  84308. * \a iterator has been successfully initialized with
  84309. * FLAC__metadata_simple_iterator_init()
  84310. * \retval FLAC__StreamMetadata*
  84311. * The current metadata block, or \c NULL if there was a memory
  84312. * allocation error.
  84313. */
  84314. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  84315. /** Write a block back to the FLAC file. This function tries to be
  84316. * as efficient as possible; how the block is actually written is
  84317. * shown by the following:
  84318. *
  84319. * Existing block is a STREAMINFO block and the new block is a
  84320. * STREAMINFO block: the new block is written in place. Make sure
  84321. * you know what you're doing when changing the values of a
  84322. * STREAMINFO block.
  84323. *
  84324. * Existing block is a STREAMINFO block and the new block is a
  84325. * not a STREAMINFO block: this is an error since the first block
  84326. * must be a STREAMINFO block. Returns \c false without altering the
  84327. * file.
  84328. *
  84329. * Existing block is not a STREAMINFO block and the new block is a
  84330. * STREAMINFO block: this is an error since there may be only one
  84331. * STREAMINFO block. Returns \c false without altering the file.
  84332. *
  84333. * Existing block and new block are the same length: the existing
  84334. * block will be replaced by the new block, written in place.
  84335. *
  84336. * Existing block is longer than new block: if use_padding is \c true,
  84337. * the existing block will be overwritten in place with the new
  84338. * block followed by a PADDING block, if possible, to make the total
  84339. * size the same as the existing block. Remember that a padding
  84340. * block requires at least four bytes so if the difference in size
  84341. * between the new block and existing block is less than that, the
  84342. * entire file will have to be rewritten, using the new block's
  84343. * exact size. If use_padding is \c false, the entire file will be
  84344. * rewritten, replacing the existing block by the new block.
  84345. *
  84346. * Existing block is shorter than new block: if use_padding is \c true,
  84347. * the function will try and expand the new block into the following
  84348. * PADDING block, if it exists and doing so won't shrink the PADDING
  84349. * block to less than 4 bytes. If there is no following PADDING
  84350. * block, or it will shrink to less than 4 bytes, or use_padding is
  84351. * \c false, the entire file is rewritten, replacing the existing block
  84352. * with the new block. Note that in this case any following PADDING
  84353. * block is preserved as is.
  84354. *
  84355. * After writing the block, the iterator will remain in the same
  84356. * place, i.e. pointing to the new block.
  84357. *
  84358. * \param iterator A pointer to an existing initialized iterator.
  84359. * \param block The block to set.
  84360. * \param use_padding See above.
  84361. * \assert
  84362. * \code iterator != NULL \endcode
  84363. * \a iterator has been successfully initialized with
  84364. * FLAC__metadata_simple_iterator_init()
  84365. * \code block != NULL \endcode
  84366. * \retval FLAC__bool
  84367. * \c true if successful, else \c false.
  84368. */
  84369. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  84370. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  84371. * except that instead of writing over an existing block, it appends
  84372. * a block after the existing block. \a use_padding is again used to
  84373. * tell the function to try an expand into following padding in an
  84374. * attempt to avoid rewriting the entire file.
  84375. *
  84376. * This function will fail and return \c false if given a STREAMINFO
  84377. * block.
  84378. *
  84379. * After writing the block, the iterator will be pointing to the
  84380. * new block.
  84381. *
  84382. * \param iterator A pointer to an existing initialized iterator.
  84383. * \param block The block to set.
  84384. * \param use_padding See above.
  84385. * \assert
  84386. * \code iterator != NULL \endcode
  84387. * \a iterator has been successfully initialized with
  84388. * FLAC__metadata_simple_iterator_init()
  84389. * \code block != NULL \endcode
  84390. * \retval FLAC__bool
  84391. * \c true if successful, else \c false.
  84392. */
  84393. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  84394. /** Deletes the block at the current position. This will cause the
  84395. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  84396. * in which case the block will be replaced by an equal-sized PADDING
  84397. * block. The iterator will be left pointing to the block before the
  84398. * one just deleted.
  84399. *
  84400. * You may not delete the STREAMINFO block.
  84401. *
  84402. * \param iterator A pointer to an existing initialized iterator.
  84403. * \param use_padding See above.
  84404. * \assert
  84405. * \code iterator != NULL \endcode
  84406. * \a iterator has been successfully initialized with
  84407. * FLAC__metadata_simple_iterator_init()
  84408. * \retval FLAC__bool
  84409. * \c true if successful, else \c false.
  84410. */
  84411. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  84412. /* \} */
  84413. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  84414. * \ingroup flac_metadata
  84415. *
  84416. * \brief
  84417. * The level 2 interface provides read-write access to FLAC file metadata;
  84418. * all metadata is read into memory, operated on in memory, and then written
  84419. * to file, which is more efficient than level 1 when editing multiple blocks.
  84420. *
  84421. * Currently Ogg FLAC is supported for read only, via
  84422. * FLAC__metadata_chain_read_ogg() but a subsequent
  84423. * FLAC__metadata_chain_write() will fail.
  84424. *
  84425. * The general usage of this interface is:
  84426. *
  84427. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  84428. * linked list of FLAC metadata blocks.
  84429. * - Read all metadata into the the chain from a FLAC file using
  84430. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  84431. * check the status.
  84432. * - Optionally, consolidate the padding using
  84433. * FLAC__metadata_chain_merge_padding() or
  84434. * FLAC__metadata_chain_sort_padding().
  84435. * - Create a new iterator using FLAC__metadata_iterator_new()
  84436. * - Initialize the iterator to point to the first element in the chain
  84437. * using FLAC__metadata_iterator_init()
  84438. * - Traverse the chain using FLAC__metadata_iterator_next and
  84439. * FLAC__metadata_iterator_prev().
  84440. * - Get a block for reading or modification using
  84441. * FLAC__metadata_iterator_get_block(). The pointer to the object
  84442. * inside the chain is returned, so the block is yours to modify.
  84443. * Changes will be reflected in the FLAC file when you write the
  84444. * chain. You can also add and delete blocks (see functions below).
  84445. * - When done, write out the chain using FLAC__metadata_chain_write().
  84446. * Make sure to read the whole comment to the function below.
  84447. * - Delete the chain using FLAC__metadata_chain_delete().
  84448. *
  84449. * \note
  84450. * Even though the FLAC file is not open while the chain is being
  84451. * manipulated, you must not alter the file externally during
  84452. * this time. The chain assumes the FLAC file will not change
  84453. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  84454. * and FLAC__metadata_chain_write().
  84455. *
  84456. * \note
  84457. * Do not modify the is_last, length, or type fields of returned
  84458. * FLAC__StreamMetadata objects. These are managed automatically.
  84459. *
  84460. * \note
  84461. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  84462. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  84463. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  84464. * become owned by the chain and they will be deleted when the chain is
  84465. * deleted.
  84466. *
  84467. * \{
  84468. */
  84469. struct FLAC__Metadata_Chain;
  84470. /** The opaque structure definition for the level 2 chain type.
  84471. */
  84472. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  84473. struct FLAC__Metadata_Iterator;
  84474. /** The opaque structure definition for the level 2 iterator type.
  84475. */
  84476. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  84477. typedef enum {
  84478. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  84479. /**< The chain is in the normal OK state */
  84480. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  84481. /**< The data passed into a function violated the function's usage criteria */
  84482. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  84483. /**< The chain could not open the target file */
  84484. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  84485. /**< The chain could not find the FLAC signature at the start of the file */
  84486. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  84487. /**< The chain tried to write to a file that was not writable */
  84488. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  84489. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  84490. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  84491. /**< The chain encountered an error while reading the FLAC file */
  84492. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  84493. /**< The chain encountered an error while seeking in the FLAC file */
  84494. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  84495. /**< The chain encountered an error while writing the FLAC file */
  84496. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  84497. /**< The chain encountered an error renaming the FLAC file */
  84498. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  84499. /**< The chain encountered an error removing the temporary file */
  84500. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  84501. /**< Memory allocation failed */
  84502. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  84503. /**< The caller violated an assertion or an unexpected error occurred */
  84504. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  84505. /**< One or more of the required callbacks was NULL */
  84506. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  84507. /**< FLAC__metadata_chain_write() was called on a chain read by
  84508. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84509. * or
  84510. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  84511. * was called on a chain read by
  84512. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84513. * Matching read/write methods must always be used. */
  84514. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  84515. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  84516. * chain write requires a tempfile; use
  84517. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  84518. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  84519. * called when the chain write does not require a tempfile; use
  84520. * FLAC__metadata_chain_write_with_callbacks() instead.
  84521. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  84522. * before writing via callbacks. */
  84523. } FLAC__Metadata_ChainStatus;
  84524. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  84525. *
  84526. * Using a FLAC__Metadata_ChainStatus as the index to this array
  84527. * will give the string equivalent. The contents should not be modified.
  84528. */
  84529. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  84530. /*********** FLAC__Metadata_Chain ***********/
  84531. /** Create a new chain instance.
  84532. *
  84533. * \retval FLAC__Metadata_Chain*
  84534. * \c NULL if there was an error allocating memory, else the new instance.
  84535. */
  84536. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  84537. /** Free a chain instance. Deletes the object pointed to by \a chain.
  84538. *
  84539. * \param chain A pointer to an existing chain.
  84540. * \assert
  84541. * \code chain != NULL \endcode
  84542. */
  84543. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  84544. /** Get the current status of the chain. Call this after a function
  84545. * returns \c false to get the reason for the error. Also resets the
  84546. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  84547. *
  84548. * \param chain A pointer to an existing chain.
  84549. * \assert
  84550. * \code chain != NULL \endcode
  84551. * \retval FLAC__Metadata_ChainStatus
  84552. * The current status of the chain.
  84553. */
  84554. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  84555. /** Read all metadata from a FLAC file into the chain.
  84556. *
  84557. * \param chain A pointer to an existing chain.
  84558. * \param filename The path to the 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(FLAC__Metadata_Chain *chain, const char *filename);
  84568. /** Read all metadata from an Ogg FLAC file into the chain.
  84569. *
  84570. * \note Ogg FLAC metadata data writing is not supported yet and
  84571. * FLAC__metadata_chain_write() will fail.
  84572. *
  84573. * \param chain A pointer to an existing chain.
  84574. * \param filename The path to the Ogg FLAC file to read.
  84575. * \assert
  84576. * \code chain != NULL \endcode
  84577. * \code filename != NULL \endcode
  84578. * \retval FLAC__bool
  84579. * \c true if a valid list of metadata blocks was read from
  84580. * \a filename, else \c false. On failure, check the status with
  84581. * FLAC__metadata_chain_status().
  84582. */
  84583. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  84584. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  84585. *
  84586. * The \a handle need only be open for reading, but must be seekable.
  84587. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84588. * for Windows).
  84589. *
  84590. * \param chain A pointer to an existing chain.
  84591. * \param handle The I/O handle of the FLAC stream to read. The
  84592. * handle will NOT be closed after the metadata is read;
  84593. * that is the duty of the caller.
  84594. * \param callbacks
  84595. * A set of callbacks to use for I/O. The mandatory
  84596. * callbacks are \a read, \a seek, and \a tell.
  84597. * \assert
  84598. * \code chain != NULL \endcode
  84599. * \retval FLAC__bool
  84600. * \c true if a valid list of metadata blocks was read from
  84601. * \a handle, else \c false. On failure, check the status with
  84602. * FLAC__metadata_chain_status().
  84603. */
  84604. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84605. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  84606. *
  84607. * The \a handle need only be open for reading, but must be seekable.
  84608. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84609. * for Windows).
  84610. *
  84611. * \note Ogg FLAC metadata data writing is not supported yet and
  84612. * FLAC__metadata_chain_write() will fail.
  84613. *
  84614. * \param chain A pointer to an existing chain.
  84615. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  84616. * handle will NOT be closed after the metadata is read;
  84617. * that is the duty of the caller.
  84618. * \param callbacks
  84619. * A set of callbacks to use for I/O. The mandatory
  84620. * callbacks are \a read, \a seek, and \a tell.
  84621. * \assert
  84622. * \code chain != NULL \endcode
  84623. * \retval FLAC__bool
  84624. * \c true if a valid list of metadata blocks was read from
  84625. * \a handle, else \c false. On failure, check the status with
  84626. * FLAC__metadata_chain_status().
  84627. */
  84628. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84629. /** Checks if writing the given chain would require the use of a
  84630. * temporary file, or if it could be written in place.
  84631. *
  84632. * Under certain conditions, padding can be utilized so that writing
  84633. * edited metadata back to the FLAC file does not require rewriting the
  84634. * entire file. If rewriting is required, then a temporary workfile is
  84635. * required. When writing metadata using callbacks, you must check
  84636. * this function to know whether to call
  84637. * FLAC__metadata_chain_write_with_callbacks() or
  84638. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  84639. * writing with FLAC__metadata_chain_write(), the temporary file is
  84640. * handled internally.
  84641. *
  84642. * \param chain A pointer to an existing chain.
  84643. * \param use_padding
  84644. * Whether or not padding will be allowed to be used
  84645. * during the write. The value of \a use_padding given
  84646. * here must match the value later passed to
  84647. * FLAC__metadata_chain_write_with_callbacks() or
  84648. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  84649. * \assert
  84650. * \code chain != NULL \endcode
  84651. * \retval FLAC__bool
  84652. * \c true if writing the current chain would require a tempfile, or
  84653. * \c false if metadata can be written in place.
  84654. */
  84655. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  84656. /** Write all metadata out to the FLAC file. This function tries to be as
  84657. * efficient as possible; how the metadata is actually written is shown by
  84658. * the following:
  84659. *
  84660. * If the current chain is the same size as the existing metadata, the new
  84661. * data is written in place.
  84662. *
  84663. * If the current chain is longer than the existing metadata, and
  84664. * \a use_padding is \c true, and the last block is a PADDING block of
  84665. * sufficient length, the function will truncate the final padding block
  84666. * so that the overall size of the metadata is the same as the existing
  84667. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  84668. * the above conditions are met, the entire FLAC file must be rewritten.
  84669. * If you want to use padding this way it is a good idea to call
  84670. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  84671. * amount of padding to work with, unless you need to preserve ordering
  84672. * of the PADDING blocks for some reason.
  84673. *
  84674. * If the current chain is shorter than the existing metadata, and
  84675. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  84676. * is extended to make the overall size the same as the existing data. If
  84677. * \a use_padding is \c true and the last block is not a PADDING block, a new
  84678. * PADDING block is added to the end of the new data to make it the same
  84679. * size as the existing data (if possible, see the note to
  84680. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  84681. * and the new data is written in place. If none of the above apply or
  84682. * \a use_padding is \c false, the entire FLAC file is rewritten.
  84683. *
  84684. * If \a preserve_file_stats is \c true, the owner and modification time will
  84685. * be preserved even if the FLAC file is written.
  84686. *
  84687. * For this write function to be used, the chain must have been read with
  84688. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  84689. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  84690. *
  84691. * \param chain A pointer to an existing chain.
  84692. * \param use_padding See above.
  84693. * \param preserve_file_stats See above.
  84694. * \assert
  84695. * \code chain != NULL \endcode
  84696. * \retval FLAC__bool
  84697. * \c true if the write succeeded, else \c false. On failure,
  84698. * check the status with FLAC__metadata_chain_status().
  84699. */
  84700. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  84701. /** Write all metadata out to a FLAC stream via callbacks.
  84702. *
  84703. * (See FLAC__metadata_chain_write() for the details on how padding is
  84704. * used to write metadata in place if possible.)
  84705. *
  84706. * The \a handle must be open for updating and be seekable. The
  84707. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  84708. * for Windows).
  84709. *
  84710. * For this write function to be used, the chain must have been read with
  84711. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84712. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84713. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  84714. * \c false.
  84715. *
  84716. * \param chain A pointer to an existing chain.
  84717. * \param use_padding See FLAC__metadata_chain_write()
  84718. * \param handle The I/O handle of the FLAC stream to write. The
  84719. * handle will NOT be closed after the metadata is
  84720. * written; that is the duty of the caller.
  84721. * \param callbacks A set of callbacks to use for I/O. The mandatory
  84722. * callbacks are \a write and \a seek.
  84723. * \assert
  84724. * \code chain != NULL \endcode
  84725. * \retval FLAC__bool
  84726. * \c true if the write succeeded, else \c false. On failure,
  84727. * check the status with FLAC__metadata_chain_status().
  84728. */
  84729. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84730. /** Write all metadata out to a FLAC stream via callbacks.
  84731. *
  84732. * (See FLAC__metadata_chain_write() for the details on how padding is
  84733. * used to write metadata in place if possible.)
  84734. *
  84735. * This version of the write-with-callbacks function must be used when
  84736. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  84737. * this function, you must supply an I/O handle corresponding to the
  84738. * FLAC file to edit, and a temporary handle to which the new FLAC
  84739. * file will be written. It is the caller's job to move this temporary
  84740. * FLAC file on top of the original FLAC file to complete the metadata
  84741. * edit.
  84742. *
  84743. * The \a handle must be open for reading and be seekable. The
  84744. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84745. * for Windows).
  84746. *
  84747. * The \a temp_handle must be open for writing. The
  84748. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  84749. * for Windows). It should be an empty stream, or at least positioned
  84750. * at the start-of-file (in which case it is the caller's duty to
  84751. * truncate it on return).
  84752. *
  84753. * For this write function to be used, the chain must have been read with
  84754. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84755. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84756. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  84757. * \c true.
  84758. *
  84759. * \param chain A pointer to an existing chain.
  84760. * \param use_padding See FLAC__metadata_chain_write()
  84761. * \param handle The I/O handle of the original FLAC stream to read.
  84762. * The handle will NOT be closed after the metadata is
  84763. * written; that is the duty of the caller.
  84764. * \param callbacks A set of callbacks to use for I/O on \a handle.
  84765. * The mandatory callbacks are \a read, \a seek, and
  84766. * \a eof.
  84767. * \param temp_handle The I/O handle of the FLAC stream to write. The
  84768. * handle will NOT be closed after the metadata is
  84769. * written; that is the duty of the caller.
  84770. * \param temp_callbacks
  84771. * A set of callbacks to use for I/O on temp_handle.
  84772. * The only mandatory callback is \a write.
  84773. * \assert
  84774. * \code chain != NULL \endcode
  84775. * \retval FLAC__bool
  84776. * \c true if the write succeeded, else \c false. On failure,
  84777. * check the status with FLAC__metadata_chain_status().
  84778. */
  84779. 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);
  84780. /** Merge adjacent PADDING blocks into a single block.
  84781. *
  84782. * \note This function does not write to the FLAC file, it only
  84783. * modifies the chain.
  84784. *
  84785. * \warning Any iterator on the current chain will become invalid after this
  84786. * call. You should delete the iterator and get a new one.
  84787. *
  84788. * \param chain A pointer to an existing chain.
  84789. * \assert
  84790. * \code chain != NULL \endcode
  84791. */
  84792. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  84793. /** This function will move all PADDING blocks to the end on the metadata,
  84794. * then merge them into a single block.
  84795. *
  84796. * \note This function does not write to the FLAC file, it only
  84797. * modifies the chain.
  84798. *
  84799. * \warning Any iterator on the current chain will become invalid after this
  84800. * call. You should delete the iterator and get a new one.
  84801. *
  84802. * \param chain A pointer to an existing chain.
  84803. * \assert
  84804. * \code chain != NULL \endcode
  84805. */
  84806. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  84807. /*********** FLAC__Metadata_Iterator ***********/
  84808. /** Create a new iterator instance.
  84809. *
  84810. * \retval FLAC__Metadata_Iterator*
  84811. * \c NULL if there was an error allocating memory, else the new instance.
  84812. */
  84813. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  84814. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84815. *
  84816. * \param iterator A pointer to an existing iterator.
  84817. * \assert
  84818. * \code iterator != NULL \endcode
  84819. */
  84820. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  84821. /** Initialize the iterator to point to the first metadata block in the
  84822. * given chain.
  84823. *
  84824. * \param iterator A pointer to an existing iterator.
  84825. * \param chain A pointer to an existing and initialized (read) chain.
  84826. * \assert
  84827. * \code iterator != NULL \endcode
  84828. * \code chain != NULL \endcode
  84829. */
  84830. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  84831. /** Moves the iterator forward one metadata block, returning \c false if
  84832. * already at the end.
  84833. *
  84834. * \param iterator A pointer to an existing initialized iterator.
  84835. * \assert
  84836. * \code iterator != NULL \endcode
  84837. * \a iterator has been successfully initialized with
  84838. * FLAC__metadata_iterator_init()
  84839. * \retval FLAC__bool
  84840. * \c false if already at the last metadata block of the chain, else
  84841. * \c true.
  84842. */
  84843. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  84844. /** Moves the iterator backward one metadata block, returning \c false if
  84845. * already at the beginning.
  84846. *
  84847. * \param iterator A pointer to an existing initialized iterator.
  84848. * \assert
  84849. * \code iterator != NULL \endcode
  84850. * \a iterator has been successfully initialized with
  84851. * FLAC__metadata_iterator_init()
  84852. * \retval FLAC__bool
  84853. * \c false if already at the first metadata block of the chain, else
  84854. * \c true.
  84855. */
  84856. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  84857. /** Get the type of the metadata block at the current position.
  84858. *
  84859. * \param iterator A pointer to an existing initialized iterator.
  84860. * \assert
  84861. * \code iterator != NULL \endcode
  84862. * \a iterator has been successfully initialized with
  84863. * FLAC__metadata_iterator_init()
  84864. * \retval FLAC__MetadataType
  84865. * The type of the metadata block at the current iterator position.
  84866. */
  84867. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  84868. /** Get the metadata block at the current position. You can modify
  84869. * the block in place but must write the chain before the changes
  84870. * are reflected to the FLAC file. You do not need to call
  84871. * FLAC__metadata_iterator_set_block() to reflect the changes;
  84872. * the pointer returned by FLAC__metadata_iterator_get_block()
  84873. * points directly into the chain.
  84874. *
  84875. * \warning
  84876. * Do not call FLAC__metadata_object_delete() on the returned object;
  84877. * to delete a block use FLAC__metadata_iterator_delete_block().
  84878. *
  84879. * \param iterator A pointer to an existing initialized iterator.
  84880. * \assert
  84881. * \code iterator != NULL \endcode
  84882. * \a iterator has been successfully initialized with
  84883. * FLAC__metadata_iterator_init()
  84884. * \retval FLAC__StreamMetadata*
  84885. * The current metadata block.
  84886. */
  84887. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  84888. /** Set the metadata block at the current position, replacing the existing
  84889. * block. The new block passed in becomes owned by the chain and it will be
  84890. * deleted when the chain is deleted.
  84891. *
  84892. * \param iterator A pointer to an existing initialized iterator.
  84893. * \param block A pointer to a metadata block.
  84894. * \assert
  84895. * \code iterator != NULL \endcode
  84896. * \a iterator has been successfully initialized with
  84897. * FLAC__metadata_iterator_init()
  84898. * \code block != NULL \endcode
  84899. * \retval FLAC__bool
  84900. * \c false if the conditions in the above description are not met, or
  84901. * a memory allocation error occurs, otherwise \c true.
  84902. */
  84903. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84904. /** Removes the current block from the chain. If \a replace_with_padding is
  84905. * \c true, the block will instead be replaced with a padding block of equal
  84906. * size. You can not delete the STREAMINFO block. The iterator will be
  84907. * left pointing to the block before the one just "deleted", even if
  84908. * \a replace_with_padding is \c true.
  84909. *
  84910. * \param iterator A pointer to an existing initialized iterator.
  84911. * \param replace_with_padding See above.
  84912. * \assert
  84913. * \code iterator != NULL \endcode
  84914. * \a iterator has been successfully initialized with
  84915. * FLAC__metadata_iterator_init()
  84916. * \retval FLAC__bool
  84917. * \c false if the conditions in the above description are not met,
  84918. * otherwise \c true.
  84919. */
  84920. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  84921. /** Insert a new block before the current block. You cannot insert a block
  84922. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  84923. * as there can be only one, the one that already exists at the head when you
  84924. * read in a chain. The chain takes ownership of the new block and it will be
  84925. * deleted when the chain is deleted. The iterator will be left pointing to
  84926. * the new block.
  84927. *
  84928. * \param iterator A pointer to an existing initialized iterator.
  84929. * \param block A pointer to a metadata block to insert.
  84930. * \assert
  84931. * \code iterator != NULL \endcode
  84932. * \a iterator has been successfully initialized with
  84933. * FLAC__metadata_iterator_init()
  84934. * \retval FLAC__bool
  84935. * \c false if the conditions in the above description are not met, or
  84936. * a memory allocation error occurs, otherwise \c true.
  84937. */
  84938. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84939. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  84940. * block as there can be only one, the one that already exists at the head when
  84941. * you read in a chain. The chain takes ownership of the new block and it will
  84942. * be deleted when the chain is deleted. The iterator will be left pointing to
  84943. * the new block.
  84944. *
  84945. * \param iterator A pointer to an existing initialized iterator.
  84946. * \param block A pointer to a metadata block to insert.
  84947. * \assert
  84948. * \code iterator != NULL \endcode
  84949. * \a iterator has been successfully initialized with
  84950. * FLAC__metadata_iterator_init()
  84951. * \retval FLAC__bool
  84952. * \c false if the conditions in the above description are not met, or
  84953. * a memory allocation error occurs, otherwise \c true.
  84954. */
  84955. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84956. /* \} */
  84957. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  84958. * \ingroup flac_metadata
  84959. *
  84960. * \brief
  84961. * This module contains methods for manipulating FLAC metadata objects.
  84962. *
  84963. * Since many are variable length we have to be careful about the memory
  84964. * management. We decree that all pointers to data in the object are
  84965. * owned by the object and memory-managed by the object.
  84966. *
  84967. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  84968. * functions to create all instances. When using the
  84969. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  84970. * \a copy to \c true to have the function make it's own copy of the data, or
  84971. * to \c false to give the object ownership of your data. In the latter case
  84972. * your pointer must be freeable by free() and will be free()d when the object
  84973. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  84974. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  84975. * the length argument is 0 and the \a copy argument is \c false.
  84976. *
  84977. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  84978. * will return \c NULL in the case of a memory allocation error, otherwise a new
  84979. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  84980. * case of a memory allocation error.
  84981. *
  84982. * We don't have the convenience of C++ here, so note that the library relies
  84983. * on you to keep the types straight. In other words, if you pass, for
  84984. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  84985. * FLAC__metadata_object_application_set_data(), you will get an assertion
  84986. * failure.
  84987. *
  84988. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  84989. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  84990. * toward the length or stored in the stream, but it can make working with plain
  84991. * comments (those that don't contain embedded-NULs in the value) easier.
  84992. * Entries passed into these functions have trailing NULs added if missing, and
  84993. * returned entries are guaranteed to have a trailing NUL.
  84994. *
  84995. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  84996. * comment entry/name/value will first validate that it complies with the Vorbis
  84997. * comment specification and return false if it does not.
  84998. *
  84999. * There is no need to recalculate the length field on metadata blocks you
  85000. * have modified. They will be calculated automatically before they are
  85001. * written back to a file.
  85002. *
  85003. * \{
  85004. */
  85005. /** Create a new metadata object instance of the given type.
  85006. *
  85007. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  85008. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  85009. * the vendor string set (but zero comments).
  85010. *
  85011. * Do not pass in a value greater than or equal to
  85012. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  85013. * doing.
  85014. *
  85015. * \param type Type of object to create
  85016. * \retval FLAC__StreamMetadata*
  85017. * \c NULL if there was an error allocating memory or the type code is
  85018. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  85019. */
  85020. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  85021. /** Create a copy of an existing metadata object.
  85022. *
  85023. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  85024. * object is also copied. The caller takes ownership of the new block and
  85025. * is responsible for freeing it with FLAC__metadata_object_delete().
  85026. *
  85027. * \param object Pointer to object to copy.
  85028. * \assert
  85029. * \code object != NULL \endcode
  85030. * \retval FLAC__StreamMetadata*
  85031. * \c NULL if there was an error allocating memory, else the new instance.
  85032. */
  85033. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  85034. /** Free a metadata object. Deletes the object pointed to by \a object.
  85035. *
  85036. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  85037. * object is also deleted.
  85038. *
  85039. * \param object A pointer to an existing object.
  85040. * \assert
  85041. * \code object != NULL \endcode
  85042. */
  85043. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  85044. /** Compares two metadata objects.
  85045. *
  85046. * The compare is "deep", i.e. dynamically allocated data within the
  85047. * object is also compared.
  85048. *
  85049. * \param block1 A pointer to an existing object.
  85050. * \param block2 A pointer to an existing object.
  85051. * \assert
  85052. * \code block1 != NULL \endcode
  85053. * \code block2 != NULL \endcode
  85054. * \retval FLAC__bool
  85055. * \c true if objects are identical, else \c false.
  85056. */
  85057. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  85058. /** Sets the application data of an APPLICATION block.
  85059. *
  85060. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85061. * takes ownership of the pointer. The existing data will be freed if this
  85062. * function is successful, otherwise the original data will remain if \a copy
  85063. * is \c true and malloc() fails.
  85064. *
  85065. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85066. *
  85067. * \param object A pointer to an existing APPLICATION object.
  85068. * \param data A pointer to the data to set.
  85069. * \param length The length of \a data in bytes.
  85070. * \param copy See above.
  85071. * \assert
  85072. * \code object != NULL \endcode
  85073. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  85074. * \code (data != NULL && length > 0) ||
  85075. * (data == NULL && length == 0 && copy == false) \endcode
  85076. * \retval FLAC__bool
  85077. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85078. */
  85079. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  85080. /** Resize the seekpoint array.
  85081. *
  85082. * If the size shrinks, elements will truncated; if it grows, new placeholder
  85083. * points will be added to the end.
  85084. *
  85085. * \param object A pointer to an existing SEEKTABLE object.
  85086. * \param new_num_points The desired length of the array; may be \c 0.
  85087. * \assert
  85088. * \code object != NULL \endcode
  85089. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85090. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  85091. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  85092. * \retval FLAC__bool
  85093. * \c false if memory allocation error, else \c true.
  85094. */
  85095. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  85096. /** Set a seekpoint in a seektable.
  85097. *
  85098. * \param object A pointer to an existing SEEKTABLE object.
  85099. * \param point_num Index into seekpoint array to set.
  85100. * \param point The point to set.
  85101. * \assert
  85102. * \code object != NULL \endcode
  85103. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85104. * \code object->data.seek_table.num_points > point_num \endcode
  85105. */
  85106. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85107. /** Insert a seekpoint into a seektable.
  85108. *
  85109. * \param object A pointer to an existing SEEKTABLE object.
  85110. * \param point_num Index into seekpoint array to set.
  85111. * \param point The point to set.
  85112. * \assert
  85113. * \code object != NULL \endcode
  85114. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85115. * \code object->data.seek_table.num_points >= point_num \endcode
  85116. * \retval FLAC__bool
  85117. * \c false if memory allocation error, else \c true.
  85118. */
  85119. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85120. /** Delete a seekpoint from a seektable.
  85121. *
  85122. * \param object A pointer to an existing SEEKTABLE object.
  85123. * \param point_num Index into seekpoint array to set.
  85124. * \assert
  85125. * \code object != NULL \endcode
  85126. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85127. * \code object->data.seek_table.num_points > point_num \endcode
  85128. * \retval FLAC__bool
  85129. * \c false if memory allocation error, else \c true.
  85130. */
  85131. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  85132. /** Check a seektable to see if it conforms to the FLAC specification.
  85133. * See the format specification for limits on the contents of the
  85134. * seektable.
  85135. *
  85136. * \param object A pointer to an existing SEEKTABLE object.
  85137. * \assert
  85138. * \code object != NULL \endcode
  85139. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85140. * \retval FLAC__bool
  85141. * \c false if seek table is illegal, else \c true.
  85142. */
  85143. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  85144. /** Append a number of placeholder points 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 num The number of placeholder points to append.
  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_placeholders(FLAC__StreamMetadata *object, unsigned num);
  85160. /** Append a specific seek point template 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_number The sample number of the seek point template.
  85169. * \assert
  85170. * \code object != NULL \endcode
  85171. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85172. * \retval FLAC__bool
  85173. * \c false if memory allocation fails, else \c true.
  85174. */
  85175. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  85176. /** Append specific seek point templates to the end of a seek table.
  85177. *
  85178. * \note
  85179. * As with the other ..._seektable_template_... functions, you should
  85180. * call FLAC__metadata_object_seektable_template_sort() when finished
  85181. * to make the seek table legal.
  85182. *
  85183. * \param object A pointer to an existing SEEKTABLE object.
  85184. * \param sample_numbers An array of sample numbers for the seek points.
  85185. * \param num The number of seek point templates to append.
  85186. * \assert
  85187. * \code object != NULL \endcode
  85188. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85189. * \retval FLAC__bool
  85190. * \c false if memory allocation fails, else \c true.
  85191. */
  85192. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  85193. /** Append a set of evenly-spaced seek point templates to the end of a
  85194. * seek table.
  85195. *
  85196. * \note
  85197. * As with the other ..._seektable_template_... functions, you should
  85198. * call FLAC__metadata_object_seektable_template_sort() when finished
  85199. * to make the seek table legal.
  85200. *
  85201. * \param object A pointer to an existing SEEKTABLE object.
  85202. * \param num The number of placeholder points to append.
  85203. * \param total_samples The total number of samples to be encoded;
  85204. * the seekpoints will be spaced approximately
  85205. * \a total_samples / \a num samples apart.
  85206. * \assert
  85207. * \code object != NULL \endcode
  85208. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85209. * \code total_samples > 0 \endcode
  85210. * \retval FLAC__bool
  85211. * \c false if memory allocation fails, else \c true.
  85212. */
  85213. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  85214. /** Append a set of evenly-spaced seek point templates to the end of a
  85215. * seek table.
  85216. *
  85217. * \note
  85218. * As with the other ..._seektable_template_... functions, you should
  85219. * call FLAC__metadata_object_seektable_template_sort() when finished
  85220. * to make the seek table legal.
  85221. *
  85222. * \param object A pointer to an existing SEEKTABLE object.
  85223. * \param samples The number of samples apart to space the placeholder
  85224. * points. The first point will be at sample \c 0, the
  85225. * second at sample \a samples, then 2*\a samples, and
  85226. * so on. As long as \a samples and \a total_samples
  85227. * are greater than \c 0, there will always be at least
  85228. * one seekpoint at sample \c 0.
  85229. * \param total_samples The total number of samples to be encoded;
  85230. * the seekpoints will be spaced
  85231. * \a samples samples apart.
  85232. * \assert
  85233. * \code object != NULL \endcode
  85234. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85235. * \code samples > 0 \endcode
  85236. * \code total_samples > 0 \endcode
  85237. * \retval FLAC__bool
  85238. * \c false if memory allocation fails, else \c true.
  85239. */
  85240. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  85241. /** Sort a seek table's seek points according to the format specification,
  85242. * removing duplicates.
  85243. *
  85244. * \param object A pointer to a seek table to be sorted.
  85245. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  85246. * If \c true, duplicates are deleted and the seek table is
  85247. * shrunk appropriately; the number of placeholder points
  85248. * present in the seek table will be the same after the call
  85249. * as before.
  85250. * \assert
  85251. * \code object != NULL \endcode
  85252. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85253. * \retval FLAC__bool
  85254. * \c false if realloc() fails, else \c true.
  85255. */
  85256. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  85257. /** Sets the vendor string in a VORBIS_COMMENT block.
  85258. *
  85259. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85260. * one already.
  85261. *
  85262. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85263. * takes ownership of the \c entry.entry pointer.
  85264. *
  85265. * \note If this function returns \c false, the caller still owns the
  85266. * pointer.
  85267. *
  85268. * \param object A pointer to an existing VORBIS_COMMENT object.
  85269. * \param entry The entry to set the vendor string to.
  85270. * \param copy See above.
  85271. * \assert
  85272. * \code object != NULL \endcode
  85273. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85274. * \code (entry.entry != NULL && entry.length > 0) ||
  85275. * (entry.entry == NULL && entry.length == 0) \endcode
  85276. * \retval FLAC__bool
  85277. * \c false if memory allocation fails or \a entry does not comply with the
  85278. * Vorbis comment specification, else \c true.
  85279. */
  85280. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85281. /** Resize the comment array.
  85282. *
  85283. * If the size shrinks, elements will truncated; if it grows, new empty
  85284. * fields will be added to the end.
  85285. *
  85286. * \param object A pointer to an existing VORBIS_COMMENT object.
  85287. * \param new_num_comments The desired length of the array; may be \c 0.
  85288. * \assert
  85289. * \code object != NULL \endcode
  85290. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85291. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  85292. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  85293. * \retval FLAC__bool
  85294. * \c false if memory allocation fails, else \c true.
  85295. */
  85296. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  85297. /** Sets a comment in a VORBIS_COMMENT block.
  85298. *
  85299. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85300. * one already.
  85301. *
  85302. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85303. * takes ownership of the \c entry.entry pointer.
  85304. *
  85305. * \note If this function returns \c false, the caller still owns the
  85306. * pointer.
  85307. *
  85308. * \param object A pointer to an existing VORBIS_COMMENT object.
  85309. * \param comment_num Index into comment array to set.
  85310. * \param entry The entry to set the comment to.
  85311. * \param copy See above.
  85312. * \assert
  85313. * \code object != NULL \endcode
  85314. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85315. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  85316. * \code (entry.entry != NULL && entry.length > 0) ||
  85317. * (entry.entry == NULL && entry.length == 0) \endcode
  85318. * \retval FLAC__bool
  85319. * \c false if memory allocation fails or \a entry does not comply with the
  85320. * Vorbis comment specification, else \c true.
  85321. */
  85322. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85323. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  85324. *
  85325. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85326. * one already.
  85327. *
  85328. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85329. * takes ownership of the \c entry.entry pointer.
  85330. *
  85331. * \note If this function returns \c false, the caller still owns the
  85332. * pointer.
  85333. *
  85334. * \param object A pointer to an existing VORBIS_COMMENT object.
  85335. * \param comment_num The index at which to insert the comment. The comments
  85336. * at and after \a comment_num move right one position.
  85337. * To append a comment to the end, set \a comment_num to
  85338. * \c object->data.vorbis_comment.num_comments .
  85339. * \param entry The comment to insert.
  85340. * \param copy See above.
  85341. * \assert
  85342. * \code object != NULL \endcode
  85343. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85344. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  85345. * \code (entry.entry != NULL && entry.length > 0) ||
  85346. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85347. * \retval FLAC__bool
  85348. * \c false if memory allocation fails or \a entry does not comply with the
  85349. * Vorbis comment specification, else \c true.
  85350. */
  85351. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85352. /** Appends a comment to a VORBIS_COMMENT block.
  85353. *
  85354. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85355. * one already.
  85356. *
  85357. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85358. * takes ownership of the \c entry.entry pointer.
  85359. *
  85360. * \note If this function returns \c false, the caller still owns the
  85361. * pointer.
  85362. *
  85363. * \param object A pointer to an existing VORBIS_COMMENT object.
  85364. * \param entry The comment to insert.
  85365. * \param copy See above.
  85366. * \assert
  85367. * \code object != NULL \endcode
  85368. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85369. * \code (entry.entry != NULL && entry.length > 0) ||
  85370. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85371. * \retval FLAC__bool
  85372. * \c false if memory allocation fails or \a entry does not comply with the
  85373. * Vorbis comment specification, else \c true.
  85374. */
  85375. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85376. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  85377. *
  85378. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85379. * one already.
  85380. *
  85381. * Depending on the the value of \a all, either all or just the first comment
  85382. * whose field name(s) match the given entry's name will be replaced by the
  85383. * given entry. If no comments match, \a entry will simply be appended.
  85384. *
  85385. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85386. * takes ownership of the \c entry.entry pointer.
  85387. *
  85388. * \note If this function returns \c false, the caller still owns the
  85389. * pointer.
  85390. *
  85391. * \param object A pointer to an existing VORBIS_COMMENT object.
  85392. * \param entry The comment to insert.
  85393. * \param all If \c true, all comments whose field name matches
  85394. * \a entry's field name will be removed, and \a entry will
  85395. * be inserted at the position of the first matching
  85396. * comment. If \c false, only the first comment whose
  85397. * field name matches \a entry's field name will be
  85398. * replaced with \a entry.
  85399. * \param copy See above.
  85400. * \assert
  85401. * \code object != NULL \endcode
  85402. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85403. * \code (entry.entry != NULL && entry.length > 0) ||
  85404. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85405. * \retval FLAC__bool
  85406. * \c false if memory allocation fails or \a entry does not comply with the
  85407. * Vorbis comment specification, else \c true.
  85408. */
  85409. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  85410. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  85411. *
  85412. * \param object A pointer to an existing VORBIS_COMMENT object.
  85413. * \param comment_num The index of the comment to delete.
  85414. * \assert
  85415. * \code object != NULL \endcode
  85416. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85417. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  85418. * \retval FLAC__bool
  85419. * \c false if realloc() fails, else \c true.
  85420. */
  85421. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  85422. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  85423. *
  85424. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  85425. * memory and shall be owned by the caller. For convenience the entry will
  85426. * have a terminating NUL.
  85427. *
  85428. * \param entry A pointer to a Vorbis comment entry. The entry's
  85429. * \c entry pointer should not point to allocated
  85430. * memory as it will be overwritten.
  85431. * \param field_name The field name in ASCII, \c NUL terminated.
  85432. * \param field_value The field value in UTF-8, \c NUL terminated.
  85433. * \assert
  85434. * \code entry != NULL \endcode
  85435. * \code field_name != NULL \endcode
  85436. * \code field_value != NULL \endcode
  85437. * \retval FLAC__bool
  85438. * \c false if malloc() fails, or if \a field_name or \a field_value does
  85439. * not comply with the Vorbis comment specification, else \c true.
  85440. */
  85441. 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);
  85442. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  85443. *
  85444. * The returned pointers to name and value will be allocated by malloc()
  85445. * and shall be owned by the caller.
  85446. *
  85447. * \param entry An existing Vorbis comment entry.
  85448. * \param field_name The address of where the returned pointer to the
  85449. * field name will be stored.
  85450. * \param field_value The address of where the returned pointer to the
  85451. * field value will be stored.
  85452. * \assert
  85453. * \code (entry.entry != NULL && entry.length > 0) \endcode
  85454. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  85455. * \code field_name != NULL \endcode
  85456. * \code field_value != NULL \endcode
  85457. * \retval FLAC__bool
  85458. * \c false if memory allocation fails or \a entry does not comply with the
  85459. * Vorbis comment specification, else \c true.
  85460. */
  85461. 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);
  85462. /** Check if the given Vorbis comment entry's field name matches the given
  85463. * field name.
  85464. *
  85465. * \param entry An existing Vorbis comment entry.
  85466. * \param field_name The field name to check.
  85467. * \param field_name_length The length of \a field_name, not including the
  85468. * terminating \c NUL.
  85469. * \assert
  85470. * \code (entry.entry != NULL && entry.length > 0) \endcode
  85471. * \retval FLAC__bool
  85472. * \c true if the field names match, else \c false
  85473. */
  85474. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  85475. /** Find a Vorbis comment with the given field name.
  85476. *
  85477. * The search begins at entry number \a offset; use an offset of 0 to
  85478. * search from the beginning of the comment array.
  85479. *
  85480. * \param object A pointer to an existing VORBIS_COMMENT object.
  85481. * \param offset The offset into the comment array from where to start
  85482. * the search.
  85483. * \param field_name The field name of the comment to find.
  85484. * \assert
  85485. * \code object != NULL \endcode
  85486. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85487. * \code field_name != NULL \endcode
  85488. * \retval int
  85489. * The offset in the comment array of the first comment whose field
  85490. * name matches \a field_name, or \c -1 if no match was found.
  85491. */
  85492. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  85493. /** Remove first Vorbis comment matching the given field name.
  85494. *
  85495. * \param object A pointer to an existing VORBIS_COMMENT object.
  85496. * \param field_name The field name of comment to delete.
  85497. * \assert
  85498. * \code object != NULL \endcode
  85499. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85500. * \retval int
  85501. * \c -1 for memory allocation error, \c 0 for no matching entries,
  85502. * \c 1 for one matching entry deleted.
  85503. */
  85504. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  85505. /** Remove all Vorbis comments matching the given field name.
  85506. *
  85507. * \param object A pointer to an existing VORBIS_COMMENT object.
  85508. * \param field_name The field name of comments to delete.
  85509. * \assert
  85510. * \code object != NULL \endcode
  85511. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85512. * \retval int
  85513. * \c -1 for memory allocation error, \c 0 for no matching entries,
  85514. * else the number of matching entries deleted.
  85515. */
  85516. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  85517. /** Create a new CUESHEET track instance.
  85518. *
  85519. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  85520. *
  85521. * \retval FLAC__StreamMetadata_CueSheet_Track*
  85522. * \c NULL if there was an error allocating memory, else the new instance.
  85523. */
  85524. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  85525. /** Create a copy of an existing CUESHEET track object.
  85526. *
  85527. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  85528. * object is also copied. The caller takes ownership of the new object and
  85529. * is responsible for freeing it with
  85530. * FLAC__metadata_object_cuesheet_track_delete().
  85531. *
  85532. * \param object Pointer to object to copy.
  85533. * \assert
  85534. * \code object != NULL \endcode
  85535. * \retval FLAC__StreamMetadata_CueSheet_Track*
  85536. * \c NULL if there was an error allocating memory, else the new instance.
  85537. */
  85538. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  85539. /** Delete a CUESHEET track object
  85540. *
  85541. * \param object A pointer to an existing CUESHEET track object.
  85542. * \assert
  85543. * \code object != NULL \endcode
  85544. */
  85545. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  85546. /** Resize a track's index point array.
  85547. *
  85548. * If the size shrinks, elements will truncated; if it grows, new blank
  85549. * indices will be added to the end.
  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 new_num_indices The desired length of the array; may be \c 0.
  85555. * \assert
  85556. * \code object != NULL \endcode
  85557. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85558. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85559. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  85560. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  85561. * \retval FLAC__bool
  85562. * \c false if memory allocation error, else \c true.
  85563. */
  85564. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  85565. /** Insert an index point in a CUESHEET track at the given index.
  85566. *
  85567. * \param object A pointer to an existing CUESHEET object.
  85568. * \param track_num The index of the track to modify. NOTE: this is not
  85569. * necessarily the same as the track's \a number field.
  85570. * \param index_num The index into the track's index array at which to
  85571. * insert the index point. NOTE: this is not necessarily
  85572. * the same as the index point's \a number field. The
  85573. * indices at and after \a index_num move right one
  85574. * position. To append an index point to the end, set
  85575. * \a index_num to
  85576. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  85577. * \param index The index point to insert.
  85578. * \assert
  85579. * \code object != NULL \endcode
  85580. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85581. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85582. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  85583. * \retval FLAC__bool
  85584. * \c false if realloc() fails, else \c true.
  85585. */
  85586. 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);
  85587. /** Insert a blank index point in a CUESHEET track at the given index.
  85588. *
  85589. * A blank index point is one in which all field values are zero.
  85590. *
  85591. * \param object A pointer to an existing CUESHEET object.
  85592. * \param track_num The index of the track to modify. NOTE: this is not
  85593. * necessarily the same as the track's \a number field.
  85594. * \param index_num The index into the track's index array at which to
  85595. * insert the index point. NOTE: this is not necessarily
  85596. * the same as the index point's \a number field. The
  85597. * indices at and after \a index_num move right one
  85598. * position. To append an index point to the end, set
  85599. * \a index_num to
  85600. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  85601. * \assert
  85602. * \code object != NULL \endcode
  85603. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85604. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85605. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  85606. * \retval FLAC__bool
  85607. * \c false if realloc() fails, else \c true.
  85608. */
  85609. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  85610. /** Delete an index point in a CUESHEET track at the given index.
  85611. *
  85612. * \param object A pointer to an existing CUESHEET object.
  85613. * \param track_num The index into the track array of the track to
  85614. * modify. NOTE: this is not necessarily the same
  85615. * as the track's \a number field.
  85616. * \param index_num The index into the track's index array of the index
  85617. * to delete. NOTE: this is not necessarily the same
  85618. * as the index's \a number field.
  85619. * \assert
  85620. * \code object != NULL \endcode
  85621. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85622. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85623. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  85624. * \retval FLAC__bool
  85625. * \c false if realloc() fails, else \c true.
  85626. */
  85627. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  85628. /** Resize the track array.
  85629. *
  85630. * If the size shrinks, elements will truncated; if it grows, new blank
  85631. * tracks will be added to the end.
  85632. *
  85633. * \param object A pointer to an existing CUESHEET object.
  85634. * \param new_num_tracks The desired length of the array; may be \c 0.
  85635. * \assert
  85636. * \code object != NULL \endcode
  85637. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85638. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  85639. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  85640. * \retval FLAC__bool
  85641. * \c false if memory allocation error, else \c true.
  85642. */
  85643. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  85644. /** Sets a track in a CUESHEET block.
  85645. *
  85646. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  85647. * takes ownership of the \a track pointer.
  85648. *
  85649. * \param object A pointer to an existing CUESHEET object.
  85650. * \param track_num Index into track array to set. NOTE: this is not
  85651. * necessarily the same as the track's \a number field.
  85652. * \param track The track to set the track to. You may safely pass in
  85653. * a const pointer if \a copy is \c true.
  85654. * \param copy See above.
  85655. * \assert
  85656. * \code object != NULL \endcode
  85657. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85658. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  85659. * \code (track->indices != NULL && track->num_indices > 0) ||
  85660. * (track->indices == NULL && track->num_indices == 0)
  85661. * \retval FLAC__bool
  85662. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85663. */
  85664. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  85665. /** Insert a track in a CUESHEET block at the given index.
  85666. *
  85667. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  85668. * takes ownership of the \a track pointer.
  85669. *
  85670. * \param object A pointer to an existing CUESHEET object.
  85671. * \param track_num The index at which to insert the track. NOTE: this
  85672. * is not necessarily the same as the track's \a number
  85673. * field. The tracks at and after \a track_num move right
  85674. * one position. To append a track to the end, set
  85675. * \a track_num to \c object->data.cue_sheet.num_tracks .
  85676. * \param track The track to insert. You may safely pass in a const
  85677. * pointer if \a copy is \c true.
  85678. * \param copy See above.
  85679. * \assert
  85680. * \code object != NULL \endcode
  85681. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85682. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  85683. * \retval FLAC__bool
  85684. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85685. */
  85686. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  85687. /** Insert a blank track in a CUESHEET block at the given index.
  85688. *
  85689. * A blank track is one in which all field values are zero.
  85690. *
  85691. * \param object A pointer to an existing CUESHEET object.
  85692. * \param track_num The index at which to insert the track. NOTE: this
  85693. * is not necessarily the same as the track's \a number
  85694. * field. The tracks at and after \a track_num move right
  85695. * one position. To append a track to the end, set
  85696. * \a track_num to \c object->data.cue_sheet.num_tracks .
  85697. * \assert
  85698. * \code object != NULL \endcode
  85699. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85700. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  85701. * \retval FLAC__bool
  85702. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85703. */
  85704. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  85705. /** Delete a track in a CUESHEET block at the given index.
  85706. *
  85707. * \param object A pointer to an existing CUESHEET object.
  85708. * \param track_num The index into the track array of the track to
  85709. * delete. NOTE: this is not necessarily the same
  85710. * as the track's \a number field.
  85711. * \assert
  85712. * \code object != NULL \endcode
  85713. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85714. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85715. * \retval FLAC__bool
  85716. * \c false if realloc() fails, else \c true.
  85717. */
  85718. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  85719. /** Check a cue sheet to see if it conforms to the FLAC specification.
  85720. * See the format specification for limits on the contents of the
  85721. * cue sheet.
  85722. *
  85723. * \param object A pointer to an existing CUESHEET object.
  85724. * \param check_cd_da_subset If \c true, check CUESHEET against more
  85725. * stringent requirements for a CD-DA (audio) disc.
  85726. * \param violation Address of a pointer to a string. If there is a
  85727. * violation, a pointer to a string explanation of the
  85728. * violation will be returned here. \a violation may be
  85729. * \c NULL if you don't need the returned string. Do not
  85730. * free the returned string; it will always point to static
  85731. * data.
  85732. * \assert
  85733. * \code object != NULL \endcode
  85734. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85735. * \retval FLAC__bool
  85736. * \c false if cue sheet is illegal, else \c true.
  85737. */
  85738. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  85739. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  85740. * assumes the cue sheet corresponds to a CD; the result is undefined
  85741. * if the cuesheet's is_cd bit is not set.
  85742. *
  85743. * \param object A pointer to an existing CUESHEET object.
  85744. * \assert
  85745. * \code object != NULL \endcode
  85746. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85747. * \retval FLAC__uint32
  85748. * The unsigned integer representation of the CDDB/freedb ID
  85749. */
  85750. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  85751. /** Sets the MIME type of a PICTURE block.
  85752. *
  85753. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85754. * takes ownership of the pointer. The existing string will be freed if this
  85755. * function is successful, otherwise the original string will remain if \a copy
  85756. * is \c true and malloc() fails.
  85757. *
  85758. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  85759. *
  85760. * \param object A pointer to an existing PICTURE object.
  85761. * \param mime_type A pointer to the MIME type string. The string must be
  85762. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  85763. * is done.
  85764. * \param copy See above.
  85765. * \assert
  85766. * \code object != NULL \endcode
  85767. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85768. * \code (mime_type != NULL) \endcode
  85769. * \retval FLAC__bool
  85770. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85771. */
  85772. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  85773. /** Sets the description of a PICTURE block.
  85774. *
  85775. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85776. * takes ownership of the pointer. The existing string will be freed if this
  85777. * function is successful, otherwise the original string will remain if \a copy
  85778. * is \c true and malloc() fails.
  85779. *
  85780. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  85781. *
  85782. * \param object A pointer to an existing PICTURE object.
  85783. * \param description A pointer to the description string. The string must be
  85784. * valid UTF-8, NUL-terminated. No validation is done.
  85785. * \param copy See above.
  85786. * \assert
  85787. * \code object != NULL \endcode
  85788. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85789. * \code (description != NULL) \endcode
  85790. * \retval FLAC__bool
  85791. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85792. */
  85793. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  85794. /** Sets the picture data of a PICTURE block.
  85795. *
  85796. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85797. * takes ownership of the pointer. Also sets the \a data_length field of the
  85798. * metadata object to what is passed in as the \a length parameter. The
  85799. * existing data will be freed if this function is successful, otherwise the
  85800. * original data and data_length will remain if \a copy is \c true and
  85801. * malloc() fails.
  85802. *
  85803. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85804. *
  85805. * \param object A pointer to an existing PICTURE object.
  85806. * \param data A pointer to the data to set.
  85807. * \param length The length of \a data in bytes.
  85808. * \param copy See above.
  85809. * \assert
  85810. * \code object != NULL \endcode
  85811. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85812. * \code (data != NULL && length > 0) ||
  85813. * (data == NULL && length == 0 && copy == false) \endcode
  85814. * \retval FLAC__bool
  85815. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85816. */
  85817. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  85818. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  85819. * See the format specification for limits on the contents of the
  85820. * PICTURE block.
  85821. *
  85822. * \param object A pointer to existing PICTURE block to be checked.
  85823. * \param violation Address of a pointer to a string. If there is a
  85824. * violation, a pointer to a string explanation of the
  85825. * violation will be returned here. \a violation may be
  85826. * \c NULL if you don't need the returned string. Do not
  85827. * free the returned string; it will always point to static
  85828. * data.
  85829. * \assert
  85830. * \code object != NULL \endcode
  85831. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85832. * \retval FLAC__bool
  85833. * \c false if PICTURE block is illegal, else \c true.
  85834. */
  85835. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  85836. /* \} */
  85837. #ifdef __cplusplus
  85838. }
  85839. #endif
  85840. #endif
  85841. /*** End of inlined file: metadata.h ***/
  85842. /*** Start of inlined file: stream_decoder.h ***/
  85843. #ifndef FLAC__STREAM_DECODER_H
  85844. #define FLAC__STREAM_DECODER_H
  85845. #include <stdio.h> /* for FILE */
  85846. #ifdef __cplusplus
  85847. extern "C" {
  85848. #endif
  85849. /** \file include/FLAC/stream_decoder.h
  85850. *
  85851. * \brief
  85852. * This module contains the functions which implement the stream
  85853. * decoder.
  85854. *
  85855. * See the detailed documentation in the
  85856. * \link flac_stream_decoder stream decoder \endlink module.
  85857. */
  85858. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  85859. * \ingroup flac
  85860. *
  85861. * \brief
  85862. * This module describes the decoder layers provided by libFLAC.
  85863. *
  85864. * The stream decoder can be used to decode complete streams either from
  85865. * the client via callbacks, or directly from a file, depending on how
  85866. * it is initialized. When decoding via callbacks, the client provides
  85867. * callbacks for reading FLAC data and writing decoded samples, and
  85868. * handling metadata and errors. If the client also supplies seek-related
  85869. * callback, the decoder function for sample-accurate seeking within the
  85870. * FLAC input is also available. When decoding from a file, the client
  85871. * needs only supply a filename or open \c FILE* and write/metadata/error
  85872. * callbacks; the rest of the callbacks are supplied internally. For more
  85873. * info see the \link flac_stream_decoder stream decoder \endlink module.
  85874. */
  85875. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  85876. * \ingroup flac_decoder
  85877. *
  85878. * \brief
  85879. * This module contains the functions which implement the stream
  85880. * decoder.
  85881. *
  85882. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  85883. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85884. *
  85885. * The basic usage of this decoder is as follows:
  85886. * - The program creates an instance of a decoder using
  85887. * FLAC__stream_decoder_new().
  85888. * - The program overrides the default settings using
  85889. * FLAC__stream_decoder_set_*() functions.
  85890. * - The program initializes the instance to validate the settings and
  85891. * prepare for decoding using
  85892. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  85893. * or FLAC__stream_decoder_init_file() for native FLAC,
  85894. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  85895. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  85896. * - The program calls the FLAC__stream_decoder_process_*() functions
  85897. * to decode data, which subsequently calls the callbacks.
  85898. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  85899. * which flushes the input and output and resets the decoder to the
  85900. * uninitialized state.
  85901. * - The instance may be used again or deleted with
  85902. * FLAC__stream_decoder_delete().
  85903. *
  85904. * In more detail, the program will create a new instance by calling
  85905. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  85906. * functions to override the default decoder options, and call
  85907. * one of the FLAC__stream_decoder_init_*() functions.
  85908. *
  85909. * There are three initialization functions for native FLAC, one for
  85910. * setting up the decoder to decode FLAC data from the client via
  85911. * callbacks, and two for decoding directly from a FLAC file.
  85912. *
  85913. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  85914. * You must also supply several callbacks for handling I/O. Some (like
  85915. * seeking) are optional, depending on the capabilities of the input.
  85916. *
  85917. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  85918. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  85919. * \c FILE* or filename and fewer callbacks; the decoder will handle
  85920. * the other callbacks internally.
  85921. *
  85922. * There are three similarly-named init functions for decoding from Ogg
  85923. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85924. * library has been built with Ogg support.
  85925. *
  85926. * Once the decoder is initialized, your program will call one of several
  85927. * functions to start the decoding process:
  85928. *
  85929. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  85930. * most one metadata block or audio frame and return, calling either the
  85931. * metadata callback or write callback, respectively, once. If the decoder
  85932. * loses sync it will return with only the error callback being called.
  85933. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  85934. * to process the stream from the current location and stop upon reaching
  85935. * the first audio frame. The client will get one metadata, write, or error
  85936. * callback per metadata block, audio frame, or sync error, respectively.
  85937. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  85938. * to process the stream from the current location until the read callback
  85939. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  85940. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  85941. * write, or error callback per metadata block, audio frame, or sync error,
  85942. * respectively.
  85943. *
  85944. * When the decoder has finished decoding (normally or through an abort),
  85945. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  85946. * ensures the decoder is in the correct state and frees memory. Then the
  85947. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  85948. * again to decode another stream.
  85949. *
  85950. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  85951. * At any point after the stream decoder has been initialized, the client can
  85952. * call this function to seek to an exact sample within the stream.
  85953. * Subsequently, the first time the write callback is called it will be
  85954. * passed a (possibly partial) block starting at that sample.
  85955. *
  85956. * If the client cannot seek via the callback interface provided, but still
  85957. * has another way of seeking, it can flush the decoder using
  85958. * FLAC__stream_decoder_flush() and start feeding data from the new position
  85959. * through the read callback.
  85960. *
  85961. * The stream decoder also provides MD5 signature checking. If this is
  85962. * turned on before initialization, FLAC__stream_decoder_finish() will
  85963. * report when the decoded MD5 signature does not match the one stored
  85964. * in the STREAMINFO block. MD5 checking is automatically turned off
  85965. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  85966. * in the STREAMINFO block or when a seek is attempted.
  85967. *
  85968. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  85969. * attention. By default, the decoder only calls the metadata_callback for
  85970. * the STREAMINFO block. These functions allow you to tell the decoder
  85971. * explicitly which blocks to parse and return via the metadata_callback
  85972. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  85973. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  85974. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  85975. * which blocks to return. Remember that metadata blocks can potentially
  85976. * be big (for example, cover art) so filtering out the ones you don't
  85977. * use can reduce the memory requirements of the decoder. Also note the
  85978. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  85979. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  85980. * filtering APPLICATION blocks based on the application ID.
  85981. *
  85982. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  85983. * they still can legally be filtered from the metadata_callback.
  85984. *
  85985. * \note
  85986. * The "set" functions may only be called when the decoder is in the
  85987. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  85988. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  85989. * before FLAC__stream_decoder_init_*(). If this is the case they will
  85990. * return \c true, otherwise \c false.
  85991. *
  85992. * \note
  85993. * FLAC__stream_decoder_finish() resets all settings to the constructor
  85994. * defaults, including the callbacks.
  85995. *
  85996. * \{
  85997. */
  85998. /** State values for a FLAC__StreamDecoder
  85999. *
  86000. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  86001. */
  86002. typedef enum {
  86003. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  86004. /**< The decoder is ready to search for metadata. */
  86005. FLAC__STREAM_DECODER_READ_METADATA,
  86006. /**< The decoder is ready to or is in the process of reading metadata. */
  86007. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  86008. /**< The decoder is ready to or is in the process of searching for the
  86009. * frame sync code.
  86010. */
  86011. FLAC__STREAM_DECODER_READ_FRAME,
  86012. /**< The decoder is ready to or is in the process of reading a frame. */
  86013. FLAC__STREAM_DECODER_END_OF_STREAM,
  86014. /**< The decoder has reached the end of the stream. */
  86015. FLAC__STREAM_DECODER_OGG_ERROR,
  86016. /**< An error occurred in the underlying Ogg layer. */
  86017. FLAC__STREAM_DECODER_SEEK_ERROR,
  86018. /**< An error occurred while seeking. The decoder must be flushed
  86019. * with FLAC__stream_decoder_flush() or reset with
  86020. * FLAC__stream_decoder_reset() before decoding can continue.
  86021. */
  86022. FLAC__STREAM_DECODER_ABORTED,
  86023. /**< The decoder was aborted by the read callback. */
  86024. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  86025. /**< An error occurred allocating memory. The decoder is in an invalid
  86026. * state and can no longer be used.
  86027. */
  86028. FLAC__STREAM_DECODER_UNINITIALIZED
  86029. /**< The decoder is in the uninitialized state; one of the
  86030. * FLAC__stream_decoder_init_*() functions must be called before samples
  86031. * can be processed.
  86032. */
  86033. } FLAC__StreamDecoderState;
  86034. /** Maps a FLAC__StreamDecoderState to a C string.
  86035. *
  86036. * Using a FLAC__StreamDecoderState as the index to this array
  86037. * will give the string equivalent. The contents should not be modified.
  86038. */
  86039. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  86040. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  86041. */
  86042. typedef enum {
  86043. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  86044. /**< Initialization was successful. */
  86045. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86046. /**< The library was not compiled with support for the given container
  86047. * format.
  86048. */
  86049. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  86050. /**< A required callback was not supplied. */
  86051. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  86052. /**< An error occurred allocating memory. */
  86053. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  86054. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  86055. * FLAC__stream_decoder_init_ogg_file(). */
  86056. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  86057. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  86058. * already initialized, usually because
  86059. * FLAC__stream_decoder_finish() was not called.
  86060. */
  86061. } FLAC__StreamDecoderInitStatus;
  86062. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  86063. *
  86064. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  86065. * will give the string equivalent. The contents should not be modified.
  86066. */
  86067. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  86068. /** Return values for the FLAC__StreamDecoder read callback.
  86069. */
  86070. typedef enum {
  86071. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  86072. /**< The read was OK and decoding can continue. */
  86073. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  86074. /**< The read was attempted while at the end of the stream. Note that
  86075. * the client must only return this value when the read callback was
  86076. * called when already at the end of the stream. Otherwise, if the read
  86077. * itself moves to the end of the stream, the client should still return
  86078. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  86079. * the next read callback it should return
  86080. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  86081. * of \c 0.
  86082. */
  86083. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  86084. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86085. } FLAC__StreamDecoderReadStatus;
  86086. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  86087. *
  86088. * Using a FLAC__StreamDecoderReadStatus 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__StreamDecoderReadStatusString[];
  86092. /** Return values for the FLAC__StreamDecoder seek callback.
  86093. */
  86094. typedef enum {
  86095. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  86096. /**< The seek was OK and decoding can continue. */
  86097. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  86098. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86099. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86100. /**< Client does not support seeking. */
  86101. } FLAC__StreamDecoderSeekStatus;
  86102. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  86103. *
  86104. * Using a FLAC__StreamDecoderSeekStatus 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__StreamDecoderSeekStatusString[];
  86108. /** Return values for the FLAC__StreamDecoder tell callback.
  86109. */
  86110. typedef enum {
  86111. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  86112. /**< The tell was OK and decoding can continue. */
  86113. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  86114. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86115. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86116. /**< Client does not support telling the position. */
  86117. } FLAC__StreamDecoderTellStatus;
  86118. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  86119. *
  86120. * Using a FLAC__StreamDecoderTellStatus 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__StreamDecoderTellStatusString[];
  86124. /** Return values for the FLAC__StreamDecoder length callback.
  86125. */
  86126. typedef enum {
  86127. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  86128. /**< The length call was OK and decoding can continue. */
  86129. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  86130. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86131. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86132. /**< Client does not support reporting the length. */
  86133. } FLAC__StreamDecoderLengthStatus;
  86134. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  86135. *
  86136. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  86137. * will give the string equivalent. The contents should not be modified.
  86138. */
  86139. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  86140. /** Return values for the FLAC__StreamDecoder write callback.
  86141. */
  86142. typedef enum {
  86143. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  86144. /**< The write was OK and decoding can continue. */
  86145. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  86146. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86147. } FLAC__StreamDecoderWriteStatus;
  86148. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  86149. *
  86150. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  86151. * will give the string equivalent. The contents should not be modified.
  86152. */
  86153. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  86154. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  86155. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  86156. * all. The rest could be caused by bad sync (false synchronization on
  86157. * data that is not the start of a frame) or corrupted data. The error
  86158. * itself is the decoder's best guess at what happened assuming a correct
  86159. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  86160. * could be caused by a correct sync on the start of a frame, but some
  86161. * data in the frame header was corrupted. Or it could be the result of
  86162. * syncing on a point the stream that looked like the starting of a frame
  86163. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86164. * could be because the decoder encountered a valid frame made by a future
  86165. * version of the encoder which it cannot parse, or because of a false
  86166. * sync making it appear as though an encountered frame was generated by
  86167. * a future encoder.
  86168. */
  86169. typedef enum {
  86170. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  86171. /**< An error in the stream caused the decoder to lose synchronization. */
  86172. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  86173. /**< The decoder encountered a corrupted frame header. */
  86174. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  86175. /**< The frame's data did not match the CRC in the footer. */
  86176. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86177. /**< The decoder encountered reserved fields in use in the stream. */
  86178. } FLAC__StreamDecoderErrorStatus;
  86179. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  86180. *
  86181. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  86182. * will give the string equivalent. The contents should not be modified.
  86183. */
  86184. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  86185. /***********************************************************************
  86186. *
  86187. * class FLAC__StreamDecoder
  86188. *
  86189. ***********************************************************************/
  86190. struct FLAC__StreamDecoderProtected;
  86191. struct FLAC__StreamDecoderPrivate;
  86192. /** The opaque structure definition for the stream decoder type.
  86193. * See the \link flac_stream_decoder stream decoder module \endlink
  86194. * for a detailed description.
  86195. */
  86196. typedef struct {
  86197. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86198. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86199. } FLAC__StreamDecoder;
  86200. /** Signature for the read callback.
  86201. *
  86202. * A function pointer matching this signature must be passed to
  86203. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86204. * called when the decoder needs more input data. The address of the
  86205. * buffer to be filled is supplied, along with the number of bytes the
  86206. * buffer can hold. The callback may choose to supply less data and
  86207. * modify the byte count but must be careful not to overflow the buffer.
  86208. * The callback then returns a status code chosen from
  86209. * FLAC__StreamDecoderReadStatus.
  86210. *
  86211. * Here is an example of a read callback for stdio streams:
  86212. * \code
  86213. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86214. * {
  86215. * FILE *file = ((MyClientData*)client_data)->file;
  86216. * if(*bytes > 0) {
  86217. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86218. * if(ferror(file))
  86219. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86220. * else if(*bytes == 0)
  86221. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  86222. * else
  86223. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  86224. * }
  86225. * else
  86226. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86227. * }
  86228. * \endcode
  86229. *
  86230. * \note In general, FLAC__StreamDecoder functions which change the
  86231. * state should not be called on the \a decoder while in the callback.
  86232. *
  86233. * \param decoder The decoder instance calling the callback.
  86234. * \param buffer A pointer to a location for the callee to store
  86235. * data to be decoded.
  86236. * \param bytes A pointer to the size of the buffer. On entry
  86237. * to the callback, it contains the maximum number
  86238. * of bytes that may be stored in \a buffer. The
  86239. * callee must set it to the actual number of bytes
  86240. * stored (0 in case of error or end-of-stream) before
  86241. * returning.
  86242. * \param client_data The callee's client data set through
  86243. * FLAC__stream_decoder_init_*().
  86244. * \retval FLAC__StreamDecoderReadStatus
  86245. * The callee's return status. Note that the callback should return
  86246. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  86247. * zero bytes were read and there is no more data to be read.
  86248. */
  86249. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86250. /** Signature for the seek callback.
  86251. *
  86252. * A function pointer matching this signature may be passed to
  86253. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86254. * called when the decoder needs to seek the input stream. The decoder
  86255. * will pass the absolute byte offset to seek to, 0 meaning the
  86256. * beginning of the stream.
  86257. *
  86258. * Here is an example of a seek callback for stdio streams:
  86259. * \code
  86260. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86261. * {
  86262. * FILE *file = ((MyClientData*)client_data)->file;
  86263. * if(file == stdin)
  86264. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  86265. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86266. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  86267. * else
  86268. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  86269. * }
  86270. * \endcode
  86271. *
  86272. * \note In general, FLAC__StreamDecoder functions which change the
  86273. * state should not be called on the \a decoder while in the callback.
  86274. *
  86275. * \param decoder The decoder instance calling the callback.
  86276. * \param absolute_byte_offset The offset from the beginning of the stream
  86277. * to seek to.
  86278. * \param client_data The callee's client data set through
  86279. * FLAC__stream_decoder_init_*().
  86280. * \retval FLAC__StreamDecoderSeekStatus
  86281. * The callee's return status.
  86282. */
  86283. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86284. /** Signature for the tell callback.
  86285. *
  86286. * A function pointer matching this signature may be passed to
  86287. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86288. * called when the decoder wants to know the current position of the
  86289. * stream. The callback should return the byte offset from the
  86290. * beginning of the stream.
  86291. *
  86292. * Here is an example of a tell callback for stdio streams:
  86293. * \code
  86294. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86295. * {
  86296. * FILE *file = ((MyClientData*)client_data)->file;
  86297. * off_t pos;
  86298. * if(file == stdin)
  86299. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  86300. * else if((pos = ftello(file)) < 0)
  86301. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  86302. * else {
  86303. * *absolute_byte_offset = (FLAC__uint64)pos;
  86304. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  86305. * }
  86306. * }
  86307. * \endcode
  86308. *
  86309. * \note In general, FLAC__StreamDecoder functions which change the
  86310. * state should not be called on the \a decoder while in the callback.
  86311. *
  86312. * \param decoder The decoder instance calling the callback.
  86313. * \param absolute_byte_offset A pointer to storage for the current offset
  86314. * from the beginning of the stream.
  86315. * \param client_data The callee's client data set through
  86316. * FLAC__stream_decoder_init_*().
  86317. * \retval FLAC__StreamDecoderTellStatus
  86318. * The callee's return status.
  86319. */
  86320. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86321. /** Signature for the length callback.
  86322. *
  86323. * A function pointer matching this signature may be passed to
  86324. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86325. * called when the decoder wants to know the total length of the stream
  86326. * in bytes.
  86327. *
  86328. * Here is an example of a length callback for stdio streams:
  86329. * \code
  86330. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  86331. * {
  86332. * FILE *file = ((MyClientData*)client_data)->file;
  86333. * struct stat filestats;
  86334. *
  86335. * if(file == stdin)
  86336. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  86337. * else if(fstat(fileno(file), &filestats) != 0)
  86338. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  86339. * else {
  86340. * *stream_length = (FLAC__uint64)filestats.st_size;
  86341. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  86342. * }
  86343. * }
  86344. * \endcode
  86345. *
  86346. * \note In general, FLAC__StreamDecoder functions which change the
  86347. * state should not be called on the \a decoder while in the callback.
  86348. *
  86349. * \param decoder The decoder instance calling the callback.
  86350. * \param stream_length A pointer to storage for the length of the stream
  86351. * in bytes.
  86352. * \param client_data The callee's client data set through
  86353. * FLAC__stream_decoder_init_*().
  86354. * \retval FLAC__StreamDecoderLengthStatus
  86355. * The callee's return status.
  86356. */
  86357. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  86358. /** Signature for the EOF callback.
  86359. *
  86360. * A function pointer matching this signature may be passed to
  86361. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86362. * called when the decoder needs to know if the end of the stream has
  86363. * been reached.
  86364. *
  86365. * Here is an example of a EOF callback for stdio streams:
  86366. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  86367. * \code
  86368. * {
  86369. * FILE *file = ((MyClientData*)client_data)->file;
  86370. * return feof(file)? true : false;
  86371. * }
  86372. * \endcode
  86373. *
  86374. * \note In general, FLAC__StreamDecoder functions which change the
  86375. * state should not be called on the \a decoder while in the callback.
  86376. *
  86377. * \param decoder The decoder instance calling the callback.
  86378. * \param client_data The callee's client data set through
  86379. * FLAC__stream_decoder_init_*().
  86380. * \retval FLAC__bool
  86381. * \c true if the currently at the end of the stream, else \c false.
  86382. */
  86383. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  86384. /** Signature for the write callback.
  86385. *
  86386. * A function pointer matching this signature must be passed to one of
  86387. * the FLAC__stream_decoder_init_*() functions.
  86388. * The supplied function will be called when the decoder has decoded a
  86389. * single audio frame. The decoder will pass the frame metadata as well
  86390. * as an array of pointers (one for each channel) pointing to the
  86391. * decoded audio.
  86392. *
  86393. * \note In general, FLAC__StreamDecoder functions which change the
  86394. * state should not be called on the \a decoder while in the callback.
  86395. *
  86396. * \param decoder The decoder instance calling the callback.
  86397. * \param frame The description of the decoded frame. See
  86398. * FLAC__Frame.
  86399. * \param buffer An array of pointers to decoded channels of data.
  86400. * Each pointer will point to an array of signed
  86401. * samples of length \a frame->header.blocksize.
  86402. * Channels will be ordered according to the FLAC
  86403. * specification; see the documentation for the
  86404. * <A HREF="../format.html#frame_header">frame header</A>.
  86405. * \param client_data The callee's client data set through
  86406. * FLAC__stream_decoder_init_*().
  86407. * \retval FLAC__StreamDecoderWriteStatus
  86408. * The callee's return status.
  86409. */
  86410. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  86411. /** Signature for the metadata callback.
  86412. *
  86413. * A function pointer matching this signature must be passed to one of
  86414. * the FLAC__stream_decoder_init_*() functions.
  86415. * The supplied function will be called when the decoder has decoded a
  86416. * metadata block. In a valid FLAC file there will always be one
  86417. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  86418. * These will be supplied by the decoder in the same order as they
  86419. * appear in the stream and always before the first audio frame (i.e.
  86420. * write callback). The metadata block that is passed in must not be
  86421. * modified, and it doesn't live beyond the callback, so you should make
  86422. * a copy of it with FLAC__metadata_object_clone() if you will need it
  86423. * elsewhere. Since metadata blocks can potentially be large, by
  86424. * default the decoder only calls the metadata callback for the
  86425. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  86426. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  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 metadata The decoded metadata block.
  86433. * \param client_data The callee's client data set through
  86434. * FLAC__stream_decoder_init_*().
  86435. */
  86436. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86437. /** Signature for the error callback.
  86438. *
  86439. * A function pointer matching this signature must be passed to one of
  86440. * the FLAC__stream_decoder_init_*() functions.
  86441. * The supplied function will be called whenever an error occurs during
  86442. * decoding.
  86443. *
  86444. * \note In general, FLAC__StreamDecoder functions which change the
  86445. * state should not be called on the \a decoder while in the callback.
  86446. *
  86447. * \param decoder The decoder instance calling the callback.
  86448. * \param status The error encountered by the decoder.
  86449. * \param client_data The callee's client data set through
  86450. * FLAC__stream_decoder_init_*().
  86451. */
  86452. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  86453. /***********************************************************************
  86454. *
  86455. * Class constructor/destructor
  86456. *
  86457. ***********************************************************************/
  86458. /** Create a new stream decoder instance. The instance is created with
  86459. * default settings; see the individual FLAC__stream_decoder_set_*()
  86460. * functions for each setting's default.
  86461. *
  86462. * \retval FLAC__StreamDecoder*
  86463. * \c NULL if there was an error allocating memory, else the new instance.
  86464. */
  86465. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  86466. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  86467. *
  86468. * \param decoder A pointer to an existing decoder.
  86469. * \assert
  86470. * \code decoder != NULL \endcode
  86471. */
  86472. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  86473. /***********************************************************************
  86474. *
  86475. * Public class method prototypes
  86476. *
  86477. ***********************************************************************/
  86478. /** Set the serial number for the FLAC stream within the Ogg container.
  86479. * The default behavior is to use the serial number of the first Ogg
  86480. * page. Setting a serial number here will explicitly specify which
  86481. * stream is to be decoded.
  86482. *
  86483. * \note
  86484. * This does not need to be set for native FLAC decoding.
  86485. *
  86486. * \default \c use serial number of first page
  86487. * \param decoder A decoder instance to set.
  86488. * \param serial_number See above.
  86489. * \assert
  86490. * \code decoder != NULL \endcode
  86491. * \retval FLAC__bool
  86492. * \c false if the decoder is already initialized, else \c true.
  86493. */
  86494. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  86495. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  86496. * compute the MD5 signature of the unencoded audio data while decoding
  86497. * and compare it to the signature from the STREAMINFO block, if it
  86498. * exists, during FLAC__stream_decoder_finish().
  86499. *
  86500. * MD5 signature checking will be turned off (until the next
  86501. * FLAC__stream_decoder_reset()) if there is no signature in the
  86502. * STREAMINFO block or when a seek is attempted.
  86503. *
  86504. * Clients that do not use the MD5 check should leave this off to speed
  86505. * up decoding.
  86506. *
  86507. * \default \c false
  86508. * \param decoder A decoder instance to set.
  86509. * \param value Flag value (see above).
  86510. * \assert
  86511. * \code decoder != NULL \endcode
  86512. * \retval FLAC__bool
  86513. * \c false if the decoder is already initialized, else \c true.
  86514. */
  86515. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  86516. /** Direct the decoder to pass on all metadata blocks of type \a type.
  86517. *
  86518. * \default By default, only the \c STREAMINFO block is returned via the
  86519. * metadata callback.
  86520. * \param decoder A decoder instance to set.
  86521. * \param type See above.
  86522. * \assert
  86523. * \code decoder != NULL \endcode
  86524. * \a type is valid
  86525. * \retval FLAC__bool
  86526. * \c false if the decoder is already initialized, else \c true.
  86527. */
  86528. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  86529. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  86530. * given \a id.
  86531. *
  86532. * \default By default, only the \c STREAMINFO block is returned via the
  86533. * metadata callback.
  86534. * \param decoder A decoder instance to set.
  86535. * \param id See above.
  86536. * \assert
  86537. * \code decoder != NULL \endcode
  86538. * \code id != NULL \endcode
  86539. * \retval FLAC__bool
  86540. * \c false if the decoder is already initialized, else \c true.
  86541. */
  86542. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  86543. /** Direct the decoder to pass on all metadata blocks of any type.
  86544. *
  86545. * \default By default, only the \c STREAMINFO block is returned via the
  86546. * metadata callback.
  86547. * \param decoder A decoder instance to set.
  86548. * \assert
  86549. * \code decoder != NULL \endcode
  86550. * \retval FLAC__bool
  86551. * \c false if the decoder is already initialized, else \c true.
  86552. */
  86553. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  86554. /** Direct the decoder to filter out all metadata blocks of type \a type.
  86555. *
  86556. * \default By default, only the \c STREAMINFO block is returned via the
  86557. * metadata callback.
  86558. * \param decoder A decoder instance to set.
  86559. * \param type See above.
  86560. * \assert
  86561. * \code decoder != NULL \endcode
  86562. * \a type is valid
  86563. * \retval FLAC__bool
  86564. * \c false if the decoder is already initialized, else \c true.
  86565. */
  86566. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  86567. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  86568. * the given \a id.
  86569. *
  86570. * \default By default, only the \c STREAMINFO block is returned via the
  86571. * metadata callback.
  86572. * \param decoder A decoder instance to set.
  86573. * \param id See above.
  86574. * \assert
  86575. * \code decoder != NULL \endcode
  86576. * \code id != NULL \endcode
  86577. * \retval FLAC__bool
  86578. * \c false if the decoder is already initialized, else \c true.
  86579. */
  86580. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  86581. /** Direct the decoder to filter out all metadata blocks of any type.
  86582. *
  86583. * \default By default, only the \c STREAMINFO block is returned via the
  86584. * metadata callback.
  86585. * \param decoder A decoder instance to set.
  86586. * \assert
  86587. * \code decoder != NULL \endcode
  86588. * \retval FLAC__bool
  86589. * \c false if the decoder is already initialized, else \c true.
  86590. */
  86591. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  86592. /** Get the current decoder state.
  86593. *
  86594. * \param decoder A decoder instance to query.
  86595. * \assert
  86596. * \code decoder != NULL \endcode
  86597. * \retval FLAC__StreamDecoderState
  86598. * The current decoder state.
  86599. */
  86600. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  86601. /** Get the current decoder state as a C string.
  86602. *
  86603. * \param decoder A decoder instance to query.
  86604. * \assert
  86605. * \code decoder != NULL \endcode
  86606. * \retval const char *
  86607. * The decoder state as a C string. Do not modify the contents.
  86608. */
  86609. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  86610. /** Get the "MD5 signature checking" flag.
  86611. * This is the value of the setting, not whether or not the decoder is
  86612. * currently checking the MD5 (remember, it can be turned off automatically
  86613. * by a seek). When the decoder is reset the flag will be restored to the
  86614. * value returned by this function.
  86615. *
  86616. * \param decoder A decoder instance to query.
  86617. * \assert
  86618. * \code decoder != NULL \endcode
  86619. * \retval FLAC__bool
  86620. * See above.
  86621. */
  86622. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  86623. /** Get the total number of samples in the stream being decoded.
  86624. * Will only be valid after decoding has started and will contain the
  86625. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  86626. *
  86627. * \param decoder A decoder instance to query.
  86628. * \assert
  86629. * \code decoder != NULL \endcode
  86630. * \retval unsigned
  86631. * See above.
  86632. */
  86633. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  86634. /** Get the current number of channels in the stream being decoded.
  86635. * Will only be valid after decoding has started and will contain the
  86636. * value from the most recently decoded frame header.
  86637. *
  86638. * \param decoder A decoder instance to query.
  86639. * \assert
  86640. * \code decoder != NULL \endcode
  86641. * \retval unsigned
  86642. * See above.
  86643. */
  86644. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  86645. /** Get the current channel assignment in the stream being decoded.
  86646. * Will only be valid after decoding has started and will contain the
  86647. * value from the most recently decoded frame header.
  86648. *
  86649. * \param decoder A decoder instance to query.
  86650. * \assert
  86651. * \code decoder != NULL \endcode
  86652. * \retval FLAC__ChannelAssignment
  86653. * See above.
  86654. */
  86655. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  86656. /** Get the current sample resolution in the stream being decoded.
  86657. * Will only be valid after decoding has started and will contain the
  86658. * value from the most recently decoded frame header.
  86659. *
  86660. * \param decoder A decoder instance to query.
  86661. * \assert
  86662. * \code decoder != NULL \endcode
  86663. * \retval unsigned
  86664. * See above.
  86665. */
  86666. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  86667. /** Get the current sample rate in Hz of the stream being decoded.
  86668. * Will only be valid after decoding has started and will contain the
  86669. * value from the most recently decoded frame header.
  86670. *
  86671. * \param decoder A decoder instance to query.
  86672. * \assert
  86673. * \code decoder != NULL \endcode
  86674. * \retval unsigned
  86675. * See above.
  86676. */
  86677. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  86678. /** Get the current blocksize of the stream being decoded.
  86679. * Will only be valid after decoding has started and will contain the
  86680. * value from the most recently decoded frame header.
  86681. *
  86682. * \param decoder A decoder instance to query.
  86683. * \assert
  86684. * \code decoder != NULL \endcode
  86685. * \retval unsigned
  86686. * See above.
  86687. */
  86688. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  86689. /** Returns the decoder's current read position within the stream.
  86690. * The position is the byte offset from the start of the stream.
  86691. * Bytes before this position have been fully decoded. Note that
  86692. * there may still be undecoded bytes in the decoder's read FIFO.
  86693. * The returned position is correct even after a seek.
  86694. *
  86695. * \warning This function currently only works for native FLAC,
  86696. * not Ogg FLAC streams.
  86697. *
  86698. * \param decoder A decoder instance to query.
  86699. * \param position Address at which to return the desired position.
  86700. * \assert
  86701. * \code decoder != NULL \endcode
  86702. * \code position != NULL \endcode
  86703. * \retval FLAC__bool
  86704. * \c true if successful, \c false if the stream is not native FLAC,
  86705. * or there was an error from the 'tell' callback or it returned
  86706. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  86707. */
  86708. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  86709. /** Initialize the decoder instance to decode native FLAC streams.
  86710. *
  86711. * This flavor of initialization sets up the decoder to decode from a
  86712. * native FLAC stream. I/O is performed via callbacks to the client.
  86713. * For decoding from a plain file via filename or open FILE*,
  86714. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  86715. * provide a simpler interface.
  86716. *
  86717. * This function should be called after FLAC__stream_decoder_new() and
  86718. * FLAC__stream_decoder_set_*() but before any of the
  86719. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86720. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86721. * if initialization succeeded.
  86722. *
  86723. * \param decoder An uninitialized decoder instance.
  86724. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  86725. * pointer must not be \c NULL.
  86726. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  86727. * pointer may be \c NULL if seeking is not
  86728. * supported. If \a seek_callback is not \c NULL then a
  86729. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86730. * Alternatively, a dummy seek callback that just
  86731. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86732. * may also be supplied, all though this is slightly
  86733. * less efficient for the decoder.
  86734. * \param tell_callback See FLAC__StreamDecoderTellCallback. 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 tell_callback must also be supplied.
  86738. * Alternatively, a dummy tell callback that just
  86739. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86740. * may also be supplied, all though this is slightly
  86741. * less efficient for the decoder.
  86742. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86743. * pointer may be \c NULL if not supported by the client. If
  86744. * \a seek_callback is not \c NULL then a
  86745. * \a length_callback must also be supplied.
  86746. * Alternatively, a dummy length callback that just
  86747. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86748. * may also be supplied, all though this is slightly
  86749. * less efficient for the decoder.
  86750. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86751. * pointer may be \c NULL if not supported by the client. If
  86752. * \a seek_callback is not \c NULL then a
  86753. * \a eof_callback must also be supplied.
  86754. * Alternatively, a dummy length callback that just
  86755. * returns \c false
  86756. * may also be supplied, all though this is slightly
  86757. * less efficient for the decoder.
  86758. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86759. * pointer must not be \c NULL.
  86760. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86761. * pointer may be \c NULL if the callback is not
  86762. * desired.
  86763. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86764. * pointer must not be \c NULL.
  86765. * \param client_data This value will be supplied to callbacks in their
  86766. * \a client_data argument.
  86767. * \assert
  86768. * \code decoder != NULL \endcode
  86769. * \retval FLAC__StreamDecoderInitStatus
  86770. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86771. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86772. */
  86773. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  86774. FLAC__StreamDecoder *decoder,
  86775. FLAC__StreamDecoderReadCallback read_callback,
  86776. FLAC__StreamDecoderSeekCallback seek_callback,
  86777. FLAC__StreamDecoderTellCallback tell_callback,
  86778. FLAC__StreamDecoderLengthCallback length_callback,
  86779. FLAC__StreamDecoderEofCallback eof_callback,
  86780. FLAC__StreamDecoderWriteCallback write_callback,
  86781. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86782. FLAC__StreamDecoderErrorCallback error_callback,
  86783. void *client_data
  86784. );
  86785. /** Initialize the decoder instance to decode Ogg FLAC streams.
  86786. *
  86787. * This flavor of initialization sets up the decoder to decode from a
  86788. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  86789. * client. For decoding from a plain file via filename or open FILE*,
  86790. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  86791. * provide a simpler interface.
  86792. *
  86793. * This function should be called after FLAC__stream_decoder_new() and
  86794. * FLAC__stream_decoder_set_*() but before any of the
  86795. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86796. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86797. * if initialization succeeded.
  86798. *
  86799. * \note Support for Ogg FLAC in the library is optional. If this
  86800. * library has been built without support for Ogg FLAC, this function
  86801. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86802. *
  86803. * \param decoder An uninitialized decoder instance.
  86804. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  86805. * pointer must not be \c NULL.
  86806. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  86807. * pointer may be \c NULL if seeking is not
  86808. * supported. If \a seek_callback is not \c NULL then a
  86809. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86810. * Alternatively, a dummy seek callback that just
  86811. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86812. * may also be supplied, all though this is slightly
  86813. * less efficient for the decoder.
  86814. * \param tell_callback See FLAC__StreamDecoderTellCallback. 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 tell_callback must also be supplied.
  86818. * Alternatively, a dummy tell callback that just
  86819. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86820. * may also be supplied, all though this is slightly
  86821. * less efficient for the decoder.
  86822. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86823. * pointer may be \c NULL if not supported by the client. If
  86824. * \a seek_callback is not \c NULL then a
  86825. * \a length_callback must also be supplied.
  86826. * Alternatively, a dummy length callback that just
  86827. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86828. * may also be supplied, all though this is slightly
  86829. * less efficient for the decoder.
  86830. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86831. * pointer may be \c NULL if not supported by the client. If
  86832. * \a seek_callback is not \c NULL then a
  86833. * \a eof_callback must also be supplied.
  86834. * Alternatively, a dummy length callback that just
  86835. * returns \c false
  86836. * may also be supplied, all though this is slightly
  86837. * less efficient for the decoder.
  86838. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86839. * pointer must not be \c NULL.
  86840. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86841. * pointer may be \c NULL if the callback is not
  86842. * desired.
  86843. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86844. * pointer must not be \c NULL.
  86845. * \param client_data This value will be supplied to callbacks in their
  86846. * \a client_data argument.
  86847. * \assert
  86848. * \code decoder != NULL \endcode
  86849. * \retval FLAC__StreamDecoderInitStatus
  86850. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86851. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86852. */
  86853. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  86854. FLAC__StreamDecoder *decoder,
  86855. FLAC__StreamDecoderReadCallback read_callback,
  86856. FLAC__StreamDecoderSeekCallback seek_callback,
  86857. FLAC__StreamDecoderTellCallback tell_callback,
  86858. FLAC__StreamDecoderLengthCallback length_callback,
  86859. FLAC__StreamDecoderEofCallback eof_callback,
  86860. FLAC__StreamDecoderWriteCallback write_callback,
  86861. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86862. FLAC__StreamDecoderErrorCallback error_callback,
  86863. void *client_data
  86864. );
  86865. /** Initialize the decoder instance to decode native FLAC files.
  86866. *
  86867. * This flavor of initialization sets up the decoder to decode from a
  86868. * plain native FLAC file. For non-stdio streams, you must use
  86869. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  86870. *
  86871. * This function should be called after FLAC__stream_decoder_new() and
  86872. * FLAC__stream_decoder_set_*() but before any of the
  86873. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86874. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86875. * if initialization succeeded.
  86876. *
  86877. * \param decoder An uninitialized decoder instance.
  86878. * \param file An open FLAC file. The file should have been
  86879. * opened with mode \c "rb" and rewound. The file
  86880. * becomes owned by the decoder and should not be
  86881. * manipulated by the client while decoding.
  86882. * Unless \a file is \c stdin, it will be closed
  86883. * when FLAC__stream_decoder_finish() is called.
  86884. * Note however that seeking will not work when
  86885. * decoding from \c stdout since it is not seekable.
  86886. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86887. * pointer must not be \c NULL.
  86888. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86889. * pointer may be \c NULL if the callback is not
  86890. * desired.
  86891. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86892. * pointer must not be \c NULL.
  86893. * \param client_data This value will be supplied to callbacks in their
  86894. * \a client_data argument.
  86895. * \assert
  86896. * \code decoder != NULL \endcode
  86897. * \code file != NULL \endcode
  86898. * \retval FLAC__StreamDecoderInitStatus
  86899. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86900. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86901. */
  86902. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  86903. FLAC__StreamDecoder *decoder,
  86904. FILE *file,
  86905. FLAC__StreamDecoderWriteCallback write_callback,
  86906. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86907. FLAC__StreamDecoderErrorCallback error_callback,
  86908. void *client_data
  86909. );
  86910. /** Initialize the decoder instance to decode Ogg FLAC files.
  86911. *
  86912. * This flavor of initialization sets up the decoder to decode from a
  86913. * plain Ogg FLAC file. For non-stdio streams, you must use
  86914. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  86915. *
  86916. * This function should be called after FLAC__stream_decoder_new() and
  86917. * FLAC__stream_decoder_set_*() but before any of the
  86918. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86919. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86920. * if initialization succeeded.
  86921. *
  86922. * \note Support for Ogg FLAC in the library is optional. If this
  86923. * library has been built without support for Ogg FLAC, this function
  86924. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86925. *
  86926. * \param decoder An uninitialized decoder instance.
  86927. * \param file An open FLAC file. The file should have been
  86928. * opened with mode \c "rb" and rewound. The file
  86929. * becomes owned by the decoder and should not be
  86930. * manipulated by the client while decoding.
  86931. * Unless \a file is \c stdin, it will be closed
  86932. * when FLAC__stream_decoder_finish() is called.
  86933. * Note however that seeking will not work when
  86934. * decoding from \c stdout since it is not seekable.
  86935. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86936. * pointer must not be \c NULL.
  86937. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86938. * pointer may be \c NULL if the callback is not
  86939. * desired.
  86940. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86941. * pointer must not be \c NULL.
  86942. * \param client_data This value will be supplied to callbacks in their
  86943. * \a client_data argument.
  86944. * \assert
  86945. * \code decoder != NULL \endcode
  86946. * \code file != NULL \endcode
  86947. * \retval FLAC__StreamDecoderInitStatus
  86948. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86949. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86950. */
  86951. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  86952. FLAC__StreamDecoder *decoder,
  86953. FILE *file,
  86954. FLAC__StreamDecoderWriteCallback write_callback,
  86955. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86956. FLAC__StreamDecoderErrorCallback error_callback,
  86957. void *client_data
  86958. );
  86959. /** Initialize the decoder instance to decode native FLAC files.
  86960. *
  86961. * This flavor of initialization sets up the decoder to decode from a plain
  86962. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86963. * example, with Unicode filenames on Windows), you must use
  86964. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  86965. * and provide callbacks for the I/O.
  86966. *
  86967. * This function should be called after FLAC__stream_decoder_new() and
  86968. * FLAC__stream_decoder_set_*() but before any of the
  86969. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86970. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86971. * if initialization succeeded.
  86972. *
  86973. * \param decoder An uninitialized decoder instance.
  86974. * \param filename The name of the file to decode from. The file will
  86975. * be opened with fopen(). Use \c NULL to decode from
  86976. * \c stdin. Note that \c stdin is not seekable.
  86977. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86978. * pointer must not be \c NULL.
  86979. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86980. * pointer may be \c NULL if the callback is not
  86981. * desired.
  86982. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86983. * pointer must not be \c NULL.
  86984. * \param client_data This value will be supplied to callbacks in their
  86985. * \a client_data argument.
  86986. * \assert
  86987. * \code decoder != NULL \endcode
  86988. * \retval FLAC__StreamDecoderInitStatus
  86989. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86990. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86991. */
  86992. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  86993. FLAC__StreamDecoder *decoder,
  86994. const char *filename,
  86995. FLAC__StreamDecoderWriteCallback write_callback,
  86996. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86997. FLAC__StreamDecoderErrorCallback error_callback,
  86998. void *client_data
  86999. );
  87000. /** Initialize the decoder instance to decode Ogg FLAC files.
  87001. *
  87002. * This flavor of initialization sets up the decoder to decode from a plain
  87003. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  87004. * example, with Unicode filenames on Windows), you must use
  87005. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  87006. * and provide callbacks for the I/O.
  87007. *
  87008. * This function should be called after FLAC__stream_decoder_new() and
  87009. * FLAC__stream_decoder_set_*() but before any of the
  87010. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87011. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87012. * if initialization succeeded.
  87013. *
  87014. * \note Support for Ogg FLAC in the library is optional. If this
  87015. * library has been built without support for Ogg FLAC, this function
  87016. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87017. *
  87018. * \param decoder An uninitialized decoder instance.
  87019. * \param filename The name of the file to decode from. The file will
  87020. * be opened with fopen(). Use \c NULL to decode from
  87021. * \c stdin. Note that \c stdin is not seekable.
  87022. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87023. * pointer must not be \c NULL.
  87024. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87025. * pointer may be \c NULL if the callback is not
  87026. * desired.
  87027. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87028. * pointer must not be \c NULL.
  87029. * \param client_data This value will be supplied to callbacks in their
  87030. * \a client_data argument.
  87031. * \assert
  87032. * \code decoder != NULL \endcode
  87033. * \retval FLAC__StreamDecoderInitStatus
  87034. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87035. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87036. */
  87037. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  87038. FLAC__StreamDecoder *decoder,
  87039. const char *filename,
  87040. FLAC__StreamDecoderWriteCallback write_callback,
  87041. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87042. FLAC__StreamDecoderErrorCallback error_callback,
  87043. void *client_data
  87044. );
  87045. /** Finish the decoding process.
  87046. * Flushes the decoding buffer, releases resources, resets the decoder
  87047. * settings to their defaults, and returns the decoder state to
  87048. * FLAC__STREAM_DECODER_UNINITIALIZED.
  87049. *
  87050. * In the event of a prematurely-terminated decode, it is not strictly
  87051. * necessary to call this immediately before FLAC__stream_decoder_delete()
  87052. * but it is good practice to match every FLAC__stream_decoder_init_*()
  87053. * with a FLAC__stream_decoder_finish().
  87054. *
  87055. * \param decoder An uninitialized decoder instance.
  87056. * \assert
  87057. * \code decoder != NULL \endcode
  87058. * \retval FLAC__bool
  87059. * \c false if MD5 checking is on AND a STREAMINFO block was available
  87060. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  87061. * signature does not match the one computed by the decoder; else
  87062. * \c true.
  87063. */
  87064. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  87065. /** Flush the stream input.
  87066. * The decoder's input buffer will be cleared and the state set to
  87067. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  87068. * off MD5 checking.
  87069. *
  87070. * \param decoder A decoder instance.
  87071. * \assert
  87072. * \code decoder != NULL \endcode
  87073. * \retval FLAC__bool
  87074. * \c true if successful, else \c false if a memory allocation
  87075. * error occurs (in which case the state will be set to
  87076. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  87077. */
  87078. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  87079. /** Reset the decoding process.
  87080. * The decoder's input buffer will be cleared and the state set to
  87081. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  87082. * FLAC__stream_decoder_finish() except that the settings are
  87083. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  87084. * before decoding again. MD5 checking will be restored to its original
  87085. * setting.
  87086. *
  87087. * If the decoder is seekable, or was initialized with
  87088. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  87089. * the decoder will also attempt to seek to the beginning of the file.
  87090. * If this rewind fails, this function will return \c false. It follows
  87091. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  87092. * \c stdin.
  87093. *
  87094. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  87095. * and is not seekable (i.e. no seek callback was provided or the seek
  87096. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  87097. * is the duty of the client to start feeding data from the beginning of
  87098. * the stream on the next FLAC__stream_decoder_process() or
  87099. * FLAC__stream_decoder_process_interleaved() call.
  87100. *
  87101. * \param decoder A decoder instance.
  87102. * \assert
  87103. * \code decoder != NULL \endcode
  87104. * \retval FLAC__bool
  87105. * \c true if successful, else \c false if a memory allocation occurs
  87106. * (in which case the state will be set to
  87107. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  87108. * occurs (the state will be unchanged).
  87109. */
  87110. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  87111. /** Decode one metadata block or audio frame.
  87112. * This version instructs the decoder to decode a either a single metadata
  87113. * block or a single frame and stop, unless the callbacks return a fatal
  87114. * error or the read callback returns
  87115. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87116. *
  87117. * As the decoder needs more input it will call the read callback.
  87118. * Depending on what was decoded, the metadata or write callback will be
  87119. * called with the decoded metadata block or audio frame.
  87120. *
  87121. * Unless there is a fatal read error or end of stream, this function
  87122. * will return once one whole frame is decoded. In other words, if the
  87123. * stream is not synchronized or points to a corrupt frame header, the
  87124. * decoder will continue to try and resync until it gets to a valid
  87125. * frame, then decode one frame, then return. If the decoder points to
  87126. * a frame whose frame CRC in the frame footer does not match the
  87127. * computed frame CRC, this function will issue a
  87128. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  87129. * error callback, and return, having decoded one complete, although
  87130. * corrupt, frame. (Such corrupted frames are sent as silence of the
  87131. * correct length to the write callback.)
  87132. *
  87133. * \param decoder An initialized decoder instance.
  87134. * \assert
  87135. * \code decoder != NULL \endcode
  87136. * \retval FLAC__bool
  87137. * \c false if any fatal read, write, or memory allocation error
  87138. * occurred (meaning decoding must stop), else \c true; for more
  87139. * information about the decoder, check the decoder state with
  87140. * FLAC__stream_decoder_get_state().
  87141. */
  87142. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  87143. /** Decode until the end of the metadata.
  87144. * This version instructs the decoder to decode from the current position
  87145. * and continue until all the metadata has been read, or until the
  87146. * callbacks return a fatal error or the read callback returns
  87147. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87148. *
  87149. * As the decoder needs more input it will call the read callback.
  87150. * As each metadata block is decoded, the metadata callback will be called
  87151. * with the decoded metadata.
  87152. *
  87153. * \param decoder An initialized decoder instance.
  87154. * \assert
  87155. * \code decoder != NULL \endcode
  87156. * \retval FLAC__bool
  87157. * \c false if any fatal read, write, or memory allocation error
  87158. * occurred (meaning decoding must stop), else \c true; for more
  87159. * information about the decoder, check the decoder state with
  87160. * FLAC__stream_decoder_get_state().
  87161. */
  87162. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  87163. /** Decode until the end of the stream.
  87164. * This version instructs the decoder to decode from the current position
  87165. * and continue until the end of stream (the read callback returns
  87166. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  87167. * callbacks return a fatal error.
  87168. *
  87169. * As the decoder needs more input it will call the read callback.
  87170. * As each metadata block and frame is decoded, the metadata or write
  87171. * callback will be called with the decoded metadata or frame.
  87172. *
  87173. * \param decoder An initialized decoder instance.
  87174. * \assert
  87175. * \code decoder != NULL \endcode
  87176. * \retval FLAC__bool
  87177. * \c false if any fatal read, write, or memory allocation error
  87178. * occurred (meaning decoding must stop), else \c true; for more
  87179. * information about the decoder, check the decoder state with
  87180. * FLAC__stream_decoder_get_state().
  87181. */
  87182. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  87183. /** Skip one audio frame.
  87184. * This version instructs the decoder to 'skip' a single frame and stop,
  87185. * unless the callbacks return a fatal error or the read callback returns
  87186. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87187. *
  87188. * The decoding flow is the same as what occurs when
  87189. * FLAC__stream_decoder_process_single() is called to process an audio
  87190. * frame, except that this function does not decode the parsed data into
  87191. * PCM or call the write callback. The integrity of the frame is still
  87192. * checked the same way as in the other process functions.
  87193. *
  87194. * This function will return once one whole frame is skipped, in the
  87195. * same way that FLAC__stream_decoder_process_single() will return once
  87196. * one whole frame is decoded.
  87197. *
  87198. * This function can be used in more quickly determining FLAC frame
  87199. * boundaries when decoding of the actual data is not needed, for
  87200. * example when an application is separating a FLAC stream into frames
  87201. * for editing or storing in a container. To do this, the application
  87202. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  87203. * to the next frame, then use
  87204. * FLAC__stream_decoder_get_decode_position() to find the new frame
  87205. * boundary.
  87206. *
  87207. * This function should only be called when the stream has advanced
  87208. * past all the metadata, otherwise it will return \c false.
  87209. *
  87210. * \param decoder An initialized decoder instance not in a metadata
  87211. * state.
  87212. * \assert
  87213. * \code decoder != NULL \endcode
  87214. * \retval FLAC__bool
  87215. * \c false if any fatal read, write, or memory allocation error
  87216. * occurred (meaning decoding must stop), or if the decoder
  87217. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  87218. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  87219. * information about the decoder, check the decoder state with
  87220. * FLAC__stream_decoder_get_state().
  87221. */
  87222. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  87223. /** Flush the input and seek to an absolute sample.
  87224. * Decoding will resume at the given sample. Note that because of
  87225. * this, the next write callback may contain a partial block. The
  87226. * client must support seeking the input or this function will fail
  87227. * and return \c false. Furthermore, if the decoder state is
  87228. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  87229. * with FLAC__stream_decoder_flush() or reset with
  87230. * FLAC__stream_decoder_reset() before decoding can continue.
  87231. *
  87232. * \param decoder A decoder instance.
  87233. * \param sample The target sample number to seek to.
  87234. * \assert
  87235. * \code decoder != NULL \endcode
  87236. * \retval FLAC__bool
  87237. * \c true if successful, else \c false.
  87238. */
  87239. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  87240. /* \} */
  87241. #ifdef __cplusplus
  87242. }
  87243. #endif
  87244. #endif
  87245. /*** End of inlined file: stream_decoder.h ***/
  87246. /*** Start of inlined file: stream_encoder.h ***/
  87247. #ifndef FLAC__STREAM_ENCODER_H
  87248. #define FLAC__STREAM_ENCODER_H
  87249. #include <stdio.h> /* for FILE */
  87250. #ifdef __cplusplus
  87251. extern "C" {
  87252. #endif
  87253. /** \file include/FLAC/stream_encoder.h
  87254. *
  87255. * \brief
  87256. * This module contains the functions which implement the stream
  87257. * encoder.
  87258. *
  87259. * See the detailed documentation in the
  87260. * \link flac_stream_encoder stream encoder \endlink module.
  87261. */
  87262. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  87263. * \ingroup flac
  87264. *
  87265. * \brief
  87266. * This module describes the encoder layers provided by libFLAC.
  87267. *
  87268. * The stream encoder can be used to encode complete streams either to the
  87269. * client via callbacks, or directly to a file, depending on how it is
  87270. * initialized. When encoding via callbacks, the client provides a write
  87271. * callback which will be called whenever FLAC data is ready to be written.
  87272. * If the client also supplies a seek callback, the encoder will also
  87273. * automatically handle the writing back of metadata discovered while
  87274. * encoding, like stream info, seek points offsets, etc. When encoding to
  87275. * a file, the client needs only supply a filename or open \c FILE* and an
  87276. * optional progress callback for periodic notification of progress; the
  87277. * write and seek callbacks are supplied internally. For more info see the
  87278. * \link flac_stream_encoder stream encoder \endlink module.
  87279. */
  87280. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  87281. * \ingroup flac_encoder
  87282. *
  87283. * \brief
  87284. * This module contains the functions which implement the stream
  87285. * encoder.
  87286. *
  87287. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  87288. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  87289. *
  87290. * The basic usage of this encoder is as follows:
  87291. * - The program creates an instance of an encoder using
  87292. * FLAC__stream_encoder_new().
  87293. * - The program overrides the default settings using
  87294. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  87295. * functions should be called:
  87296. * - FLAC__stream_encoder_set_channels()
  87297. * - FLAC__stream_encoder_set_bits_per_sample()
  87298. * - FLAC__stream_encoder_set_sample_rate()
  87299. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  87300. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  87301. * - If the application wants to control the compression level or set its own
  87302. * metadata, then the following should also be called:
  87303. * - FLAC__stream_encoder_set_compression_level()
  87304. * - FLAC__stream_encoder_set_verify()
  87305. * - FLAC__stream_encoder_set_metadata()
  87306. * - The rest of the set functions should only be called if the client needs
  87307. * exact control over how the audio is compressed; thorough understanding
  87308. * of the FLAC format is necessary to achieve good results.
  87309. * - The program initializes the instance to validate the settings and
  87310. * prepare for encoding using
  87311. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  87312. * or FLAC__stream_encoder_init_file() for native FLAC
  87313. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  87314. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  87315. * - The program calls FLAC__stream_encoder_process() or
  87316. * FLAC__stream_encoder_process_interleaved() to encode data, which
  87317. * subsequently calls the callbacks when there is encoder data ready
  87318. * to be written.
  87319. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  87320. * which causes the encoder to encode any data still in its input pipe,
  87321. * update the metadata with the final encoding statistics if output
  87322. * seeking is possible, and finally reset the encoder to the
  87323. * uninitialized state.
  87324. * - The instance may be used again or deleted with
  87325. * FLAC__stream_encoder_delete().
  87326. *
  87327. * In more detail, the stream encoder functions similarly to the
  87328. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  87329. * callbacks and more options. Typically the client will create a new
  87330. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  87331. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  87332. * calling one of the FLAC__stream_encoder_init_*() functions.
  87333. *
  87334. * Unlike the decoders, the stream encoder has many options that can
  87335. * affect the speed and compression ratio. When setting these parameters
  87336. * you should have some basic knowledge of the format (see the
  87337. * <A HREF="../documentation.html#format">user-level documentation</A>
  87338. * or the <A HREF="../format.html">formal description</A>). The
  87339. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  87340. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  87341. * functions will do this, so make sure to pay attention to the state
  87342. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  87343. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  87344. * before FLAC__stream_encoder_init_*() will take on the defaults from
  87345. * the constructor.
  87346. *
  87347. * There are three initialization functions for native FLAC, one for
  87348. * setting up the encoder to encode FLAC data to the client via
  87349. * callbacks, and two for encoding directly to a file.
  87350. *
  87351. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  87352. * You must also supply a write callback which will be called anytime
  87353. * there is raw encoded data to write. If the client can seek the output
  87354. * it is best to also supply seek and tell callbacks, as this allows the
  87355. * encoder to go back after encoding is finished to write back
  87356. * information that was collected while encoding, like seek point offsets,
  87357. * frame sizes, etc.
  87358. *
  87359. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  87360. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  87361. * filename or open \c FILE*; the encoder will handle all the callbacks
  87362. * internally. You may also supply a progress callback for periodic
  87363. * notification of the encoding progress.
  87364. *
  87365. * There are three similarly-named init functions for encoding to Ogg
  87366. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  87367. * library has been built with Ogg support.
  87368. *
  87369. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  87370. * call the write callback several times, once with the \c fLaC signature,
  87371. * and once for each encoded metadata block. Note that for Ogg FLAC
  87372. * encoding you will usually get at least twice the number of callbacks than
  87373. * with native FLAC, one for the Ogg page header and one for the page body.
  87374. *
  87375. * After initializing the instance, the client may feed audio data to the
  87376. * encoder in one of two ways:
  87377. *
  87378. * - Channel separate, through FLAC__stream_encoder_process() - The client
  87379. * will pass an array of pointers to buffers, one for each channel, to
  87380. * the encoder, each of the same length. The samples need not be
  87381. * block-aligned, but each channel should have the same number of samples.
  87382. * - Channel interleaved, through
  87383. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  87384. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  87385. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87386. * Again, the samples need not be block-aligned but they must be
  87387. * sample-aligned, i.e. the first value should be channel0_sample0 and
  87388. * the last value channelN_sampleM.
  87389. *
  87390. * Note that for either process call, each sample in the buffers should be a
  87391. * signed integer, right-justified to the resolution set by
  87392. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  87393. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  87394. *
  87395. * When the client is finished encoding data, it calls
  87396. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  87397. * data still in its input pipe, and call the metadata callback with the
  87398. * final encoding statistics. Then the instance may be deleted with
  87399. * FLAC__stream_encoder_delete() or initialized again to encode another
  87400. * stream.
  87401. *
  87402. * For programs that write their own metadata, but that do not know the
  87403. * actual metadata until after encoding, it is advantageous to instruct
  87404. * the encoder to write a PADDING block of the correct size, so that
  87405. * instead of rewriting the whole stream after encoding, the program can
  87406. * just overwrite the PADDING block. If only the maximum size of the
  87407. * metadata is known, the program can write a slightly larger padding
  87408. * block, then split it after encoding.
  87409. *
  87410. * Make sure you understand how lengths are calculated. All FLAC metadata
  87411. * blocks have a 4 byte header which contains the type and length. This
  87412. * length does not include the 4 bytes of the header. See the format page
  87413. * for the specification of metadata blocks and their lengths.
  87414. *
  87415. * \note
  87416. * If you are writing the FLAC data to a file via callbacks, make sure it
  87417. * is open for update (e.g. mode "w+" for stdio streams). This is because
  87418. * after the first encoding pass, the encoder will try to seek back to the
  87419. * beginning of the stream, to the STREAMINFO block, to write some data
  87420. * there. (If using FLAC__stream_encoder_init*_file() or
  87421. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  87422. *
  87423. * \note
  87424. * The "set" functions may only be called when the encoder is in the
  87425. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  87426. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  87427. * before FLAC__stream_encoder_init_*(). If this is the case they will
  87428. * return \c true, otherwise \c false.
  87429. *
  87430. * \note
  87431. * FLAC__stream_encoder_finish() resets all settings to the constructor
  87432. * defaults.
  87433. *
  87434. * \{
  87435. */
  87436. /** State values for a FLAC__StreamEncoder.
  87437. *
  87438. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  87439. *
  87440. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  87441. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  87442. * must be deleted with FLAC__stream_encoder_delete().
  87443. */
  87444. typedef enum {
  87445. FLAC__STREAM_ENCODER_OK = 0,
  87446. /**< The encoder is in the normal OK state and samples can be processed. */
  87447. FLAC__STREAM_ENCODER_UNINITIALIZED,
  87448. /**< The encoder is in the uninitialized state; one of the
  87449. * FLAC__stream_encoder_init_*() functions must be called before samples
  87450. * can be processed.
  87451. */
  87452. FLAC__STREAM_ENCODER_OGG_ERROR,
  87453. /**< An error occurred in the underlying Ogg layer. */
  87454. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  87455. /**< An error occurred in the underlying verify stream decoder;
  87456. * check FLAC__stream_encoder_get_verify_decoder_state().
  87457. */
  87458. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  87459. /**< The verify decoder detected a mismatch between the original
  87460. * audio signal and the decoded audio signal.
  87461. */
  87462. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  87463. /**< One of the callbacks returned a fatal error. */
  87464. FLAC__STREAM_ENCODER_IO_ERROR,
  87465. /**< An I/O error occurred while opening/reading/writing a file.
  87466. * Check \c errno.
  87467. */
  87468. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  87469. /**< An error occurred while writing the stream; usually, the
  87470. * write_callback returned an error.
  87471. */
  87472. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  87473. /**< Memory allocation failed. */
  87474. } FLAC__StreamEncoderState;
  87475. /** Maps a FLAC__StreamEncoderState to a C string.
  87476. *
  87477. * Using a FLAC__StreamEncoderState as the index to this array
  87478. * will give the string equivalent. The contents should not be modified.
  87479. */
  87480. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  87481. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  87482. */
  87483. typedef enum {
  87484. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  87485. /**< Initialization was successful. */
  87486. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  87487. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  87488. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  87489. /**< The library was not compiled with support for the given container
  87490. * format.
  87491. */
  87492. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  87493. /**< A required callback was not supplied. */
  87494. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  87495. /**< The encoder has an invalid setting for number of channels. */
  87496. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  87497. /**< The encoder has an invalid setting for bits-per-sample.
  87498. * FLAC supports 4-32 bps but the reference encoder currently supports
  87499. * only up to 24 bps.
  87500. */
  87501. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  87502. /**< The encoder has an invalid setting for the input sample rate. */
  87503. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  87504. /**< The encoder has an invalid setting for the block size. */
  87505. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  87506. /**< The encoder has an invalid setting for the maximum LPC order. */
  87507. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  87508. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  87509. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  87510. /**< The specified block size is less than the maximum LPC order. */
  87511. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  87512. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  87513. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  87514. /**< The metadata input to the encoder is invalid, in one of the following ways:
  87515. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  87516. * - One of the metadata blocks contains an undefined type
  87517. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  87518. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  87519. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  87520. */
  87521. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  87522. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  87523. * already initialized, usually because
  87524. * FLAC__stream_encoder_finish() was not called.
  87525. */
  87526. } FLAC__StreamEncoderInitStatus;
  87527. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  87528. *
  87529. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  87530. * will give the string equivalent. The contents should not be modified.
  87531. */
  87532. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  87533. /** Return values for the FLAC__StreamEncoder read callback.
  87534. */
  87535. typedef enum {
  87536. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  87537. /**< The read was OK and decoding can continue. */
  87538. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  87539. /**< The read was attempted at the end of the stream. */
  87540. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  87541. /**< An unrecoverable error occurred. */
  87542. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  87543. /**< Client does not support reading back from the output. */
  87544. } FLAC__StreamEncoderReadStatus;
  87545. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  87546. *
  87547. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  87548. * will give the string equivalent. The contents should not be modified.
  87549. */
  87550. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  87551. /** Return values for the FLAC__StreamEncoder write callback.
  87552. */
  87553. typedef enum {
  87554. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  87555. /**< The write was OK and encoding can continue. */
  87556. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  87557. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  87558. } FLAC__StreamEncoderWriteStatus;
  87559. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  87560. *
  87561. * Using a FLAC__StreamEncoderWriteStatus 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__StreamEncoderWriteStatusString[];
  87565. /** Return values for the FLAC__StreamEncoder seek callback.
  87566. */
  87567. typedef enum {
  87568. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  87569. /**< The seek was OK and encoding can continue. */
  87570. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  87571. /**< An unrecoverable error occurred. */
  87572. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87573. /**< Client does not support seeking. */
  87574. } FLAC__StreamEncoderSeekStatus;
  87575. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  87576. *
  87577. * Using a FLAC__StreamEncoderSeekStatus 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__StreamEncoderSeekStatusString[];
  87581. /** Return values for the FLAC__StreamEncoder tell callback.
  87582. */
  87583. typedef enum {
  87584. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  87585. /**< The tell was OK and encoding can continue. */
  87586. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  87587. /**< An unrecoverable error occurred. */
  87588. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87589. /**< Client does not support seeking. */
  87590. } FLAC__StreamEncoderTellStatus;
  87591. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  87592. *
  87593. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  87594. * will give the string equivalent. The contents should not be modified.
  87595. */
  87596. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  87597. /***********************************************************************
  87598. *
  87599. * class FLAC__StreamEncoder
  87600. *
  87601. ***********************************************************************/
  87602. struct FLAC__StreamEncoderProtected;
  87603. struct FLAC__StreamEncoderPrivate;
  87604. /** The opaque structure definition for the stream encoder type.
  87605. * See the \link flac_stream_encoder stream encoder module \endlink
  87606. * for a detailed description.
  87607. */
  87608. typedef struct {
  87609. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  87610. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  87611. } FLAC__StreamEncoder;
  87612. /** Signature for the read callback.
  87613. *
  87614. * A function pointer matching this signature must be passed to
  87615. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  87616. * The supplied function will be called when the encoder needs to read back
  87617. * encoded data. This happens during the metadata callback, when the encoder
  87618. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  87619. * while encoding. The address of the buffer to be filled is supplied, along
  87620. * with the number of bytes the buffer can hold. The callback may choose to
  87621. * supply less data and modify the byte count but must be careful not to
  87622. * overflow the buffer. The callback then returns a status code chosen from
  87623. * FLAC__StreamEncoderReadStatus.
  87624. *
  87625. * Here is an example of a read callback for stdio streams:
  87626. * \code
  87627. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  87628. * {
  87629. * FILE *file = ((MyClientData*)client_data)->file;
  87630. * if(*bytes > 0) {
  87631. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  87632. * if(ferror(file))
  87633. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  87634. * else if(*bytes == 0)
  87635. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  87636. * else
  87637. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  87638. * }
  87639. * else
  87640. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  87641. * }
  87642. * \endcode
  87643. *
  87644. * \note In general, FLAC__StreamEncoder functions which change the
  87645. * state should not be called on the \a encoder while in the callback.
  87646. *
  87647. * \param encoder The encoder instance calling the callback.
  87648. * \param buffer A pointer to a location for the callee to store
  87649. * data to be encoded.
  87650. * \param bytes A pointer to the size of the buffer. On entry
  87651. * to the callback, it contains the maximum number
  87652. * of bytes that may be stored in \a buffer. The
  87653. * callee must set it to the actual number of bytes
  87654. * stored (0 in case of error or end-of-stream) before
  87655. * returning.
  87656. * \param client_data The callee's client data set through
  87657. * FLAC__stream_encoder_set_client_data().
  87658. * \retval FLAC__StreamEncoderReadStatus
  87659. * The callee's return status.
  87660. */
  87661. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  87662. /** Signature for the write callback.
  87663. *
  87664. * A function pointer matching this signature must be passed to
  87665. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87666. * by the encoder anytime there is raw encoded data ready to write. It may
  87667. * include metadata mixed with encoded audio frames and the data is not
  87668. * guaranteed to be aligned on frame or metadata block boundaries.
  87669. *
  87670. * The only duty of the callback is to write out the \a bytes worth of data
  87671. * in \a buffer to the current position in the output stream. The arguments
  87672. * \a samples and \a current_frame are purely informational. If \a samples
  87673. * is greater than \c 0, then \a current_frame will hold the current frame
  87674. * number that is being written; otherwise it indicates that the write
  87675. * callback is being called to write metadata.
  87676. *
  87677. * \note
  87678. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  87679. * write callback will be called twice when writing each audio
  87680. * frame; once for the page header, and once for the page body.
  87681. * When writing the page header, the \a samples argument to the
  87682. * write callback will be \c 0.
  87683. *
  87684. * \note In general, FLAC__StreamEncoder functions which change the
  87685. * state should not be called on the \a encoder while in the callback.
  87686. *
  87687. * \param encoder The encoder instance calling the callback.
  87688. * \param buffer An array of encoded data of length \a bytes.
  87689. * \param bytes The byte length of \a buffer.
  87690. * \param samples The number of samples encoded by \a buffer.
  87691. * \c 0 has a special meaning; see above.
  87692. * \param current_frame The number of the current frame being encoded.
  87693. * \param client_data The callee's client data set through
  87694. * FLAC__stream_encoder_init_*().
  87695. * \retval FLAC__StreamEncoderWriteStatus
  87696. * The callee's return status.
  87697. */
  87698. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  87699. /** Signature for the seek callback.
  87700. *
  87701. * A function pointer matching this signature may be passed to
  87702. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87703. * when the encoder needs to seek the output stream. The encoder will pass
  87704. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  87705. *
  87706. * Here is an example of a seek callback for stdio streams:
  87707. * \code
  87708. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  87709. * {
  87710. * FILE *file = ((MyClientData*)client_data)->file;
  87711. * if(file == stdin)
  87712. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  87713. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  87714. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  87715. * else
  87716. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  87717. * }
  87718. * \endcode
  87719. *
  87720. * \note In general, FLAC__StreamEncoder functions which change the
  87721. * state should not be called on the \a encoder while in the callback.
  87722. *
  87723. * \param encoder The encoder instance calling the callback.
  87724. * \param absolute_byte_offset The offset from the beginning of the stream
  87725. * to seek to.
  87726. * \param client_data The callee's client data set through
  87727. * FLAC__stream_encoder_init_*().
  87728. * \retval FLAC__StreamEncoderSeekStatus
  87729. * The callee's return status.
  87730. */
  87731. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  87732. /** Signature for the tell callback.
  87733. *
  87734. * A function pointer matching this signature may be passed to
  87735. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87736. * when the encoder needs to know the current position of the output stream.
  87737. *
  87738. * \warning
  87739. * The callback must return the true current byte offset of the output to
  87740. * which the encoder is writing. If you are buffering the output, make
  87741. * sure and take this into account. If you are writing directly to a
  87742. * FILE* from your write callback, ftell() is sufficient. If you are
  87743. * writing directly to a file descriptor from your write callback, you
  87744. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  87745. * these points to rewrite metadata after encoding.
  87746. *
  87747. * Here is an example of a tell callback for stdio streams:
  87748. * \code
  87749. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  87750. * {
  87751. * FILE *file = ((MyClientData*)client_data)->file;
  87752. * off_t pos;
  87753. * if(file == stdin)
  87754. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  87755. * else if((pos = ftello(file)) < 0)
  87756. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  87757. * else {
  87758. * *absolute_byte_offset = (FLAC__uint64)pos;
  87759. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  87760. * }
  87761. * }
  87762. * \endcode
  87763. *
  87764. * \note In general, FLAC__StreamEncoder functions which change the
  87765. * state should not be called on the \a encoder while in the callback.
  87766. *
  87767. * \param encoder The encoder instance calling the callback.
  87768. * \param absolute_byte_offset The address at which to store the current
  87769. * position of the output.
  87770. * \param client_data The callee's client data set through
  87771. * FLAC__stream_encoder_init_*().
  87772. * \retval FLAC__StreamEncoderTellStatus
  87773. * The callee's return status.
  87774. */
  87775. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  87776. /** Signature for the metadata callback.
  87777. *
  87778. * A function pointer matching this signature may be passed to
  87779. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87780. * once at the end of encoding with the populated STREAMINFO structure. This
  87781. * is so the client can seek back to the beginning of the file and write the
  87782. * STREAMINFO block with the correct statistics after encoding (like
  87783. * minimum/maximum frame size and total samples).
  87784. *
  87785. * \note In general, FLAC__StreamEncoder functions which change the
  87786. * state should not be called on the \a encoder while in the callback.
  87787. *
  87788. * \param encoder The encoder instance calling the callback.
  87789. * \param metadata The final populated STREAMINFO block.
  87790. * \param client_data The callee's client data set through
  87791. * FLAC__stream_encoder_init_*().
  87792. */
  87793. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  87794. /** Signature for the progress callback.
  87795. *
  87796. * A function pointer matching this signature may be passed to
  87797. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  87798. * The supplied function will be called when the encoder has finished
  87799. * writing a frame. The \c total_frames_estimate argument to the
  87800. * callback will be based on the value from
  87801. * FLAC__stream_encoder_set_total_samples_estimate().
  87802. *
  87803. * \note In general, FLAC__StreamEncoder functions which change the
  87804. * state should not be called on the \a encoder while in the callback.
  87805. *
  87806. * \param encoder The encoder instance calling the callback.
  87807. * \param bytes_written Bytes written so far.
  87808. * \param samples_written Samples written so far.
  87809. * \param frames_written Frames written so far.
  87810. * \param total_frames_estimate The estimate of the total number of
  87811. * frames to be written.
  87812. * \param client_data The callee's client data set through
  87813. * FLAC__stream_encoder_init_*().
  87814. */
  87815. 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);
  87816. /***********************************************************************
  87817. *
  87818. * Class constructor/destructor
  87819. *
  87820. ***********************************************************************/
  87821. /** Create a new stream encoder instance. The instance is created with
  87822. * default settings; see the individual FLAC__stream_encoder_set_*()
  87823. * functions for each setting's default.
  87824. *
  87825. * \retval FLAC__StreamEncoder*
  87826. * \c NULL if there was an error allocating memory, else the new instance.
  87827. */
  87828. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  87829. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  87830. *
  87831. * \param encoder A pointer to an existing encoder.
  87832. * \assert
  87833. * \code encoder != NULL \endcode
  87834. */
  87835. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  87836. /***********************************************************************
  87837. *
  87838. * Public class method prototypes
  87839. *
  87840. ***********************************************************************/
  87841. /** Set the serial number for the FLAC stream to use in the Ogg container.
  87842. *
  87843. * \note
  87844. * This does not need to be set for native FLAC encoding.
  87845. *
  87846. * \note
  87847. * It is recommended to set a serial number explicitly as the default of '0'
  87848. * may collide with other streams.
  87849. *
  87850. * \default \c 0
  87851. * \param encoder An encoder instance to set.
  87852. * \param serial_number See above.
  87853. * \assert
  87854. * \code encoder != NULL \endcode
  87855. * \retval FLAC__bool
  87856. * \c false if the encoder is already initialized, else \c true.
  87857. */
  87858. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  87859. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  87860. * encoded output by feeding it through an internal decoder and comparing
  87861. * the original signal against the decoded signal. If a mismatch occurs,
  87862. * the process call will return \c false. Note that this will slow the
  87863. * encoding process by the extra time required for decoding and comparison.
  87864. *
  87865. * \default \c false
  87866. * \param encoder An encoder instance to set.
  87867. * \param value Flag value (see above).
  87868. * \assert
  87869. * \code encoder != NULL \endcode
  87870. * \retval FLAC__bool
  87871. * \c false if the encoder is already initialized, else \c true.
  87872. */
  87873. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87874. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  87875. * the encoder will comply with the Subset and will check the
  87876. * settings during FLAC__stream_encoder_init_*() to see if all settings
  87877. * comply. If \c false, the settings may take advantage of the full
  87878. * range that the format allows.
  87879. *
  87880. * Make sure you know what it entails before setting this to \c false.
  87881. *
  87882. * \default \c true
  87883. * \param encoder An encoder instance to set.
  87884. * \param value Flag value (see above).
  87885. * \assert
  87886. * \code encoder != NULL \endcode
  87887. * \retval FLAC__bool
  87888. * \c false if the encoder is already initialized, else \c true.
  87889. */
  87890. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87891. /** Set the number of channels to be encoded.
  87892. *
  87893. * \default \c 2
  87894. * \param encoder An encoder instance to set.
  87895. * \param value See above.
  87896. * \assert
  87897. * \code encoder != NULL \endcode
  87898. * \retval FLAC__bool
  87899. * \c false if the encoder is already initialized, else \c true.
  87900. */
  87901. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  87902. /** Set the sample resolution of the input to be encoded.
  87903. *
  87904. * \warning
  87905. * Do not feed the encoder data that is wider than the value you
  87906. * set here or you will generate an invalid stream.
  87907. *
  87908. * \default \c 16
  87909. * \param encoder An encoder instance to set.
  87910. * \param value See above.
  87911. * \assert
  87912. * \code encoder != NULL \endcode
  87913. * \retval FLAC__bool
  87914. * \c false if the encoder is already initialized, else \c true.
  87915. */
  87916. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  87917. /** Set the sample rate (in Hz) of the input to be encoded.
  87918. *
  87919. * \default \c 44100
  87920. * \param encoder An encoder instance to set.
  87921. * \param value See above.
  87922. * \assert
  87923. * \code encoder != NULL \endcode
  87924. * \retval FLAC__bool
  87925. * \c false if the encoder is already initialized, else \c true.
  87926. */
  87927. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  87928. /** Set the compression level
  87929. *
  87930. * The compression level is roughly proportional to the amount of effort
  87931. * the encoder expends to compress the file. A higher level usually
  87932. * means more computation but higher compression. The default level is
  87933. * suitable for most applications.
  87934. *
  87935. * Currently the levels range from \c 0 (fastest, least compression) to
  87936. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  87937. * treated as \c 8.
  87938. *
  87939. * This function automatically calls the following other \c _set_
  87940. * functions with appropriate values, so the client does not need to
  87941. * unless it specifically wants to override them:
  87942. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  87943. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  87944. * - FLAC__stream_encoder_set_apodization()
  87945. * - FLAC__stream_encoder_set_max_lpc_order()
  87946. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  87947. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  87948. * - FLAC__stream_encoder_set_do_escape_coding()
  87949. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  87950. * - FLAC__stream_encoder_set_min_residual_partition_order()
  87951. * - FLAC__stream_encoder_set_max_residual_partition_order()
  87952. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  87953. *
  87954. * The actual values set for each level are:
  87955. * <table>
  87956. * <tr>
  87957. * <td><b>level</b><td>
  87958. * <td>do mid-side stereo<td>
  87959. * <td>loose mid-side stereo<td>
  87960. * <td>apodization<td>
  87961. * <td>max lpc order<td>
  87962. * <td>qlp coeff precision<td>
  87963. * <td>qlp coeff prec search<td>
  87964. * <td>escape coding<td>
  87965. * <td>exhaustive model search<td>
  87966. * <td>min residual partition order<td>
  87967. * <td>max residual partition order<td>
  87968. * <td>rice parameter search dist<td>
  87969. * </tr>
  87970. * <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>
  87971. * <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>
  87972. * <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>
  87973. * <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>
  87974. * <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>
  87975. * <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>
  87976. * <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>
  87977. * <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>
  87978. * <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>
  87979. * </table>
  87980. *
  87981. * \default \c 5
  87982. * \param encoder An encoder instance to set.
  87983. * \param value See above.
  87984. * \assert
  87985. * \code encoder != NULL \endcode
  87986. * \retval FLAC__bool
  87987. * \c false if the encoder is already initialized, else \c true.
  87988. */
  87989. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  87990. /** Set the blocksize to use while encoding.
  87991. *
  87992. * The number of samples to use per frame. Use \c 0 to let the encoder
  87993. * estimate a blocksize; this is usually best.
  87994. *
  87995. * \default \c 0
  87996. * \param encoder An encoder instance to set.
  87997. * \param value See above.
  87998. * \assert
  87999. * \code encoder != NULL \endcode
  88000. * \retval FLAC__bool
  88001. * \c false if the encoder is already initialized, else \c true.
  88002. */
  88003. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  88004. /** Set to \c true to enable mid-side encoding on stereo input. The
  88005. * number of channels must be 2 for this to have any effect. Set to
  88006. * \c false to use only independent channel coding.
  88007. *
  88008. * \default \c false
  88009. * \param encoder An encoder instance to set.
  88010. * \param value Flag value (see above).
  88011. * \assert
  88012. * \code encoder != NULL \endcode
  88013. * \retval FLAC__bool
  88014. * \c false if the encoder is already initialized, else \c true.
  88015. */
  88016. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88017. /** Set to \c true to enable adaptive switching between mid-side and
  88018. * left-right encoding on stereo input. Set to \c false to use
  88019. * exhaustive searching. Setting this to \c true requires
  88020. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  88021. * \c true in order to have any effect.
  88022. *
  88023. * \default \c false
  88024. * \param encoder An encoder instance to set.
  88025. * \param value Flag value (see above).
  88026. * \assert
  88027. * \code encoder != NULL \endcode
  88028. * \retval FLAC__bool
  88029. * \c false if the encoder is already initialized, else \c true.
  88030. */
  88031. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88032. /** Sets the apodization function(s) the encoder will use when windowing
  88033. * audio data for LPC analysis.
  88034. *
  88035. * The \a specification is a plain ASCII string which specifies exactly
  88036. * which functions to use. There may be more than one (up to 32),
  88037. * separated by \c ';' characters. Some functions take one or more
  88038. * comma-separated arguments in parentheses.
  88039. *
  88040. * The available functions are \c bartlett, \c bartlett_hann,
  88041. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  88042. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  88043. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  88044. *
  88045. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  88046. * (0<STDDEV<=0.5).
  88047. *
  88048. * For \c tukey(P), P specifies the fraction of the window that is
  88049. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  88050. * corresponds to \c hann.
  88051. *
  88052. * Example specifications are \c "blackman" or
  88053. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  88054. *
  88055. * Any function that is specified erroneously is silently dropped. Up
  88056. * to 32 functions are kept, the rest are dropped. If the specification
  88057. * is empty the encoder defaults to \c "tukey(0.5)".
  88058. *
  88059. * When more than one function is specified, then for every subframe the
  88060. * encoder will try each of them separately and choose the window that
  88061. * results in the smallest compressed subframe.
  88062. *
  88063. * Note that each function specified causes the encoder to occupy a
  88064. * floating point array in which to store the window.
  88065. *
  88066. * \default \c "tukey(0.5)"
  88067. * \param encoder An encoder instance to set.
  88068. * \param specification See above.
  88069. * \assert
  88070. * \code encoder != NULL \endcode
  88071. * \code specification != NULL \endcode
  88072. * \retval FLAC__bool
  88073. * \c false if the encoder is already initialized, else \c true.
  88074. */
  88075. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  88076. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  88077. *
  88078. * \default \c 0
  88079. * \param encoder An encoder instance to set.
  88080. * \param value See above.
  88081. * \assert
  88082. * \code encoder != NULL \endcode
  88083. * \retval FLAC__bool
  88084. * \c false if the encoder is already initialized, else \c true.
  88085. */
  88086. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  88087. /** Set the precision, in bits, of the quantized linear predictor
  88088. * coefficients, or \c 0 to let the encoder select it based on the
  88089. * blocksize.
  88090. *
  88091. * \note
  88092. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  88093. * be less than 32.
  88094. *
  88095. * \default \c 0
  88096. * \param encoder An encoder instance to set.
  88097. * \param value See above.
  88098. * \assert
  88099. * \code encoder != NULL \endcode
  88100. * \retval FLAC__bool
  88101. * \c false if the encoder is already initialized, else \c true.
  88102. */
  88103. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  88104. /** Set to \c false to use only the specified quantized linear predictor
  88105. * coefficient precision, or \c true to search neighboring precision
  88106. * values and use the best one.
  88107. *
  88108. * \default \c false
  88109. * \param encoder An encoder instance to set.
  88110. * \param value See above.
  88111. * \assert
  88112. * \code encoder != NULL \endcode
  88113. * \retval FLAC__bool
  88114. * \c false if the encoder is already initialized, else \c true.
  88115. */
  88116. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88117. /** Deprecated. Setting this value has no effect.
  88118. *
  88119. * \default \c false
  88120. * \param encoder An encoder instance to set.
  88121. * \param value See above.
  88122. * \assert
  88123. * \code encoder != NULL \endcode
  88124. * \retval FLAC__bool
  88125. * \c false if the encoder is already initialized, else \c true.
  88126. */
  88127. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88128. /** Set to \c false to let the encoder estimate the best model order
  88129. * based on the residual signal energy, or \c true to force the
  88130. * encoder to evaluate all order models and select the best.
  88131. *
  88132. * \default \c false
  88133. * \param encoder An encoder instance to set.
  88134. * \param value See above.
  88135. * \assert
  88136. * \code encoder != NULL \endcode
  88137. * \retval FLAC__bool
  88138. * \c false if the encoder is already initialized, else \c true.
  88139. */
  88140. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88141. /** Set the minimum partition order to search when coding the residual.
  88142. * This is used in tandem with
  88143. * FLAC__stream_encoder_set_max_residual_partition_order().
  88144. *
  88145. * The partition order determines the context size in the residual.
  88146. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88147. *
  88148. * Set both min and max values to \c 0 to force a single context,
  88149. * whose Rice parameter is based on the residual signal variance.
  88150. * Otherwise, set a min and max order, and the encoder will search
  88151. * all orders, using the mean of each context for its Rice parameter,
  88152. * and use the best.
  88153. *
  88154. * \default \c 0
  88155. * \param encoder An encoder instance to set.
  88156. * \param value See above.
  88157. * \assert
  88158. * \code encoder != NULL \endcode
  88159. * \retval FLAC__bool
  88160. * \c false if the encoder is already initialized, else \c true.
  88161. */
  88162. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88163. /** Set the maximum partition order to search when coding the residual.
  88164. * This is used in tandem with
  88165. * FLAC__stream_encoder_set_min_residual_partition_order().
  88166. *
  88167. * The partition order determines the context size in the residual.
  88168. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88169. *
  88170. * Set both min and max values to \c 0 to force a single context,
  88171. * whose Rice parameter is based on the residual signal variance.
  88172. * Otherwise, set a min and max order, and the encoder will search
  88173. * all orders, using the mean of each context for its Rice parameter,
  88174. * and use the best.
  88175. *
  88176. * \default \c 0
  88177. * \param encoder An encoder instance to set.
  88178. * \param value See above.
  88179. * \assert
  88180. * \code encoder != NULL \endcode
  88181. * \retval FLAC__bool
  88182. * \c false if the encoder is already initialized, else \c true.
  88183. */
  88184. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88185. /** Deprecated. Setting this value has no effect.
  88186. *
  88187. * \default \c 0
  88188. * \param encoder An encoder instance to set.
  88189. * \param value See above.
  88190. * \assert
  88191. * \code encoder != NULL \endcode
  88192. * \retval FLAC__bool
  88193. * \c false if the encoder is already initialized, else \c true.
  88194. */
  88195. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  88196. /** Set an estimate of the total samples that will be encoded.
  88197. * This is merely an estimate and may be set to \c 0 if unknown.
  88198. * This value will be written to the STREAMINFO block before encoding,
  88199. * and can remove the need for the caller to rewrite the value later
  88200. * if the value is known before encoding.
  88201. *
  88202. * \default \c 0
  88203. * \param encoder An encoder instance to set.
  88204. * \param value See above.
  88205. * \assert
  88206. * \code encoder != NULL \endcode
  88207. * \retval FLAC__bool
  88208. * \c false if the encoder is already initialized, else \c true.
  88209. */
  88210. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  88211. /** Set the metadata blocks to be emitted to the stream before encoding.
  88212. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  88213. * array of pointers to metadata blocks. The array is non-const since
  88214. * the encoder may need to change the \a is_last flag inside them, and
  88215. * in some cases update seek point offsets. Otherwise, the encoder will
  88216. * not modify or free the blocks. It is up to the caller to free the
  88217. * metadata blocks after encoding finishes.
  88218. *
  88219. * \note
  88220. * The encoder stores only copies of the pointers in the \a metadata array;
  88221. * the metadata blocks themselves must survive at least until after
  88222. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  88223. *
  88224. * \note
  88225. * The STREAMINFO block is always written and no STREAMINFO block may
  88226. * occur in the supplied array.
  88227. *
  88228. * \note
  88229. * By default the encoder does not create a SEEKTABLE. If one is supplied
  88230. * in the \a metadata array, but the client has specified that it does not
  88231. * support seeking, then the SEEKTABLE will be written verbatim. However
  88232. * by itself this is not very useful as the client will not know the stream
  88233. * offsets for the seekpoints ahead of time. In order to get a proper
  88234. * seektable the client must support seeking. See next note.
  88235. *
  88236. * \note
  88237. * SEEKTABLE blocks are handled specially. Since you will not know
  88238. * the values for the seek point stream offsets, you should pass in
  88239. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  88240. * required sample numbers (or placeholder points), with \c 0 for the
  88241. * \a frame_samples and \a stream_offset fields for each point. If the
  88242. * client has specified that it supports seeking by providing a seek
  88243. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  88244. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  88245. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  88246. * then while it is encoding the encoder will fill the stream offsets in
  88247. * for you and when encoding is finished, it will seek back and write the
  88248. * real values into the SEEKTABLE block in the stream. There are helper
  88249. * routines for manipulating seektable template blocks; see metadata.h:
  88250. * FLAC__metadata_object_seektable_template_*(). If the client does
  88251. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  88252. * will slow down or remove the ability to seek in the FLAC stream.
  88253. *
  88254. * \note
  88255. * The encoder instance \b will modify the first \c SEEKTABLE block
  88256. * as it transforms the template to a valid seektable while encoding,
  88257. * but it is still up to the caller to free all metadata blocks after
  88258. * encoding.
  88259. *
  88260. * \note
  88261. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  88262. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  88263. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  88264. * will simply write it's own into the stream. If no VORBIS_COMMENT
  88265. * block is present in the \a metadata array, libFLAC will write an
  88266. * empty one, containing only the vendor string.
  88267. *
  88268. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  88269. * the second metadata block of the stream. The encoder already supplies
  88270. * the STREAMINFO block automatically. If \a metadata does not contain a
  88271. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  88272. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  88273. * first, the init function will reorder \a metadata by moving the
  88274. * VORBIS_COMMENT block to the front; the relative ordering of the other
  88275. * blocks will remain as they were.
  88276. *
  88277. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  88278. * stream to \c 65535. If \a num_blocks exceeds this the function will
  88279. * return \c false.
  88280. *
  88281. * \default \c NULL, 0
  88282. * \param encoder An encoder instance to set.
  88283. * \param metadata See above.
  88284. * \param num_blocks See above.
  88285. * \assert
  88286. * \code encoder != NULL \endcode
  88287. * \retval FLAC__bool
  88288. * \c false if the encoder is already initialized, else \c true.
  88289. * \c false if the encoder is already initialized, or if
  88290. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  88291. */
  88292. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  88293. /** Get the current encoder state.
  88294. *
  88295. * \param encoder An encoder instance to query.
  88296. * \assert
  88297. * \code encoder != NULL \endcode
  88298. * \retval FLAC__StreamEncoderState
  88299. * The current encoder state.
  88300. */
  88301. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  88302. /** Get the state of the verify stream decoder.
  88303. * Useful when the stream encoder state is
  88304. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  88305. *
  88306. * \param encoder An encoder instance to query.
  88307. * \assert
  88308. * \code encoder != NULL \endcode
  88309. * \retval FLAC__StreamDecoderState
  88310. * The verify stream decoder state.
  88311. */
  88312. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  88313. /** Get the current encoder state as a C string.
  88314. * This version automatically resolves
  88315. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  88316. * verify decoder's state.
  88317. *
  88318. * \param encoder A encoder instance to query.
  88319. * \assert
  88320. * \code encoder != NULL \endcode
  88321. * \retval const char *
  88322. * The encoder state as a C string. Do not modify the contents.
  88323. */
  88324. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  88325. /** Get relevant values about the nature of a verify decoder error.
  88326. * Useful when the stream encoder state is
  88327. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  88328. * be addresses in which the stats will be returned, or NULL if value
  88329. * is not desired.
  88330. *
  88331. * \param encoder An encoder instance to query.
  88332. * \param absolute_sample The absolute sample number of the mismatch.
  88333. * \param frame_number The number of the frame in which the mismatch occurred.
  88334. * \param channel The channel in which the mismatch occurred.
  88335. * \param sample The number of the sample (relative to the frame) in
  88336. * which the mismatch occurred.
  88337. * \param expected The expected value for the sample in question.
  88338. * \param got The actual value returned by the decoder.
  88339. * \assert
  88340. * \code encoder != NULL \endcode
  88341. */
  88342. 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);
  88343. /** Get the "verify" flag.
  88344. *
  88345. * \param encoder An encoder instance to query.
  88346. * \assert
  88347. * \code encoder != NULL \endcode
  88348. * \retval FLAC__bool
  88349. * See FLAC__stream_encoder_set_verify().
  88350. */
  88351. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  88352. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  88353. *
  88354. * \param encoder An encoder instance to query.
  88355. * \assert
  88356. * \code encoder != NULL \endcode
  88357. * \retval FLAC__bool
  88358. * See FLAC__stream_encoder_set_streamable_subset().
  88359. */
  88360. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  88361. /** Get the number of input channels being processed.
  88362. *
  88363. * \param encoder An encoder instance to query.
  88364. * \assert
  88365. * \code encoder != NULL \endcode
  88366. * \retval unsigned
  88367. * See FLAC__stream_encoder_set_channels().
  88368. */
  88369. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  88370. /** Get the input sample resolution setting.
  88371. *
  88372. * \param encoder An encoder instance to query.
  88373. * \assert
  88374. * \code encoder != NULL \endcode
  88375. * \retval unsigned
  88376. * See FLAC__stream_encoder_set_bits_per_sample().
  88377. */
  88378. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  88379. /** Get the input sample rate setting.
  88380. *
  88381. * \param encoder An encoder instance to query.
  88382. * \assert
  88383. * \code encoder != NULL \endcode
  88384. * \retval unsigned
  88385. * See FLAC__stream_encoder_set_sample_rate().
  88386. */
  88387. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  88388. /** Get the blocksize setting.
  88389. *
  88390. * \param encoder An encoder instance to query.
  88391. * \assert
  88392. * \code encoder != NULL \endcode
  88393. * \retval unsigned
  88394. * See FLAC__stream_encoder_set_blocksize().
  88395. */
  88396. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  88397. /** Get the "mid/side stereo coding" flag.
  88398. *
  88399. * \param encoder An encoder instance to query.
  88400. * \assert
  88401. * \code encoder != NULL \endcode
  88402. * \retval FLAC__bool
  88403. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  88404. */
  88405. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  88406. /** Get the "adaptive mid/side switching" flag.
  88407. *
  88408. * \param encoder An encoder instance to query.
  88409. * \assert
  88410. * \code encoder != NULL \endcode
  88411. * \retval FLAC__bool
  88412. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  88413. */
  88414. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  88415. /** Get the maximum LPC order setting.
  88416. *
  88417. * \param encoder An encoder instance to query.
  88418. * \assert
  88419. * \code encoder != NULL \endcode
  88420. * \retval unsigned
  88421. * See FLAC__stream_encoder_set_max_lpc_order().
  88422. */
  88423. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  88424. /** Get the quantized linear predictor coefficient precision setting.
  88425. *
  88426. * \param encoder An encoder instance to query.
  88427. * \assert
  88428. * \code encoder != NULL \endcode
  88429. * \retval unsigned
  88430. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  88431. */
  88432. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  88433. /** Get the qlp coefficient precision search flag.
  88434. *
  88435. * \param encoder An encoder instance to query.
  88436. * \assert
  88437. * \code encoder != NULL \endcode
  88438. * \retval FLAC__bool
  88439. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  88440. */
  88441. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  88442. /** Get the "escape coding" flag.
  88443. *
  88444. * \param encoder An encoder instance to query.
  88445. * \assert
  88446. * \code encoder != NULL \endcode
  88447. * \retval FLAC__bool
  88448. * See FLAC__stream_encoder_set_do_escape_coding().
  88449. */
  88450. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  88451. /** Get the exhaustive model search flag.
  88452. *
  88453. * \param encoder An encoder instance to query.
  88454. * \assert
  88455. * \code encoder != NULL \endcode
  88456. * \retval FLAC__bool
  88457. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  88458. */
  88459. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  88460. /** Get the minimum residual partition order setting.
  88461. *
  88462. * \param encoder An encoder instance to query.
  88463. * \assert
  88464. * \code encoder != NULL \endcode
  88465. * \retval unsigned
  88466. * See FLAC__stream_encoder_set_min_residual_partition_order().
  88467. */
  88468. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  88469. /** Get maximum residual partition order setting.
  88470. *
  88471. * \param encoder An encoder instance to query.
  88472. * \assert
  88473. * \code encoder != NULL \endcode
  88474. * \retval unsigned
  88475. * See FLAC__stream_encoder_set_max_residual_partition_order().
  88476. */
  88477. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  88478. /** Get the Rice parameter search distance setting.
  88479. *
  88480. * \param encoder An encoder instance to query.
  88481. * \assert
  88482. * \code encoder != NULL \endcode
  88483. * \retval unsigned
  88484. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  88485. */
  88486. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  88487. /** Get the previously set estimate of the total samples to be encoded.
  88488. * The encoder merely mimics back the value given to
  88489. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  88490. * other way of knowing how many samples the client will encode.
  88491. *
  88492. * \param encoder An encoder instance to set.
  88493. * \assert
  88494. * \code encoder != NULL \endcode
  88495. * \retval FLAC__uint64
  88496. * See FLAC__stream_encoder_get_total_samples_estimate().
  88497. */
  88498. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  88499. /** Initialize the encoder instance to encode native FLAC streams.
  88500. *
  88501. * This flavor of initialization sets up the encoder to encode to a
  88502. * native FLAC stream. I/O is performed via callbacks to the client.
  88503. * For encoding to a plain file via filename or open \c FILE*,
  88504. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  88505. * provide a simpler interface.
  88506. *
  88507. * This function should be called after FLAC__stream_encoder_new() and
  88508. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88509. * or FLAC__stream_encoder_process_interleaved().
  88510. * initialization succeeded.
  88511. *
  88512. * The call to FLAC__stream_encoder_init_stream() currently will also
  88513. * immediately call the write callback several times, once with the \c fLaC
  88514. * signature, and once for each encoded metadata block.
  88515. *
  88516. * \param encoder An uninitialized encoder instance.
  88517. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  88518. * pointer must not be \c NULL.
  88519. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  88520. * pointer may be \c NULL if seeking is not
  88521. * supported. The encoder uses seeking to go back
  88522. * and write some some stream statistics to the
  88523. * STREAMINFO block; this is recommended but not
  88524. * necessary to create a valid FLAC stream. If
  88525. * \a seek_callback is not \c NULL then a
  88526. * \a tell_callback must also be supplied.
  88527. * Alternatively, a dummy seek callback that just
  88528. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  88529. * may also be supplied, all though this is slightly
  88530. * less efficient for the encoder.
  88531. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  88532. * pointer may be \c NULL if seeking is not
  88533. * supported. If \a seek_callback is \c NULL then
  88534. * this argument will be ignored. If
  88535. * \a seek_callback is not \c NULL then a
  88536. * \a tell_callback must also be supplied.
  88537. * Alternatively, a dummy tell callback that just
  88538. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  88539. * may also be supplied, all though this is slightly
  88540. * less efficient for the encoder.
  88541. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  88542. * pointer may be \c NULL if the callback is not
  88543. * desired. If the client provides a seek callback,
  88544. * this function is not necessary as the encoder
  88545. * will automatically seek back and update the
  88546. * STREAMINFO block. It may also be \c NULL if the
  88547. * client does not support seeking, since it will
  88548. * have no way of going back to update the
  88549. * STREAMINFO. However the client can still supply
  88550. * a callback if it would like to know the details
  88551. * from the STREAMINFO.
  88552. * \param client_data This value will be supplied to callbacks in their
  88553. * \a client_data argument.
  88554. * \assert
  88555. * \code encoder != NULL \endcode
  88556. * \retval FLAC__StreamEncoderInitStatus
  88557. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88558. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88559. */
  88560. 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);
  88561. /** Initialize the encoder instance to encode Ogg FLAC streams.
  88562. *
  88563. * This flavor of initialization sets up the encoder to encode to a FLAC
  88564. * stream in an Ogg container. I/O is performed via callbacks to the
  88565. * client. For encoding to a plain file via filename or open \c FILE*,
  88566. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  88567. * provide a simpler interface.
  88568. *
  88569. * This function should be called after FLAC__stream_encoder_new() and
  88570. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88571. * or FLAC__stream_encoder_process_interleaved().
  88572. * initialization succeeded.
  88573. *
  88574. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  88575. * immediately call the write callback several times to write the metadata
  88576. * packets.
  88577. *
  88578. * \param encoder An uninitialized encoder instance.
  88579. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  88580. * pointer must not be \c NULL if \a seek_callback
  88581. * is non-NULL since they are both needed to be
  88582. * able to write data back to the Ogg FLAC stream
  88583. * in the post-encode phase.
  88584. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  88585. * pointer must not be \c NULL.
  88586. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  88587. * pointer may be \c NULL if seeking is not
  88588. * supported. The encoder uses seeking to go back
  88589. * and write some some stream statistics to the
  88590. * STREAMINFO block; this is recommended but not
  88591. * necessary to create a valid FLAC stream. If
  88592. * \a seek_callback is not \c NULL then a
  88593. * \a tell_callback must also be supplied.
  88594. * Alternatively, a dummy seek callback that just
  88595. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  88596. * may also be supplied, all though this is slightly
  88597. * less efficient for the encoder.
  88598. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  88599. * pointer may be \c NULL if seeking is not
  88600. * supported. If \a seek_callback is \c NULL then
  88601. * this argument will be ignored. If
  88602. * \a seek_callback is not \c NULL then a
  88603. * \a tell_callback must also be supplied.
  88604. * Alternatively, a dummy tell callback that just
  88605. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  88606. * may also be supplied, all though this is slightly
  88607. * less efficient for the encoder.
  88608. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  88609. * pointer may be \c NULL if the callback is not
  88610. * desired. If the client provides a seek callback,
  88611. * this function is not necessary as the encoder
  88612. * will automatically seek back and update the
  88613. * STREAMINFO block. It may also be \c NULL if the
  88614. * client does not support seeking, since it will
  88615. * have no way of going back to update the
  88616. * STREAMINFO. However the client can still supply
  88617. * a callback if it would like to know the details
  88618. * from the STREAMINFO.
  88619. * \param client_data This value will be supplied to callbacks in their
  88620. * \a client_data argument.
  88621. * \assert
  88622. * \code encoder != NULL \endcode
  88623. * \retval FLAC__StreamEncoderInitStatus
  88624. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88625. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88626. */
  88627. 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);
  88628. /** Initialize the encoder instance to encode native FLAC files.
  88629. *
  88630. * This flavor of initialization sets up the encoder to encode to a
  88631. * plain native FLAC file. For non-stdio streams, you must use
  88632. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  88633. *
  88634. * This function should be called after FLAC__stream_encoder_new() and
  88635. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88636. * or FLAC__stream_encoder_process_interleaved().
  88637. * initialization succeeded.
  88638. *
  88639. * \param encoder An uninitialized encoder instance.
  88640. * \param file An open file. The file should have been opened
  88641. * with mode \c "w+b" and rewound. The file
  88642. * becomes owned by the encoder and should not be
  88643. * manipulated by the client while encoding.
  88644. * Unless \a file is \c stdout, it will be closed
  88645. * when FLAC__stream_encoder_finish() is called.
  88646. * Note however that a proper SEEKTABLE cannot be
  88647. * created when encoding to \c stdout since it is
  88648. * not seekable.
  88649. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88650. * pointer may be \c NULL if the callback is not
  88651. * desired.
  88652. * \param client_data This value will be supplied to callbacks in their
  88653. * \a client_data argument.
  88654. * \assert
  88655. * \code encoder != NULL \endcode
  88656. * \code file != NULL \endcode
  88657. * \retval FLAC__StreamEncoderInitStatus
  88658. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88659. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88660. */
  88661. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88662. /** Initialize the encoder instance to encode Ogg FLAC files.
  88663. *
  88664. * This flavor of initialization sets up the encoder to encode to a
  88665. * plain Ogg FLAC file. For non-stdio streams, you must use
  88666. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  88667. *
  88668. * This function should be called after FLAC__stream_encoder_new() and
  88669. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88670. * or FLAC__stream_encoder_process_interleaved().
  88671. * initialization succeeded.
  88672. *
  88673. * \param encoder An uninitialized encoder instance.
  88674. * \param file An open file. The file should have been opened
  88675. * with mode \c "w+b" and rewound. The file
  88676. * becomes owned by the encoder and should not be
  88677. * manipulated by the client while encoding.
  88678. * Unless \a file is \c stdout, it will be closed
  88679. * when FLAC__stream_encoder_finish() is called.
  88680. * Note however that a proper SEEKTABLE cannot be
  88681. * created when encoding to \c stdout since it is
  88682. * not seekable.
  88683. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88684. * pointer may be \c NULL if the callback is not
  88685. * desired.
  88686. * \param client_data This value will be supplied to callbacks in their
  88687. * \a client_data argument.
  88688. * \assert
  88689. * \code encoder != NULL \endcode
  88690. * \code file != NULL \endcode
  88691. * \retval FLAC__StreamEncoderInitStatus
  88692. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88693. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88694. */
  88695. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88696. /** Initialize the encoder instance to encode native FLAC files.
  88697. *
  88698. * This flavor of initialization sets up the encoder to encode to a plain
  88699. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  88700. * with Unicode filenames on Windows), you must use
  88701. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  88702. * and provide callbacks for the I/O.
  88703. *
  88704. * This function should be called after FLAC__stream_encoder_new() and
  88705. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88706. * or FLAC__stream_encoder_process_interleaved().
  88707. * initialization succeeded.
  88708. *
  88709. * \param encoder An uninitialized encoder instance.
  88710. * \param filename The name of the file to encode to. The file will
  88711. * be opened with fopen(). Use \c NULL to encode to
  88712. * \c stdout. Note however that a proper SEEKTABLE
  88713. * cannot be created when encoding to \c stdout since
  88714. * it is not seekable.
  88715. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88716. * pointer may be \c NULL if the callback is not
  88717. * desired.
  88718. * \param client_data This value will be supplied to callbacks in their
  88719. * \a client_data argument.
  88720. * \assert
  88721. * \code encoder != NULL \endcode
  88722. * \retval FLAC__StreamEncoderInitStatus
  88723. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88724. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88725. */
  88726. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88727. /** Initialize the encoder instance to encode Ogg FLAC files.
  88728. *
  88729. * This flavor of initialization sets up the encoder to encode to a plain
  88730. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  88731. * with Unicode filenames on Windows), you must use
  88732. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  88733. * and provide callbacks for the I/O.
  88734. *
  88735. * This function should be called after FLAC__stream_encoder_new() and
  88736. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88737. * or FLAC__stream_encoder_process_interleaved().
  88738. * initialization succeeded.
  88739. *
  88740. * \param encoder An uninitialized encoder instance.
  88741. * \param filename The name of the file to encode to. The file will
  88742. * be opened with fopen(). Use \c NULL to encode to
  88743. * \c stdout. Note however that a proper SEEKTABLE
  88744. * cannot be created when encoding to \c stdout since
  88745. * it is not seekable.
  88746. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88747. * pointer may be \c NULL if the callback is not
  88748. * desired.
  88749. * \param client_data This value will be supplied to callbacks in their
  88750. * \a client_data argument.
  88751. * \assert
  88752. * \code encoder != NULL \endcode
  88753. * \retval FLAC__StreamEncoderInitStatus
  88754. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88755. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88756. */
  88757. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88758. /** Finish the encoding process.
  88759. * Flushes the encoding buffer, releases resources, resets the encoder
  88760. * settings to their defaults, and returns the encoder state to
  88761. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  88762. * one or more write callbacks before returning, and will generate
  88763. * a metadata callback.
  88764. *
  88765. * Note that in the course of processing the last frame, errors can
  88766. * occur, so the caller should be sure to check the return value to
  88767. * ensure the file was encoded properly.
  88768. *
  88769. * In the event of a prematurely-terminated encode, it is not strictly
  88770. * necessary to call this immediately before FLAC__stream_encoder_delete()
  88771. * but it is good practice to match every FLAC__stream_encoder_init_*()
  88772. * with a FLAC__stream_encoder_finish().
  88773. *
  88774. * \param encoder An uninitialized encoder instance.
  88775. * \assert
  88776. * \code encoder != NULL \endcode
  88777. * \retval FLAC__bool
  88778. * \c false if an error occurred processing the last frame; or if verify
  88779. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  88780. * verify mismatch; else \c true. If \c false, caller should check the
  88781. * state with FLAC__stream_encoder_get_state() for more information
  88782. * about the error.
  88783. */
  88784. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  88785. /** Submit data for encoding.
  88786. * This version allows you to supply the input data via an array of
  88787. * pointers, each pointer pointing to an array of \a samples samples
  88788. * representing one channel. The samples need not be block-aligned,
  88789. * but each channel should have the same number of samples. Each sample
  88790. * should be a signed integer, right-justified to the resolution set by
  88791. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88792. * resolution is 16 bits per sample, the samples should all be in the
  88793. * range [-32768,32767].
  88794. *
  88795. * For applications where channel order is important, channels must
  88796. * follow the order as described in the
  88797. * <A HREF="../format.html#frame_header">frame header</A>.
  88798. *
  88799. * \param encoder An initialized encoder instance in the OK state.
  88800. * \param buffer An array of pointers to each channel's signal.
  88801. * \param samples The number of samples in one channel.
  88802. * \assert
  88803. * \code encoder != NULL \endcode
  88804. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88805. * \retval FLAC__bool
  88806. * \c true if successful, else \c false; in this case, check the
  88807. * encoder state with FLAC__stream_encoder_get_state() to see what
  88808. * went wrong.
  88809. */
  88810. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  88811. /** Submit data for encoding.
  88812. * This version allows you to supply the input data where the channels
  88813. * are interleaved into a single array (i.e. channel0_sample0,
  88814. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  88815. * The samples need not be block-aligned but they must be
  88816. * sample-aligned, i.e. the first value should be channel0_sample0
  88817. * and the last value channelN_sampleM. Each sample should be a signed
  88818. * integer, right-justified to the resolution set by
  88819. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88820. * resolution is 16 bits per sample, the samples should all be in the
  88821. * range [-32768,32767].
  88822. *
  88823. * For applications where channel order is important, channels must
  88824. * follow the order as described in the
  88825. * <A HREF="../format.html#frame_header">frame header</A>.
  88826. *
  88827. * \param encoder An initialized encoder instance in the OK state.
  88828. * \param buffer An array of channel-interleaved data (see above).
  88829. * \param samples The number of samples in one channel, the same as for
  88830. * FLAC__stream_encoder_process(). For example, if
  88831. * encoding two channels, \c 1000 \a samples corresponds
  88832. * to a \a buffer of 2000 values.
  88833. * \assert
  88834. * \code encoder != NULL \endcode
  88835. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88836. * \retval FLAC__bool
  88837. * \c true if successful, else \c false; in this case, check the
  88838. * encoder state with FLAC__stream_encoder_get_state() to see what
  88839. * went wrong.
  88840. */
  88841. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  88842. /* \} */
  88843. #ifdef __cplusplus
  88844. }
  88845. #endif
  88846. #endif
  88847. /*** End of inlined file: stream_encoder.h ***/
  88848. #ifdef _MSC_VER
  88849. /* OPT: an MSVC built-in would be better */
  88850. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  88851. {
  88852. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  88853. return (x>>16) | (x<<16);
  88854. }
  88855. #endif
  88856. #if defined(_MSC_VER) && defined(_X86_)
  88857. /* OPT: an MSVC built-in would be better */
  88858. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  88859. {
  88860. __asm {
  88861. mov edx, start
  88862. mov ecx, len
  88863. test ecx, ecx
  88864. loop1:
  88865. jz done1
  88866. mov eax, [edx]
  88867. bswap eax
  88868. mov [edx], eax
  88869. add edx, 4
  88870. dec ecx
  88871. jmp short loop1
  88872. done1:
  88873. }
  88874. }
  88875. #endif
  88876. /** \mainpage
  88877. *
  88878. * \section intro Introduction
  88879. *
  88880. * This is the documentation for the FLAC C and C++ APIs. It is
  88881. * highly interconnected; this introduction should give you a top
  88882. * level idea of the structure and how to find the information you
  88883. * need. As a prerequisite you should have at least a basic
  88884. * knowledge of the FLAC format, documented
  88885. * <A HREF="../format.html">here</A>.
  88886. *
  88887. * \section c_api FLAC C API
  88888. *
  88889. * The FLAC C API is the interface to libFLAC, a set of structures
  88890. * describing the components of FLAC streams, and functions for
  88891. * encoding and decoding streams, as well as manipulating FLAC
  88892. * metadata in files. The public include files will be installed
  88893. * in your include area (for example /usr/include/FLAC/...).
  88894. *
  88895. * By writing a little code and linking against libFLAC, it is
  88896. * relatively easy to add FLAC support to another program. The
  88897. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  88898. * Complete source code of libFLAC as well as the command-line
  88899. * encoder and plugins is available and is a useful source of
  88900. * examples.
  88901. *
  88902. * Aside from encoders and decoders, libFLAC provides a powerful
  88903. * metadata interface for manipulating metadata in FLAC files. It
  88904. * allows the user to add, delete, and modify FLAC metadata blocks
  88905. * and it can automatically take advantage of PADDING blocks to avoid
  88906. * rewriting the entire FLAC file when changing the size of the
  88907. * metadata.
  88908. *
  88909. * libFLAC usually only requires the standard C library and C math
  88910. * library. In particular, threading is not used so there is no
  88911. * dependency on a thread library. However, libFLAC does not use
  88912. * global variables and should be thread-safe.
  88913. *
  88914. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  88915. * However the metadata editing interfaces currently have limited
  88916. * read-only support for Ogg FLAC files.
  88917. *
  88918. * \section cpp_api FLAC C++ API
  88919. *
  88920. * The FLAC C++ API is a set of classes that encapsulate the
  88921. * structures and functions in libFLAC. They provide slightly more
  88922. * functionality with respect to metadata but are otherwise
  88923. * equivalent. For the most part, they share the same usage as
  88924. * their counterparts in libFLAC, and the FLAC C API documentation
  88925. * can be used as a supplement. The public include files
  88926. * for the C++ API will be installed in your include area (for
  88927. * example /usr/include/FLAC++/...).
  88928. *
  88929. * libFLAC++ is also licensed under
  88930. * <A HREF="../license.html">Xiph's BSD license</A>.
  88931. *
  88932. * \section getting_started Getting Started
  88933. *
  88934. * A good starting point for learning the API is to browse through
  88935. * the <A HREF="modules.html">modules</A>. Modules are logical
  88936. * groupings of related functions or classes, which correspond roughly
  88937. * to header files or sections of header files. Each module includes a
  88938. * detailed description of the general usage of its functions or
  88939. * classes.
  88940. *
  88941. * From there you can go on to look at the documentation of
  88942. * individual functions. You can see different views of the individual
  88943. * functions through the links in top bar across this page.
  88944. *
  88945. * If you prefer a more hands-on approach, you can jump right to some
  88946. * <A HREF="../documentation_example_code.html">example code</A>.
  88947. *
  88948. * \section porting_guide Porting Guide
  88949. *
  88950. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  88951. * has been introduced which gives detailed instructions on how to
  88952. * port your code to newer versions of FLAC.
  88953. *
  88954. * \section embedded_developers Embedded Developers
  88955. *
  88956. * libFLAC has grown larger over time as more functionality has been
  88957. * included, but much of it may be unnecessary for a particular embedded
  88958. * implementation. Unused parts may be pruned by some simple editing of
  88959. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  88960. * metadata interface are all independent from each other.
  88961. *
  88962. * It is easiest to just describe the dependencies:
  88963. *
  88964. * - All modules depend on the \link flac_format Format \endlink module.
  88965. * - The decoders and encoders depend on the bitbuffer.
  88966. * - The decoder is independent of the encoder. The encoder uses the
  88967. * decoder because of the verify feature, but this can be removed if
  88968. * not needed.
  88969. * - Parts of the metadata interface require the stream decoder (but not
  88970. * the encoder).
  88971. * - Ogg support is selectable through the compile time macro
  88972. * \c FLAC__HAS_OGG.
  88973. *
  88974. * For example, if your application only requires the stream decoder, no
  88975. * encoder, and no metadata interface, you can remove the stream encoder
  88976. * and the metadata interface, which will greatly reduce the size of the
  88977. * library.
  88978. *
  88979. * Also, there are several places in the libFLAC code with comments marked
  88980. * with "OPT:" where a #define can be changed to enable code that might be
  88981. * faster on a specific platform. Experimenting with these can yield faster
  88982. * binaries.
  88983. */
  88984. /** \defgroup porting Porting Guide for New Versions
  88985. *
  88986. * This module describes differences in the library interfaces from
  88987. * version to version. It assists in the porting of code that uses
  88988. * the libraries to newer versions of FLAC.
  88989. *
  88990. * One simple facility for making porting easier that has been added
  88991. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  88992. * library's includes (e.g. \c include/FLAC/export.h). The
  88993. * \c #defines mirror the libraries'
  88994. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  88995. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  88996. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  88997. * These can be used to support multiple versions of an API during the
  88998. * transition phase, e.g.
  88999. *
  89000. * \code
  89001. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  89002. * legacy code
  89003. * #else
  89004. * new code
  89005. * #endif
  89006. * \endcode
  89007. *
  89008. * The the source will work for multiple versions and the legacy code can
  89009. * easily be removed when the transition is complete.
  89010. *
  89011. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  89012. * include/FLAC/export.h), which can be used to determine whether or not
  89013. * the library has been compiled with support for Ogg FLAC. This is
  89014. * simpler than trying to call an Ogg init function and catching the
  89015. * error.
  89016. */
  89017. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  89018. * \ingroup porting
  89019. *
  89020. * \brief
  89021. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  89022. *
  89023. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  89024. * been simplified. First, libOggFLAC has been merged into libFLAC and
  89025. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  89026. * decoding layers and three encoding layers have been merged into a
  89027. * single stream decoder and stream encoder. That is, the functionality
  89028. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  89029. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  89030. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  89031. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  89032. * is there is now a single API that can be used to encode or decode
  89033. * streams to/from native FLAC or Ogg FLAC and the single API can work
  89034. * on both seekable and non-seekable streams.
  89035. *
  89036. * Instead of creating an encoder or decoder of a certain layer, now the
  89037. * client will always create a FLAC__StreamEncoder or
  89038. * FLAC__StreamDecoder. The old layers are now differentiated by the
  89039. * initialization function. For example, for the decoder,
  89040. * FLAC__stream_decoder_init() has been replaced by
  89041. * FLAC__stream_decoder_init_stream(). This init function takes
  89042. * callbacks for the I/O, and the seeking callbacks are optional. This
  89043. * allows the client to use the same object for seekable and
  89044. * non-seekable streams. For decoding a FLAC file directly, the client
  89045. * can use FLAC__stream_decoder_init_file() and pass just a filename
  89046. * and fewer callbacks; most of the other callbacks are supplied
  89047. * internally. For situations where fopen()ing by filename is not
  89048. * possible (e.g. Unicode filenames on Windows) the client can instead
  89049. * open the file itself and supply the FILE* to
  89050. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  89051. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  89052. * Since the callbacks and client data are now passed to the init
  89053. * function, the FLAC__stream_decoder_set_*_callback() functions and
  89054. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  89055. * rest of the calls to the decoder are the same as before.
  89056. *
  89057. * There are counterpart init functions for Ogg FLAC, e.g.
  89058. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  89059. * and callbacks are the same as for native FLAC.
  89060. *
  89061. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  89062. * been set up like so:
  89063. *
  89064. * \code
  89065. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  89066. * if(decoder == NULL) do_something;
  89067. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  89068. * [... other settings ...]
  89069. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  89070. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  89071. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  89072. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  89073. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  89074. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  89075. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  89076. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  89077. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  89078. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  89079. * \endcode
  89080. *
  89081. * In FLAC 1.1.3 it is like this:
  89082. *
  89083. * \code
  89084. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  89085. * if(decoder == NULL) do_something;
  89086. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  89087. * [... other settings ...]
  89088. * if(FLAC__stream_decoder_init_stream(
  89089. * decoder,
  89090. * my_read_callback,
  89091. * my_seek_callback, // or NULL
  89092. * my_tell_callback, // or NULL
  89093. * my_length_callback, // or NULL
  89094. * my_eof_callback, // or NULL
  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 you could do;
  89103. *
  89104. * \code
  89105. * [...]
  89106. * FILE *file = fopen("somefile.flac","rb");
  89107. * if(file == NULL) do_somthing;
  89108. * if(FLAC__stream_decoder_init_FILE(
  89109. * decoder,
  89110. * file,
  89111. * my_write_callback,
  89112. * my_metadata_callback, // or NULL
  89113. * my_error_callback,
  89114. * my_client_data
  89115. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89116. * \endcode
  89117. *
  89118. * or just:
  89119. *
  89120. * \code
  89121. * [...]
  89122. * if(FLAC__stream_decoder_init_file(
  89123. * decoder,
  89124. * "somefile.flac",
  89125. * my_write_callback,
  89126. * my_metadata_callback, // or NULL
  89127. * my_error_callback,
  89128. * my_client_data
  89129. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89130. * \endcode
  89131. *
  89132. * Another small change to the decoder is in how it handles unparseable
  89133. * streams. Before, when the decoder found an unparseable stream
  89134. * (reserved for when the decoder encounters a stream from a future
  89135. * encoder that it can't parse), it changed the state to
  89136. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  89137. * drops sync and calls the error callback with a new error code
  89138. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  89139. * more robust. If your error callback does not discriminate on the the
  89140. * error state, your code does not need to be changed.
  89141. *
  89142. * The encoder now has a new setting:
  89143. * FLAC__stream_encoder_set_apodization(). This is for setting the
  89144. * method used to window the data before LPC analysis. You only need to
  89145. * add a call to this function if the default is not suitable. There
  89146. * are also two new convenience functions that may be useful:
  89147. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  89148. * FLAC__metadata_get_cuesheet().
  89149. *
  89150. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  89151. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  89152. * is now \c size_t instead of \c unsigned.
  89153. */
  89154. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  89155. * \ingroup porting
  89156. *
  89157. * \brief
  89158. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  89159. *
  89160. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  89161. * There was a slight change in the implementation of
  89162. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  89163. * of the \a metadata array of pointers so the client no longer needs
  89164. * to maintain it after the call. The objects themselves that are
  89165. * pointed to by the array are still not copied though and must be
  89166. * maintained until the call to FLAC__stream_encoder_finish().
  89167. */
  89168. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  89169. * \ingroup porting
  89170. *
  89171. * \brief
  89172. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  89173. *
  89174. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  89175. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  89176. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  89177. *
  89178. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  89179. * has changed to reflect the conversion of one of the reserved bits
  89180. * into active use. It used to be \c 2 and now is \c 1. However the
  89181. * FLAC frame header length has not changed, so to skip the proper
  89182. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  89183. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  89184. */
  89185. /** \defgroup flac FLAC C API
  89186. *
  89187. * The FLAC C API is the interface to libFLAC, a set of structures
  89188. * describing the components of FLAC streams, and functions for
  89189. * encoding and decoding streams, as well as manipulating FLAC
  89190. * metadata in files.
  89191. *
  89192. * You should start with the format components as all other modules
  89193. * are dependent on it.
  89194. */
  89195. #endif
  89196. /*** End of inlined file: all.h ***/
  89197. /*** Start of inlined file: bitmath.c ***/
  89198. /*** Start of inlined file: juce_FlacHeader.h ***/
  89199. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89200. // tasks..
  89201. #define VERSION "1.2.1"
  89202. #define FLAC__NO_DLL 1
  89203. #if JUCE_MSVC
  89204. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89205. #endif
  89206. #if JUCE_MAC
  89207. #define FLAC__SYS_DARWIN 1
  89208. #endif
  89209. /*** End of inlined file: juce_FlacHeader.h ***/
  89210. #if JUCE_USE_FLAC
  89211. #if HAVE_CONFIG_H
  89212. # include <config.h>
  89213. #endif
  89214. /*** Start of inlined file: bitmath.h ***/
  89215. #ifndef FLAC__PRIVATE__BITMATH_H
  89216. #define FLAC__PRIVATE__BITMATH_H
  89217. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  89218. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  89219. unsigned FLAC__bitmath_silog2(int v);
  89220. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  89221. #endif
  89222. /*** End of inlined file: bitmath.h ***/
  89223. /* An example of what FLAC__bitmath_ilog2() computes:
  89224. *
  89225. * ilog2( 0) = assertion failure
  89226. * ilog2( 1) = 0
  89227. * ilog2( 2) = 1
  89228. * ilog2( 3) = 1
  89229. * ilog2( 4) = 2
  89230. * ilog2( 5) = 2
  89231. * ilog2( 6) = 2
  89232. * ilog2( 7) = 2
  89233. * ilog2( 8) = 3
  89234. * ilog2( 9) = 3
  89235. * ilog2(10) = 3
  89236. * ilog2(11) = 3
  89237. * ilog2(12) = 3
  89238. * ilog2(13) = 3
  89239. * ilog2(14) = 3
  89240. * ilog2(15) = 3
  89241. * ilog2(16) = 4
  89242. * ilog2(17) = 4
  89243. * ilog2(18) = 4
  89244. */
  89245. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  89246. {
  89247. unsigned l = 0;
  89248. FLAC__ASSERT(v > 0);
  89249. while(v >>= 1)
  89250. l++;
  89251. return l;
  89252. }
  89253. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  89254. {
  89255. unsigned l = 0;
  89256. FLAC__ASSERT(v > 0);
  89257. while(v >>= 1)
  89258. l++;
  89259. return l;
  89260. }
  89261. /* An example of what FLAC__bitmath_silog2() computes:
  89262. *
  89263. * silog2(-10) = 5
  89264. * silog2(- 9) = 5
  89265. * silog2(- 8) = 4
  89266. * silog2(- 7) = 4
  89267. * silog2(- 6) = 4
  89268. * silog2(- 5) = 4
  89269. * silog2(- 4) = 3
  89270. * silog2(- 3) = 3
  89271. * silog2(- 2) = 2
  89272. * silog2(- 1) = 2
  89273. * silog2( 0) = 0
  89274. * silog2( 1) = 2
  89275. * silog2( 2) = 3
  89276. * silog2( 3) = 3
  89277. * silog2( 4) = 4
  89278. * silog2( 5) = 4
  89279. * silog2( 6) = 4
  89280. * silog2( 7) = 4
  89281. * silog2( 8) = 5
  89282. * silog2( 9) = 5
  89283. * silog2( 10) = 5
  89284. */
  89285. unsigned FLAC__bitmath_silog2(int v)
  89286. {
  89287. while(1) {
  89288. if(v == 0) {
  89289. return 0;
  89290. }
  89291. else if(v > 0) {
  89292. unsigned l = 0;
  89293. while(v) {
  89294. l++;
  89295. v >>= 1;
  89296. }
  89297. return l+1;
  89298. }
  89299. else if(v == -1) {
  89300. return 2;
  89301. }
  89302. else {
  89303. v++;
  89304. v = -v;
  89305. }
  89306. }
  89307. }
  89308. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  89309. {
  89310. while(1) {
  89311. if(v == 0) {
  89312. return 0;
  89313. }
  89314. else if(v > 0) {
  89315. unsigned l = 0;
  89316. while(v) {
  89317. l++;
  89318. v >>= 1;
  89319. }
  89320. return l+1;
  89321. }
  89322. else if(v == -1) {
  89323. return 2;
  89324. }
  89325. else {
  89326. v++;
  89327. v = -v;
  89328. }
  89329. }
  89330. }
  89331. #endif
  89332. /*** End of inlined file: bitmath.c ***/
  89333. /*** Start of inlined file: bitreader.c ***/
  89334. /*** Start of inlined file: juce_FlacHeader.h ***/
  89335. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89336. // tasks..
  89337. #define VERSION "1.2.1"
  89338. #define FLAC__NO_DLL 1
  89339. #if JUCE_MSVC
  89340. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89341. #endif
  89342. #if JUCE_MAC
  89343. #define FLAC__SYS_DARWIN 1
  89344. #endif
  89345. /*** End of inlined file: juce_FlacHeader.h ***/
  89346. #if JUCE_USE_FLAC
  89347. #if HAVE_CONFIG_H
  89348. # include <config.h>
  89349. #endif
  89350. #include <stdlib.h> /* for malloc() */
  89351. #include <string.h> /* for memcpy(), memset() */
  89352. #ifdef _MSC_VER
  89353. #include <winsock.h> /* for ntohl() */
  89354. #elif defined FLAC__SYS_DARWIN
  89355. #include <machine/endian.h> /* for ntohl() */
  89356. #elif defined __MINGW32__
  89357. #include <winsock.h> /* for ntohl() */
  89358. #else
  89359. #include <netinet/in.h> /* for ntohl() */
  89360. #endif
  89361. /*** Start of inlined file: bitreader.h ***/
  89362. #ifndef FLAC__PRIVATE__BITREADER_H
  89363. #define FLAC__PRIVATE__BITREADER_H
  89364. #include <stdio.h> /* for FILE */
  89365. /*** Start of inlined file: cpu.h ***/
  89366. #ifndef FLAC__PRIVATE__CPU_H
  89367. #define FLAC__PRIVATE__CPU_H
  89368. #ifdef HAVE_CONFIG_H
  89369. #include <config.h>
  89370. #endif
  89371. typedef enum {
  89372. FLAC__CPUINFO_TYPE_IA32,
  89373. FLAC__CPUINFO_TYPE_PPC,
  89374. FLAC__CPUINFO_TYPE_UNKNOWN
  89375. } FLAC__CPUInfo_Type;
  89376. typedef struct {
  89377. FLAC__bool cpuid;
  89378. FLAC__bool bswap;
  89379. FLAC__bool cmov;
  89380. FLAC__bool mmx;
  89381. FLAC__bool fxsr;
  89382. FLAC__bool sse;
  89383. FLAC__bool sse2;
  89384. FLAC__bool sse3;
  89385. FLAC__bool ssse3;
  89386. FLAC__bool _3dnow;
  89387. FLAC__bool ext3dnow;
  89388. FLAC__bool extmmx;
  89389. } FLAC__CPUInfo_IA32;
  89390. typedef struct {
  89391. FLAC__bool altivec;
  89392. FLAC__bool ppc64;
  89393. } FLAC__CPUInfo_PPC;
  89394. typedef struct {
  89395. FLAC__bool use_asm;
  89396. FLAC__CPUInfo_Type type;
  89397. union {
  89398. FLAC__CPUInfo_IA32 ia32;
  89399. FLAC__CPUInfo_PPC ppc;
  89400. } data;
  89401. } FLAC__CPUInfo;
  89402. void FLAC__cpu_info(FLAC__CPUInfo *info);
  89403. #ifndef FLAC__NO_ASM
  89404. #ifdef FLAC__CPU_IA32
  89405. #ifdef FLAC__HAS_NASM
  89406. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  89407. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  89408. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  89409. #endif
  89410. #endif
  89411. #endif
  89412. #endif
  89413. /*** End of inlined file: cpu.h ***/
  89414. /*
  89415. * opaque structure definition
  89416. */
  89417. struct FLAC__BitReader;
  89418. typedef struct FLAC__BitReader FLAC__BitReader;
  89419. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  89420. /*
  89421. * construction, deletion, initialization, etc functions
  89422. */
  89423. FLAC__BitReader *FLAC__bitreader_new(void);
  89424. void FLAC__bitreader_delete(FLAC__BitReader *br);
  89425. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  89426. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  89427. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  89428. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  89429. /*
  89430. * CRC functions
  89431. */
  89432. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  89433. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  89434. /*
  89435. * info functions
  89436. */
  89437. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  89438. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  89439. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  89440. /*
  89441. * read functions
  89442. */
  89443. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  89444. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  89445. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  89446. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  89447. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  89448. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  89449. 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! */
  89450. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  89451. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  89452. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  89453. #ifndef FLAC__NO_ASM
  89454. # ifdef FLAC__CPU_IA32
  89455. # ifdef FLAC__HAS_NASM
  89456. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  89457. # endif
  89458. # endif
  89459. #endif
  89460. #if 0 /* UNUSED */
  89461. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  89462. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  89463. #endif
  89464. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  89465. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  89466. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  89467. #endif
  89468. /*** End of inlined file: bitreader.h ***/
  89469. /*** Start of inlined file: crc.h ***/
  89470. #ifndef FLAC__PRIVATE__CRC_H
  89471. #define FLAC__PRIVATE__CRC_H
  89472. /* 8 bit CRC generator, MSB shifted first
  89473. ** polynomial = x^8 + x^2 + x^1 + x^0
  89474. ** init = 0
  89475. */
  89476. extern FLAC__byte const FLAC__crc8_table[256];
  89477. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  89478. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  89479. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  89480. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  89481. /* 16 bit CRC generator, MSB shifted first
  89482. ** polynomial = x^16 + x^15 + x^2 + x^0
  89483. ** init = 0
  89484. */
  89485. extern unsigned FLAC__crc16_table[256];
  89486. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  89487. /* this alternate may be faster on some systems/compilers */
  89488. #if 0
  89489. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  89490. #endif
  89491. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  89492. #endif
  89493. /*** End of inlined file: crc.h ***/
  89494. /* Things should be fastest when this matches the machine word size */
  89495. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  89496. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  89497. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  89498. typedef FLAC__uint32 brword;
  89499. #define FLAC__BYTES_PER_WORD 4
  89500. #define FLAC__BITS_PER_WORD 32
  89501. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  89502. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  89503. #if WORDS_BIGENDIAN
  89504. #define SWAP_BE_WORD_TO_HOST(x) (x)
  89505. #else
  89506. #if defined (_MSC_VER) && defined (_X86_)
  89507. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  89508. #else
  89509. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  89510. #endif
  89511. #endif
  89512. /* counts the # of zero MSBs in a word */
  89513. #define COUNT_ZERO_MSBS(word) ( \
  89514. (word) <= 0xffff ? \
  89515. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  89516. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  89517. )
  89518. /* this alternate might be slightly faster on some systems/compilers: */
  89519. #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])) )
  89520. /*
  89521. * This should be at least twice as large as the largest number of words
  89522. * required to represent any 'number' (in any encoding) you are going to
  89523. * read. With FLAC this is on the order of maybe a few hundred bits.
  89524. * If the buffer is smaller than that, the decoder won't be able to read
  89525. * in a whole number that is in a variable length encoding (e.g. Rice).
  89526. * But to be practical it should be at least 1K bytes.
  89527. *
  89528. * Increase this number to decrease the number of read callbacks, at the
  89529. * expense of using more memory. Or decrease for the reverse effect,
  89530. * keeping in mind the limit from the first paragraph. The optimal size
  89531. * also depends on the CPU cache size and other factors; some twiddling
  89532. * may be necessary to squeeze out the best performance.
  89533. */
  89534. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  89535. static const unsigned char byte_to_unary_table[] = {
  89536. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  89537. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  89538. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  89539. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  89540. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89541. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89542. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89543. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  89552. };
  89553. #ifdef min
  89554. #undef min
  89555. #endif
  89556. #define min(x,y) ((x)<(y)?(x):(y))
  89557. #ifdef max
  89558. #undef max
  89559. #endif
  89560. #define max(x,y) ((x)>(y)?(x):(y))
  89561. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89562. #ifdef _MSC_VER
  89563. #define FLAC__U64L(x) x
  89564. #else
  89565. #define FLAC__U64L(x) x##LLU
  89566. #endif
  89567. #ifndef FLaC__INLINE
  89568. #define FLaC__INLINE
  89569. #endif
  89570. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  89571. struct FLAC__BitReader {
  89572. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  89573. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  89574. brword *buffer;
  89575. unsigned capacity; /* in words */
  89576. unsigned words; /* # of completed words in buffer */
  89577. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  89578. unsigned consumed_words; /* #words ... */
  89579. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  89580. unsigned read_crc16; /* the running frame CRC */
  89581. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  89582. FLAC__BitReaderReadCallback read_callback;
  89583. void *client_data;
  89584. FLAC__CPUInfo cpu_info;
  89585. };
  89586. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  89587. {
  89588. register unsigned crc = br->read_crc16;
  89589. #if FLAC__BYTES_PER_WORD == 4
  89590. switch(br->crc16_align) {
  89591. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  89592. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  89593. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  89594. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  89595. }
  89596. #elif FLAC__BYTES_PER_WORD == 8
  89597. switch(br->crc16_align) {
  89598. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  89599. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  89600. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  89601. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  89602. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  89603. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  89604. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  89605. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  89606. }
  89607. #else
  89608. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  89609. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  89610. br->read_crc16 = crc;
  89611. #endif
  89612. br->crc16_align = 0;
  89613. }
  89614. /* would be static except it needs to be called by asm routines */
  89615. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  89616. {
  89617. unsigned start, end;
  89618. size_t bytes;
  89619. FLAC__byte *target;
  89620. /* first shift the unconsumed buffer data toward the front as much as possible */
  89621. if(br->consumed_words > 0) {
  89622. start = br->consumed_words;
  89623. end = br->words + (br->bytes? 1:0);
  89624. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  89625. br->words -= start;
  89626. br->consumed_words = 0;
  89627. }
  89628. /*
  89629. * set the target for reading, taking into account word alignment and endianness
  89630. */
  89631. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  89632. if(bytes == 0)
  89633. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  89634. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  89635. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  89636. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  89637. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  89638. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  89639. * ^^-------target, bytes=3
  89640. * on LE machines, have to byteswap the odd tail word so nothing is
  89641. * overwritten:
  89642. */
  89643. #if WORDS_BIGENDIAN
  89644. #else
  89645. if(br->bytes)
  89646. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  89647. #endif
  89648. /* now it looks like:
  89649. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  89650. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  89651. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  89652. * ^^-------target, bytes=3
  89653. */
  89654. /* read in the data; note that the callback may return a smaller number of bytes */
  89655. if(!br->read_callback(target, &bytes, br->client_data))
  89656. return false;
  89657. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  89658. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  89659. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  89660. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  89661. * now have to byteswap on LE machines:
  89662. */
  89663. #if WORDS_BIGENDIAN
  89664. #else
  89665. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  89666. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  89667. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  89668. start = br->words;
  89669. local_swap32_block_(br->buffer + start, end - start);
  89670. }
  89671. else
  89672. # endif
  89673. for(start = br->words; start < end; start++)
  89674. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  89675. #endif
  89676. /* now it looks like:
  89677. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  89678. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  89679. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  89680. * finally we'll update the reader values:
  89681. */
  89682. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  89683. br->words = end / FLAC__BYTES_PER_WORD;
  89684. br->bytes = end % FLAC__BYTES_PER_WORD;
  89685. return true;
  89686. }
  89687. /***********************************************************************
  89688. *
  89689. * Class constructor/destructor
  89690. *
  89691. ***********************************************************************/
  89692. FLAC__BitReader *FLAC__bitreader_new(void)
  89693. {
  89694. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  89695. /* calloc() implies:
  89696. memset(br, 0, sizeof(FLAC__BitReader));
  89697. br->buffer = 0;
  89698. br->capacity = 0;
  89699. br->words = br->bytes = 0;
  89700. br->consumed_words = br->consumed_bits = 0;
  89701. br->read_callback = 0;
  89702. br->client_data = 0;
  89703. */
  89704. return br;
  89705. }
  89706. void FLAC__bitreader_delete(FLAC__BitReader *br)
  89707. {
  89708. FLAC__ASSERT(0 != br);
  89709. FLAC__bitreader_free(br);
  89710. free(br);
  89711. }
  89712. /***********************************************************************
  89713. *
  89714. * Public class methods
  89715. *
  89716. ***********************************************************************/
  89717. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  89718. {
  89719. FLAC__ASSERT(0 != br);
  89720. br->words = br->bytes = 0;
  89721. br->consumed_words = br->consumed_bits = 0;
  89722. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  89723. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  89724. if(br->buffer == 0)
  89725. return false;
  89726. br->read_callback = rcb;
  89727. br->client_data = cd;
  89728. br->cpu_info = cpu;
  89729. return true;
  89730. }
  89731. void FLAC__bitreader_free(FLAC__BitReader *br)
  89732. {
  89733. FLAC__ASSERT(0 != br);
  89734. if(0 != br->buffer)
  89735. free(br->buffer);
  89736. br->buffer = 0;
  89737. br->capacity = 0;
  89738. br->words = br->bytes = 0;
  89739. br->consumed_words = br->consumed_bits = 0;
  89740. br->read_callback = 0;
  89741. br->client_data = 0;
  89742. }
  89743. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  89744. {
  89745. br->words = br->bytes = 0;
  89746. br->consumed_words = br->consumed_bits = 0;
  89747. return true;
  89748. }
  89749. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  89750. {
  89751. unsigned i, j;
  89752. if(br == 0) {
  89753. fprintf(out, "bitreader is NULL\n");
  89754. }
  89755. else {
  89756. 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);
  89757. for(i = 0; i < br->words; i++) {
  89758. fprintf(out, "%08X: ", i);
  89759. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  89760. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  89761. fprintf(out, ".");
  89762. else
  89763. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  89764. fprintf(out, "\n");
  89765. }
  89766. if(br->bytes > 0) {
  89767. fprintf(out, "%08X: ", i);
  89768. for(j = 0; j < br->bytes*8; j++)
  89769. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  89770. fprintf(out, ".");
  89771. else
  89772. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  89773. fprintf(out, "\n");
  89774. }
  89775. }
  89776. }
  89777. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  89778. {
  89779. FLAC__ASSERT(0 != br);
  89780. FLAC__ASSERT(0 != br->buffer);
  89781. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89782. br->read_crc16 = (unsigned)seed;
  89783. br->crc16_align = br->consumed_bits;
  89784. }
  89785. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  89786. {
  89787. FLAC__ASSERT(0 != br);
  89788. FLAC__ASSERT(0 != br->buffer);
  89789. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89790. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  89791. /* CRC any tail bytes in a partially-consumed word */
  89792. if(br->consumed_bits) {
  89793. const brword tail = br->buffer[br->consumed_words];
  89794. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  89795. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  89796. }
  89797. return br->read_crc16;
  89798. }
  89799. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  89800. {
  89801. return ((br->consumed_bits & 7) == 0);
  89802. }
  89803. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  89804. {
  89805. return 8 - (br->consumed_bits & 7);
  89806. }
  89807. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  89808. {
  89809. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  89810. }
  89811. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  89812. {
  89813. FLAC__ASSERT(0 != br);
  89814. FLAC__ASSERT(0 != br->buffer);
  89815. FLAC__ASSERT(bits <= 32);
  89816. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  89817. FLAC__ASSERT(br->consumed_words <= br->words);
  89818. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89819. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89820. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  89821. *val = 0;
  89822. return true;
  89823. }
  89824. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  89825. if(!bitreader_read_from_client_(br))
  89826. return false;
  89827. }
  89828. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89829. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89830. if(br->consumed_bits) {
  89831. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89832. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  89833. const brword word = br->buffer[br->consumed_words];
  89834. if(bits < n) {
  89835. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  89836. br->consumed_bits += bits;
  89837. return true;
  89838. }
  89839. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  89840. bits -= n;
  89841. crc16_update_word_(br, word);
  89842. br->consumed_words++;
  89843. br->consumed_bits = 0;
  89844. 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 */
  89845. *val <<= bits;
  89846. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  89847. br->consumed_bits = bits;
  89848. }
  89849. return true;
  89850. }
  89851. else {
  89852. const brword word = br->buffer[br->consumed_words];
  89853. if(bits < FLAC__BITS_PER_WORD) {
  89854. *val = word >> (FLAC__BITS_PER_WORD-bits);
  89855. br->consumed_bits = bits;
  89856. return true;
  89857. }
  89858. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  89859. *val = word;
  89860. crc16_update_word_(br, word);
  89861. br->consumed_words++;
  89862. return true;
  89863. }
  89864. }
  89865. else {
  89866. /* in this case we're starting our read at a partial tail word;
  89867. * the reader has guaranteed that we have at least 'bits' bits
  89868. * available to read, which makes this case simpler.
  89869. */
  89870. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89871. if(br->consumed_bits) {
  89872. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89873. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  89874. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  89875. br->consumed_bits += bits;
  89876. return true;
  89877. }
  89878. else {
  89879. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  89880. br->consumed_bits += bits;
  89881. return true;
  89882. }
  89883. }
  89884. }
  89885. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  89886. {
  89887. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  89888. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  89889. return false;
  89890. /* sign-extend: */
  89891. *val <<= (32-bits);
  89892. *val >>= (32-bits);
  89893. return true;
  89894. }
  89895. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  89896. {
  89897. FLAC__uint32 hi, lo;
  89898. if(bits > 32) {
  89899. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  89900. return false;
  89901. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  89902. return false;
  89903. *val = hi;
  89904. *val <<= 32;
  89905. *val |= lo;
  89906. }
  89907. else {
  89908. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  89909. return false;
  89910. *val = lo;
  89911. }
  89912. return true;
  89913. }
  89914. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  89915. {
  89916. FLAC__uint32 x8, x32 = 0;
  89917. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89918. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  89919. return false;
  89920. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89921. return false;
  89922. x32 |= (x8 << 8);
  89923. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89924. return false;
  89925. x32 |= (x8 << 16);
  89926. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89927. return false;
  89928. x32 |= (x8 << 24);
  89929. *val = x32;
  89930. return true;
  89931. }
  89932. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  89933. {
  89934. /*
  89935. * OPT: a faster implementation is possible but probably not that useful
  89936. * since this is only called a couple of times in the metadata readers.
  89937. */
  89938. FLAC__ASSERT(0 != br);
  89939. FLAC__ASSERT(0 != br->buffer);
  89940. if(bits > 0) {
  89941. const unsigned n = br->consumed_bits & 7;
  89942. unsigned m;
  89943. FLAC__uint32 x;
  89944. if(n != 0) {
  89945. m = min(8-n, bits);
  89946. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  89947. return false;
  89948. bits -= m;
  89949. }
  89950. m = bits / 8;
  89951. if(m > 0) {
  89952. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  89953. return false;
  89954. bits %= 8;
  89955. }
  89956. if(bits > 0) {
  89957. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  89958. return false;
  89959. }
  89960. }
  89961. return true;
  89962. }
  89963. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  89964. {
  89965. FLAC__uint32 x;
  89966. FLAC__ASSERT(0 != br);
  89967. FLAC__ASSERT(0 != br->buffer);
  89968. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89969. /* step 1: skip over partial head word to get word aligned */
  89970. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89971. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89972. return false;
  89973. nvals--;
  89974. }
  89975. if(0 == nvals)
  89976. return true;
  89977. /* step 2: skip whole words in chunks */
  89978. while(nvals >= FLAC__BYTES_PER_WORD) {
  89979. if(br->consumed_words < br->words) {
  89980. br->consumed_words++;
  89981. nvals -= FLAC__BYTES_PER_WORD;
  89982. }
  89983. else if(!bitreader_read_from_client_(br))
  89984. return false;
  89985. }
  89986. /* step 3: skip any remainder from partial tail bytes */
  89987. while(nvals) {
  89988. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89989. return false;
  89990. nvals--;
  89991. }
  89992. return true;
  89993. }
  89994. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  89995. {
  89996. FLAC__uint32 x;
  89997. FLAC__ASSERT(0 != br);
  89998. FLAC__ASSERT(0 != br->buffer);
  89999. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  90000. /* step 1: read from partial head word to get word aligned */
  90001. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  90002. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90003. return false;
  90004. *val++ = (FLAC__byte)x;
  90005. nvals--;
  90006. }
  90007. if(0 == nvals)
  90008. return true;
  90009. /* step 2: read whole words in chunks */
  90010. while(nvals >= FLAC__BYTES_PER_WORD) {
  90011. if(br->consumed_words < br->words) {
  90012. const brword word = br->buffer[br->consumed_words++];
  90013. #if FLAC__BYTES_PER_WORD == 4
  90014. val[0] = (FLAC__byte)(word >> 24);
  90015. val[1] = (FLAC__byte)(word >> 16);
  90016. val[2] = (FLAC__byte)(word >> 8);
  90017. val[3] = (FLAC__byte)word;
  90018. #elif FLAC__BYTES_PER_WORD == 8
  90019. val[0] = (FLAC__byte)(word >> 56);
  90020. val[1] = (FLAC__byte)(word >> 48);
  90021. val[2] = (FLAC__byte)(word >> 40);
  90022. val[3] = (FLAC__byte)(word >> 32);
  90023. val[4] = (FLAC__byte)(word >> 24);
  90024. val[5] = (FLAC__byte)(word >> 16);
  90025. val[6] = (FLAC__byte)(word >> 8);
  90026. val[7] = (FLAC__byte)word;
  90027. #else
  90028. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  90029. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  90030. #endif
  90031. val += FLAC__BYTES_PER_WORD;
  90032. nvals -= FLAC__BYTES_PER_WORD;
  90033. }
  90034. else if(!bitreader_read_from_client_(br))
  90035. return false;
  90036. }
  90037. /* step 3: read any remainder from partial tail bytes */
  90038. while(nvals) {
  90039. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90040. return false;
  90041. *val++ = (FLAC__byte)x;
  90042. nvals--;
  90043. }
  90044. return true;
  90045. }
  90046. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  90047. #if 0 /* slow but readable version */
  90048. {
  90049. unsigned bit;
  90050. FLAC__ASSERT(0 != br);
  90051. FLAC__ASSERT(0 != br->buffer);
  90052. *val = 0;
  90053. while(1) {
  90054. if(!FLAC__bitreader_read_bit(br, &bit))
  90055. return false;
  90056. if(bit)
  90057. break;
  90058. else
  90059. *val++;
  90060. }
  90061. return true;
  90062. }
  90063. #else
  90064. {
  90065. unsigned i;
  90066. FLAC__ASSERT(0 != br);
  90067. FLAC__ASSERT(0 != br->buffer);
  90068. *val = 0;
  90069. while(1) {
  90070. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  90071. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  90072. if(b) {
  90073. i = COUNT_ZERO_MSBS(b);
  90074. *val += i;
  90075. i++;
  90076. br->consumed_bits += i;
  90077. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  90078. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90079. br->consumed_words++;
  90080. br->consumed_bits = 0;
  90081. }
  90082. return true;
  90083. }
  90084. else {
  90085. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  90086. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90087. br->consumed_words++;
  90088. br->consumed_bits = 0;
  90089. /* didn't find stop bit yet, have to keep going... */
  90090. }
  90091. }
  90092. /* at this point we've eaten up all the whole words; have to try
  90093. * reading through any tail bytes before calling the read callback.
  90094. * this is a repeat of the above logic adjusted for the fact we
  90095. * don't have a whole word. note though if the client is feeding
  90096. * us data a byte at a time (unlikely), br->consumed_bits may not
  90097. * be zero.
  90098. */
  90099. if(br->bytes) {
  90100. const unsigned end = br->bytes * 8;
  90101. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  90102. if(b) {
  90103. i = COUNT_ZERO_MSBS(b);
  90104. *val += i;
  90105. i++;
  90106. br->consumed_bits += i;
  90107. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90108. return true;
  90109. }
  90110. else {
  90111. *val += end - br->consumed_bits;
  90112. br->consumed_bits += end;
  90113. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90114. /* didn't find stop bit yet, have to keep going... */
  90115. }
  90116. }
  90117. if(!bitreader_read_from_client_(br))
  90118. return false;
  90119. }
  90120. }
  90121. #endif
  90122. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  90123. {
  90124. FLAC__uint32 lsbs = 0, msbs = 0;
  90125. unsigned uval;
  90126. FLAC__ASSERT(0 != br);
  90127. FLAC__ASSERT(0 != br->buffer);
  90128. FLAC__ASSERT(parameter <= 31);
  90129. /* read the unary MSBs and end bit */
  90130. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  90131. return false;
  90132. /* read the binary LSBs */
  90133. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  90134. return false;
  90135. /* compose the value */
  90136. uval = (msbs << parameter) | lsbs;
  90137. if(uval & 1)
  90138. *val = -((int)(uval >> 1)) - 1;
  90139. else
  90140. *val = (int)(uval >> 1);
  90141. return true;
  90142. }
  90143. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  90144. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  90145. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  90146. /* OPT: possibly faster version for use with MSVC */
  90147. #ifdef _MSC_VER
  90148. {
  90149. unsigned i;
  90150. unsigned uval = 0;
  90151. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  90152. /* try and get br->consumed_words and br->consumed_bits into register;
  90153. * must remember to flush them back to *br before calling other
  90154. * bitwriter functions that use them, and before returning */
  90155. register unsigned cwords;
  90156. register unsigned cbits;
  90157. FLAC__ASSERT(0 != br);
  90158. FLAC__ASSERT(0 != br->buffer);
  90159. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90160. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90161. FLAC__ASSERT(parameter < 32);
  90162. /* 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 */
  90163. if(nvals == 0)
  90164. return true;
  90165. cbits = br->consumed_bits;
  90166. cwords = br->consumed_words;
  90167. while(1) {
  90168. /* read unary part */
  90169. while(1) {
  90170. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90171. brword b = br->buffer[cwords] << cbits;
  90172. if(b) {
  90173. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  90174. __asm {
  90175. bsr eax, b
  90176. not eax
  90177. and eax, 31
  90178. mov i, eax
  90179. }
  90180. #else
  90181. i = COUNT_ZERO_MSBS(b);
  90182. #endif
  90183. uval += i;
  90184. bits = parameter;
  90185. i++;
  90186. cbits += i;
  90187. if(cbits == FLAC__BITS_PER_WORD) {
  90188. crc16_update_word_(br, br->buffer[cwords]);
  90189. cwords++;
  90190. cbits = 0;
  90191. }
  90192. goto break1;
  90193. }
  90194. else {
  90195. uval += FLAC__BITS_PER_WORD - cbits;
  90196. crc16_update_word_(br, br->buffer[cwords]);
  90197. cwords++;
  90198. cbits = 0;
  90199. /* didn't find stop bit yet, have to keep going... */
  90200. }
  90201. }
  90202. /* at this point we've eaten up all the whole words; have to try
  90203. * reading through any tail bytes before calling the read callback.
  90204. * this is a repeat of the above logic adjusted for the fact we
  90205. * don't have a whole word. note though if the client is feeding
  90206. * us data a byte at a time (unlikely), br->consumed_bits may not
  90207. * be zero.
  90208. */
  90209. if(br->bytes) {
  90210. const unsigned end = br->bytes * 8;
  90211. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  90212. if(b) {
  90213. i = COUNT_ZERO_MSBS(b);
  90214. uval += i;
  90215. bits = parameter;
  90216. i++;
  90217. cbits += i;
  90218. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90219. goto break1;
  90220. }
  90221. else {
  90222. uval += end - cbits;
  90223. cbits += end;
  90224. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90225. /* didn't find stop bit yet, have to keep going... */
  90226. }
  90227. }
  90228. /* flush registers and read; bitreader_read_from_client_() does
  90229. * not touch br->consumed_bits at all but we still need to set
  90230. * it in case it fails and we have to return false.
  90231. */
  90232. br->consumed_bits = cbits;
  90233. br->consumed_words = cwords;
  90234. if(!bitreader_read_from_client_(br))
  90235. return false;
  90236. cwords = br->consumed_words;
  90237. }
  90238. break1:
  90239. /* read binary part */
  90240. FLAC__ASSERT(cwords <= br->words);
  90241. if(bits) {
  90242. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  90243. /* flush registers and read; bitreader_read_from_client_() does
  90244. * not touch br->consumed_bits at all but we still need to set
  90245. * it in case it fails and we have to return false.
  90246. */
  90247. br->consumed_bits = cbits;
  90248. br->consumed_words = cwords;
  90249. if(!bitreader_read_from_client_(br))
  90250. return false;
  90251. cwords = br->consumed_words;
  90252. }
  90253. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90254. if(cbits) {
  90255. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90256. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90257. const brword word = br->buffer[cwords];
  90258. if(bits < n) {
  90259. uval <<= bits;
  90260. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  90261. cbits += bits;
  90262. goto break2;
  90263. }
  90264. uval <<= n;
  90265. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90266. bits -= n;
  90267. crc16_update_word_(br, word);
  90268. cwords++;
  90269. cbits = 0;
  90270. 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 */
  90271. uval <<= bits;
  90272. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  90273. cbits = bits;
  90274. }
  90275. goto break2;
  90276. }
  90277. else {
  90278. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  90279. uval <<= bits;
  90280. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90281. cbits = bits;
  90282. goto break2;
  90283. }
  90284. }
  90285. else {
  90286. /* in this case we're starting our read at a partial tail word;
  90287. * the reader has guaranteed that we have at least 'bits' bits
  90288. * available to read, which makes this case simpler.
  90289. */
  90290. uval <<= bits;
  90291. if(cbits) {
  90292. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90293. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  90294. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  90295. cbits += bits;
  90296. goto break2;
  90297. }
  90298. else {
  90299. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90300. cbits += bits;
  90301. goto break2;
  90302. }
  90303. }
  90304. }
  90305. break2:
  90306. /* compose the value */
  90307. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90308. /* are we done? */
  90309. --nvals;
  90310. if(nvals == 0) {
  90311. br->consumed_bits = cbits;
  90312. br->consumed_words = cwords;
  90313. return true;
  90314. }
  90315. uval = 0;
  90316. ++vals;
  90317. }
  90318. }
  90319. #else
  90320. {
  90321. unsigned i;
  90322. unsigned uval = 0;
  90323. /* try and get br->consumed_words and br->consumed_bits into register;
  90324. * must remember to flush them back to *br before calling other
  90325. * bitwriter functions that use them, and before returning */
  90326. register unsigned cwords;
  90327. register unsigned cbits;
  90328. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  90329. FLAC__ASSERT(0 != br);
  90330. FLAC__ASSERT(0 != br->buffer);
  90331. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90332. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90333. FLAC__ASSERT(parameter < 32);
  90334. /* 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 */
  90335. if(nvals == 0)
  90336. return true;
  90337. cbits = br->consumed_bits;
  90338. cwords = br->consumed_words;
  90339. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90340. while(1) {
  90341. /* read unary part */
  90342. while(1) {
  90343. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90344. brword b = br->buffer[cwords] << cbits;
  90345. if(b) {
  90346. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  90347. asm volatile (
  90348. "bsrl %1, %0;"
  90349. "notl %0;"
  90350. "andl $31, %0;"
  90351. : "=r"(i)
  90352. : "r"(b)
  90353. );
  90354. #else
  90355. i = COUNT_ZERO_MSBS(b);
  90356. #endif
  90357. uval += i;
  90358. cbits += i;
  90359. cbits++; /* skip over stop bit */
  90360. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  90361. crc16_update_word_(br, br->buffer[cwords]);
  90362. cwords++;
  90363. cbits = 0;
  90364. }
  90365. goto break1;
  90366. }
  90367. else {
  90368. uval += FLAC__BITS_PER_WORD - cbits;
  90369. crc16_update_word_(br, br->buffer[cwords]);
  90370. cwords++;
  90371. cbits = 0;
  90372. /* didn't find stop bit yet, have to keep going... */
  90373. }
  90374. }
  90375. /* at this point we've eaten up all the whole words; have to try
  90376. * reading through any tail bytes before calling the read callback.
  90377. * this is a repeat of the above logic adjusted for the fact we
  90378. * don't have a whole word. note though if the client is feeding
  90379. * us data a byte at a time (unlikely), br->consumed_bits may not
  90380. * be zero.
  90381. */
  90382. if(br->bytes) {
  90383. const unsigned end = br->bytes * 8;
  90384. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  90385. if(b) {
  90386. i = COUNT_ZERO_MSBS(b);
  90387. uval += i;
  90388. cbits += i;
  90389. cbits++; /* skip over stop bit */
  90390. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90391. goto break1;
  90392. }
  90393. else {
  90394. uval += end - cbits;
  90395. cbits += end;
  90396. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90397. /* didn't find stop bit yet, have to keep going... */
  90398. }
  90399. }
  90400. /* flush registers and read; bitreader_read_from_client_() does
  90401. * not touch br->consumed_bits at all but we still need to set
  90402. * it in case it fails and we have to return false.
  90403. */
  90404. br->consumed_bits = cbits;
  90405. br->consumed_words = cwords;
  90406. if(!bitreader_read_from_client_(br))
  90407. return false;
  90408. cwords = br->consumed_words;
  90409. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  90410. /* + uval to offset our count by the # of unary bits already
  90411. * consumed before the read, because we will add these back
  90412. * in all at once at break1
  90413. */
  90414. }
  90415. break1:
  90416. ucbits -= uval;
  90417. ucbits--; /* account for stop bit */
  90418. /* read binary part */
  90419. FLAC__ASSERT(cwords <= br->words);
  90420. if(parameter) {
  90421. while(ucbits < parameter) {
  90422. /* flush registers and read; bitreader_read_from_client_() does
  90423. * not touch br->consumed_bits at all but we still need to set
  90424. * it in case it fails and we have to return false.
  90425. */
  90426. br->consumed_bits = cbits;
  90427. br->consumed_words = cwords;
  90428. if(!bitreader_read_from_client_(br))
  90429. return false;
  90430. cwords = br->consumed_words;
  90431. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90432. }
  90433. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90434. if(cbits) {
  90435. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  90436. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90437. const brword word = br->buffer[cwords];
  90438. if(parameter < n) {
  90439. uval <<= parameter;
  90440. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  90441. cbits += parameter;
  90442. }
  90443. else {
  90444. uval <<= n;
  90445. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90446. crc16_update_word_(br, word);
  90447. cwords++;
  90448. cbits = parameter - n;
  90449. 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 */
  90450. uval <<= cbits;
  90451. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  90452. }
  90453. }
  90454. }
  90455. else {
  90456. cbits = parameter;
  90457. uval <<= parameter;
  90458. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  90459. }
  90460. }
  90461. else {
  90462. /* in this case we're starting our read at a partial tail word;
  90463. * the reader has guaranteed that we have at least 'parameter'
  90464. * bits available to read, which makes this case simpler.
  90465. */
  90466. uval <<= parameter;
  90467. if(cbits) {
  90468. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90469. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  90470. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  90471. cbits += parameter;
  90472. }
  90473. else {
  90474. cbits = parameter;
  90475. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  90476. }
  90477. }
  90478. }
  90479. ucbits -= parameter;
  90480. /* compose the value */
  90481. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90482. /* are we done? */
  90483. --nvals;
  90484. if(nvals == 0) {
  90485. br->consumed_bits = cbits;
  90486. br->consumed_words = cwords;
  90487. return true;
  90488. }
  90489. uval = 0;
  90490. ++vals;
  90491. }
  90492. }
  90493. #endif
  90494. #if 0 /* UNUSED */
  90495. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  90496. {
  90497. FLAC__uint32 lsbs = 0, msbs = 0;
  90498. unsigned bit, uval, k;
  90499. FLAC__ASSERT(0 != br);
  90500. FLAC__ASSERT(0 != br->buffer);
  90501. k = FLAC__bitmath_ilog2(parameter);
  90502. /* read the unary MSBs and end bit */
  90503. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  90504. return false;
  90505. /* read the binary LSBs */
  90506. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  90507. return false;
  90508. if(parameter == 1u<<k) {
  90509. /* compose the value */
  90510. uval = (msbs << k) | lsbs;
  90511. }
  90512. else {
  90513. unsigned d = (1 << (k+1)) - parameter;
  90514. if(lsbs >= d) {
  90515. if(!FLAC__bitreader_read_bit(br, &bit))
  90516. return false;
  90517. lsbs <<= 1;
  90518. lsbs |= bit;
  90519. lsbs -= d;
  90520. }
  90521. /* compose the value */
  90522. uval = msbs * parameter + lsbs;
  90523. }
  90524. /* unfold unsigned to signed */
  90525. if(uval & 1)
  90526. *val = -((int)(uval >> 1)) - 1;
  90527. else
  90528. *val = (int)(uval >> 1);
  90529. return true;
  90530. }
  90531. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  90532. {
  90533. FLAC__uint32 lsbs, msbs = 0;
  90534. unsigned bit, k;
  90535. FLAC__ASSERT(0 != br);
  90536. FLAC__ASSERT(0 != br->buffer);
  90537. k = FLAC__bitmath_ilog2(parameter);
  90538. /* read the unary MSBs and end bit */
  90539. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  90540. return false;
  90541. /* read the binary LSBs */
  90542. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  90543. return false;
  90544. if(parameter == 1u<<k) {
  90545. /* compose the value */
  90546. *val = (msbs << k) | lsbs;
  90547. }
  90548. else {
  90549. unsigned d = (1 << (k+1)) - parameter;
  90550. if(lsbs >= d) {
  90551. if(!FLAC__bitreader_read_bit(br, &bit))
  90552. return false;
  90553. lsbs <<= 1;
  90554. lsbs |= bit;
  90555. lsbs -= d;
  90556. }
  90557. /* compose the value */
  90558. *val = msbs * parameter + lsbs;
  90559. }
  90560. return true;
  90561. }
  90562. #endif /* UNUSED */
  90563. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  90564. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  90565. {
  90566. FLAC__uint32 v = 0;
  90567. FLAC__uint32 x;
  90568. unsigned i;
  90569. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90570. return false;
  90571. if(raw)
  90572. raw[(*rawlen)++] = (FLAC__byte)x;
  90573. if(!(x & 0x80)) { /* 0xxxxxxx */
  90574. v = x;
  90575. i = 0;
  90576. }
  90577. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  90578. v = x & 0x1F;
  90579. i = 1;
  90580. }
  90581. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  90582. v = x & 0x0F;
  90583. i = 2;
  90584. }
  90585. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  90586. v = x & 0x07;
  90587. i = 3;
  90588. }
  90589. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  90590. v = x & 0x03;
  90591. i = 4;
  90592. }
  90593. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  90594. v = x & 0x01;
  90595. i = 5;
  90596. }
  90597. else {
  90598. *val = 0xffffffff;
  90599. return true;
  90600. }
  90601. for( ; i; i--) {
  90602. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90603. return false;
  90604. if(raw)
  90605. raw[(*rawlen)++] = (FLAC__byte)x;
  90606. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  90607. *val = 0xffffffff;
  90608. return true;
  90609. }
  90610. v <<= 6;
  90611. v |= (x & 0x3F);
  90612. }
  90613. *val = v;
  90614. return true;
  90615. }
  90616. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  90617. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  90618. {
  90619. FLAC__uint64 v = 0;
  90620. FLAC__uint32 x;
  90621. unsigned i;
  90622. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90623. return false;
  90624. if(raw)
  90625. raw[(*rawlen)++] = (FLAC__byte)x;
  90626. if(!(x & 0x80)) { /* 0xxxxxxx */
  90627. v = x;
  90628. i = 0;
  90629. }
  90630. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  90631. v = x & 0x1F;
  90632. i = 1;
  90633. }
  90634. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  90635. v = x & 0x0F;
  90636. i = 2;
  90637. }
  90638. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  90639. v = x & 0x07;
  90640. i = 3;
  90641. }
  90642. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  90643. v = x & 0x03;
  90644. i = 4;
  90645. }
  90646. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  90647. v = x & 0x01;
  90648. i = 5;
  90649. }
  90650. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  90651. v = 0;
  90652. i = 6;
  90653. }
  90654. else {
  90655. *val = FLAC__U64L(0xffffffffffffffff);
  90656. return true;
  90657. }
  90658. for( ; i; i--) {
  90659. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90660. return false;
  90661. if(raw)
  90662. raw[(*rawlen)++] = (FLAC__byte)x;
  90663. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  90664. *val = FLAC__U64L(0xffffffffffffffff);
  90665. return true;
  90666. }
  90667. v <<= 6;
  90668. v |= (x & 0x3F);
  90669. }
  90670. *val = v;
  90671. return true;
  90672. }
  90673. #endif
  90674. /*** End of inlined file: bitreader.c ***/
  90675. /*** Start of inlined file: bitwriter.c ***/
  90676. /*** Start of inlined file: juce_FlacHeader.h ***/
  90677. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90678. // tasks..
  90679. #define VERSION "1.2.1"
  90680. #define FLAC__NO_DLL 1
  90681. #if JUCE_MSVC
  90682. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90683. #endif
  90684. #if JUCE_MAC
  90685. #define FLAC__SYS_DARWIN 1
  90686. #endif
  90687. /*** End of inlined file: juce_FlacHeader.h ***/
  90688. #if JUCE_USE_FLAC
  90689. #if HAVE_CONFIG_H
  90690. # include <config.h>
  90691. #endif
  90692. #include <stdlib.h> /* for malloc() */
  90693. #include <string.h> /* for memcpy(), memset() */
  90694. #ifdef _MSC_VER
  90695. #include <winsock.h> /* for ntohl() */
  90696. #elif defined FLAC__SYS_DARWIN
  90697. #include <machine/endian.h> /* for ntohl() */
  90698. #elif defined __MINGW32__
  90699. #include <winsock.h> /* for ntohl() */
  90700. #else
  90701. #include <netinet/in.h> /* for ntohl() */
  90702. #endif
  90703. #if 0 /* UNUSED */
  90704. #endif
  90705. /*** Start of inlined file: bitwriter.h ***/
  90706. #ifndef FLAC__PRIVATE__BITWRITER_H
  90707. #define FLAC__PRIVATE__BITWRITER_H
  90708. #include <stdio.h> /* for FILE */
  90709. /*
  90710. * opaque structure definition
  90711. */
  90712. struct FLAC__BitWriter;
  90713. typedef struct FLAC__BitWriter FLAC__BitWriter;
  90714. /*
  90715. * construction, deletion, initialization, etc functions
  90716. */
  90717. FLAC__BitWriter *FLAC__bitwriter_new(void);
  90718. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  90719. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  90720. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  90721. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  90722. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  90723. /*
  90724. * CRC functions
  90725. *
  90726. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  90727. */
  90728. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  90729. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  90730. /*
  90731. * info functions
  90732. */
  90733. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  90734. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  90735. /*
  90736. * direct buffer access
  90737. *
  90738. * there may be no calls on the bitwriter between get and release.
  90739. * the bitwriter continues to own the returned buffer.
  90740. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  90741. */
  90742. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  90743. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  90744. /*
  90745. * write functions
  90746. */
  90747. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  90748. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  90749. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  90750. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  90751. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  90752. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  90753. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  90754. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  90755. #if 0 /* UNUSED */
  90756. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  90757. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  90758. #endif
  90759. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  90760. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  90761. #if 0 /* UNUSED */
  90762. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  90763. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  90764. #endif
  90765. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  90766. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  90767. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  90768. #endif
  90769. /*** End of inlined file: bitwriter.h ***/
  90770. /*** Start of inlined file: alloc.h ***/
  90771. #ifndef FLAC__SHARE__ALLOC_H
  90772. #define FLAC__SHARE__ALLOC_H
  90773. #if HAVE_CONFIG_H
  90774. # include <config.h>
  90775. #endif
  90776. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  90777. * before #including this file, otherwise SIZE_MAX might not be defined
  90778. */
  90779. #include <limits.h> /* for SIZE_MAX */
  90780. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  90781. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  90782. #endif
  90783. #include <stdlib.h> /* for size_t, malloc(), etc */
  90784. #ifndef SIZE_MAX
  90785. # ifndef SIZE_T_MAX
  90786. # ifdef _MSC_VER
  90787. # define SIZE_T_MAX UINT_MAX
  90788. # else
  90789. # error
  90790. # endif
  90791. # endif
  90792. # define SIZE_MAX SIZE_T_MAX
  90793. #endif
  90794. #ifndef FLaC__INLINE
  90795. #define FLaC__INLINE
  90796. #endif
  90797. /* avoid malloc()ing 0 bytes, see:
  90798. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  90799. */
  90800. static FLaC__INLINE void *safe_malloc_(size_t size)
  90801. {
  90802. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90803. if(!size)
  90804. size++;
  90805. return malloc(size);
  90806. }
  90807. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  90808. {
  90809. if(!nmemb || !size)
  90810. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90811. return calloc(nmemb, size);
  90812. }
  90813. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  90814. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  90815. {
  90816. size2 += size1;
  90817. if(size2 < size1)
  90818. return 0;
  90819. return safe_malloc_(size2);
  90820. }
  90821. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  90822. {
  90823. size2 += size1;
  90824. if(size2 < size1)
  90825. return 0;
  90826. size3 += size2;
  90827. if(size3 < size2)
  90828. return 0;
  90829. return safe_malloc_(size3);
  90830. }
  90831. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  90832. {
  90833. size2 += size1;
  90834. if(size2 < size1)
  90835. return 0;
  90836. size3 += size2;
  90837. if(size3 < size2)
  90838. return 0;
  90839. size4 += size3;
  90840. if(size4 < size3)
  90841. return 0;
  90842. return safe_malloc_(size4);
  90843. }
  90844. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  90845. #if 0
  90846. needs support for cases where sizeof(size_t) != 4
  90847. {
  90848. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  90849. if(sizeof(size_t) == 4) {
  90850. if ((double)size1 * (double)size2 < 4294967296.0)
  90851. return malloc(size1*size2);
  90852. }
  90853. return 0;
  90854. }
  90855. #else
  90856. /* better? */
  90857. {
  90858. if(!size1 || !size2)
  90859. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90860. if(size1 > SIZE_MAX / size2)
  90861. return 0;
  90862. return malloc(size1*size2);
  90863. }
  90864. #endif
  90865. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  90866. {
  90867. if(!size1 || !size2 || !size3)
  90868. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90869. if(size1 > SIZE_MAX / size2)
  90870. return 0;
  90871. size1 *= size2;
  90872. if(size1 > SIZE_MAX / size3)
  90873. return 0;
  90874. return malloc(size1*size3);
  90875. }
  90876. /* size1*size2 + size3 */
  90877. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  90878. {
  90879. if(!size1 || !size2)
  90880. return safe_malloc_(size3);
  90881. if(size1 > SIZE_MAX / size2)
  90882. return 0;
  90883. return safe_malloc_add_2op_(size1*size2, size3);
  90884. }
  90885. /* size1 * (size2 + size3) */
  90886. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  90887. {
  90888. if(!size1 || (!size2 && !size3))
  90889. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90890. size2 += size3;
  90891. if(size2 < size3)
  90892. return 0;
  90893. return safe_malloc_mul_2op_(size1, size2);
  90894. }
  90895. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  90896. {
  90897. size2 += size1;
  90898. if(size2 < size1)
  90899. return 0;
  90900. return realloc(ptr, size2);
  90901. }
  90902. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  90903. {
  90904. size2 += size1;
  90905. if(size2 < size1)
  90906. return 0;
  90907. size3 += size2;
  90908. if(size3 < size2)
  90909. return 0;
  90910. return realloc(ptr, size3);
  90911. }
  90912. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  90913. {
  90914. size2 += size1;
  90915. if(size2 < size1)
  90916. return 0;
  90917. size3 += size2;
  90918. if(size3 < size2)
  90919. return 0;
  90920. size4 += size3;
  90921. if(size4 < size3)
  90922. return 0;
  90923. return realloc(ptr, size4);
  90924. }
  90925. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  90926. {
  90927. if(!size1 || !size2)
  90928. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90929. if(size1 > SIZE_MAX / size2)
  90930. return 0;
  90931. return realloc(ptr, size1*size2);
  90932. }
  90933. /* size1 * (size2 + size3) */
  90934. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  90935. {
  90936. if(!size1 || (!size2 && !size3))
  90937. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90938. size2 += size3;
  90939. if(size2 < size3)
  90940. return 0;
  90941. return safe_realloc_mul_2op_(ptr, size1, size2);
  90942. }
  90943. #endif
  90944. /*** End of inlined file: alloc.h ***/
  90945. /* Things should be fastest when this matches the machine word size */
  90946. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  90947. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  90948. typedef FLAC__uint32 bwword;
  90949. #define FLAC__BYTES_PER_WORD 4
  90950. #define FLAC__BITS_PER_WORD 32
  90951. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90952. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  90953. #if WORDS_BIGENDIAN
  90954. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90955. #else
  90956. #ifdef _MSC_VER
  90957. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90958. #else
  90959. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90960. #endif
  90961. #endif
  90962. /*
  90963. * The default capacity here doesn't matter too much. The buffer always grows
  90964. * to hold whatever is written to it. Usually the encoder will stop adding at
  90965. * a frame or metadata block, then write that out and clear the buffer for the
  90966. * next one.
  90967. */
  90968. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  90969. /* When growing, increment 4K at a time */
  90970. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  90971. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  90972. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  90973. #ifdef min
  90974. #undef min
  90975. #endif
  90976. #define min(x,y) ((x)<(y)?(x):(y))
  90977. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90978. #ifdef _MSC_VER
  90979. #define FLAC__U64L(x) x
  90980. #else
  90981. #define FLAC__U64L(x) x##LLU
  90982. #endif
  90983. #ifndef FLaC__INLINE
  90984. #define FLaC__INLINE
  90985. #endif
  90986. struct FLAC__BitWriter {
  90987. bwword *buffer;
  90988. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  90989. unsigned capacity; /* capacity of buffer in words */
  90990. unsigned words; /* # of complete words in buffer */
  90991. unsigned bits; /* # of used bits in accum */
  90992. };
  90993. /* * WATCHOUT: The current implementation only grows the buffer. */
  90994. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  90995. {
  90996. unsigned new_capacity;
  90997. bwword *new_buffer;
  90998. FLAC__ASSERT(0 != bw);
  90999. FLAC__ASSERT(0 != bw->buffer);
  91000. /* calculate total words needed to store 'bits_to_add' additional bits */
  91001. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  91002. /* it's possible (due to pessimism in the growth estimation that
  91003. * leads to this call) that we don't actually need to grow
  91004. */
  91005. if(bw->capacity >= new_capacity)
  91006. return true;
  91007. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  91008. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  91009. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  91010. /* make sure we got everything right */
  91011. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  91012. FLAC__ASSERT(new_capacity > bw->capacity);
  91013. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  91014. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  91015. if(new_buffer == 0)
  91016. return false;
  91017. bw->buffer = new_buffer;
  91018. bw->capacity = new_capacity;
  91019. return true;
  91020. }
  91021. /***********************************************************************
  91022. *
  91023. * Class constructor/destructor
  91024. *
  91025. ***********************************************************************/
  91026. FLAC__BitWriter *FLAC__bitwriter_new(void)
  91027. {
  91028. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  91029. /* note that calloc() sets all members to 0 for us */
  91030. return bw;
  91031. }
  91032. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  91033. {
  91034. FLAC__ASSERT(0 != bw);
  91035. FLAC__bitwriter_free(bw);
  91036. free(bw);
  91037. }
  91038. /***********************************************************************
  91039. *
  91040. * Public class methods
  91041. *
  91042. ***********************************************************************/
  91043. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  91044. {
  91045. FLAC__ASSERT(0 != bw);
  91046. bw->words = bw->bits = 0;
  91047. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  91048. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  91049. if(bw->buffer == 0)
  91050. return false;
  91051. return true;
  91052. }
  91053. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  91054. {
  91055. FLAC__ASSERT(0 != bw);
  91056. if(0 != bw->buffer)
  91057. free(bw->buffer);
  91058. bw->buffer = 0;
  91059. bw->capacity = 0;
  91060. bw->words = bw->bits = 0;
  91061. }
  91062. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  91063. {
  91064. bw->words = bw->bits = 0;
  91065. }
  91066. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  91067. {
  91068. unsigned i, j;
  91069. if(bw == 0) {
  91070. fprintf(out, "bitwriter is NULL\n");
  91071. }
  91072. else {
  91073. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  91074. for(i = 0; i < bw->words; i++) {
  91075. fprintf(out, "%08X: ", i);
  91076. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  91077. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  91078. fprintf(out, "\n");
  91079. }
  91080. if(bw->bits > 0) {
  91081. fprintf(out, "%08X: ", i);
  91082. for(j = 0; j < bw->bits; j++)
  91083. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  91084. fprintf(out, "\n");
  91085. }
  91086. }
  91087. }
  91088. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  91089. {
  91090. const FLAC__byte *buffer;
  91091. size_t bytes;
  91092. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91093. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91094. return false;
  91095. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  91096. FLAC__bitwriter_release_buffer(bw);
  91097. return true;
  91098. }
  91099. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  91100. {
  91101. const FLAC__byte *buffer;
  91102. size_t bytes;
  91103. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91104. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91105. return false;
  91106. *crc = FLAC__crc8(buffer, bytes);
  91107. FLAC__bitwriter_release_buffer(bw);
  91108. return true;
  91109. }
  91110. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  91111. {
  91112. return ((bw->bits & 7) == 0);
  91113. }
  91114. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  91115. {
  91116. return FLAC__TOTAL_BITS(bw);
  91117. }
  91118. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  91119. {
  91120. FLAC__ASSERT((bw->bits & 7) == 0);
  91121. /* double protection */
  91122. if(bw->bits & 7)
  91123. return false;
  91124. /* if we have bits in the accumulator we have to flush those to the buffer first */
  91125. if(bw->bits) {
  91126. FLAC__ASSERT(bw->words <= bw->capacity);
  91127. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  91128. return false;
  91129. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  91130. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  91131. }
  91132. /* now we can just return what we have */
  91133. *buffer = (FLAC__byte*)bw->buffer;
  91134. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  91135. return true;
  91136. }
  91137. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  91138. {
  91139. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  91140. * get-mode' flag could be added everywhere and then cleared here
  91141. */
  91142. (void)bw;
  91143. }
  91144. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  91145. {
  91146. unsigned n;
  91147. FLAC__ASSERT(0 != bw);
  91148. FLAC__ASSERT(0 != bw->buffer);
  91149. if(bits == 0)
  91150. return true;
  91151. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91152. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91153. return false;
  91154. /* first part gets to word alignment */
  91155. if(bw->bits) {
  91156. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  91157. bw->accum <<= n;
  91158. bits -= n;
  91159. bw->bits += n;
  91160. if(bw->bits == FLAC__BITS_PER_WORD) {
  91161. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91162. bw->bits = 0;
  91163. }
  91164. else
  91165. return true;
  91166. }
  91167. /* do whole words */
  91168. while(bits >= FLAC__BITS_PER_WORD) {
  91169. bw->buffer[bw->words++] = 0;
  91170. bits -= FLAC__BITS_PER_WORD;
  91171. }
  91172. /* do any leftovers */
  91173. if(bits > 0) {
  91174. bw->accum = 0;
  91175. bw->bits = bits;
  91176. }
  91177. return true;
  91178. }
  91179. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  91180. {
  91181. register unsigned left;
  91182. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91183. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91184. FLAC__ASSERT(0 != bw);
  91185. FLAC__ASSERT(0 != bw->buffer);
  91186. FLAC__ASSERT(bits <= 32);
  91187. if(bits == 0)
  91188. return true;
  91189. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91190. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91191. return false;
  91192. left = FLAC__BITS_PER_WORD - bw->bits;
  91193. if(bits < left) {
  91194. bw->accum <<= bits;
  91195. bw->accum |= val;
  91196. bw->bits += bits;
  91197. }
  91198. 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 */
  91199. bw->accum <<= left;
  91200. bw->accum |= val >> (bw->bits = bits - left);
  91201. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91202. bw->accum = val;
  91203. }
  91204. else {
  91205. bw->accum = val;
  91206. bw->bits = 0;
  91207. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  91208. }
  91209. return true;
  91210. }
  91211. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  91212. {
  91213. /* zero-out unused bits */
  91214. if(bits < 32)
  91215. val &= (~(0xffffffff << bits));
  91216. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91217. }
  91218. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  91219. {
  91220. /* this could be a little faster but it's not used for much */
  91221. if(bits > 32) {
  91222. return
  91223. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  91224. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  91225. }
  91226. else
  91227. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91228. }
  91229. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  91230. {
  91231. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  91232. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  91233. return false;
  91234. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  91235. return false;
  91236. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  91237. return false;
  91238. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  91239. return false;
  91240. return true;
  91241. }
  91242. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  91243. {
  91244. unsigned i;
  91245. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  91246. for(i = 0; i < nvals; i++) {
  91247. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  91248. return false;
  91249. }
  91250. return true;
  91251. }
  91252. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  91253. {
  91254. if(val < 32)
  91255. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  91256. else
  91257. return
  91258. FLAC__bitwriter_write_zeroes(bw, val) &&
  91259. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  91260. }
  91261. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  91262. {
  91263. FLAC__uint32 uval;
  91264. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  91265. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91266. uval = (val<<1) ^ (val>>31);
  91267. return 1 + parameter + (uval >> parameter);
  91268. }
  91269. #if 0 /* UNUSED */
  91270. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  91271. {
  91272. unsigned bits, msbs, uval;
  91273. unsigned k;
  91274. FLAC__ASSERT(parameter > 0);
  91275. /* fold signed to unsigned */
  91276. if(val < 0)
  91277. uval = (unsigned)(((-(++val)) << 1) + 1);
  91278. else
  91279. uval = (unsigned)(val << 1);
  91280. k = FLAC__bitmath_ilog2(parameter);
  91281. if(parameter == 1u<<k) {
  91282. FLAC__ASSERT(k <= 30);
  91283. msbs = uval >> k;
  91284. bits = 1 + k + msbs;
  91285. }
  91286. else {
  91287. unsigned q, r, d;
  91288. d = (1 << (k+1)) - parameter;
  91289. q = uval / parameter;
  91290. r = uval - (q * parameter);
  91291. bits = 1 + q + k;
  91292. if(r >= d)
  91293. bits++;
  91294. }
  91295. return bits;
  91296. }
  91297. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  91298. {
  91299. unsigned bits, msbs;
  91300. unsigned k;
  91301. FLAC__ASSERT(parameter > 0);
  91302. k = FLAC__bitmath_ilog2(parameter);
  91303. if(parameter == 1u<<k) {
  91304. FLAC__ASSERT(k <= 30);
  91305. msbs = uval >> k;
  91306. bits = 1 + k + msbs;
  91307. }
  91308. else {
  91309. unsigned q, r, d;
  91310. d = (1 << (k+1)) - parameter;
  91311. q = uval / parameter;
  91312. r = uval - (q * parameter);
  91313. bits = 1 + q + k;
  91314. if(r >= d)
  91315. bits++;
  91316. }
  91317. return bits;
  91318. }
  91319. #endif /* UNUSED */
  91320. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  91321. {
  91322. unsigned total_bits, interesting_bits, msbs;
  91323. FLAC__uint32 uval, pattern;
  91324. FLAC__ASSERT(0 != bw);
  91325. FLAC__ASSERT(0 != bw->buffer);
  91326. FLAC__ASSERT(parameter < 8*sizeof(uval));
  91327. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91328. uval = (val<<1) ^ (val>>31);
  91329. msbs = uval >> parameter;
  91330. interesting_bits = 1 + parameter;
  91331. total_bits = interesting_bits + msbs;
  91332. pattern = 1 << parameter; /* the unary end bit */
  91333. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  91334. if(total_bits <= 32)
  91335. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  91336. else
  91337. return
  91338. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  91339. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  91340. }
  91341. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  91342. {
  91343. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  91344. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  91345. FLAC__uint32 uval;
  91346. unsigned left;
  91347. const unsigned lsbits = 1 + parameter;
  91348. unsigned msbits;
  91349. FLAC__ASSERT(0 != bw);
  91350. FLAC__ASSERT(0 != bw->buffer);
  91351. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  91352. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91353. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91354. while(nvals) {
  91355. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91356. uval = (*vals<<1) ^ (*vals>>31);
  91357. msbits = uval >> parameter;
  91358. #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) */
  91359. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  91360. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  91361. bw->bits = bw->bits + msbits + lsbits;
  91362. uval |= mask1; /* set stop bit */
  91363. uval &= mask2; /* mask off unused top bits */
  91364. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  91365. bw->accum <<= msbits;
  91366. bw->accum <<= lsbits;
  91367. bw->accum |= uval;
  91368. if(bw->bits == FLAC__BITS_PER_WORD) {
  91369. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91370. bw->bits = 0;
  91371. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  91372. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  91373. FLAC__ASSERT(bw->capacity == bw->words);
  91374. return false;
  91375. }
  91376. }
  91377. }
  91378. else {
  91379. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  91380. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  91381. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  91382. bw->bits = bw->bits + msbits + lsbits;
  91383. uval |= mask1; /* set stop bit */
  91384. uval &= mask2; /* mask off unused top bits */
  91385. bw->accum <<= msbits + lsbits;
  91386. bw->accum |= uval;
  91387. }
  91388. else {
  91389. #endif
  91390. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91391. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  91392. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  91393. return false;
  91394. if(msbits) {
  91395. /* first part gets to word alignment */
  91396. if(bw->bits) {
  91397. left = FLAC__BITS_PER_WORD - bw->bits;
  91398. if(msbits < left) {
  91399. bw->accum <<= msbits;
  91400. bw->bits += msbits;
  91401. goto break1;
  91402. }
  91403. else {
  91404. bw->accum <<= left;
  91405. msbits -= left;
  91406. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91407. bw->bits = 0;
  91408. }
  91409. }
  91410. /* do whole words */
  91411. while(msbits >= FLAC__BITS_PER_WORD) {
  91412. bw->buffer[bw->words++] = 0;
  91413. msbits -= FLAC__BITS_PER_WORD;
  91414. }
  91415. /* do any leftovers */
  91416. if(msbits > 0) {
  91417. bw->accum = 0;
  91418. bw->bits = msbits;
  91419. }
  91420. }
  91421. break1:
  91422. uval |= mask1; /* set stop bit */
  91423. uval &= mask2; /* mask off unused top bits */
  91424. left = FLAC__BITS_PER_WORD - bw->bits;
  91425. if(lsbits < left) {
  91426. bw->accum <<= lsbits;
  91427. bw->accum |= uval;
  91428. bw->bits += lsbits;
  91429. }
  91430. else {
  91431. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  91432. * be > lsbits (because of previous assertions) so it would have
  91433. * triggered the (lsbits<left) case above.
  91434. */
  91435. FLAC__ASSERT(bw->bits);
  91436. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  91437. bw->accum <<= left;
  91438. bw->accum |= uval >> (bw->bits = lsbits - left);
  91439. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91440. bw->accum = uval;
  91441. }
  91442. #if 1
  91443. }
  91444. #endif
  91445. vals++;
  91446. nvals--;
  91447. }
  91448. return true;
  91449. }
  91450. #if 0 /* UNUSED */
  91451. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  91452. {
  91453. unsigned total_bits, msbs, uval;
  91454. unsigned k;
  91455. FLAC__ASSERT(0 != bw);
  91456. FLAC__ASSERT(0 != bw->buffer);
  91457. FLAC__ASSERT(parameter > 0);
  91458. /* fold signed to unsigned */
  91459. if(val < 0)
  91460. uval = (unsigned)(((-(++val)) << 1) + 1);
  91461. else
  91462. uval = (unsigned)(val << 1);
  91463. k = FLAC__bitmath_ilog2(parameter);
  91464. if(parameter == 1u<<k) {
  91465. unsigned pattern;
  91466. FLAC__ASSERT(k <= 30);
  91467. msbs = uval >> k;
  91468. total_bits = 1 + k + msbs;
  91469. pattern = 1 << k; /* the unary end bit */
  91470. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  91471. if(total_bits <= 32) {
  91472. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  91473. return false;
  91474. }
  91475. else {
  91476. /* write the unary MSBs */
  91477. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  91478. return false;
  91479. /* write the unary end bit and binary LSBs */
  91480. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  91481. return false;
  91482. }
  91483. }
  91484. else {
  91485. unsigned q, r, d;
  91486. d = (1 << (k+1)) - parameter;
  91487. q = uval / parameter;
  91488. r = uval - (q * parameter);
  91489. /* write the unary MSBs */
  91490. if(!FLAC__bitwriter_write_zeroes(bw, q))
  91491. return false;
  91492. /* write the unary end bit */
  91493. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  91494. return false;
  91495. /* write the binary LSBs */
  91496. if(r >= d) {
  91497. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  91498. return false;
  91499. }
  91500. else {
  91501. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  91502. return false;
  91503. }
  91504. }
  91505. return true;
  91506. }
  91507. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  91508. {
  91509. unsigned total_bits, msbs;
  91510. unsigned k;
  91511. FLAC__ASSERT(0 != bw);
  91512. FLAC__ASSERT(0 != bw->buffer);
  91513. FLAC__ASSERT(parameter > 0);
  91514. k = FLAC__bitmath_ilog2(parameter);
  91515. if(parameter == 1u<<k) {
  91516. unsigned pattern;
  91517. FLAC__ASSERT(k <= 30);
  91518. msbs = uval >> k;
  91519. total_bits = 1 + k + msbs;
  91520. pattern = 1 << k; /* the unary end bit */
  91521. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  91522. if(total_bits <= 32) {
  91523. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  91524. return false;
  91525. }
  91526. else {
  91527. /* write the unary MSBs */
  91528. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  91529. return false;
  91530. /* write the unary end bit and binary LSBs */
  91531. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  91532. return false;
  91533. }
  91534. }
  91535. else {
  91536. unsigned q, r, d;
  91537. d = (1 << (k+1)) - parameter;
  91538. q = uval / parameter;
  91539. r = uval - (q * parameter);
  91540. /* write the unary MSBs */
  91541. if(!FLAC__bitwriter_write_zeroes(bw, q))
  91542. return false;
  91543. /* write the unary end bit */
  91544. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  91545. return false;
  91546. /* write the binary LSBs */
  91547. if(r >= d) {
  91548. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  91549. return false;
  91550. }
  91551. else {
  91552. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  91553. return false;
  91554. }
  91555. }
  91556. return true;
  91557. }
  91558. #endif /* UNUSED */
  91559. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  91560. {
  91561. FLAC__bool ok = 1;
  91562. FLAC__ASSERT(0 != bw);
  91563. FLAC__ASSERT(0 != bw->buffer);
  91564. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  91565. if(val < 0x80) {
  91566. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  91567. }
  91568. else if(val < 0x800) {
  91569. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  91570. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91571. }
  91572. else if(val < 0x10000) {
  91573. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  91574. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91575. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91576. }
  91577. else if(val < 0x200000) {
  91578. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  91579. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  91580. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91581. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91582. }
  91583. else if(val < 0x4000000) {
  91584. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  91585. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  91586. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  91587. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91588. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91589. }
  91590. else {
  91591. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  91592. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  91593. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  91594. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  91595. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91596. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91597. }
  91598. return ok;
  91599. }
  91600. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  91601. {
  91602. FLAC__bool ok = 1;
  91603. FLAC__ASSERT(0 != bw);
  91604. FLAC__ASSERT(0 != bw->buffer);
  91605. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  91606. if(val < 0x80) {
  91607. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  91608. }
  91609. else if(val < 0x800) {
  91610. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  91611. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91612. }
  91613. else if(val < 0x10000) {
  91614. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  91615. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91616. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91617. }
  91618. else if(val < 0x200000) {
  91619. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  91620. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91621. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91622. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91623. }
  91624. else if(val < 0x4000000) {
  91625. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  91626. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  91627. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91628. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91629. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91630. }
  91631. else if(val < 0x80000000) {
  91632. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  91633. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  91634. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  91635. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91636. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91637. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91638. }
  91639. else {
  91640. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  91641. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  91642. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  91643. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  91644. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91645. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91646. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91647. }
  91648. return ok;
  91649. }
  91650. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  91651. {
  91652. /* 0-pad to byte boundary */
  91653. if(bw->bits & 7u)
  91654. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  91655. else
  91656. return true;
  91657. }
  91658. #endif
  91659. /*** End of inlined file: bitwriter.c ***/
  91660. /*** Start of inlined file: cpu.c ***/
  91661. /*** Start of inlined file: juce_FlacHeader.h ***/
  91662. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91663. // tasks..
  91664. #define VERSION "1.2.1"
  91665. #define FLAC__NO_DLL 1
  91666. #if JUCE_MSVC
  91667. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91668. #endif
  91669. #if JUCE_MAC
  91670. #define FLAC__SYS_DARWIN 1
  91671. #endif
  91672. /*** End of inlined file: juce_FlacHeader.h ***/
  91673. #if JUCE_USE_FLAC
  91674. #if HAVE_CONFIG_H
  91675. # include <config.h>
  91676. #endif
  91677. #include <stdlib.h>
  91678. #include <stdio.h>
  91679. #if defined FLAC__CPU_IA32
  91680. # include <signal.h>
  91681. #elif defined FLAC__CPU_PPC
  91682. # if !defined FLAC__NO_ASM
  91683. # if defined FLAC__SYS_DARWIN
  91684. # include <sys/sysctl.h>
  91685. # include <mach/mach.h>
  91686. # include <mach/mach_host.h>
  91687. # include <mach/host_info.h>
  91688. # include <mach/machine.h>
  91689. # ifndef CPU_SUBTYPE_POWERPC_970
  91690. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  91691. # endif
  91692. # else /* FLAC__SYS_DARWIN */
  91693. # include <signal.h>
  91694. # include <setjmp.h>
  91695. static sigjmp_buf jmpbuf;
  91696. static volatile sig_atomic_t canjump = 0;
  91697. static void sigill_handler (int sig)
  91698. {
  91699. if (!canjump) {
  91700. signal (sig, SIG_DFL);
  91701. raise (sig);
  91702. }
  91703. canjump = 0;
  91704. siglongjmp (jmpbuf, 1);
  91705. }
  91706. # endif /* FLAC__SYS_DARWIN */
  91707. # endif /* FLAC__NO_ASM */
  91708. #endif /* FLAC__CPU_PPC */
  91709. #if defined (__NetBSD__) || defined(__OpenBSD__)
  91710. #include <sys/param.h>
  91711. #include <sys/sysctl.h>
  91712. #include <machine/cpu.h>
  91713. #endif
  91714. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  91715. #include <sys/types.h>
  91716. #include <sys/sysctl.h>
  91717. #endif
  91718. #if defined(__APPLE__)
  91719. /* how to get sysctlbyname()? */
  91720. #endif
  91721. /* these are flags in EDX of CPUID AX=00000001 */
  91722. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  91723. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  91724. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  91725. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  91726. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  91727. /* these are flags in ECX of CPUID AX=00000001 */
  91728. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  91729. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  91730. /* these are flags in EDX of CPUID AX=80000001 */
  91731. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  91732. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  91733. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  91734. /*
  91735. * Extra stuff needed for detection of OS support for SSE on IA-32
  91736. */
  91737. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  91738. # if defined(__linux__)
  91739. /*
  91740. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  91741. * modify the return address to jump over the offending SSE instruction
  91742. * and also the operation following it that indicates the instruction
  91743. * executed successfully. In this way we use no global variables and
  91744. * stay thread-safe.
  91745. *
  91746. * 3 + 3 + 6:
  91747. * 3 bytes for "xorps xmm0,xmm0"
  91748. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  91749. * 6 bytes extra in case our estimate is wrong
  91750. * 12 bytes puts us in the NOP "landing zone"
  91751. */
  91752. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  91753. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91754. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  91755. {
  91756. (void)signal;
  91757. sc.eip += 3 + 3 + 6;
  91758. }
  91759. # else
  91760. # include <sys/ucontext.h>
  91761. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  91762. {
  91763. (void)signal, (void)si;
  91764. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  91765. }
  91766. # endif
  91767. # elif defined(_MSC_VER)
  91768. # include <windows.h>
  91769. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  91770. # ifdef USE_TRY_CATCH_FLAVOR
  91771. # else
  91772. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  91773. {
  91774. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  91775. ep->ContextRecord->Eip += 3 + 3 + 6;
  91776. return EXCEPTION_CONTINUE_EXECUTION;
  91777. }
  91778. return EXCEPTION_CONTINUE_SEARCH;
  91779. }
  91780. # endif
  91781. # endif
  91782. #endif
  91783. void FLAC__cpu_info(FLAC__CPUInfo *info)
  91784. {
  91785. /*
  91786. * IA32-specific
  91787. */
  91788. #ifdef FLAC__CPU_IA32
  91789. info->type = FLAC__CPUINFO_TYPE_IA32;
  91790. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  91791. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  91792. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  91793. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  91794. info->data.ia32.cmov = false;
  91795. info->data.ia32.mmx = false;
  91796. info->data.ia32.fxsr = false;
  91797. info->data.ia32.sse = false;
  91798. info->data.ia32.sse2 = false;
  91799. info->data.ia32.sse3 = false;
  91800. info->data.ia32.ssse3 = false;
  91801. info->data.ia32._3dnow = false;
  91802. info->data.ia32.ext3dnow = false;
  91803. info->data.ia32.extmmx = false;
  91804. if(info->data.ia32.cpuid) {
  91805. /* http://www.sandpile.org/ia32/cpuid.htm */
  91806. FLAC__uint32 flags_edx, flags_ecx;
  91807. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  91808. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  91809. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  91810. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  91811. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  91812. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  91813. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  91814. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  91815. #ifdef FLAC__USE_3DNOW
  91816. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  91817. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  91818. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  91819. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  91820. #else
  91821. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  91822. #endif
  91823. #ifdef DEBUG
  91824. fprintf(stderr, "CPU info (IA-32):\n");
  91825. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  91826. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  91827. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  91828. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  91829. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  91830. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91831. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  91832. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  91833. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  91834. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  91835. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  91836. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  91837. #endif
  91838. /*
  91839. * now have to check for OS support of SSE/SSE2
  91840. */
  91841. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  91842. #if defined FLAC__NO_SSE_OS
  91843. /* assume user knows better than us; turn it off */
  91844. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91845. #elif defined FLAC__SSE_OS
  91846. /* assume user knows better than us; leave as detected above */
  91847. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  91848. int sse = 0;
  91849. size_t len;
  91850. /* at least one of these must work: */
  91851. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  91852. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  91853. if(!sse)
  91854. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91855. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  91856. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  91857. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  91858. size_t len = sizeof(val);
  91859. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91860. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91861. else { /* double-check SSE2 */
  91862. mib[1] = CPU_SSE2;
  91863. len = sizeof(val);
  91864. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91865. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91866. }
  91867. # else
  91868. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91869. # endif
  91870. #elif defined(__linux__)
  91871. int sse = 0;
  91872. struct sigaction sigill_save;
  91873. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91874. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  91875. #else
  91876. struct sigaction sigill_sse;
  91877. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  91878. __sigemptyset(&sigill_sse.sa_mask);
  91879. 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 */
  91880. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  91881. #endif
  91882. {
  91883. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  91884. /* see sigill_handler_sse_os() for an explanation of the following: */
  91885. asm volatile (
  91886. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  91887. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  91888. "incl %0\n\t" /* SIGILL handler will jump over this */
  91889. /* landing zone */
  91890. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  91891. "nop\n\t"
  91892. "nop\n\t"
  91893. "nop\n\t"
  91894. "nop\n\t"
  91895. "nop\n\t"
  91896. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  91897. "nop\n\t"
  91898. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  91899. : "=r"(sse)
  91900. : "r"(sse)
  91901. );
  91902. sigaction(SIGILL, &sigill_save, NULL);
  91903. }
  91904. if(!sse)
  91905. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91906. #elif defined(_MSC_VER)
  91907. # ifdef USE_TRY_CATCH_FLAVOR
  91908. _try {
  91909. __asm {
  91910. # if _MSC_VER <= 1200
  91911. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91912. _emit 0x0F
  91913. _emit 0x57
  91914. _emit 0xC0
  91915. # else
  91916. xorps xmm0,xmm0
  91917. # endif
  91918. }
  91919. }
  91920. _except(EXCEPTION_EXECUTE_HANDLER) {
  91921. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  91922. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91923. }
  91924. # else
  91925. int sse = 0;
  91926. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  91927. /* see GCC version above for explanation */
  91928. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  91929. /* http://www.codeproject.com/cpp/gccasm.asp */
  91930. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  91931. __asm {
  91932. # if _MSC_VER <= 1200
  91933. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91934. _emit 0x0F
  91935. _emit 0x57
  91936. _emit 0xC0
  91937. # else
  91938. xorps xmm0,xmm0
  91939. # endif
  91940. inc sse
  91941. nop
  91942. nop
  91943. nop
  91944. nop
  91945. nop
  91946. nop
  91947. nop
  91948. nop
  91949. nop
  91950. }
  91951. SetUnhandledExceptionFilter(save);
  91952. if(!sse)
  91953. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91954. # endif
  91955. #else
  91956. /* no way to test, disable to be safe */
  91957. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91958. #endif
  91959. #ifdef DEBUG
  91960. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91961. #endif
  91962. }
  91963. }
  91964. #else
  91965. info->use_asm = false;
  91966. #endif
  91967. /*
  91968. * PPC-specific
  91969. */
  91970. #elif defined FLAC__CPU_PPC
  91971. info->type = FLAC__CPUINFO_TYPE_PPC;
  91972. # if !defined FLAC__NO_ASM
  91973. info->use_asm = true;
  91974. # ifdef FLAC__USE_ALTIVEC
  91975. # if defined FLAC__SYS_DARWIN
  91976. {
  91977. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  91978. size_t len = sizeof(val);
  91979. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  91980. }
  91981. {
  91982. host_basic_info_data_t hostInfo;
  91983. mach_msg_type_number_t infoCount;
  91984. infoCount = HOST_BASIC_INFO_COUNT;
  91985. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  91986. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  91987. }
  91988. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  91989. {
  91990. /* no Darwin, do it the brute-force way */
  91991. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  91992. info->data.ppc.altivec = 0;
  91993. info->data.ppc.ppc64 = 0;
  91994. signal (SIGILL, sigill_handler);
  91995. canjump = 0;
  91996. if (!sigsetjmp (jmpbuf, 1)) {
  91997. canjump = 1;
  91998. asm volatile (
  91999. "mtspr 256, %0\n\t"
  92000. "vand %%v0, %%v0, %%v0"
  92001. :
  92002. : "r" (-1)
  92003. );
  92004. info->data.ppc.altivec = 1;
  92005. }
  92006. canjump = 0;
  92007. if (!sigsetjmp (jmpbuf, 1)) {
  92008. int x = 0;
  92009. canjump = 1;
  92010. /* PPC64 hardware implements the cntlzd instruction */
  92011. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  92012. info->data.ppc.ppc64 = 1;
  92013. }
  92014. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  92015. }
  92016. # endif
  92017. # else /* !FLAC__USE_ALTIVEC */
  92018. info->data.ppc.altivec = 0;
  92019. info->data.ppc.ppc64 = 0;
  92020. # endif
  92021. # else
  92022. info->use_asm = false;
  92023. # endif
  92024. /*
  92025. * unknown CPI
  92026. */
  92027. #else
  92028. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  92029. info->use_asm = false;
  92030. #endif
  92031. }
  92032. #endif
  92033. /*** End of inlined file: cpu.c ***/
  92034. /*** Start of inlined file: crc.c ***/
  92035. /*** Start of inlined file: juce_FlacHeader.h ***/
  92036. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92037. // tasks..
  92038. #define VERSION "1.2.1"
  92039. #define FLAC__NO_DLL 1
  92040. #if JUCE_MSVC
  92041. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92042. #endif
  92043. #if JUCE_MAC
  92044. #define FLAC__SYS_DARWIN 1
  92045. #endif
  92046. /*** End of inlined file: juce_FlacHeader.h ***/
  92047. #if JUCE_USE_FLAC
  92048. #if HAVE_CONFIG_H
  92049. # include <config.h>
  92050. #endif
  92051. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  92052. FLAC__byte const FLAC__crc8_table[256] = {
  92053. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  92054. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  92055. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  92056. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  92057. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  92058. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  92059. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  92060. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  92061. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  92062. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  92063. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  92064. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  92065. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  92066. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  92067. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  92068. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  92069. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  92070. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  92071. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  92072. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  92073. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  92074. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  92075. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  92076. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  92077. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  92078. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  92079. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  92080. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  92081. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  92082. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  92083. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  92084. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  92085. };
  92086. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  92087. unsigned FLAC__crc16_table[256] = {
  92088. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  92089. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  92090. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  92091. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  92092. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  92093. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  92094. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  92095. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  92096. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  92097. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  92098. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  92099. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  92100. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  92101. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  92102. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  92103. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  92104. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  92105. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  92106. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  92107. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  92108. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  92109. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  92110. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  92111. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  92112. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  92113. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  92114. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  92115. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  92116. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  92117. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  92118. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  92119. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  92120. };
  92121. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  92122. {
  92123. *crc = FLAC__crc8_table[*crc ^ data];
  92124. }
  92125. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  92126. {
  92127. while(len--)
  92128. *crc = FLAC__crc8_table[*crc ^ *data++];
  92129. }
  92130. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  92131. {
  92132. FLAC__uint8 crc = 0;
  92133. while(len--)
  92134. crc = FLAC__crc8_table[crc ^ *data++];
  92135. return crc;
  92136. }
  92137. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  92138. {
  92139. unsigned crc = 0;
  92140. while(len--)
  92141. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  92142. return crc;
  92143. }
  92144. #endif
  92145. /*** End of inlined file: crc.c ***/
  92146. /*** Start of inlined file: fixed.c ***/
  92147. /*** Start of inlined file: juce_FlacHeader.h ***/
  92148. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92149. // tasks..
  92150. #define VERSION "1.2.1"
  92151. #define FLAC__NO_DLL 1
  92152. #if JUCE_MSVC
  92153. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92154. #endif
  92155. #if JUCE_MAC
  92156. #define FLAC__SYS_DARWIN 1
  92157. #endif
  92158. /*** End of inlined file: juce_FlacHeader.h ***/
  92159. #if JUCE_USE_FLAC
  92160. #if HAVE_CONFIG_H
  92161. # include <config.h>
  92162. #endif
  92163. #include <math.h>
  92164. #include <string.h>
  92165. /*** Start of inlined file: fixed.h ***/
  92166. #ifndef FLAC__PRIVATE__FIXED_H
  92167. #define FLAC__PRIVATE__FIXED_H
  92168. #ifdef HAVE_CONFIG_H
  92169. #include <config.h>
  92170. #endif
  92171. /*** Start of inlined file: float.h ***/
  92172. #ifndef FLAC__PRIVATE__FLOAT_H
  92173. #define FLAC__PRIVATE__FLOAT_H
  92174. #ifdef HAVE_CONFIG_H
  92175. #include <config.h>
  92176. #endif
  92177. /*
  92178. * These typedefs make it easier to ensure that integer versions of
  92179. * the library really only contain integer operations. All the code
  92180. * in libFLAC should use FLAC__float and FLAC__double in place of
  92181. * float and double, and be protected by checks of the macro
  92182. * FLAC__INTEGER_ONLY_LIBRARY.
  92183. *
  92184. * FLAC__real is the basic floating point type used in LPC analysis.
  92185. */
  92186. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92187. typedef double FLAC__double;
  92188. typedef float FLAC__float;
  92189. /*
  92190. * WATCHOUT: changing FLAC__real will change the signatures of many
  92191. * functions that have assembly language equivalents and break them.
  92192. */
  92193. typedef float FLAC__real;
  92194. #else
  92195. /*
  92196. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  92197. * for the integer part and lower 16 bits for the fractional part.
  92198. */
  92199. typedef FLAC__int32 FLAC__fixedpoint;
  92200. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  92201. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  92202. extern const FLAC__fixedpoint FLAC__FP_ONE;
  92203. extern const FLAC__fixedpoint FLAC__FP_LN2;
  92204. extern const FLAC__fixedpoint FLAC__FP_E;
  92205. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  92206. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  92207. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  92208. /*
  92209. * FLAC__fixedpoint_log2()
  92210. * --------------------------------------------------------------------
  92211. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  92212. * algorithm by Knuth for x >= 1.0
  92213. *
  92214. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  92215. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  92216. *
  92217. * 'precision' roughly limits the number of iterations that are done;
  92218. * use (unsigned)(-1) for maximum precision.
  92219. *
  92220. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  92221. * function will punt and return 0.
  92222. *
  92223. * The return value will also have 'fracbits' fractional bits.
  92224. */
  92225. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  92226. #endif
  92227. #endif
  92228. /*** End of inlined file: float.h ***/
  92229. /*** Start of inlined file: format.h ***/
  92230. #ifndef FLAC__PRIVATE__FORMAT_H
  92231. #define FLAC__PRIVATE__FORMAT_H
  92232. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  92233. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  92234. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  92235. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92236. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92237. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  92238. #endif
  92239. /*** End of inlined file: format.h ***/
  92240. /*
  92241. * FLAC__fixed_compute_best_predictor()
  92242. * --------------------------------------------------------------------
  92243. * Compute the best fixed predictor and the expected bits-per-sample
  92244. * of the residual signal for each order. The _wide() version uses
  92245. * 64-bit integers which is statistically necessary when bits-per-
  92246. * sample + log2(blocksize) > 30
  92247. *
  92248. * IN data[0,data_len-1]
  92249. * IN data_len
  92250. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  92251. */
  92252. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92253. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92254. # ifndef FLAC__NO_ASM
  92255. # ifdef FLAC__CPU_IA32
  92256. # ifdef FLAC__HAS_NASM
  92257. 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]);
  92258. # endif
  92259. # endif
  92260. # endif
  92261. 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]);
  92262. #else
  92263. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92264. 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]);
  92265. #endif
  92266. /*
  92267. * FLAC__fixed_compute_residual()
  92268. * --------------------------------------------------------------------
  92269. * Compute the residual signal obtained from sutracting the predicted
  92270. * signal from the original.
  92271. *
  92272. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92273. * IN data_len length of original signal
  92274. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92275. * OUT residual[0,data_len-1] residual signal
  92276. */
  92277. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  92278. /*
  92279. * FLAC__fixed_restore_signal()
  92280. * --------------------------------------------------------------------
  92281. * Restore the original signal by summing the residual and the
  92282. * predictor.
  92283. *
  92284. * IN residual[0,data_len-1] residual signal
  92285. * IN data_len length of original signal
  92286. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92287. * *** IMPORTANT: the caller must pass in the historical samples:
  92288. * IN data[-order,-1] previously-reconstructed historical samples
  92289. * OUT data[0,data_len-1] original signal
  92290. */
  92291. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  92292. #endif
  92293. /*** End of inlined file: fixed.h ***/
  92294. #ifndef M_LN2
  92295. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92296. #define M_LN2 0.69314718055994530942
  92297. #endif
  92298. #ifdef min
  92299. #undef min
  92300. #endif
  92301. #define min(x,y) ((x) < (y)? (x) : (y))
  92302. #ifdef local_abs
  92303. #undef local_abs
  92304. #endif
  92305. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  92306. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  92307. /* rbps stands for residual bits per sample
  92308. *
  92309. * (ln(2) * err)
  92310. * rbps = log (-----------)
  92311. * 2 ( n )
  92312. */
  92313. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  92314. {
  92315. FLAC__uint32 rbps;
  92316. unsigned bits; /* the number of bits required to represent a number */
  92317. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92318. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92319. FLAC__ASSERT(err > 0);
  92320. FLAC__ASSERT(n > 0);
  92321. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92322. if(err <= n)
  92323. return 0;
  92324. /*
  92325. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92326. * These allow us later to know we won't lose too much precision in the
  92327. * fixed-point division (err<<fracbits)/n.
  92328. */
  92329. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  92330. err <<= fracbits;
  92331. err /= n;
  92332. /* err now holds err/n with fracbits fractional bits */
  92333. /*
  92334. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92335. * our purposes.
  92336. */
  92337. FLAC__ASSERT(err > 0);
  92338. bits = FLAC__bitmath_ilog2(err)+1;
  92339. if(bits > 16) {
  92340. err >>= (bits-16);
  92341. fracbits -= (bits-16);
  92342. }
  92343. rbps = (FLAC__uint32)err;
  92344. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92345. rbps *= FLAC__FP_LN2;
  92346. fracbits += 16;
  92347. FLAC__ASSERT(fracbits >= 0);
  92348. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92349. {
  92350. const int f = fracbits & 3;
  92351. if(f) {
  92352. rbps >>= f;
  92353. fracbits -= f;
  92354. }
  92355. }
  92356. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  92357. if(rbps == 0)
  92358. return 0;
  92359. /*
  92360. * The return value must have 16 fractional bits. Since the whole part
  92361. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  92362. * must be >= -3, these assertion allows us to be able to shift rbps
  92363. * left if necessary to get 16 fracbits without losing any bits of the
  92364. * whole part of rbps.
  92365. *
  92366. * There is a slight chance due to accumulated error that the whole part
  92367. * will require 6 bits, so we use 6 in the assertion. Really though as
  92368. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  92369. */
  92370. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  92371. FLAC__ASSERT(fracbits >= -3);
  92372. /* now shift the decimal point into place */
  92373. if(fracbits < 16)
  92374. return rbps << (16-fracbits);
  92375. else if(fracbits > 16)
  92376. return rbps >> (fracbits-16);
  92377. else
  92378. return rbps;
  92379. }
  92380. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  92381. {
  92382. FLAC__uint32 rbps;
  92383. unsigned bits; /* the number of bits required to represent a number */
  92384. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92385. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92386. FLAC__ASSERT(err > 0);
  92387. FLAC__ASSERT(n > 0);
  92388. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92389. if(err <= n)
  92390. return 0;
  92391. /*
  92392. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92393. * These allow us later to know we won't lose too much precision in the
  92394. * fixed-point division (err<<fracbits)/n.
  92395. */
  92396. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  92397. err <<= fracbits;
  92398. err /= n;
  92399. /* err now holds err/n with fracbits fractional bits */
  92400. /*
  92401. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92402. * our purposes.
  92403. */
  92404. FLAC__ASSERT(err > 0);
  92405. bits = FLAC__bitmath_ilog2_wide(err)+1;
  92406. if(bits > 16) {
  92407. err >>= (bits-16);
  92408. fracbits -= (bits-16);
  92409. }
  92410. rbps = (FLAC__uint32)err;
  92411. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92412. rbps *= FLAC__FP_LN2;
  92413. fracbits += 16;
  92414. FLAC__ASSERT(fracbits >= 0);
  92415. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92416. {
  92417. const int f = fracbits & 3;
  92418. if(f) {
  92419. rbps >>= f;
  92420. fracbits -= f;
  92421. }
  92422. }
  92423. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  92424. if(rbps == 0)
  92425. return 0;
  92426. /*
  92427. * The return value must have 16 fractional bits. Since the whole part
  92428. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  92429. * must be >= -3, these assertion allows us to be able to shift rbps
  92430. * left if necessary to get 16 fracbits without losing any bits of the
  92431. * whole part of rbps.
  92432. *
  92433. * There is a slight chance due to accumulated error that the whole part
  92434. * will require 6 bits, so we use 6 in the assertion. Really though as
  92435. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  92436. */
  92437. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  92438. FLAC__ASSERT(fracbits >= -3);
  92439. /* now shift the decimal point into place */
  92440. if(fracbits < 16)
  92441. return rbps << (16-fracbits);
  92442. else if(fracbits > 16)
  92443. return rbps >> (fracbits-16);
  92444. else
  92445. return rbps;
  92446. }
  92447. #endif
  92448. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92449. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  92450. #else
  92451. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  92452. #endif
  92453. {
  92454. FLAC__int32 last_error_0 = data[-1];
  92455. FLAC__int32 last_error_1 = data[-1] - data[-2];
  92456. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  92457. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  92458. FLAC__int32 error, save;
  92459. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  92460. unsigned i, order;
  92461. for(i = 0; i < data_len; i++) {
  92462. error = data[i] ; total_error_0 += local_abs(error); save = error;
  92463. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  92464. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  92465. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  92466. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  92467. }
  92468. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  92469. order = 0;
  92470. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  92471. order = 1;
  92472. else if(total_error_2 < min(total_error_3, total_error_4))
  92473. order = 2;
  92474. else if(total_error_3 < total_error_4)
  92475. order = 3;
  92476. else
  92477. order = 4;
  92478. /* Estimate the expected number of bits per residual signal sample. */
  92479. /* 'total_error*' is linearly related to the variance of the residual */
  92480. /* signal, so we use it directly to compute E(|x|) */
  92481. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  92482. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  92483. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  92484. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  92485. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  92486. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92487. 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);
  92488. 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);
  92489. 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);
  92490. 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);
  92491. 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);
  92492. #else
  92493. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  92494. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  92495. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  92496. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  92497. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  92498. #endif
  92499. return order;
  92500. }
  92501. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92502. 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])
  92503. #else
  92504. 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])
  92505. #endif
  92506. {
  92507. FLAC__int32 last_error_0 = data[-1];
  92508. FLAC__int32 last_error_1 = data[-1] - data[-2];
  92509. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  92510. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  92511. FLAC__int32 error, save;
  92512. /* total_error_* are 64-bits to avoid overflow when encoding
  92513. * erratic signals when the bits-per-sample and blocksize are
  92514. * large.
  92515. */
  92516. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  92517. unsigned i, order;
  92518. for(i = 0; i < data_len; i++) {
  92519. error = data[i] ; total_error_0 += local_abs(error); save = error;
  92520. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  92521. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  92522. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  92523. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  92524. }
  92525. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  92526. order = 0;
  92527. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  92528. order = 1;
  92529. else if(total_error_2 < min(total_error_3, total_error_4))
  92530. order = 2;
  92531. else if(total_error_3 < total_error_4)
  92532. order = 3;
  92533. else
  92534. order = 4;
  92535. /* Estimate the expected number of bits per residual signal sample. */
  92536. /* 'total_error*' is linearly related to the variance of the residual */
  92537. /* signal, so we use it directly to compute E(|x|) */
  92538. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  92539. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  92540. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  92541. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  92542. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  92543. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92544. #if defined _MSC_VER || defined __MINGW32__
  92545. /* with MSVC you have to spoon feed it the casting */
  92546. 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);
  92547. 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);
  92548. 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);
  92549. 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);
  92550. 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);
  92551. #else
  92552. 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);
  92553. 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);
  92554. 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);
  92555. 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);
  92556. 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);
  92557. #endif
  92558. #else
  92559. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  92560. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  92561. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  92562. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  92563. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  92564. #endif
  92565. return order;
  92566. }
  92567. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  92568. {
  92569. const int idata_len = (int)data_len;
  92570. int i;
  92571. switch(order) {
  92572. case 0:
  92573. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  92574. memcpy(residual, data, sizeof(residual[0])*data_len);
  92575. break;
  92576. case 1:
  92577. for(i = 0; i < idata_len; i++)
  92578. residual[i] = data[i] - data[i-1];
  92579. break;
  92580. case 2:
  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] << 1) + data[i-2];
  92584. #else
  92585. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  92586. #endif
  92587. break;
  92588. case 3:
  92589. for(i = 0; i < idata_len; i++)
  92590. #if 1 /* OPT: may be faster with some compilers on some systems */
  92591. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  92592. #else
  92593. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  92594. #endif
  92595. break;
  92596. case 4:
  92597. for(i = 0; i < idata_len; i++)
  92598. #if 1 /* OPT: may be faster with some compilers on some systems */
  92599. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  92600. #else
  92601. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  92602. #endif
  92603. break;
  92604. default:
  92605. FLAC__ASSERT(0);
  92606. }
  92607. }
  92608. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  92609. {
  92610. int i, idata_len = (int)data_len;
  92611. switch(order) {
  92612. case 0:
  92613. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  92614. memcpy(data, residual, sizeof(residual[0])*data_len);
  92615. break;
  92616. case 1:
  92617. for(i = 0; i < idata_len; i++)
  92618. data[i] = residual[i] + data[i-1];
  92619. break;
  92620. case 2:
  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]<<1) - data[i-2];
  92624. #else
  92625. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  92626. #endif
  92627. break;
  92628. case 3:
  92629. for(i = 0; i < idata_len; i++)
  92630. #if 1 /* OPT: may be faster with some compilers on some systems */
  92631. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  92632. #else
  92633. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  92634. #endif
  92635. break;
  92636. case 4:
  92637. for(i = 0; i < idata_len; i++)
  92638. #if 1 /* OPT: may be faster with some compilers on some systems */
  92639. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  92640. #else
  92641. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  92642. #endif
  92643. break;
  92644. default:
  92645. FLAC__ASSERT(0);
  92646. }
  92647. }
  92648. #endif
  92649. /*** End of inlined file: fixed.c ***/
  92650. /*** Start of inlined file: float.c ***/
  92651. /*** Start of inlined file: juce_FlacHeader.h ***/
  92652. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92653. // tasks..
  92654. #define VERSION "1.2.1"
  92655. #define FLAC__NO_DLL 1
  92656. #if JUCE_MSVC
  92657. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92658. #endif
  92659. #if JUCE_MAC
  92660. #define FLAC__SYS_DARWIN 1
  92661. #endif
  92662. /*** End of inlined file: juce_FlacHeader.h ***/
  92663. #if JUCE_USE_FLAC
  92664. #if HAVE_CONFIG_H
  92665. # include <config.h>
  92666. #endif
  92667. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  92668. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92669. #ifdef _MSC_VER
  92670. #define FLAC__U64L(x) x
  92671. #else
  92672. #define FLAC__U64L(x) x##LLU
  92673. #endif
  92674. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  92675. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  92676. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  92677. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  92678. const FLAC__fixedpoint FLAC__FP_E = 178145;
  92679. /* Lookup tables for Knuth's logarithm algorithm */
  92680. #define LOG2_LOOKUP_PRECISION 16
  92681. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  92682. {
  92683. /*
  92684. * 0 fraction bits
  92685. */
  92686. /* undefined */ 0x00000000,
  92687. /* lg(2/1) = */ 0x00000001,
  92688. /* lg(4/3) = */ 0x00000000,
  92689. /* lg(8/7) = */ 0x00000000,
  92690. /* lg(16/15) = */ 0x00000000,
  92691. /* lg(32/31) = */ 0x00000000,
  92692. /* lg(64/63) = */ 0x00000000,
  92693. /* lg(128/127) = */ 0x00000000,
  92694. /* lg(256/255) = */ 0x00000000,
  92695. /* lg(512/511) = */ 0x00000000,
  92696. /* lg(1024/1023) = */ 0x00000000,
  92697. /* lg(2048/2047) = */ 0x00000000,
  92698. /* lg(4096/4095) = */ 0x00000000,
  92699. /* lg(8192/8191) = */ 0x00000000,
  92700. /* lg(16384/16383) = */ 0x00000000,
  92701. /* lg(32768/32767) = */ 0x00000000
  92702. },
  92703. {
  92704. /*
  92705. * 4 fraction bits
  92706. */
  92707. /* undefined */ 0x00000000,
  92708. /* lg(2/1) = */ 0x00000010,
  92709. /* lg(4/3) = */ 0x00000007,
  92710. /* lg(8/7) = */ 0x00000003,
  92711. /* lg(16/15) = */ 0x00000001,
  92712. /* lg(32/31) = */ 0x00000001,
  92713. /* lg(64/63) = */ 0x00000000,
  92714. /* lg(128/127) = */ 0x00000000,
  92715. /* lg(256/255) = */ 0x00000000,
  92716. /* lg(512/511) = */ 0x00000000,
  92717. /* lg(1024/1023) = */ 0x00000000,
  92718. /* lg(2048/2047) = */ 0x00000000,
  92719. /* lg(4096/4095) = */ 0x00000000,
  92720. /* lg(8192/8191) = */ 0x00000000,
  92721. /* lg(16384/16383) = */ 0x00000000,
  92722. /* lg(32768/32767) = */ 0x00000000
  92723. },
  92724. {
  92725. /*
  92726. * 8 fraction bits
  92727. */
  92728. /* undefined */ 0x00000000,
  92729. /* lg(2/1) = */ 0x00000100,
  92730. /* lg(4/3) = */ 0x0000006a,
  92731. /* lg(8/7) = */ 0x00000031,
  92732. /* lg(16/15) = */ 0x00000018,
  92733. /* lg(32/31) = */ 0x0000000c,
  92734. /* lg(64/63) = */ 0x00000006,
  92735. /* lg(128/127) = */ 0x00000003,
  92736. /* lg(256/255) = */ 0x00000001,
  92737. /* lg(512/511) = */ 0x00000001,
  92738. /* lg(1024/1023) = */ 0x00000000,
  92739. /* lg(2048/2047) = */ 0x00000000,
  92740. /* lg(4096/4095) = */ 0x00000000,
  92741. /* lg(8192/8191) = */ 0x00000000,
  92742. /* lg(16384/16383) = */ 0x00000000,
  92743. /* lg(32768/32767) = */ 0x00000000
  92744. },
  92745. {
  92746. /*
  92747. * 12 fraction bits
  92748. */
  92749. /* undefined */ 0x00000000,
  92750. /* lg(2/1) = */ 0x00001000,
  92751. /* lg(4/3) = */ 0x000006a4,
  92752. /* lg(8/7) = */ 0x00000315,
  92753. /* lg(16/15) = */ 0x0000017d,
  92754. /* lg(32/31) = */ 0x000000bc,
  92755. /* lg(64/63) = */ 0x0000005d,
  92756. /* lg(128/127) = */ 0x0000002e,
  92757. /* lg(256/255) = */ 0x00000017,
  92758. /* lg(512/511) = */ 0x0000000c,
  92759. /* lg(1024/1023) = */ 0x00000006,
  92760. /* lg(2048/2047) = */ 0x00000003,
  92761. /* lg(4096/4095) = */ 0x00000001,
  92762. /* lg(8192/8191) = */ 0x00000001,
  92763. /* lg(16384/16383) = */ 0x00000000,
  92764. /* lg(32768/32767) = */ 0x00000000
  92765. },
  92766. {
  92767. /*
  92768. * 16 fraction bits
  92769. */
  92770. /* undefined */ 0x00000000,
  92771. /* lg(2/1) = */ 0x00010000,
  92772. /* lg(4/3) = */ 0x00006a40,
  92773. /* lg(8/7) = */ 0x00003151,
  92774. /* lg(16/15) = */ 0x000017d6,
  92775. /* lg(32/31) = */ 0x00000bba,
  92776. /* lg(64/63) = */ 0x000005d1,
  92777. /* lg(128/127) = */ 0x000002e6,
  92778. /* lg(256/255) = */ 0x00000172,
  92779. /* lg(512/511) = */ 0x000000b9,
  92780. /* lg(1024/1023) = */ 0x0000005c,
  92781. /* lg(2048/2047) = */ 0x0000002e,
  92782. /* lg(4096/4095) = */ 0x00000017,
  92783. /* lg(8192/8191) = */ 0x0000000c,
  92784. /* lg(16384/16383) = */ 0x00000006,
  92785. /* lg(32768/32767) = */ 0x00000003
  92786. },
  92787. {
  92788. /*
  92789. * 20 fraction bits
  92790. */
  92791. /* undefined */ 0x00000000,
  92792. /* lg(2/1) = */ 0x00100000,
  92793. /* lg(4/3) = */ 0x0006a3fe,
  92794. /* lg(8/7) = */ 0x00031513,
  92795. /* lg(16/15) = */ 0x00017d60,
  92796. /* lg(32/31) = */ 0x0000bb9d,
  92797. /* lg(64/63) = */ 0x00005d10,
  92798. /* lg(128/127) = */ 0x00002e59,
  92799. /* lg(256/255) = */ 0x00001721,
  92800. /* lg(512/511) = */ 0x00000b8e,
  92801. /* lg(1024/1023) = */ 0x000005c6,
  92802. /* lg(2048/2047) = */ 0x000002e3,
  92803. /* lg(4096/4095) = */ 0x00000171,
  92804. /* lg(8192/8191) = */ 0x000000b9,
  92805. /* lg(16384/16383) = */ 0x0000005c,
  92806. /* lg(32768/32767) = */ 0x0000002e
  92807. },
  92808. {
  92809. /*
  92810. * 24 fraction bits
  92811. */
  92812. /* undefined */ 0x00000000,
  92813. /* lg(2/1) = */ 0x01000000,
  92814. /* lg(4/3) = */ 0x006a3fe6,
  92815. /* lg(8/7) = */ 0x00315130,
  92816. /* lg(16/15) = */ 0x0017d605,
  92817. /* lg(32/31) = */ 0x000bb9ca,
  92818. /* lg(64/63) = */ 0x0005d0fc,
  92819. /* lg(128/127) = */ 0x0002e58f,
  92820. /* lg(256/255) = */ 0x0001720e,
  92821. /* lg(512/511) = */ 0x0000b8d8,
  92822. /* lg(1024/1023) = */ 0x00005c61,
  92823. /* lg(2048/2047) = */ 0x00002e2d,
  92824. /* lg(4096/4095) = */ 0x00001716,
  92825. /* lg(8192/8191) = */ 0x00000b8b,
  92826. /* lg(16384/16383) = */ 0x000005c5,
  92827. /* lg(32768/32767) = */ 0x000002e3
  92828. },
  92829. {
  92830. /*
  92831. * 28 fraction bits
  92832. */
  92833. /* undefined */ 0x00000000,
  92834. /* lg(2/1) = */ 0x10000000,
  92835. /* lg(4/3) = */ 0x06a3fe5c,
  92836. /* lg(8/7) = */ 0x03151301,
  92837. /* lg(16/15) = */ 0x017d6049,
  92838. /* lg(32/31) = */ 0x00bb9ca6,
  92839. /* lg(64/63) = */ 0x005d0fba,
  92840. /* lg(128/127) = */ 0x002e58f7,
  92841. /* lg(256/255) = */ 0x001720da,
  92842. /* lg(512/511) = */ 0x000b8d87,
  92843. /* lg(1024/1023) = */ 0x0005c60b,
  92844. /* lg(2048/2047) = */ 0x0002e2d7,
  92845. /* lg(4096/4095) = */ 0x00017160,
  92846. /* lg(8192/8191) = */ 0x0000b8ad,
  92847. /* lg(16384/16383) = */ 0x00005c56,
  92848. /* lg(32768/32767) = */ 0x00002e2b
  92849. }
  92850. };
  92851. #if 0
  92852. static const FLAC__uint64 log2_lookup_wide[] = {
  92853. {
  92854. /*
  92855. * 32 fraction bits
  92856. */
  92857. /* undefined */ 0x00000000,
  92858. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  92859. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  92860. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  92861. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  92862. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  92863. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  92864. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  92865. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  92866. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  92867. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  92868. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  92869. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  92870. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  92871. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  92872. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  92873. },
  92874. {
  92875. /*
  92876. * 48 fraction bits
  92877. */
  92878. /* undefined */ 0x00000000,
  92879. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  92880. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  92881. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  92882. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  92883. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  92884. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  92885. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  92886. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  92887. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  92888. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  92889. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  92890. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  92891. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  92892. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  92893. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  92894. }
  92895. };
  92896. #endif
  92897. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  92898. {
  92899. const FLAC__uint32 ONE = (1u << fracbits);
  92900. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  92901. FLAC__ASSERT(fracbits < 32);
  92902. FLAC__ASSERT((fracbits & 0x3) == 0);
  92903. if(x < ONE)
  92904. return 0;
  92905. if(precision > LOG2_LOOKUP_PRECISION)
  92906. precision = LOG2_LOOKUP_PRECISION;
  92907. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  92908. {
  92909. FLAC__uint32 y = 0;
  92910. FLAC__uint32 z = x >> 1, k = 1;
  92911. while (x > ONE && k < precision) {
  92912. if (x - z >= ONE) {
  92913. x -= z;
  92914. z = x >> k;
  92915. y += table[k];
  92916. }
  92917. else {
  92918. z >>= 1;
  92919. k++;
  92920. }
  92921. }
  92922. return y;
  92923. }
  92924. }
  92925. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92926. #endif
  92927. /*** End of inlined file: float.c ***/
  92928. /*** Start of inlined file: format.c ***/
  92929. /*** Start of inlined file: juce_FlacHeader.h ***/
  92930. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92931. // tasks..
  92932. #define VERSION "1.2.1"
  92933. #define FLAC__NO_DLL 1
  92934. #if JUCE_MSVC
  92935. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92936. #endif
  92937. #if JUCE_MAC
  92938. #define FLAC__SYS_DARWIN 1
  92939. #endif
  92940. /*** End of inlined file: juce_FlacHeader.h ***/
  92941. #if JUCE_USE_FLAC
  92942. #if HAVE_CONFIG_H
  92943. # include <config.h>
  92944. #endif
  92945. #include <stdio.h>
  92946. #include <stdlib.h> /* for qsort() */
  92947. #include <string.h> /* for memset() */
  92948. #ifndef FLaC__INLINE
  92949. #define FLaC__INLINE
  92950. #endif
  92951. #ifdef min
  92952. #undef min
  92953. #endif
  92954. #define min(a,b) ((a)<(b)?(a):(b))
  92955. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92956. #ifdef _MSC_VER
  92957. #define FLAC__U64L(x) x
  92958. #else
  92959. #define FLAC__U64L(x) x##LLU
  92960. #endif
  92961. /* VERSION should come from configure */
  92962. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92963. ;
  92964. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92965. /* yet one more hack because of MSVC6: */
  92966. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92967. #else
  92968. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92969. #endif
  92970. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92971. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92972. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92973. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92974. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92975. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92976. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92977. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92978. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92979. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92980. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92981. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92982. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92983. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92984. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92985. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92986. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92987. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92988. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92989. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92990. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92991. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92992. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92993. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92994. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92995. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92996. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92997. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92998. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92999. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  93000. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  93001. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  93002. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  93003. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  93004. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  93005. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  93006. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  93007. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  93008. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  93009. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  93010. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  93011. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  93012. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  93013. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  93014. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  93015. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  93016. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  93017. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  93018. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  93019. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  93020. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  93021. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  93022. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  93023. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  93024. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  93025. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  93026. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  93027. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  93028. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  93029. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  93030. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  93031. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  93032. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  93033. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  93034. "PARTITIONED_RICE",
  93035. "PARTITIONED_RICE2"
  93036. };
  93037. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  93038. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  93039. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  93040. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  93041. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  93042. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  93043. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  93044. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  93045. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  93046. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  93047. "CONSTANT",
  93048. "VERBATIM",
  93049. "FIXED",
  93050. "LPC"
  93051. };
  93052. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  93053. "INDEPENDENT",
  93054. "LEFT_SIDE",
  93055. "RIGHT_SIDE",
  93056. "MID_SIDE"
  93057. };
  93058. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  93059. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  93060. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  93061. };
  93062. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  93063. "STREAMINFO",
  93064. "PADDING",
  93065. "APPLICATION",
  93066. "SEEKTABLE",
  93067. "VORBIS_COMMENT",
  93068. "CUESHEET",
  93069. "PICTURE"
  93070. };
  93071. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  93072. "Other",
  93073. "32x32 pixels 'file icon' (PNG only)",
  93074. "Other file icon",
  93075. "Cover (front)",
  93076. "Cover (back)",
  93077. "Leaflet page",
  93078. "Media (e.g. label side of CD)",
  93079. "Lead artist/lead performer/soloist",
  93080. "Artist/performer",
  93081. "Conductor",
  93082. "Band/Orchestra",
  93083. "Composer",
  93084. "Lyricist/text writer",
  93085. "Recording Location",
  93086. "During recording",
  93087. "During performance",
  93088. "Movie/video screen capture",
  93089. "A bright coloured fish",
  93090. "Illustration",
  93091. "Band/artist logotype",
  93092. "Publisher/Studio logotype"
  93093. };
  93094. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  93095. {
  93096. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  93097. return false;
  93098. }
  93099. else
  93100. return true;
  93101. }
  93102. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  93103. {
  93104. if(
  93105. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  93106. (
  93107. sample_rate >= (1u << 16) &&
  93108. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  93109. )
  93110. ) {
  93111. return false;
  93112. }
  93113. else
  93114. return true;
  93115. }
  93116. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93117. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  93118. {
  93119. unsigned i;
  93120. FLAC__uint64 prev_sample_number = 0;
  93121. FLAC__bool got_prev = false;
  93122. FLAC__ASSERT(0 != seek_table);
  93123. for(i = 0; i < seek_table->num_points; i++) {
  93124. if(got_prev) {
  93125. if(
  93126. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  93127. seek_table->points[i].sample_number <= prev_sample_number
  93128. )
  93129. return false;
  93130. }
  93131. prev_sample_number = seek_table->points[i].sample_number;
  93132. got_prev = true;
  93133. }
  93134. return true;
  93135. }
  93136. /* used as the sort predicate for qsort() */
  93137. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  93138. {
  93139. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  93140. if(l->sample_number == r->sample_number)
  93141. return 0;
  93142. else if(l->sample_number < r->sample_number)
  93143. return -1;
  93144. else
  93145. return 1;
  93146. }
  93147. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93148. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  93149. {
  93150. unsigned i, j;
  93151. FLAC__bool first;
  93152. FLAC__ASSERT(0 != seek_table);
  93153. /* sort the seekpoints */
  93154. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  93155. /* uniquify the seekpoints */
  93156. first = true;
  93157. for(i = j = 0; i < seek_table->num_points; i++) {
  93158. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  93159. if(!first) {
  93160. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  93161. continue;
  93162. }
  93163. }
  93164. first = false;
  93165. seek_table->points[j++] = seek_table->points[i];
  93166. }
  93167. for(i = j; i < seek_table->num_points; i++) {
  93168. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  93169. seek_table->points[i].stream_offset = 0;
  93170. seek_table->points[i].frame_samples = 0;
  93171. }
  93172. return j;
  93173. }
  93174. /*
  93175. * also disallows non-shortest-form encodings, c.f.
  93176. * http://www.unicode.org/versions/corrigendum1.html
  93177. * and a more clear explanation at the end of this section:
  93178. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  93179. */
  93180. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  93181. {
  93182. FLAC__ASSERT(0 != utf8);
  93183. if ((utf8[0] & 0x80) == 0) {
  93184. return 1;
  93185. }
  93186. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  93187. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  93188. return 0;
  93189. return 2;
  93190. }
  93191. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  93192. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  93193. return 0;
  93194. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  93195. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  93196. return 0;
  93197. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  93198. return 0;
  93199. return 3;
  93200. }
  93201. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  93202. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  93203. return 0;
  93204. return 4;
  93205. }
  93206. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  93207. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  93208. return 0;
  93209. return 5;
  93210. }
  93211. 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) {
  93212. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  93213. return 0;
  93214. return 6;
  93215. }
  93216. else {
  93217. return 0;
  93218. }
  93219. }
  93220. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  93221. {
  93222. char c;
  93223. for(c = *name; c; c = *(++name))
  93224. if(c < 0x20 || c == 0x3d || c > 0x7d)
  93225. return false;
  93226. return true;
  93227. }
  93228. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  93229. {
  93230. if(length == (unsigned)(-1)) {
  93231. while(*value) {
  93232. unsigned n = utf8len_(value);
  93233. if(n == 0)
  93234. return false;
  93235. value += n;
  93236. }
  93237. }
  93238. else {
  93239. const FLAC__byte *end = value + length;
  93240. while(value < end) {
  93241. unsigned n = utf8len_(value);
  93242. if(n == 0)
  93243. return false;
  93244. value += n;
  93245. }
  93246. if(value != end)
  93247. return false;
  93248. }
  93249. return true;
  93250. }
  93251. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  93252. {
  93253. const FLAC__byte *s, *end;
  93254. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  93255. if(*s < 0x20 || *s > 0x7D)
  93256. return false;
  93257. }
  93258. if(s == end)
  93259. return false;
  93260. s++; /* skip '=' */
  93261. while(s < end) {
  93262. unsigned n = utf8len_(s);
  93263. if(n == 0)
  93264. return false;
  93265. s += n;
  93266. }
  93267. if(s != end)
  93268. return false;
  93269. return true;
  93270. }
  93271. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93272. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  93273. {
  93274. unsigned i, j;
  93275. if(check_cd_da_subset) {
  93276. if(cue_sheet->lead_in < 2 * 44100) {
  93277. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  93278. return false;
  93279. }
  93280. if(cue_sheet->lead_in % 588 != 0) {
  93281. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  93282. return false;
  93283. }
  93284. }
  93285. if(cue_sheet->num_tracks == 0) {
  93286. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  93287. return false;
  93288. }
  93289. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  93290. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  93291. return false;
  93292. }
  93293. for(i = 0; i < cue_sheet->num_tracks; i++) {
  93294. if(cue_sheet->tracks[i].number == 0) {
  93295. if(violation) *violation = "cue sheet may not have a track number 0";
  93296. return false;
  93297. }
  93298. if(check_cd_da_subset) {
  93299. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  93300. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  93301. return false;
  93302. }
  93303. }
  93304. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  93305. if(violation) {
  93306. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  93307. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  93308. else
  93309. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  93310. }
  93311. return false;
  93312. }
  93313. if(i < cue_sheet->num_tracks - 1) {
  93314. if(cue_sheet->tracks[i].num_indices == 0) {
  93315. if(violation) *violation = "cue sheet track must have at least one index point";
  93316. return false;
  93317. }
  93318. if(cue_sheet->tracks[i].indices[0].number > 1) {
  93319. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  93320. return false;
  93321. }
  93322. }
  93323. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  93324. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  93325. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  93326. return false;
  93327. }
  93328. if(j > 0) {
  93329. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  93330. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  93331. return false;
  93332. }
  93333. }
  93334. }
  93335. }
  93336. return true;
  93337. }
  93338. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93339. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  93340. {
  93341. char *p;
  93342. FLAC__byte *b;
  93343. for(p = picture->mime_type; *p; p++) {
  93344. if(*p < 0x20 || *p > 0x7e) {
  93345. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  93346. return false;
  93347. }
  93348. }
  93349. for(b = picture->description; *b; ) {
  93350. unsigned n = utf8len_(b);
  93351. if(n == 0) {
  93352. if(violation) *violation = "description string must be valid UTF-8";
  93353. return false;
  93354. }
  93355. b += n;
  93356. }
  93357. return true;
  93358. }
  93359. /*
  93360. * These routines are private to libFLAC
  93361. */
  93362. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  93363. {
  93364. return
  93365. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  93366. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  93367. blocksize,
  93368. predictor_order
  93369. );
  93370. }
  93371. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  93372. {
  93373. unsigned max_rice_partition_order = 0;
  93374. while(!(blocksize & 1)) {
  93375. max_rice_partition_order++;
  93376. blocksize >>= 1;
  93377. }
  93378. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  93379. }
  93380. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  93381. {
  93382. unsigned max_rice_partition_order = limit;
  93383. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  93384. max_rice_partition_order--;
  93385. FLAC__ASSERT(
  93386. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  93387. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  93388. );
  93389. return max_rice_partition_order;
  93390. }
  93391. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  93392. {
  93393. FLAC__ASSERT(0 != object);
  93394. object->parameters = 0;
  93395. object->raw_bits = 0;
  93396. object->capacity_by_order = 0;
  93397. }
  93398. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  93399. {
  93400. FLAC__ASSERT(0 != object);
  93401. if(0 != object->parameters)
  93402. free(object->parameters);
  93403. if(0 != object->raw_bits)
  93404. free(object->raw_bits);
  93405. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  93406. }
  93407. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  93408. {
  93409. FLAC__ASSERT(0 != object);
  93410. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  93411. if(object->capacity_by_order < max_partition_order) {
  93412. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  93413. return false;
  93414. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  93415. return false;
  93416. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  93417. object->capacity_by_order = max_partition_order;
  93418. }
  93419. return true;
  93420. }
  93421. #endif
  93422. /*** End of inlined file: format.c ***/
  93423. /*** Start of inlined file: lpc_flac.c ***/
  93424. /*** Start of inlined file: juce_FlacHeader.h ***/
  93425. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93426. // tasks..
  93427. #define VERSION "1.2.1"
  93428. #define FLAC__NO_DLL 1
  93429. #if JUCE_MSVC
  93430. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93431. #endif
  93432. #if JUCE_MAC
  93433. #define FLAC__SYS_DARWIN 1
  93434. #endif
  93435. /*** End of inlined file: juce_FlacHeader.h ***/
  93436. #if JUCE_USE_FLAC
  93437. #if HAVE_CONFIG_H
  93438. # include <config.h>
  93439. #endif
  93440. #include <math.h>
  93441. /*** Start of inlined file: lpc.h ***/
  93442. #ifndef FLAC__PRIVATE__LPC_H
  93443. #define FLAC__PRIVATE__LPC_H
  93444. #ifdef HAVE_CONFIG_H
  93445. #include <config.h>
  93446. #endif
  93447. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93448. /*
  93449. * FLAC__lpc_window_data()
  93450. * --------------------------------------------------------------------
  93451. * Applies the given window to the data.
  93452. * OPT: asm implementation
  93453. *
  93454. * IN in[0,data_len-1]
  93455. * IN window[0,data_len-1]
  93456. * OUT out[0,lag-1]
  93457. * IN data_len
  93458. */
  93459. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  93460. /*
  93461. * FLAC__lpc_compute_autocorrelation()
  93462. * --------------------------------------------------------------------
  93463. * Compute the autocorrelation for lags between 0 and lag-1.
  93464. * Assumes data[] outside of [0,data_len-1] == 0.
  93465. * Asserts that lag > 0.
  93466. *
  93467. * IN data[0,data_len-1]
  93468. * IN data_len
  93469. * IN 0 < lag <= data_len
  93470. * OUT autoc[0,lag-1]
  93471. */
  93472. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93473. #ifndef FLAC__NO_ASM
  93474. # ifdef FLAC__CPU_IA32
  93475. # ifdef FLAC__HAS_NASM
  93476. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93477. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93478. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93479. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93480. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93481. # endif
  93482. # endif
  93483. #endif
  93484. /*
  93485. * FLAC__lpc_compute_lp_coefficients()
  93486. * --------------------------------------------------------------------
  93487. * Computes LP coefficients for orders 1..max_order.
  93488. * Do not call if autoc[0] == 0.0. This means the signal is zero
  93489. * and there is no point in calculating a predictor.
  93490. *
  93491. * IN autoc[0,max_order] autocorrelation values
  93492. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  93493. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  93494. * *** IMPORTANT:
  93495. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  93496. * OUT error[0,max_order-1] error for each order (more
  93497. * specifically, the variance of
  93498. * the error signal times # of
  93499. * samples in the signal)
  93500. *
  93501. * Example: if max_order is 9, the LP coefficients for order 9 will be
  93502. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  93503. * in lp_coeff[7][0,7], etc.
  93504. */
  93505. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  93506. /*
  93507. * FLAC__lpc_quantize_coefficients()
  93508. * --------------------------------------------------------------------
  93509. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  93510. * must be less than 32 (sizeof(FLAC__int32)*8).
  93511. *
  93512. * IN lp_coeff[0,order-1] LP coefficients
  93513. * IN order LP order
  93514. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  93515. * desired precision (in bits, including sign
  93516. * bit) of largest coefficient
  93517. * OUT qlp_coeff[0,order-1] quantized coefficients
  93518. * OUT shift # of bits to shift right to get approximated
  93519. * LP coefficients. NOTE: could be negative.
  93520. * RETURN 0 => quantization OK
  93521. * 1 => coefficients require too much shifting for *shift to
  93522. * fit in the LPC subframe header. 'shift' is unset.
  93523. * 2 => coefficients are all zero, which is bad. 'shift' is
  93524. * unset.
  93525. */
  93526. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  93527. /*
  93528. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  93529. * --------------------------------------------------------------------
  93530. * Compute the residual signal obtained from sutracting the predicted
  93531. * signal from the original.
  93532. *
  93533. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  93534. * IN data_len length of original signal
  93535. * IN qlp_coeff[0,order-1] quantized LP coefficients
  93536. * IN order > 0 LP order
  93537. * IN lp_quantization quantization of LP coefficients in bits
  93538. * OUT residual[0,data_len-1] residual signal
  93539. */
  93540. 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[]);
  93541. 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[]);
  93542. #ifndef FLAC__NO_ASM
  93543. # ifdef FLAC__CPU_IA32
  93544. # ifdef FLAC__HAS_NASM
  93545. 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[]);
  93546. 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[]);
  93547. # endif
  93548. # endif
  93549. #endif
  93550. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93551. /*
  93552. * FLAC__lpc_restore_signal()
  93553. * --------------------------------------------------------------------
  93554. * Restore the original signal by summing the residual and the
  93555. * predictor.
  93556. *
  93557. * IN residual[0,data_len-1] residual signal
  93558. * IN data_len length of original signal
  93559. * IN qlp_coeff[0,order-1] quantized LP coefficients
  93560. * IN order > 0 LP order
  93561. * IN lp_quantization quantization of LP coefficients in bits
  93562. * *** IMPORTANT: the caller must pass in the historical samples:
  93563. * IN data[-order,-1] previously-reconstructed historical samples
  93564. * OUT data[0,data_len-1] original signal
  93565. */
  93566. 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[]);
  93567. 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[]);
  93568. #ifndef FLAC__NO_ASM
  93569. # ifdef FLAC__CPU_IA32
  93570. # ifdef FLAC__HAS_NASM
  93571. 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[]);
  93572. 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[]);
  93573. # endif /* FLAC__HAS_NASM */
  93574. # elif defined FLAC__CPU_PPC
  93575. 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[]);
  93576. 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[]);
  93577. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  93578. #endif /* FLAC__NO_ASM */
  93579. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93580. /*
  93581. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  93582. * --------------------------------------------------------------------
  93583. * Compute the expected number of bits per residual signal sample
  93584. * based on the LP error (which is related to the residual variance).
  93585. *
  93586. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  93587. * IN total_samples > 0 # of samples in residual signal
  93588. * RETURN expected bits per sample
  93589. */
  93590. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  93591. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  93592. /*
  93593. * FLAC__lpc_compute_best_order()
  93594. * --------------------------------------------------------------------
  93595. * Compute the best order from the array of signal errors returned
  93596. * during coefficient computation.
  93597. *
  93598. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  93599. * IN max_order > 0 max LP order
  93600. * IN total_samples > 0 # of samples in residual signal
  93601. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  93602. * (includes warmup sample size and quantized LP coefficient)
  93603. * RETURN [1,max_order] best order
  93604. */
  93605. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  93606. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93607. #endif
  93608. /*** End of inlined file: lpc.h ***/
  93609. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  93610. #include <stdio.h>
  93611. #endif
  93612. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93613. #ifndef M_LN2
  93614. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  93615. #define M_LN2 0.69314718055994530942
  93616. #endif
  93617. /* OPT: #undef'ing this may improve the speed on some architectures */
  93618. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  93619. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  93620. {
  93621. unsigned i;
  93622. for(i = 0; i < data_len; i++)
  93623. out[i] = in[i] * window[i];
  93624. }
  93625. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  93626. {
  93627. /* a readable, but slower, version */
  93628. #if 0
  93629. FLAC__real d;
  93630. unsigned i;
  93631. FLAC__ASSERT(lag > 0);
  93632. FLAC__ASSERT(lag <= data_len);
  93633. /*
  93634. * Technically we should subtract the mean first like so:
  93635. * for(i = 0; i < data_len; i++)
  93636. * data[i] -= mean;
  93637. * but it appears not to make enough of a difference to matter, and
  93638. * most signals are already closely centered around zero
  93639. */
  93640. while(lag--) {
  93641. for(i = lag, d = 0.0; i < data_len; i++)
  93642. d += data[i] * data[i - lag];
  93643. autoc[lag] = d;
  93644. }
  93645. #endif
  93646. /*
  93647. * this version tends to run faster because of better data locality
  93648. * ('data_len' is usually much larger than 'lag')
  93649. */
  93650. FLAC__real d;
  93651. unsigned sample, coeff;
  93652. const unsigned limit = data_len - lag;
  93653. FLAC__ASSERT(lag > 0);
  93654. FLAC__ASSERT(lag <= data_len);
  93655. for(coeff = 0; coeff < lag; coeff++)
  93656. autoc[coeff] = 0.0;
  93657. for(sample = 0; sample <= limit; sample++) {
  93658. d = data[sample];
  93659. for(coeff = 0; coeff < lag; coeff++)
  93660. autoc[coeff] += d * data[sample+coeff];
  93661. }
  93662. for(; sample < data_len; sample++) {
  93663. d = data[sample];
  93664. for(coeff = 0; coeff < data_len - sample; coeff++)
  93665. autoc[coeff] += d * data[sample+coeff];
  93666. }
  93667. }
  93668. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  93669. {
  93670. unsigned i, j;
  93671. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  93672. FLAC__ASSERT(0 != max_order);
  93673. FLAC__ASSERT(0 < *max_order);
  93674. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  93675. FLAC__ASSERT(autoc[0] != 0.0);
  93676. err = autoc[0];
  93677. for(i = 0; i < *max_order; i++) {
  93678. /* Sum up this iteration's reflection coefficient. */
  93679. r = -autoc[i+1];
  93680. for(j = 0; j < i; j++)
  93681. r -= lpc[j] * autoc[i-j];
  93682. ref[i] = (r/=err);
  93683. /* Update LPC coefficients and total error. */
  93684. lpc[i]=r;
  93685. for(j = 0; j < (i>>1); j++) {
  93686. FLAC__double tmp = lpc[j];
  93687. lpc[j] += r * lpc[i-1-j];
  93688. lpc[i-1-j] += r * tmp;
  93689. }
  93690. if(i & 1)
  93691. lpc[j] += lpc[j] * r;
  93692. err *= (1.0 - r * r);
  93693. /* save this order */
  93694. for(j = 0; j <= i; j++)
  93695. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  93696. error[i] = err;
  93697. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  93698. if(err == 0.0) {
  93699. *max_order = i+1;
  93700. return;
  93701. }
  93702. }
  93703. }
  93704. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  93705. {
  93706. unsigned i;
  93707. FLAC__double cmax;
  93708. FLAC__int32 qmax, qmin;
  93709. FLAC__ASSERT(precision > 0);
  93710. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  93711. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  93712. precision--;
  93713. qmax = 1 << precision;
  93714. qmin = -qmax;
  93715. qmax--;
  93716. /* calc cmax = max( |lp_coeff[i]| ) */
  93717. cmax = 0.0;
  93718. for(i = 0; i < order; i++) {
  93719. const FLAC__double d = fabs(lp_coeff[i]);
  93720. if(d > cmax)
  93721. cmax = d;
  93722. }
  93723. if(cmax <= 0.0) {
  93724. /* => coefficients are all 0, which means our constant-detect didn't work */
  93725. return 2;
  93726. }
  93727. else {
  93728. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  93729. const int min_shiftlimit = -max_shiftlimit - 1;
  93730. int log2cmax;
  93731. (void)frexp(cmax, &log2cmax);
  93732. log2cmax--;
  93733. *shift = (int)precision - log2cmax - 1;
  93734. if(*shift > max_shiftlimit)
  93735. *shift = max_shiftlimit;
  93736. else if(*shift < min_shiftlimit)
  93737. return 1;
  93738. }
  93739. if(*shift >= 0) {
  93740. FLAC__double error = 0.0;
  93741. FLAC__int32 q;
  93742. for(i = 0; i < order; i++) {
  93743. error += lp_coeff[i] * (1 << *shift);
  93744. #if 1 /* unfortunately lround() is C99 */
  93745. if(error >= 0.0)
  93746. q = (FLAC__int32)(error + 0.5);
  93747. else
  93748. q = (FLAC__int32)(error - 0.5);
  93749. #else
  93750. q = lround(error);
  93751. #endif
  93752. #ifdef FLAC__OVERFLOW_DETECT
  93753. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93754. 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]);
  93755. else if(q < qmin)
  93756. 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]);
  93757. #endif
  93758. if(q > qmax)
  93759. q = qmax;
  93760. else if(q < qmin)
  93761. q = qmin;
  93762. error -= q;
  93763. qlp_coeff[i] = q;
  93764. }
  93765. }
  93766. /* negative shift is very rare but due to design flaw, negative shift is
  93767. * a NOP in the decoder, so it must be handled specially by scaling down
  93768. * coeffs
  93769. */
  93770. else {
  93771. const int nshift = -(*shift);
  93772. FLAC__double error = 0.0;
  93773. FLAC__int32 q;
  93774. #ifdef DEBUG
  93775. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  93776. #endif
  93777. for(i = 0; i < order; i++) {
  93778. error += lp_coeff[i] / (1 << nshift);
  93779. #if 1 /* unfortunately lround() is C99 */
  93780. if(error >= 0.0)
  93781. q = (FLAC__int32)(error + 0.5);
  93782. else
  93783. q = (FLAC__int32)(error - 0.5);
  93784. #else
  93785. q = lround(error);
  93786. #endif
  93787. #ifdef FLAC__OVERFLOW_DETECT
  93788. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93789. 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]);
  93790. else if(q < qmin)
  93791. 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]);
  93792. #endif
  93793. if(q > qmax)
  93794. q = qmax;
  93795. else if(q < qmin)
  93796. q = qmin;
  93797. error -= q;
  93798. qlp_coeff[i] = q;
  93799. }
  93800. *shift = 0;
  93801. }
  93802. return 0;
  93803. }
  93804. 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[])
  93805. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93806. {
  93807. FLAC__int64 sumo;
  93808. unsigned i, j;
  93809. FLAC__int32 sum;
  93810. const FLAC__int32 *history;
  93811. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93812. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93813. for(i=0;i<order;i++)
  93814. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93815. fprintf(stderr,"\n");
  93816. #endif
  93817. FLAC__ASSERT(order > 0);
  93818. for(i = 0; i < data_len; i++) {
  93819. sumo = 0;
  93820. sum = 0;
  93821. history = data;
  93822. for(j = 0; j < order; j++) {
  93823. sum += qlp_coeff[j] * (*(--history));
  93824. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93825. #if defined _MSC_VER
  93826. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93827. 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);
  93828. #else
  93829. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93830. 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);
  93831. #endif
  93832. }
  93833. *(residual++) = *(data++) - (sum >> lp_quantization);
  93834. }
  93835. /* Here's a slower but clearer version:
  93836. for(i = 0; i < data_len; i++) {
  93837. sum = 0;
  93838. for(j = 0; j < order; j++)
  93839. sum += qlp_coeff[j] * data[i-j-1];
  93840. residual[i] = data[i] - (sum >> lp_quantization);
  93841. }
  93842. */
  93843. }
  93844. #else /* fully unrolled version for normal use */
  93845. {
  93846. int i;
  93847. FLAC__int32 sum;
  93848. FLAC__ASSERT(order > 0);
  93849. FLAC__ASSERT(order <= 32);
  93850. /*
  93851. * We do unique versions up to 12th order since that's the subset limit.
  93852. * Also they are roughly ordered to match frequency of occurrence to
  93853. * minimize branching.
  93854. */
  93855. if(order <= 12) {
  93856. if(order > 8) {
  93857. if(order > 10) {
  93858. if(order == 12) {
  93859. for(i = 0; i < (int)data_len; i++) {
  93860. sum = 0;
  93861. sum += qlp_coeff[11] * data[i-12];
  93862. sum += qlp_coeff[10] * data[i-11];
  93863. sum += qlp_coeff[9] * data[i-10];
  93864. sum += qlp_coeff[8] * data[i-9];
  93865. sum += qlp_coeff[7] * data[i-8];
  93866. sum += qlp_coeff[6] * data[i-7];
  93867. sum += qlp_coeff[5] * data[i-6];
  93868. sum += qlp_coeff[4] * data[i-5];
  93869. sum += qlp_coeff[3] * data[i-4];
  93870. sum += qlp_coeff[2] * data[i-3];
  93871. sum += qlp_coeff[1] * data[i-2];
  93872. sum += qlp_coeff[0] * data[i-1];
  93873. residual[i] = data[i] - (sum >> lp_quantization);
  93874. }
  93875. }
  93876. else { /* order == 11 */
  93877. for(i = 0; i < (int)data_len; i++) {
  93878. sum = 0;
  93879. sum += qlp_coeff[10] * data[i-11];
  93880. sum += qlp_coeff[9] * data[i-10];
  93881. sum += qlp_coeff[8] * data[i-9];
  93882. sum += qlp_coeff[7] * data[i-8];
  93883. sum += qlp_coeff[6] * data[i-7];
  93884. sum += qlp_coeff[5] * data[i-6];
  93885. sum += qlp_coeff[4] * data[i-5];
  93886. sum += qlp_coeff[3] * data[i-4];
  93887. sum += qlp_coeff[2] * data[i-3];
  93888. sum += qlp_coeff[1] * data[i-2];
  93889. sum += qlp_coeff[0] * data[i-1];
  93890. residual[i] = data[i] - (sum >> lp_quantization);
  93891. }
  93892. }
  93893. }
  93894. else {
  93895. if(order == 10) {
  93896. for(i = 0; i < (int)data_len; i++) {
  93897. sum = 0;
  93898. sum += qlp_coeff[9] * data[i-10];
  93899. sum += qlp_coeff[8] * data[i-9];
  93900. sum += qlp_coeff[7] * data[i-8];
  93901. sum += qlp_coeff[6] * data[i-7];
  93902. sum += qlp_coeff[5] * data[i-6];
  93903. sum += qlp_coeff[4] * data[i-5];
  93904. sum += qlp_coeff[3] * data[i-4];
  93905. sum += qlp_coeff[2] * data[i-3];
  93906. sum += qlp_coeff[1] * data[i-2];
  93907. sum += qlp_coeff[0] * data[i-1];
  93908. residual[i] = data[i] - (sum >> lp_quantization);
  93909. }
  93910. }
  93911. else { /* order == 9 */
  93912. for(i = 0; i < (int)data_len; i++) {
  93913. sum = 0;
  93914. sum += qlp_coeff[8] * data[i-9];
  93915. sum += qlp_coeff[7] * data[i-8];
  93916. sum += qlp_coeff[6] * data[i-7];
  93917. sum += qlp_coeff[5] * data[i-6];
  93918. sum += qlp_coeff[4] * data[i-5];
  93919. sum += qlp_coeff[3] * data[i-4];
  93920. sum += qlp_coeff[2] * data[i-3];
  93921. sum += qlp_coeff[1] * data[i-2];
  93922. sum += qlp_coeff[0] * data[i-1];
  93923. residual[i] = data[i] - (sum >> lp_quantization);
  93924. }
  93925. }
  93926. }
  93927. }
  93928. else if(order > 4) {
  93929. if(order > 6) {
  93930. if(order == 8) {
  93931. for(i = 0; i < (int)data_len; i++) {
  93932. sum = 0;
  93933. sum += qlp_coeff[7] * data[i-8];
  93934. sum += qlp_coeff[6] * data[i-7];
  93935. sum += qlp_coeff[5] * data[i-6];
  93936. sum += qlp_coeff[4] * data[i-5];
  93937. sum += qlp_coeff[3] * data[i-4];
  93938. sum += qlp_coeff[2] * data[i-3];
  93939. sum += qlp_coeff[1] * data[i-2];
  93940. sum += qlp_coeff[0] * data[i-1];
  93941. residual[i] = data[i] - (sum >> lp_quantization);
  93942. }
  93943. }
  93944. else { /* order == 7 */
  93945. for(i = 0; i < (int)data_len; i++) {
  93946. sum = 0;
  93947. sum += qlp_coeff[6] * data[i-7];
  93948. sum += qlp_coeff[5] * data[i-6];
  93949. sum += qlp_coeff[4] * data[i-5];
  93950. sum += qlp_coeff[3] * data[i-4];
  93951. sum += qlp_coeff[2] * data[i-3];
  93952. sum += qlp_coeff[1] * data[i-2];
  93953. sum += qlp_coeff[0] * data[i-1];
  93954. residual[i] = data[i] - (sum >> lp_quantization);
  93955. }
  93956. }
  93957. }
  93958. else {
  93959. if(order == 6) {
  93960. for(i = 0; i < (int)data_len; i++) {
  93961. sum = 0;
  93962. sum += qlp_coeff[5] * data[i-6];
  93963. sum += qlp_coeff[4] * data[i-5];
  93964. sum += qlp_coeff[3] * data[i-4];
  93965. sum += qlp_coeff[2] * data[i-3];
  93966. sum += qlp_coeff[1] * data[i-2];
  93967. sum += qlp_coeff[0] * data[i-1];
  93968. residual[i] = data[i] - (sum >> lp_quantization);
  93969. }
  93970. }
  93971. else { /* order == 5 */
  93972. for(i = 0; i < (int)data_len; i++) {
  93973. sum = 0;
  93974. sum += qlp_coeff[4] * data[i-5];
  93975. sum += qlp_coeff[3] * data[i-4];
  93976. sum += qlp_coeff[2] * data[i-3];
  93977. sum += qlp_coeff[1] * data[i-2];
  93978. sum += qlp_coeff[0] * data[i-1];
  93979. residual[i] = data[i] - (sum >> lp_quantization);
  93980. }
  93981. }
  93982. }
  93983. }
  93984. else {
  93985. if(order > 2) {
  93986. if(order == 4) {
  93987. for(i = 0; i < (int)data_len; i++) {
  93988. sum = 0;
  93989. sum += qlp_coeff[3] * data[i-4];
  93990. sum += qlp_coeff[2] * data[i-3];
  93991. sum += qlp_coeff[1] * data[i-2];
  93992. sum += qlp_coeff[0] * data[i-1];
  93993. residual[i] = data[i] - (sum >> lp_quantization);
  93994. }
  93995. }
  93996. else { /* order == 3 */
  93997. for(i = 0; i < (int)data_len; i++) {
  93998. sum = 0;
  93999. sum += qlp_coeff[2] * data[i-3];
  94000. sum += qlp_coeff[1] * data[i-2];
  94001. sum += qlp_coeff[0] * data[i-1];
  94002. residual[i] = data[i] - (sum >> lp_quantization);
  94003. }
  94004. }
  94005. }
  94006. else {
  94007. if(order == 2) {
  94008. for(i = 0; i < (int)data_len; i++) {
  94009. sum = 0;
  94010. sum += qlp_coeff[1] * data[i-2];
  94011. sum += qlp_coeff[0] * data[i-1];
  94012. residual[i] = data[i] - (sum >> lp_quantization);
  94013. }
  94014. }
  94015. else { /* order == 1 */
  94016. for(i = 0; i < (int)data_len; i++)
  94017. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  94018. }
  94019. }
  94020. }
  94021. }
  94022. else { /* order > 12 */
  94023. for(i = 0; i < (int)data_len; i++) {
  94024. sum = 0;
  94025. switch(order) {
  94026. case 32: sum += qlp_coeff[31] * data[i-32];
  94027. case 31: sum += qlp_coeff[30] * data[i-31];
  94028. case 30: sum += qlp_coeff[29] * data[i-30];
  94029. case 29: sum += qlp_coeff[28] * data[i-29];
  94030. case 28: sum += qlp_coeff[27] * data[i-28];
  94031. case 27: sum += qlp_coeff[26] * data[i-27];
  94032. case 26: sum += qlp_coeff[25] * data[i-26];
  94033. case 25: sum += qlp_coeff[24] * data[i-25];
  94034. case 24: sum += qlp_coeff[23] * data[i-24];
  94035. case 23: sum += qlp_coeff[22] * data[i-23];
  94036. case 22: sum += qlp_coeff[21] * data[i-22];
  94037. case 21: sum += qlp_coeff[20] * data[i-21];
  94038. case 20: sum += qlp_coeff[19] * data[i-20];
  94039. case 19: sum += qlp_coeff[18] * data[i-19];
  94040. case 18: sum += qlp_coeff[17] * data[i-18];
  94041. case 17: sum += qlp_coeff[16] * data[i-17];
  94042. case 16: sum += qlp_coeff[15] * data[i-16];
  94043. case 15: sum += qlp_coeff[14] * data[i-15];
  94044. case 14: sum += qlp_coeff[13] * data[i-14];
  94045. case 13: sum += qlp_coeff[12] * data[i-13];
  94046. sum += qlp_coeff[11] * data[i-12];
  94047. sum += qlp_coeff[10] * data[i-11];
  94048. sum += qlp_coeff[ 9] * data[i-10];
  94049. sum += qlp_coeff[ 8] * data[i- 9];
  94050. sum += qlp_coeff[ 7] * data[i- 8];
  94051. sum += qlp_coeff[ 6] * data[i- 7];
  94052. sum += qlp_coeff[ 5] * data[i- 6];
  94053. sum += qlp_coeff[ 4] * data[i- 5];
  94054. sum += qlp_coeff[ 3] * data[i- 4];
  94055. sum += qlp_coeff[ 2] * data[i- 3];
  94056. sum += qlp_coeff[ 1] * data[i- 2];
  94057. sum += qlp_coeff[ 0] * data[i- 1];
  94058. }
  94059. residual[i] = data[i] - (sum >> lp_quantization);
  94060. }
  94061. }
  94062. }
  94063. #endif
  94064. 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[])
  94065. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94066. {
  94067. unsigned i, j;
  94068. FLAC__int64 sum;
  94069. const FLAC__int32 *history;
  94070. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94071. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94072. for(i=0;i<order;i++)
  94073. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94074. fprintf(stderr,"\n");
  94075. #endif
  94076. FLAC__ASSERT(order > 0);
  94077. for(i = 0; i < data_len; i++) {
  94078. sum = 0;
  94079. history = data;
  94080. for(j = 0; j < order; j++)
  94081. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94082. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94083. #if defined _MSC_VER
  94084. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94085. #else
  94086. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94087. #endif
  94088. break;
  94089. }
  94090. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  94091. #if defined _MSC_VER
  94092. 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));
  94093. #else
  94094. 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)));
  94095. #endif
  94096. break;
  94097. }
  94098. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  94099. }
  94100. }
  94101. #else /* fully unrolled version for normal use */
  94102. {
  94103. int i;
  94104. FLAC__int64 sum;
  94105. FLAC__ASSERT(order > 0);
  94106. FLAC__ASSERT(order <= 32);
  94107. /*
  94108. * We do unique versions up to 12th order since that's the subset limit.
  94109. * Also they are roughly ordered to match frequency of occurrence to
  94110. * minimize branching.
  94111. */
  94112. if(order <= 12) {
  94113. if(order > 8) {
  94114. if(order > 10) {
  94115. if(order == 12) {
  94116. for(i = 0; i < (int)data_len; i++) {
  94117. sum = 0;
  94118. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94119. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94120. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94121. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94122. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94123. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94124. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94125. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94126. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94127. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94128. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94129. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94130. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94131. }
  94132. }
  94133. else { /* order == 11 */
  94134. for(i = 0; i < (int)data_len; i++) {
  94135. sum = 0;
  94136. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94137. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94138. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94139. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94140. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94141. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94142. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94143. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94144. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94145. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94146. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94147. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94148. }
  94149. }
  94150. }
  94151. else {
  94152. if(order == 10) {
  94153. for(i = 0; i < (int)data_len; i++) {
  94154. sum = 0;
  94155. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94156. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94157. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94158. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94159. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94160. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94161. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94162. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94163. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94164. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94165. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94166. }
  94167. }
  94168. else { /* order == 9 */
  94169. for(i = 0; i < (int)data_len; i++) {
  94170. sum = 0;
  94171. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94172. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94173. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94174. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94175. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94176. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94177. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94178. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94179. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94180. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94181. }
  94182. }
  94183. }
  94184. }
  94185. else if(order > 4) {
  94186. if(order > 6) {
  94187. if(order == 8) {
  94188. for(i = 0; i < (int)data_len; i++) {
  94189. sum = 0;
  94190. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94191. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94192. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94193. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94194. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94195. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94196. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94197. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94198. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94199. }
  94200. }
  94201. else { /* order == 7 */
  94202. for(i = 0; i < (int)data_len; i++) {
  94203. sum = 0;
  94204. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94205. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94206. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94207. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94208. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94209. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94210. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94211. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94212. }
  94213. }
  94214. }
  94215. else {
  94216. if(order == 6) {
  94217. for(i = 0; i < (int)data_len; i++) {
  94218. sum = 0;
  94219. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94220. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94221. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94222. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94223. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94224. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94225. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94226. }
  94227. }
  94228. else { /* order == 5 */
  94229. for(i = 0; i < (int)data_len; i++) {
  94230. sum = 0;
  94231. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94232. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94233. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94234. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94235. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94236. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94237. }
  94238. }
  94239. }
  94240. }
  94241. else {
  94242. if(order > 2) {
  94243. if(order == 4) {
  94244. for(i = 0; i < (int)data_len; i++) {
  94245. sum = 0;
  94246. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94247. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94248. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94249. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94250. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94251. }
  94252. }
  94253. else { /* order == 3 */
  94254. for(i = 0; i < (int)data_len; i++) {
  94255. sum = 0;
  94256. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94257. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94258. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94259. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94260. }
  94261. }
  94262. }
  94263. else {
  94264. if(order == 2) {
  94265. for(i = 0; i < (int)data_len; i++) {
  94266. sum = 0;
  94267. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94268. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94269. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94270. }
  94271. }
  94272. else { /* order == 1 */
  94273. for(i = 0; i < (int)data_len; i++)
  94274. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94275. }
  94276. }
  94277. }
  94278. }
  94279. else { /* order > 12 */
  94280. for(i = 0; i < (int)data_len; i++) {
  94281. sum = 0;
  94282. switch(order) {
  94283. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94284. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94285. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94286. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94287. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94288. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94289. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94290. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94291. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94292. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94293. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94294. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94295. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94296. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94297. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94298. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94299. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94300. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94301. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94302. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94303. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94304. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94305. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94306. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94307. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94308. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94309. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94310. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94311. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94312. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94313. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94314. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94315. }
  94316. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94317. }
  94318. }
  94319. }
  94320. #endif
  94321. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94322. 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[])
  94323. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94324. {
  94325. FLAC__int64 sumo;
  94326. unsigned i, j;
  94327. FLAC__int32 sum;
  94328. const FLAC__int32 *r = residual, *history;
  94329. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94330. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94331. for(i=0;i<order;i++)
  94332. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94333. fprintf(stderr,"\n");
  94334. #endif
  94335. FLAC__ASSERT(order > 0);
  94336. for(i = 0; i < data_len; i++) {
  94337. sumo = 0;
  94338. sum = 0;
  94339. history = data;
  94340. for(j = 0; j < order; j++) {
  94341. sum += qlp_coeff[j] * (*(--history));
  94342. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  94343. #if defined _MSC_VER
  94344. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  94345. 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);
  94346. #else
  94347. if(sumo > 2147483647ll || sumo < -2147483648ll)
  94348. 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);
  94349. #endif
  94350. }
  94351. *(data++) = *(r++) + (sum >> lp_quantization);
  94352. }
  94353. /* Here's a slower but clearer version:
  94354. for(i = 0; i < data_len; i++) {
  94355. sum = 0;
  94356. for(j = 0; j < order; j++)
  94357. sum += qlp_coeff[j] * data[i-j-1];
  94358. data[i] = residual[i] + (sum >> lp_quantization);
  94359. }
  94360. */
  94361. }
  94362. #else /* fully unrolled version for normal use */
  94363. {
  94364. int i;
  94365. FLAC__int32 sum;
  94366. FLAC__ASSERT(order > 0);
  94367. FLAC__ASSERT(order <= 32);
  94368. /*
  94369. * We do unique versions up to 12th order since that's the subset limit.
  94370. * Also they are roughly ordered to match frequency of occurrence to
  94371. * minimize branching.
  94372. */
  94373. if(order <= 12) {
  94374. if(order > 8) {
  94375. if(order > 10) {
  94376. if(order == 12) {
  94377. for(i = 0; i < (int)data_len; i++) {
  94378. sum = 0;
  94379. sum += qlp_coeff[11] * data[i-12];
  94380. sum += qlp_coeff[10] * data[i-11];
  94381. sum += qlp_coeff[9] * data[i-10];
  94382. sum += qlp_coeff[8] * data[i-9];
  94383. sum += qlp_coeff[7] * data[i-8];
  94384. sum += qlp_coeff[6] * data[i-7];
  94385. sum += qlp_coeff[5] * data[i-6];
  94386. sum += qlp_coeff[4] * data[i-5];
  94387. sum += qlp_coeff[3] * data[i-4];
  94388. sum += qlp_coeff[2] * data[i-3];
  94389. sum += qlp_coeff[1] * data[i-2];
  94390. sum += qlp_coeff[0] * data[i-1];
  94391. data[i] = residual[i] + (sum >> lp_quantization);
  94392. }
  94393. }
  94394. else { /* order == 11 */
  94395. for(i = 0; i < (int)data_len; i++) {
  94396. sum = 0;
  94397. sum += qlp_coeff[10] * data[i-11];
  94398. sum += qlp_coeff[9] * data[i-10];
  94399. sum += qlp_coeff[8] * data[i-9];
  94400. sum += qlp_coeff[7] * data[i-8];
  94401. sum += qlp_coeff[6] * data[i-7];
  94402. sum += qlp_coeff[5] * data[i-6];
  94403. sum += qlp_coeff[4] * data[i-5];
  94404. sum += qlp_coeff[3] * data[i-4];
  94405. sum += qlp_coeff[2] * data[i-3];
  94406. sum += qlp_coeff[1] * data[i-2];
  94407. sum += qlp_coeff[0] * data[i-1];
  94408. data[i] = residual[i] + (sum >> lp_quantization);
  94409. }
  94410. }
  94411. }
  94412. else {
  94413. if(order == 10) {
  94414. for(i = 0; i < (int)data_len; i++) {
  94415. sum = 0;
  94416. sum += qlp_coeff[9] * data[i-10];
  94417. sum += qlp_coeff[8] * data[i-9];
  94418. sum += qlp_coeff[7] * data[i-8];
  94419. sum += qlp_coeff[6] * data[i-7];
  94420. sum += qlp_coeff[5] * data[i-6];
  94421. sum += qlp_coeff[4] * data[i-5];
  94422. sum += qlp_coeff[3] * data[i-4];
  94423. sum += qlp_coeff[2] * data[i-3];
  94424. sum += qlp_coeff[1] * data[i-2];
  94425. sum += qlp_coeff[0] * data[i-1];
  94426. data[i] = residual[i] + (sum >> lp_quantization);
  94427. }
  94428. }
  94429. else { /* order == 9 */
  94430. for(i = 0; i < (int)data_len; i++) {
  94431. sum = 0;
  94432. sum += qlp_coeff[8] * data[i-9];
  94433. sum += qlp_coeff[7] * data[i-8];
  94434. sum += qlp_coeff[6] * data[i-7];
  94435. sum += qlp_coeff[5] * data[i-6];
  94436. sum += qlp_coeff[4] * data[i-5];
  94437. sum += qlp_coeff[3] * data[i-4];
  94438. sum += qlp_coeff[2] * data[i-3];
  94439. sum += qlp_coeff[1] * data[i-2];
  94440. sum += qlp_coeff[0] * data[i-1];
  94441. data[i] = residual[i] + (sum >> lp_quantization);
  94442. }
  94443. }
  94444. }
  94445. }
  94446. else if(order > 4) {
  94447. if(order > 6) {
  94448. if(order == 8) {
  94449. for(i = 0; i < (int)data_len; i++) {
  94450. sum = 0;
  94451. sum += qlp_coeff[7] * data[i-8];
  94452. sum += qlp_coeff[6] * data[i-7];
  94453. sum += qlp_coeff[5] * data[i-6];
  94454. sum += qlp_coeff[4] * data[i-5];
  94455. sum += qlp_coeff[3] * data[i-4];
  94456. sum += qlp_coeff[2] * data[i-3];
  94457. sum += qlp_coeff[1] * data[i-2];
  94458. sum += qlp_coeff[0] * data[i-1];
  94459. data[i] = residual[i] + (sum >> lp_quantization);
  94460. }
  94461. }
  94462. else { /* order == 7 */
  94463. for(i = 0; i < (int)data_len; i++) {
  94464. sum = 0;
  94465. sum += qlp_coeff[6] * data[i-7];
  94466. sum += qlp_coeff[5] * data[i-6];
  94467. sum += qlp_coeff[4] * data[i-5];
  94468. sum += qlp_coeff[3] * data[i-4];
  94469. sum += qlp_coeff[2] * data[i-3];
  94470. sum += qlp_coeff[1] * data[i-2];
  94471. sum += qlp_coeff[0] * data[i-1];
  94472. data[i] = residual[i] + (sum >> lp_quantization);
  94473. }
  94474. }
  94475. }
  94476. else {
  94477. if(order == 6) {
  94478. for(i = 0; i < (int)data_len; i++) {
  94479. sum = 0;
  94480. sum += qlp_coeff[5] * data[i-6];
  94481. sum += qlp_coeff[4] * data[i-5];
  94482. sum += qlp_coeff[3] * data[i-4];
  94483. sum += qlp_coeff[2] * data[i-3];
  94484. sum += qlp_coeff[1] * data[i-2];
  94485. sum += qlp_coeff[0] * data[i-1];
  94486. data[i] = residual[i] + (sum >> lp_quantization);
  94487. }
  94488. }
  94489. else { /* order == 5 */
  94490. for(i = 0; i < (int)data_len; i++) {
  94491. sum = 0;
  94492. sum += qlp_coeff[4] * data[i-5];
  94493. sum += qlp_coeff[3] * data[i-4];
  94494. sum += qlp_coeff[2] * data[i-3];
  94495. sum += qlp_coeff[1] * data[i-2];
  94496. sum += qlp_coeff[0] * data[i-1];
  94497. data[i] = residual[i] + (sum >> lp_quantization);
  94498. }
  94499. }
  94500. }
  94501. }
  94502. else {
  94503. if(order > 2) {
  94504. if(order == 4) {
  94505. for(i = 0; i < (int)data_len; i++) {
  94506. sum = 0;
  94507. sum += qlp_coeff[3] * data[i-4];
  94508. sum += qlp_coeff[2] * data[i-3];
  94509. sum += qlp_coeff[1] * data[i-2];
  94510. sum += qlp_coeff[0] * data[i-1];
  94511. data[i] = residual[i] + (sum >> lp_quantization);
  94512. }
  94513. }
  94514. else { /* order == 3 */
  94515. for(i = 0; i < (int)data_len; i++) {
  94516. sum = 0;
  94517. sum += qlp_coeff[2] * data[i-3];
  94518. sum += qlp_coeff[1] * data[i-2];
  94519. sum += qlp_coeff[0] * data[i-1];
  94520. data[i] = residual[i] + (sum >> lp_quantization);
  94521. }
  94522. }
  94523. }
  94524. else {
  94525. if(order == 2) {
  94526. for(i = 0; i < (int)data_len; i++) {
  94527. sum = 0;
  94528. sum += qlp_coeff[1] * data[i-2];
  94529. sum += qlp_coeff[0] * data[i-1];
  94530. data[i] = residual[i] + (sum >> lp_quantization);
  94531. }
  94532. }
  94533. else { /* order == 1 */
  94534. for(i = 0; i < (int)data_len; i++)
  94535. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  94536. }
  94537. }
  94538. }
  94539. }
  94540. else { /* order > 12 */
  94541. for(i = 0; i < (int)data_len; i++) {
  94542. sum = 0;
  94543. switch(order) {
  94544. case 32: sum += qlp_coeff[31] * data[i-32];
  94545. case 31: sum += qlp_coeff[30] * data[i-31];
  94546. case 30: sum += qlp_coeff[29] * data[i-30];
  94547. case 29: sum += qlp_coeff[28] * data[i-29];
  94548. case 28: sum += qlp_coeff[27] * data[i-28];
  94549. case 27: sum += qlp_coeff[26] * data[i-27];
  94550. case 26: sum += qlp_coeff[25] * data[i-26];
  94551. case 25: sum += qlp_coeff[24] * data[i-25];
  94552. case 24: sum += qlp_coeff[23] * data[i-24];
  94553. case 23: sum += qlp_coeff[22] * data[i-23];
  94554. case 22: sum += qlp_coeff[21] * data[i-22];
  94555. case 21: sum += qlp_coeff[20] * data[i-21];
  94556. case 20: sum += qlp_coeff[19] * data[i-20];
  94557. case 19: sum += qlp_coeff[18] * data[i-19];
  94558. case 18: sum += qlp_coeff[17] * data[i-18];
  94559. case 17: sum += qlp_coeff[16] * data[i-17];
  94560. case 16: sum += qlp_coeff[15] * data[i-16];
  94561. case 15: sum += qlp_coeff[14] * data[i-15];
  94562. case 14: sum += qlp_coeff[13] * data[i-14];
  94563. case 13: sum += qlp_coeff[12] * data[i-13];
  94564. sum += qlp_coeff[11] * data[i-12];
  94565. sum += qlp_coeff[10] * data[i-11];
  94566. sum += qlp_coeff[ 9] * data[i-10];
  94567. sum += qlp_coeff[ 8] * data[i- 9];
  94568. sum += qlp_coeff[ 7] * data[i- 8];
  94569. sum += qlp_coeff[ 6] * data[i- 7];
  94570. sum += qlp_coeff[ 5] * data[i- 6];
  94571. sum += qlp_coeff[ 4] * data[i- 5];
  94572. sum += qlp_coeff[ 3] * data[i- 4];
  94573. sum += qlp_coeff[ 2] * data[i- 3];
  94574. sum += qlp_coeff[ 1] * data[i- 2];
  94575. sum += qlp_coeff[ 0] * data[i- 1];
  94576. }
  94577. data[i] = residual[i] + (sum >> lp_quantization);
  94578. }
  94579. }
  94580. }
  94581. #endif
  94582. 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[])
  94583. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94584. {
  94585. unsigned i, j;
  94586. FLAC__int64 sum;
  94587. const FLAC__int32 *r = residual, *history;
  94588. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94589. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94590. for(i=0;i<order;i++)
  94591. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94592. fprintf(stderr,"\n");
  94593. #endif
  94594. FLAC__ASSERT(order > 0);
  94595. for(i = 0; i < data_len; i++) {
  94596. sum = 0;
  94597. history = data;
  94598. for(j = 0; j < order; j++)
  94599. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94600. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94601. #ifdef _MSC_VER
  94602. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94603. #else
  94604. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94605. #endif
  94606. break;
  94607. }
  94608. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  94609. #ifdef _MSC_VER
  94610. 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));
  94611. #else
  94612. 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)));
  94613. #endif
  94614. break;
  94615. }
  94616. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  94617. }
  94618. }
  94619. #else /* fully unrolled version for normal use */
  94620. {
  94621. int i;
  94622. FLAC__int64 sum;
  94623. FLAC__ASSERT(order > 0);
  94624. FLAC__ASSERT(order <= 32);
  94625. /*
  94626. * We do unique versions up to 12th order since that's the subset limit.
  94627. * Also they are roughly ordered to match frequency of occurrence to
  94628. * minimize branching.
  94629. */
  94630. if(order <= 12) {
  94631. if(order > 8) {
  94632. if(order > 10) {
  94633. if(order == 12) {
  94634. for(i = 0; i < (int)data_len; i++) {
  94635. sum = 0;
  94636. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94637. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94638. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94639. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94640. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94641. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94642. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94643. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94644. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94645. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94646. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94647. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94648. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94649. }
  94650. }
  94651. else { /* order == 11 */
  94652. for(i = 0; i < (int)data_len; i++) {
  94653. sum = 0;
  94654. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94655. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94656. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94657. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94658. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94659. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94660. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94661. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94662. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94663. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94664. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94665. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94666. }
  94667. }
  94668. }
  94669. else {
  94670. if(order == 10) {
  94671. for(i = 0; i < (int)data_len; i++) {
  94672. sum = 0;
  94673. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94674. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94675. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94676. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94677. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94678. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94679. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94680. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94681. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94682. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94683. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94684. }
  94685. }
  94686. else { /* order == 9 */
  94687. for(i = 0; i < (int)data_len; i++) {
  94688. sum = 0;
  94689. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94690. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94691. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94692. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94693. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94694. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94695. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94696. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94697. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94698. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94699. }
  94700. }
  94701. }
  94702. }
  94703. else if(order > 4) {
  94704. if(order > 6) {
  94705. if(order == 8) {
  94706. for(i = 0; i < (int)data_len; i++) {
  94707. sum = 0;
  94708. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94709. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94710. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94711. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94712. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94713. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94714. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94715. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94716. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94717. }
  94718. }
  94719. else { /* order == 7 */
  94720. for(i = 0; i < (int)data_len; i++) {
  94721. sum = 0;
  94722. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94723. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94724. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94725. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94726. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94727. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94728. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94729. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94730. }
  94731. }
  94732. }
  94733. else {
  94734. if(order == 6) {
  94735. for(i = 0; i < (int)data_len; i++) {
  94736. sum = 0;
  94737. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94738. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94739. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94740. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94741. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94742. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94743. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94744. }
  94745. }
  94746. else { /* order == 5 */
  94747. for(i = 0; i < (int)data_len; i++) {
  94748. sum = 0;
  94749. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94750. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94751. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94752. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94753. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94754. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94755. }
  94756. }
  94757. }
  94758. }
  94759. else {
  94760. if(order > 2) {
  94761. if(order == 4) {
  94762. for(i = 0; i < (int)data_len; i++) {
  94763. sum = 0;
  94764. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94765. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94766. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94767. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94768. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94769. }
  94770. }
  94771. else { /* order == 3 */
  94772. for(i = 0; i < (int)data_len; i++) {
  94773. sum = 0;
  94774. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94775. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94776. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94777. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94778. }
  94779. }
  94780. }
  94781. else {
  94782. if(order == 2) {
  94783. for(i = 0; i < (int)data_len; i++) {
  94784. sum = 0;
  94785. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94786. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94787. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94788. }
  94789. }
  94790. else { /* order == 1 */
  94791. for(i = 0; i < (int)data_len; i++)
  94792. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94793. }
  94794. }
  94795. }
  94796. }
  94797. else { /* order > 12 */
  94798. for(i = 0; i < (int)data_len; i++) {
  94799. sum = 0;
  94800. switch(order) {
  94801. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94802. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94803. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94804. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94805. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94806. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94807. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94808. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94809. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94810. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94811. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94812. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94813. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94814. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94815. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94816. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94817. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94818. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94819. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94820. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94821. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94822. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94823. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94824. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94825. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94826. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94827. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94828. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94829. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94830. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94831. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94832. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94833. }
  94834. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94835. }
  94836. }
  94837. }
  94838. #endif
  94839. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94840. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  94841. {
  94842. FLAC__double error_scale;
  94843. FLAC__ASSERT(total_samples > 0);
  94844. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94845. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  94846. }
  94847. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  94848. {
  94849. if(lpc_error > 0.0) {
  94850. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  94851. if(bps >= 0.0)
  94852. return bps;
  94853. else
  94854. return 0.0;
  94855. }
  94856. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  94857. return 1e32;
  94858. }
  94859. else {
  94860. return 0.0;
  94861. }
  94862. }
  94863. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  94864. {
  94865. 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 */
  94866. FLAC__double bits, best_bits, error_scale;
  94867. FLAC__ASSERT(max_order > 0);
  94868. FLAC__ASSERT(total_samples > 0);
  94869. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94870. best_index = 0;
  94871. best_bits = (unsigned)(-1);
  94872. for(index = 0, order = 1; index < max_order; index++, order++) {
  94873. 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);
  94874. if(bits < best_bits) {
  94875. best_index = index;
  94876. best_bits = bits;
  94877. }
  94878. }
  94879. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  94880. }
  94881. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94882. #endif
  94883. /*** End of inlined file: lpc_flac.c ***/
  94884. /*** Start of inlined file: md5.c ***/
  94885. /*** Start of inlined file: juce_FlacHeader.h ***/
  94886. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94887. // tasks..
  94888. #define VERSION "1.2.1"
  94889. #define FLAC__NO_DLL 1
  94890. #if JUCE_MSVC
  94891. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94892. #endif
  94893. #if JUCE_MAC
  94894. #define FLAC__SYS_DARWIN 1
  94895. #endif
  94896. /*** End of inlined file: juce_FlacHeader.h ***/
  94897. #if JUCE_USE_FLAC
  94898. #if HAVE_CONFIG_H
  94899. # include <config.h>
  94900. #endif
  94901. #include <stdlib.h> /* for malloc() */
  94902. #include <string.h> /* for memcpy() */
  94903. /*** Start of inlined file: md5.h ***/
  94904. #ifndef FLAC__PRIVATE__MD5_H
  94905. #define FLAC__PRIVATE__MD5_H
  94906. /*
  94907. * This is the header file for the MD5 message-digest algorithm.
  94908. * The algorithm is due to Ron Rivest. This code was
  94909. * written by Colin Plumb in 1993, no copyright is claimed.
  94910. * This code is in the public domain; do with it what you wish.
  94911. *
  94912. * Equivalent code is available from RSA Data Security, Inc.
  94913. * This code has been tested against that, and is equivalent,
  94914. * except that you don't need to include two pages of legalese
  94915. * with every copy.
  94916. *
  94917. * To compute the message digest of a chunk of bytes, declare an
  94918. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94919. * needed on buffers full of bytes, and then call MD5Final, which
  94920. * will fill a supplied 16-byte array with the digest.
  94921. *
  94922. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94923. * header definitions; now uses stuff from dpkg's config.h
  94924. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94925. * Still in the public domain.
  94926. *
  94927. * Josh Coalson: made some changes to integrate with libFLAC.
  94928. * Still in the public domain, with no warranty.
  94929. */
  94930. typedef struct {
  94931. FLAC__uint32 in[16];
  94932. FLAC__uint32 buf[4];
  94933. FLAC__uint32 bytes[2];
  94934. FLAC__byte *internal_buf;
  94935. size_t capacity;
  94936. } FLAC__MD5Context;
  94937. void FLAC__MD5Init(FLAC__MD5Context *context);
  94938. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94939. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94940. #endif
  94941. /*** End of inlined file: md5.h ***/
  94942. #ifndef FLaC__INLINE
  94943. #define FLaC__INLINE
  94944. #endif
  94945. /*
  94946. * This code implements the MD5 message-digest algorithm.
  94947. * The algorithm is due to Ron Rivest. This code was
  94948. * written by Colin Plumb in 1993, no copyright is claimed.
  94949. * This code is in the public domain; do with it what you wish.
  94950. *
  94951. * Equivalent code is available from RSA Data Security, Inc.
  94952. * This code has been tested against that, and is equivalent,
  94953. * except that you don't need to include two pages of legalese
  94954. * with every copy.
  94955. *
  94956. * To compute the message digest of a chunk of bytes, declare an
  94957. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94958. * needed on buffers full of bytes, and then call MD5Final, which
  94959. * will fill a supplied 16-byte array with the digest.
  94960. *
  94961. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94962. * definitions; now uses stuff from dpkg's config.h.
  94963. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94964. * Still in the public domain.
  94965. *
  94966. * Josh Coalson: made some changes to integrate with libFLAC.
  94967. * Still in the public domain.
  94968. */
  94969. /* The four core functions - F1 is optimized somewhat */
  94970. /* #define F1(x, y, z) (x & y | ~x & z) */
  94971. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94972. #define F2(x, y, z) F1(z, x, y)
  94973. #define F3(x, y, z) (x ^ y ^ z)
  94974. #define F4(x, y, z) (y ^ (x | ~z))
  94975. /* This is the central step in the MD5 algorithm. */
  94976. #define MD5STEP(f,w,x,y,z,in,s) \
  94977. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94978. /*
  94979. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94980. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94981. * the data and converts bytes into longwords for this routine.
  94982. */
  94983. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94984. {
  94985. register FLAC__uint32 a, b, c, d;
  94986. a = buf[0];
  94987. b = buf[1];
  94988. c = buf[2];
  94989. d = buf[3];
  94990. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94991. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94992. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94993. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94994. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94995. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94996. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94997. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94998. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94999. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  95000. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  95001. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  95002. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  95003. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  95004. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  95005. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  95006. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  95007. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  95008. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  95009. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  95010. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  95011. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  95012. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  95013. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  95014. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  95015. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  95016. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  95017. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  95018. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  95019. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  95020. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  95021. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  95022. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  95023. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  95024. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  95025. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  95026. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  95027. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  95028. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  95029. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  95030. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  95031. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  95032. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  95033. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  95034. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  95035. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  95036. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  95037. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  95038. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  95039. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  95040. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  95041. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  95042. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  95043. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  95044. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  95045. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  95046. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  95047. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  95048. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  95049. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  95050. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  95051. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  95052. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  95053. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  95054. buf[0] += a;
  95055. buf[1] += b;
  95056. buf[2] += c;
  95057. buf[3] += d;
  95058. }
  95059. #if WORDS_BIGENDIAN
  95060. //@@@@@@ OPT: use bswap/intrinsics
  95061. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  95062. {
  95063. register FLAC__uint32 x;
  95064. do {
  95065. x = *buf;
  95066. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  95067. *buf++ = (x >> 16) | (x << 16);
  95068. } while (--words);
  95069. }
  95070. static void byteSwapX16(FLAC__uint32 *buf)
  95071. {
  95072. register FLAC__uint32 x;
  95073. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95074. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95075. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95076. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95077. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95078. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95079. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95080. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95081. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95082. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95083. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95084. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95085. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95086. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95087. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95088. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  95089. }
  95090. #else
  95091. #define byteSwap(buf, words)
  95092. #define byteSwapX16(buf)
  95093. #endif
  95094. /*
  95095. * Update context to reflect the concatenation of another buffer full
  95096. * of bytes.
  95097. */
  95098. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  95099. {
  95100. FLAC__uint32 t;
  95101. /* Update byte count */
  95102. t = ctx->bytes[0];
  95103. if ((ctx->bytes[0] = t + len) < t)
  95104. ctx->bytes[1]++; /* Carry from low to high */
  95105. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  95106. if (t > len) {
  95107. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  95108. return;
  95109. }
  95110. /* First chunk is an odd size */
  95111. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  95112. byteSwapX16(ctx->in);
  95113. FLAC__MD5Transform(ctx->buf, ctx->in);
  95114. buf += t;
  95115. len -= t;
  95116. /* Process data in 64-byte chunks */
  95117. while (len >= 64) {
  95118. memcpy(ctx->in, buf, 64);
  95119. byteSwapX16(ctx->in);
  95120. FLAC__MD5Transform(ctx->buf, ctx->in);
  95121. buf += 64;
  95122. len -= 64;
  95123. }
  95124. /* Handle any remaining bytes of data. */
  95125. memcpy(ctx->in, buf, len);
  95126. }
  95127. /*
  95128. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  95129. * initialization constants.
  95130. */
  95131. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  95132. {
  95133. ctx->buf[0] = 0x67452301;
  95134. ctx->buf[1] = 0xefcdab89;
  95135. ctx->buf[2] = 0x98badcfe;
  95136. ctx->buf[3] = 0x10325476;
  95137. ctx->bytes[0] = 0;
  95138. ctx->bytes[1] = 0;
  95139. ctx->internal_buf = 0;
  95140. ctx->capacity = 0;
  95141. }
  95142. /*
  95143. * Final wrapup - pad to 64-byte boundary with the bit pattern
  95144. * 1 0* (64-bit count of bits processed, MSB-first)
  95145. */
  95146. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  95147. {
  95148. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  95149. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  95150. /* Set the first char of padding to 0x80. There is always room. */
  95151. *p++ = 0x80;
  95152. /* Bytes of padding needed to make 56 bytes (-8..55) */
  95153. count = 56 - 1 - count;
  95154. if (count < 0) { /* Padding forces an extra block */
  95155. memset(p, 0, count + 8);
  95156. byteSwapX16(ctx->in);
  95157. FLAC__MD5Transform(ctx->buf, ctx->in);
  95158. p = (FLAC__byte *)ctx->in;
  95159. count = 56;
  95160. }
  95161. memset(p, 0, count);
  95162. byteSwap(ctx->in, 14);
  95163. /* Append length in bits and transform */
  95164. ctx->in[14] = ctx->bytes[0] << 3;
  95165. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  95166. FLAC__MD5Transform(ctx->buf, ctx->in);
  95167. byteSwap(ctx->buf, 4);
  95168. memcpy(digest, ctx->buf, 16);
  95169. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  95170. if(0 != ctx->internal_buf) {
  95171. free(ctx->internal_buf);
  95172. ctx->internal_buf = 0;
  95173. ctx->capacity = 0;
  95174. }
  95175. }
  95176. /*
  95177. * Convert the incoming audio signal to a byte stream
  95178. */
  95179. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95180. {
  95181. unsigned channel, sample;
  95182. register FLAC__int32 a_word;
  95183. register FLAC__byte *buf_ = buf;
  95184. #if WORDS_BIGENDIAN
  95185. #else
  95186. if(channels == 2 && bytes_per_sample == 2) {
  95187. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  95188. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  95189. for(sample = 0; sample < samples; sample++, buf1_+=2)
  95190. *buf1_ = (FLAC__int16)signal[1][sample];
  95191. }
  95192. else if(channels == 1 && bytes_per_sample == 2) {
  95193. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  95194. for(sample = 0; sample < samples; sample++)
  95195. *buf1_++ = (FLAC__int16)signal[0][sample];
  95196. }
  95197. else
  95198. #endif
  95199. if(bytes_per_sample == 2) {
  95200. if(channels == 2) {
  95201. for(sample = 0; sample < samples; sample++) {
  95202. a_word = signal[0][sample];
  95203. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95204. *buf_++ = (FLAC__byte)a_word;
  95205. a_word = signal[1][sample];
  95206. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95207. *buf_++ = (FLAC__byte)a_word;
  95208. }
  95209. }
  95210. else if(channels == 1) {
  95211. for(sample = 0; sample < samples; sample++) {
  95212. a_word = signal[0][sample];
  95213. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95214. *buf_++ = (FLAC__byte)a_word;
  95215. }
  95216. }
  95217. else {
  95218. for(sample = 0; sample < samples; sample++) {
  95219. for(channel = 0; channel < channels; channel++) {
  95220. a_word = signal[channel][sample];
  95221. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95222. *buf_++ = (FLAC__byte)a_word;
  95223. }
  95224. }
  95225. }
  95226. }
  95227. else if(bytes_per_sample == 3) {
  95228. if(channels == 2) {
  95229. for(sample = 0; sample < samples; sample++) {
  95230. a_word = signal[0][sample];
  95231. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95232. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95233. *buf_++ = (FLAC__byte)a_word;
  95234. a_word = signal[1][sample];
  95235. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95236. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95237. *buf_++ = (FLAC__byte)a_word;
  95238. }
  95239. }
  95240. else if(channels == 1) {
  95241. for(sample = 0; sample < samples; sample++) {
  95242. a_word = signal[0][sample];
  95243. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95244. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95245. *buf_++ = (FLAC__byte)a_word;
  95246. }
  95247. }
  95248. else {
  95249. for(sample = 0; sample < samples; sample++) {
  95250. for(channel = 0; channel < channels; channel++) {
  95251. a_word = signal[channel][sample];
  95252. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95253. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95254. *buf_++ = (FLAC__byte)a_word;
  95255. }
  95256. }
  95257. }
  95258. }
  95259. else if(bytes_per_sample == 1) {
  95260. if(channels == 2) {
  95261. for(sample = 0; sample < samples; sample++) {
  95262. a_word = signal[0][sample];
  95263. *buf_++ = (FLAC__byte)a_word;
  95264. a_word = signal[1][sample];
  95265. *buf_++ = (FLAC__byte)a_word;
  95266. }
  95267. }
  95268. else if(channels == 1) {
  95269. for(sample = 0; sample < samples; sample++) {
  95270. a_word = signal[0][sample];
  95271. *buf_++ = (FLAC__byte)a_word;
  95272. }
  95273. }
  95274. else {
  95275. for(sample = 0; sample < samples; sample++) {
  95276. for(channel = 0; channel < channels; channel++) {
  95277. a_word = signal[channel][sample];
  95278. *buf_++ = (FLAC__byte)a_word;
  95279. }
  95280. }
  95281. }
  95282. }
  95283. else { /* bytes_per_sample == 4, maybe optimize more later */
  95284. for(sample = 0; sample < samples; sample++) {
  95285. for(channel = 0; channel < channels; channel++) {
  95286. a_word = signal[channel][sample];
  95287. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95288. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95289. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95290. *buf_++ = (FLAC__byte)a_word;
  95291. }
  95292. }
  95293. }
  95294. }
  95295. /*
  95296. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  95297. */
  95298. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95299. {
  95300. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  95301. /* overflow check */
  95302. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  95303. return false;
  95304. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  95305. return false;
  95306. if(ctx->capacity < bytes_needed) {
  95307. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  95308. if(0 == tmp) {
  95309. free(ctx->internal_buf);
  95310. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  95311. return false;
  95312. }
  95313. ctx->internal_buf = tmp;
  95314. ctx->capacity = bytes_needed;
  95315. }
  95316. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  95317. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  95318. return true;
  95319. }
  95320. #endif
  95321. /*** End of inlined file: md5.c ***/
  95322. /*** Start of inlined file: memory.c ***/
  95323. /*** Start of inlined file: juce_FlacHeader.h ***/
  95324. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95325. // tasks..
  95326. #define VERSION "1.2.1"
  95327. #define FLAC__NO_DLL 1
  95328. #if JUCE_MSVC
  95329. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95330. #endif
  95331. #if JUCE_MAC
  95332. #define FLAC__SYS_DARWIN 1
  95333. #endif
  95334. /*** End of inlined file: juce_FlacHeader.h ***/
  95335. #if JUCE_USE_FLAC
  95336. #if HAVE_CONFIG_H
  95337. # include <config.h>
  95338. #endif
  95339. /*** Start of inlined file: memory.h ***/
  95340. #ifndef FLAC__PRIVATE__MEMORY_H
  95341. #define FLAC__PRIVATE__MEMORY_H
  95342. #ifdef HAVE_CONFIG_H
  95343. #include <config.h>
  95344. #endif
  95345. #include <stdlib.h> /* for size_t */
  95346. /* Returns the unaligned address returned by malloc.
  95347. * Use free() on this address to deallocate.
  95348. */
  95349. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  95350. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  95351. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  95352. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  95353. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  95354. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95355. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  95356. #endif
  95357. #endif
  95358. /*** End of inlined file: memory.h ***/
  95359. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  95360. {
  95361. void *x;
  95362. FLAC__ASSERT(0 != aligned_address);
  95363. #ifdef FLAC__ALIGN_MALLOC_DATA
  95364. /* align on 32-byte (256-bit) boundary */
  95365. x = safe_malloc_add_2op_(bytes, /*+*/31);
  95366. #ifdef SIZEOF_VOIDP
  95367. #if SIZEOF_VOIDP == 4
  95368. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  95369. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95370. #elif SIZEOF_VOIDP == 8
  95371. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95372. #else
  95373. # error Unsupported sizeof(void*)
  95374. #endif
  95375. #else
  95376. /* there's got to be a better way to do this right for all archs */
  95377. if(sizeof(void*) == sizeof(unsigned))
  95378. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95379. else if(sizeof(void*) == sizeof(FLAC__uint64))
  95380. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95381. else
  95382. return 0;
  95383. #endif
  95384. #else
  95385. x = safe_malloc_(bytes);
  95386. *aligned_address = x;
  95387. #endif
  95388. return x;
  95389. }
  95390. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  95391. {
  95392. FLAC__int32 *pu; /* unaligned pointer */
  95393. union { /* union needed to comply with C99 pointer aliasing rules */
  95394. FLAC__int32 *pa; /* aligned pointer */
  95395. void *pv; /* aligned pointer alias */
  95396. } u;
  95397. FLAC__ASSERT(elements > 0);
  95398. FLAC__ASSERT(0 != unaligned_pointer);
  95399. FLAC__ASSERT(0 != aligned_pointer);
  95400. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95401. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  95402. if(0 == pu) {
  95403. return false;
  95404. }
  95405. else {
  95406. if(*unaligned_pointer != 0)
  95407. free(*unaligned_pointer);
  95408. *unaligned_pointer = pu;
  95409. *aligned_pointer = u.pa;
  95410. return true;
  95411. }
  95412. }
  95413. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  95414. {
  95415. FLAC__uint32 *pu; /* unaligned pointer */
  95416. union { /* union needed to comply with C99 pointer aliasing rules */
  95417. FLAC__uint32 *pa; /* aligned pointer */
  95418. void *pv; /* aligned pointer alias */
  95419. } u;
  95420. FLAC__ASSERT(elements > 0);
  95421. FLAC__ASSERT(0 != unaligned_pointer);
  95422. FLAC__ASSERT(0 != aligned_pointer);
  95423. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95424. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95425. if(0 == pu) {
  95426. return false;
  95427. }
  95428. else {
  95429. if(*unaligned_pointer != 0)
  95430. free(*unaligned_pointer);
  95431. *unaligned_pointer = pu;
  95432. *aligned_pointer = u.pa;
  95433. return true;
  95434. }
  95435. }
  95436. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  95437. {
  95438. FLAC__uint64 *pu; /* unaligned pointer */
  95439. union { /* union needed to comply with C99 pointer aliasing rules */
  95440. FLAC__uint64 *pa; /* aligned pointer */
  95441. void *pv; /* aligned pointer alias */
  95442. } u;
  95443. FLAC__ASSERT(elements > 0);
  95444. FLAC__ASSERT(0 != unaligned_pointer);
  95445. FLAC__ASSERT(0 != aligned_pointer);
  95446. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95447. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95448. if(0 == pu) {
  95449. return false;
  95450. }
  95451. else {
  95452. if(*unaligned_pointer != 0)
  95453. free(*unaligned_pointer);
  95454. *unaligned_pointer = pu;
  95455. *aligned_pointer = u.pa;
  95456. return true;
  95457. }
  95458. }
  95459. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  95460. {
  95461. unsigned *pu; /* unaligned pointer */
  95462. union { /* union needed to comply with C99 pointer aliasing rules */
  95463. unsigned *pa; /* aligned pointer */
  95464. void *pv; /* aligned pointer alias */
  95465. } u;
  95466. FLAC__ASSERT(elements > 0);
  95467. FLAC__ASSERT(0 != unaligned_pointer);
  95468. FLAC__ASSERT(0 != aligned_pointer);
  95469. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95470. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95471. if(0 == pu) {
  95472. return false;
  95473. }
  95474. else {
  95475. if(*unaligned_pointer != 0)
  95476. free(*unaligned_pointer);
  95477. *unaligned_pointer = pu;
  95478. *aligned_pointer = u.pa;
  95479. return true;
  95480. }
  95481. }
  95482. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95483. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  95484. {
  95485. FLAC__real *pu; /* unaligned pointer */
  95486. union { /* union needed to comply with C99 pointer aliasing rules */
  95487. FLAC__real *pa; /* aligned pointer */
  95488. void *pv; /* aligned pointer alias */
  95489. } u;
  95490. FLAC__ASSERT(elements > 0);
  95491. FLAC__ASSERT(0 != unaligned_pointer);
  95492. FLAC__ASSERT(0 != aligned_pointer);
  95493. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95494. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95495. if(0 == pu) {
  95496. return false;
  95497. }
  95498. else {
  95499. if(*unaligned_pointer != 0)
  95500. free(*unaligned_pointer);
  95501. *unaligned_pointer = pu;
  95502. *aligned_pointer = u.pa;
  95503. return true;
  95504. }
  95505. }
  95506. #endif
  95507. #endif
  95508. /*** End of inlined file: memory.c ***/
  95509. /*** Start of inlined file: stream_decoder.c ***/
  95510. /*** Start of inlined file: juce_FlacHeader.h ***/
  95511. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95512. // tasks..
  95513. #define VERSION "1.2.1"
  95514. #define FLAC__NO_DLL 1
  95515. #if JUCE_MSVC
  95516. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95517. #endif
  95518. #if JUCE_MAC
  95519. #define FLAC__SYS_DARWIN 1
  95520. #endif
  95521. /*** End of inlined file: juce_FlacHeader.h ***/
  95522. #if JUCE_USE_FLAC
  95523. #if HAVE_CONFIG_H
  95524. # include <config.h>
  95525. #endif
  95526. #if defined _MSC_VER || defined __MINGW32__
  95527. #include <io.h> /* for _setmode() */
  95528. #include <fcntl.h> /* for _O_BINARY */
  95529. #endif
  95530. #if defined __CYGWIN__ || defined __EMX__
  95531. #include <io.h> /* for setmode(), O_BINARY */
  95532. #include <fcntl.h> /* for _O_BINARY */
  95533. #endif
  95534. #include <stdio.h>
  95535. #include <stdlib.h> /* for malloc() */
  95536. #include <string.h> /* for memset/memcpy() */
  95537. #include <sys/stat.h> /* for stat() */
  95538. #include <sys/types.h> /* for off_t */
  95539. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  95540. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  95541. #define fseeko fseek
  95542. #define ftello ftell
  95543. #endif
  95544. #endif
  95545. /*** Start of inlined file: stream_decoder.h ***/
  95546. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  95547. #define FLAC__PROTECTED__STREAM_DECODER_H
  95548. #if FLAC__HAS_OGG
  95549. #include "include/private/ogg_decoder_aspect.h"
  95550. #endif
  95551. typedef struct FLAC__StreamDecoderProtected {
  95552. FLAC__StreamDecoderState state;
  95553. unsigned channels;
  95554. FLAC__ChannelAssignment channel_assignment;
  95555. unsigned bits_per_sample;
  95556. unsigned sample_rate; /* in Hz */
  95557. unsigned blocksize; /* in samples (per channel) */
  95558. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  95559. #if FLAC__HAS_OGG
  95560. FLAC__OggDecoderAspect ogg_decoder_aspect;
  95561. #endif
  95562. } FLAC__StreamDecoderProtected;
  95563. /*
  95564. * return the number of input bytes consumed
  95565. */
  95566. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  95567. #endif
  95568. /*** End of inlined file: stream_decoder.h ***/
  95569. #ifdef max
  95570. #undef max
  95571. #endif
  95572. #define max(a,b) ((a)>(b)?(a):(b))
  95573. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95574. #ifdef _MSC_VER
  95575. #define FLAC__U64L(x) x
  95576. #else
  95577. #define FLAC__U64L(x) x##LLU
  95578. #endif
  95579. /* technically this should be in an "export.c" but this is convenient enough */
  95580. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  95581. #if FLAC__HAS_OGG
  95582. 1
  95583. #else
  95584. 0
  95585. #endif
  95586. ;
  95587. /***********************************************************************
  95588. *
  95589. * Private static data
  95590. *
  95591. ***********************************************************************/
  95592. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  95593. /***********************************************************************
  95594. *
  95595. * Private class method prototypes
  95596. *
  95597. ***********************************************************************/
  95598. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  95599. static FILE *get_binary_stdin_(void);
  95600. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  95601. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  95602. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  95603. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  95604. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  95605. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  95606. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  95607. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  95608. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  95609. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  95610. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  95611. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  95612. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  95613. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95614. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95615. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  95616. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  95617. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95618. 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);
  95619. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  95620. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  95621. #if FLAC__HAS_OGG
  95622. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  95623. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95624. #endif
  95625. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  95626. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  95627. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  95628. #if FLAC__HAS_OGG
  95629. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  95630. #endif
  95631. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95632. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  95633. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  95634. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  95635. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  95636. /***********************************************************************
  95637. *
  95638. * Private class data
  95639. *
  95640. ***********************************************************************/
  95641. typedef struct FLAC__StreamDecoderPrivate {
  95642. #if FLAC__HAS_OGG
  95643. FLAC__bool is_ogg;
  95644. #endif
  95645. FLAC__StreamDecoderReadCallback read_callback;
  95646. FLAC__StreamDecoderSeekCallback seek_callback;
  95647. FLAC__StreamDecoderTellCallback tell_callback;
  95648. FLAC__StreamDecoderLengthCallback length_callback;
  95649. FLAC__StreamDecoderEofCallback eof_callback;
  95650. FLAC__StreamDecoderWriteCallback write_callback;
  95651. FLAC__StreamDecoderMetadataCallback metadata_callback;
  95652. FLAC__StreamDecoderErrorCallback error_callback;
  95653. /* generic 32-bit datapath: */
  95654. 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[]);
  95655. /* generic 64-bit datapath: */
  95656. 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[]);
  95657. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  95658. 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[]);
  95659. /* 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: */
  95660. 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[]);
  95661. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  95662. void *client_data;
  95663. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  95664. FLAC__BitReader *input;
  95665. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  95666. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  95667. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  95668. unsigned output_capacity, output_channels;
  95669. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  95670. FLAC__uint64 samples_decoded;
  95671. FLAC__bool has_stream_info, has_seek_table;
  95672. FLAC__StreamMetadata stream_info;
  95673. FLAC__StreamMetadata seek_table;
  95674. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  95675. FLAC__byte *metadata_filter_ids;
  95676. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  95677. FLAC__Frame frame;
  95678. FLAC__bool cached; /* true if there is a byte in lookahead */
  95679. FLAC__CPUInfo cpuinfo;
  95680. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  95681. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  95682. /* unaligned (original) pointers to allocated data */
  95683. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  95684. 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 */
  95685. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  95686. FLAC__bool is_seeking;
  95687. FLAC__MD5Context md5context;
  95688. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  95689. /* (the rest of these are only used for seeking) */
  95690. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  95691. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  95692. FLAC__uint64 target_sample;
  95693. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  95694. #if FLAC__HAS_OGG
  95695. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  95696. #endif
  95697. } FLAC__StreamDecoderPrivate;
  95698. /***********************************************************************
  95699. *
  95700. * Public static class data
  95701. *
  95702. ***********************************************************************/
  95703. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  95704. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  95705. "FLAC__STREAM_DECODER_READ_METADATA",
  95706. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  95707. "FLAC__STREAM_DECODER_READ_FRAME",
  95708. "FLAC__STREAM_DECODER_END_OF_STREAM",
  95709. "FLAC__STREAM_DECODER_OGG_ERROR",
  95710. "FLAC__STREAM_DECODER_SEEK_ERROR",
  95711. "FLAC__STREAM_DECODER_ABORTED",
  95712. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  95713. "FLAC__STREAM_DECODER_UNINITIALIZED"
  95714. };
  95715. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  95716. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  95717. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  95718. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  95719. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  95720. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  95721. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  95722. };
  95723. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  95724. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  95725. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  95726. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  95727. };
  95728. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  95729. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  95730. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  95731. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  95732. };
  95733. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  95734. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  95735. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  95736. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  95737. };
  95738. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  95739. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  95740. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  95741. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  95742. };
  95743. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  95744. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  95745. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  95746. };
  95747. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  95748. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  95749. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  95750. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  95751. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  95752. };
  95753. /***********************************************************************
  95754. *
  95755. * Class constructor/destructor
  95756. *
  95757. ***********************************************************************/
  95758. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  95759. {
  95760. FLAC__StreamDecoder *decoder;
  95761. unsigned i;
  95762. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95763. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  95764. if(decoder == 0) {
  95765. return 0;
  95766. }
  95767. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  95768. if(decoder->protected_ == 0) {
  95769. free(decoder);
  95770. return 0;
  95771. }
  95772. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  95773. if(decoder->private_ == 0) {
  95774. free(decoder->protected_);
  95775. free(decoder);
  95776. return 0;
  95777. }
  95778. decoder->private_->input = FLAC__bitreader_new();
  95779. if(decoder->private_->input == 0) {
  95780. free(decoder->private_);
  95781. free(decoder->protected_);
  95782. free(decoder);
  95783. return 0;
  95784. }
  95785. decoder->private_->metadata_filter_ids_capacity = 16;
  95786. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  95787. FLAC__bitreader_delete(decoder->private_->input);
  95788. free(decoder->private_);
  95789. free(decoder->protected_);
  95790. free(decoder);
  95791. return 0;
  95792. }
  95793. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95794. decoder->private_->output[i] = 0;
  95795. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95796. }
  95797. decoder->private_->output_capacity = 0;
  95798. decoder->private_->output_channels = 0;
  95799. decoder->private_->has_seek_table = false;
  95800. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95801. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  95802. decoder->private_->file = 0;
  95803. set_defaults_dec(decoder);
  95804. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95805. return decoder;
  95806. }
  95807. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  95808. {
  95809. unsigned i;
  95810. FLAC__ASSERT(0 != decoder);
  95811. FLAC__ASSERT(0 != decoder->protected_);
  95812. FLAC__ASSERT(0 != decoder->private_);
  95813. FLAC__ASSERT(0 != decoder->private_->input);
  95814. (void)FLAC__stream_decoder_finish(decoder);
  95815. if(0 != decoder->private_->metadata_filter_ids)
  95816. free(decoder->private_->metadata_filter_ids);
  95817. FLAC__bitreader_delete(decoder->private_->input);
  95818. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95819. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  95820. free(decoder->private_);
  95821. free(decoder->protected_);
  95822. free(decoder);
  95823. }
  95824. /***********************************************************************
  95825. *
  95826. * Public class methods
  95827. *
  95828. ***********************************************************************/
  95829. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  95830. FLAC__StreamDecoder *decoder,
  95831. FLAC__StreamDecoderReadCallback read_callback,
  95832. FLAC__StreamDecoderSeekCallback seek_callback,
  95833. FLAC__StreamDecoderTellCallback tell_callback,
  95834. FLAC__StreamDecoderLengthCallback length_callback,
  95835. FLAC__StreamDecoderEofCallback eof_callback,
  95836. FLAC__StreamDecoderWriteCallback write_callback,
  95837. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95838. FLAC__StreamDecoderErrorCallback error_callback,
  95839. void *client_data,
  95840. FLAC__bool is_ogg
  95841. )
  95842. {
  95843. FLAC__ASSERT(0 != decoder);
  95844. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95845. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  95846. #if !FLAC__HAS_OGG
  95847. if(is_ogg)
  95848. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  95849. #endif
  95850. if(
  95851. 0 == read_callback ||
  95852. 0 == write_callback ||
  95853. 0 == error_callback ||
  95854. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  95855. )
  95856. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  95857. #if FLAC__HAS_OGG
  95858. decoder->private_->is_ogg = is_ogg;
  95859. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  95860. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  95861. #endif
  95862. /*
  95863. * get the CPU info and set the function pointers
  95864. */
  95865. FLAC__cpu_info(&decoder->private_->cpuinfo);
  95866. /* first default to the non-asm routines */
  95867. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  95868. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  95869. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  95870. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  95871. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  95872. /* now override with asm where appropriate */
  95873. #ifndef FLAC__NO_ASM
  95874. if(decoder->private_->cpuinfo.use_asm) {
  95875. #ifdef FLAC__CPU_IA32
  95876. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  95877. #ifdef FLAC__HAS_NASM
  95878. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  95879. if(decoder->private_->cpuinfo.data.ia32.bswap)
  95880. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  95881. #endif
  95882. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  95883. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95884. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95885. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95886. }
  95887. else {
  95888. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95889. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  95890. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  95891. }
  95892. #endif
  95893. #elif defined FLAC__CPU_PPC
  95894. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  95895. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  95896. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  95897. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  95898. }
  95899. #endif
  95900. }
  95901. #endif
  95902. /* from here on, errors are fatal */
  95903. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  95904. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95905. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95906. }
  95907. decoder->private_->read_callback = read_callback;
  95908. decoder->private_->seek_callback = seek_callback;
  95909. decoder->private_->tell_callback = tell_callback;
  95910. decoder->private_->length_callback = length_callback;
  95911. decoder->private_->eof_callback = eof_callback;
  95912. decoder->private_->write_callback = write_callback;
  95913. decoder->private_->metadata_callback = metadata_callback;
  95914. decoder->private_->error_callback = error_callback;
  95915. decoder->private_->client_data = client_data;
  95916. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95917. decoder->private_->samples_decoded = 0;
  95918. decoder->private_->has_stream_info = false;
  95919. decoder->private_->cached = false;
  95920. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95921. decoder->private_->is_seeking = false;
  95922. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95923. if(!FLAC__stream_decoder_reset(decoder)) {
  95924. /* above call sets the state for us */
  95925. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95926. }
  95927. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95928. }
  95929. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95930. FLAC__StreamDecoder *decoder,
  95931. FLAC__StreamDecoderReadCallback read_callback,
  95932. FLAC__StreamDecoderSeekCallback seek_callback,
  95933. FLAC__StreamDecoderTellCallback tell_callback,
  95934. FLAC__StreamDecoderLengthCallback length_callback,
  95935. FLAC__StreamDecoderEofCallback eof_callback,
  95936. FLAC__StreamDecoderWriteCallback write_callback,
  95937. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95938. FLAC__StreamDecoderErrorCallback error_callback,
  95939. void *client_data
  95940. )
  95941. {
  95942. return init_stream_internal_dec(
  95943. decoder,
  95944. read_callback,
  95945. seek_callback,
  95946. tell_callback,
  95947. length_callback,
  95948. eof_callback,
  95949. write_callback,
  95950. metadata_callback,
  95951. error_callback,
  95952. client_data,
  95953. /*is_ogg=*/false
  95954. );
  95955. }
  95956. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95957. FLAC__StreamDecoder *decoder,
  95958. FLAC__StreamDecoderReadCallback read_callback,
  95959. FLAC__StreamDecoderSeekCallback seek_callback,
  95960. FLAC__StreamDecoderTellCallback tell_callback,
  95961. FLAC__StreamDecoderLengthCallback length_callback,
  95962. FLAC__StreamDecoderEofCallback eof_callback,
  95963. FLAC__StreamDecoderWriteCallback write_callback,
  95964. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95965. FLAC__StreamDecoderErrorCallback error_callback,
  95966. void *client_data
  95967. )
  95968. {
  95969. return init_stream_internal_dec(
  95970. decoder,
  95971. read_callback,
  95972. seek_callback,
  95973. tell_callback,
  95974. length_callback,
  95975. eof_callback,
  95976. write_callback,
  95977. metadata_callback,
  95978. error_callback,
  95979. client_data,
  95980. /*is_ogg=*/true
  95981. );
  95982. }
  95983. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95984. FLAC__StreamDecoder *decoder,
  95985. FILE *file,
  95986. FLAC__StreamDecoderWriteCallback write_callback,
  95987. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95988. FLAC__StreamDecoderErrorCallback error_callback,
  95989. void *client_data,
  95990. FLAC__bool is_ogg
  95991. )
  95992. {
  95993. FLAC__ASSERT(0 != decoder);
  95994. FLAC__ASSERT(0 != file);
  95995. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95996. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95997. if(0 == write_callback || 0 == error_callback)
  95998. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95999. /*
  96000. * To make sure that our file does not go unclosed after an error, we
  96001. * must assign the FILE pointer before any further error can occur in
  96002. * this routine.
  96003. */
  96004. if(file == stdin)
  96005. file = get_binary_stdin_(); /* just to be safe */
  96006. decoder->private_->file = file;
  96007. return init_stream_internal_dec(
  96008. decoder,
  96009. file_read_callback_dec,
  96010. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  96011. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  96012. decoder->private_->file == stdin? 0: file_length_callback_,
  96013. file_eof_callback_,
  96014. write_callback,
  96015. metadata_callback,
  96016. error_callback,
  96017. client_data,
  96018. is_ogg
  96019. );
  96020. }
  96021. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  96022. FLAC__StreamDecoder *decoder,
  96023. FILE *file,
  96024. FLAC__StreamDecoderWriteCallback write_callback,
  96025. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96026. FLAC__StreamDecoderErrorCallback error_callback,
  96027. void *client_data
  96028. )
  96029. {
  96030. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96031. }
  96032. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  96033. FLAC__StreamDecoder *decoder,
  96034. FILE *file,
  96035. FLAC__StreamDecoderWriteCallback write_callback,
  96036. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96037. FLAC__StreamDecoderErrorCallback error_callback,
  96038. void *client_data
  96039. )
  96040. {
  96041. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96042. }
  96043. static FLAC__StreamDecoderInitStatus init_file_internal_(
  96044. FLAC__StreamDecoder *decoder,
  96045. const char *filename,
  96046. FLAC__StreamDecoderWriteCallback write_callback,
  96047. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96048. FLAC__StreamDecoderErrorCallback error_callback,
  96049. void *client_data,
  96050. FLAC__bool is_ogg
  96051. )
  96052. {
  96053. FILE *file;
  96054. FLAC__ASSERT(0 != decoder);
  96055. /*
  96056. * To make sure that our file does not go unclosed after an error, we
  96057. * have to do the same entrance checks here that are later performed
  96058. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  96059. */
  96060. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96061. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  96062. if(0 == write_callback || 0 == error_callback)
  96063. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  96064. file = filename? fopen(filename, "rb") : stdin;
  96065. if(0 == file)
  96066. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  96067. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  96068. }
  96069. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  96070. FLAC__StreamDecoder *decoder,
  96071. const char *filename,
  96072. FLAC__StreamDecoderWriteCallback write_callback,
  96073. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96074. FLAC__StreamDecoderErrorCallback error_callback,
  96075. void *client_data
  96076. )
  96077. {
  96078. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96079. }
  96080. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  96081. FLAC__StreamDecoder *decoder,
  96082. const char *filename,
  96083. FLAC__StreamDecoderWriteCallback write_callback,
  96084. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96085. FLAC__StreamDecoderErrorCallback error_callback,
  96086. void *client_data
  96087. )
  96088. {
  96089. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96090. }
  96091. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  96092. {
  96093. FLAC__bool md5_failed = false;
  96094. unsigned i;
  96095. FLAC__ASSERT(0 != decoder);
  96096. FLAC__ASSERT(0 != decoder->private_);
  96097. FLAC__ASSERT(0 != decoder->protected_);
  96098. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  96099. return true;
  96100. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  96101. * always call FLAC__MD5Final()
  96102. */
  96103. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  96104. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96105. free(decoder->private_->seek_table.data.seek_table.points);
  96106. decoder->private_->seek_table.data.seek_table.points = 0;
  96107. decoder->private_->has_seek_table = false;
  96108. }
  96109. FLAC__bitreader_free(decoder->private_->input);
  96110. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96111. /* WATCHOUT:
  96112. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96113. * output arrays have a buffer of up to 3 zeroes in front
  96114. * (at negative indices) for alignment purposes; we use 4
  96115. * to keep the data well-aligned.
  96116. */
  96117. if(0 != decoder->private_->output[i]) {
  96118. free(decoder->private_->output[i]-4);
  96119. decoder->private_->output[i] = 0;
  96120. }
  96121. if(0 != decoder->private_->residual_unaligned[i]) {
  96122. free(decoder->private_->residual_unaligned[i]);
  96123. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96124. }
  96125. }
  96126. decoder->private_->output_capacity = 0;
  96127. decoder->private_->output_channels = 0;
  96128. #if FLAC__HAS_OGG
  96129. if(decoder->private_->is_ogg)
  96130. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  96131. #endif
  96132. if(0 != decoder->private_->file) {
  96133. if(decoder->private_->file != stdin)
  96134. fclose(decoder->private_->file);
  96135. decoder->private_->file = 0;
  96136. }
  96137. if(decoder->private_->do_md5_checking) {
  96138. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  96139. md5_failed = true;
  96140. }
  96141. decoder->private_->is_seeking = false;
  96142. set_defaults_dec(decoder);
  96143. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96144. return !md5_failed;
  96145. }
  96146. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  96147. {
  96148. FLAC__ASSERT(0 != decoder);
  96149. FLAC__ASSERT(0 != decoder->private_);
  96150. FLAC__ASSERT(0 != decoder->protected_);
  96151. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96152. return false;
  96153. #if FLAC__HAS_OGG
  96154. /* can't check decoder->private_->is_ogg since that's not set until init time */
  96155. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  96156. return true;
  96157. #else
  96158. (void)value;
  96159. return false;
  96160. #endif
  96161. }
  96162. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  96163. {
  96164. FLAC__ASSERT(0 != decoder);
  96165. FLAC__ASSERT(0 != decoder->protected_);
  96166. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96167. return false;
  96168. decoder->protected_->md5_checking = value;
  96169. return true;
  96170. }
  96171. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96172. {
  96173. FLAC__ASSERT(0 != decoder);
  96174. FLAC__ASSERT(0 != decoder->private_);
  96175. FLAC__ASSERT(0 != decoder->protected_);
  96176. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96177. /* double protection */
  96178. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96179. return false;
  96180. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96181. return false;
  96182. decoder->private_->metadata_filter[type] = true;
  96183. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96184. decoder->private_->metadata_filter_ids_count = 0;
  96185. return true;
  96186. }
  96187. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96188. {
  96189. FLAC__ASSERT(0 != decoder);
  96190. FLAC__ASSERT(0 != decoder->private_);
  96191. FLAC__ASSERT(0 != decoder->protected_);
  96192. FLAC__ASSERT(0 != id);
  96193. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96194. return false;
  96195. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96196. return true;
  96197. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96198. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96199. 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))) {
  96200. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96201. return false;
  96202. }
  96203. decoder->private_->metadata_filter_ids_capacity *= 2;
  96204. }
  96205. 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));
  96206. decoder->private_->metadata_filter_ids_count++;
  96207. return true;
  96208. }
  96209. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  96210. {
  96211. unsigned i;
  96212. FLAC__ASSERT(0 != decoder);
  96213. FLAC__ASSERT(0 != decoder->private_);
  96214. FLAC__ASSERT(0 != decoder->protected_);
  96215. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96216. return false;
  96217. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  96218. decoder->private_->metadata_filter[i] = true;
  96219. decoder->private_->metadata_filter_ids_count = 0;
  96220. return true;
  96221. }
  96222. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96223. {
  96224. FLAC__ASSERT(0 != decoder);
  96225. FLAC__ASSERT(0 != decoder->private_);
  96226. FLAC__ASSERT(0 != decoder->protected_);
  96227. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96228. /* double protection */
  96229. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96230. return false;
  96231. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96232. return false;
  96233. decoder->private_->metadata_filter[type] = false;
  96234. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96235. decoder->private_->metadata_filter_ids_count = 0;
  96236. return true;
  96237. }
  96238. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96239. {
  96240. FLAC__ASSERT(0 != decoder);
  96241. FLAC__ASSERT(0 != decoder->private_);
  96242. FLAC__ASSERT(0 != decoder->protected_);
  96243. FLAC__ASSERT(0 != id);
  96244. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96245. return false;
  96246. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96247. return true;
  96248. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96249. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96250. 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))) {
  96251. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96252. return false;
  96253. }
  96254. decoder->private_->metadata_filter_ids_capacity *= 2;
  96255. }
  96256. 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));
  96257. decoder->private_->metadata_filter_ids_count++;
  96258. return true;
  96259. }
  96260. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  96261. {
  96262. FLAC__ASSERT(0 != decoder);
  96263. FLAC__ASSERT(0 != decoder->private_);
  96264. FLAC__ASSERT(0 != decoder->protected_);
  96265. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96266. return false;
  96267. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96268. decoder->private_->metadata_filter_ids_count = 0;
  96269. return true;
  96270. }
  96271. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  96272. {
  96273. FLAC__ASSERT(0 != decoder);
  96274. FLAC__ASSERT(0 != decoder->protected_);
  96275. return decoder->protected_->state;
  96276. }
  96277. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  96278. {
  96279. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  96280. }
  96281. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  96282. {
  96283. FLAC__ASSERT(0 != decoder);
  96284. FLAC__ASSERT(0 != decoder->protected_);
  96285. return decoder->protected_->md5_checking;
  96286. }
  96287. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  96288. {
  96289. FLAC__ASSERT(0 != decoder);
  96290. FLAC__ASSERT(0 != decoder->protected_);
  96291. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  96292. }
  96293. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  96294. {
  96295. FLAC__ASSERT(0 != decoder);
  96296. FLAC__ASSERT(0 != decoder->protected_);
  96297. return decoder->protected_->channels;
  96298. }
  96299. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  96300. {
  96301. FLAC__ASSERT(0 != decoder);
  96302. FLAC__ASSERT(0 != decoder->protected_);
  96303. return decoder->protected_->channel_assignment;
  96304. }
  96305. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  96306. {
  96307. FLAC__ASSERT(0 != decoder);
  96308. FLAC__ASSERT(0 != decoder->protected_);
  96309. return decoder->protected_->bits_per_sample;
  96310. }
  96311. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  96312. {
  96313. FLAC__ASSERT(0 != decoder);
  96314. FLAC__ASSERT(0 != decoder->protected_);
  96315. return decoder->protected_->sample_rate;
  96316. }
  96317. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  96318. {
  96319. FLAC__ASSERT(0 != decoder);
  96320. FLAC__ASSERT(0 != decoder->protected_);
  96321. return decoder->protected_->blocksize;
  96322. }
  96323. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  96324. {
  96325. FLAC__ASSERT(0 != decoder);
  96326. FLAC__ASSERT(0 != decoder->private_);
  96327. FLAC__ASSERT(0 != position);
  96328. #if FLAC__HAS_OGG
  96329. if(decoder->private_->is_ogg)
  96330. return false;
  96331. #endif
  96332. if(0 == decoder->private_->tell_callback)
  96333. return false;
  96334. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  96335. return false;
  96336. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  96337. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  96338. return false;
  96339. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  96340. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  96341. return true;
  96342. }
  96343. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  96344. {
  96345. FLAC__ASSERT(0 != decoder);
  96346. FLAC__ASSERT(0 != decoder->private_);
  96347. FLAC__ASSERT(0 != decoder->protected_);
  96348. decoder->private_->samples_decoded = 0;
  96349. decoder->private_->do_md5_checking = false;
  96350. #if FLAC__HAS_OGG
  96351. if(decoder->private_->is_ogg)
  96352. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  96353. #endif
  96354. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  96355. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96356. return false;
  96357. }
  96358. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96359. return true;
  96360. }
  96361. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  96362. {
  96363. FLAC__ASSERT(0 != decoder);
  96364. FLAC__ASSERT(0 != decoder->private_);
  96365. FLAC__ASSERT(0 != decoder->protected_);
  96366. if(!FLAC__stream_decoder_flush(decoder)) {
  96367. /* above call sets the state for us */
  96368. return false;
  96369. }
  96370. #if FLAC__HAS_OGG
  96371. /*@@@ could go in !internal_reset_hack block below */
  96372. if(decoder->private_->is_ogg)
  96373. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  96374. #endif
  96375. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  96376. * (internal_reset_hack) don't try to rewind since we are already at
  96377. * the beginning of the stream and don't want to fail if the input is
  96378. * not seekable.
  96379. */
  96380. if(!decoder->private_->internal_reset_hack) {
  96381. if(decoder->private_->file == stdin)
  96382. return false; /* can't rewind stdin, reset fails */
  96383. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  96384. return false; /* seekable and seek fails, reset fails */
  96385. }
  96386. else
  96387. decoder->private_->internal_reset_hack = false;
  96388. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  96389. decoder->private_->has_stream_info = false;
  96390. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96391. free(decoder->private_->seek_table.data.seek_table.points);
  96392. decoder->private_->seek_table.data.seek_table.points = 0;
  96393. decoder->private_->has_seek_table = false;
  96394. }
  96395. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  96396. /*
  96397. * This goes in reset() and not flush() because according to the spec, a
  96398. * fixed-blocksize stream must stay that way through the whole stream.
  96399. */
  96400. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  96401. /* We initialize the FLAC__MD5Context even though we may never use it. This
  96402. * is because md5 checking may be turned on to start and then turned off if
  96403. * a seek occurs. So we init the context here and finalize it in
  96404. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  96405. * properly.
  96406. */
  96407. FLAC__MD5Init(&decoder->private_->md5context);
  96408. decoder->private_->first_frame_offset = 0;
  96409. decoder->private_->unparseable_frame_count = 0;
  96410. return true;
  96411. }
  96412. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  96413. {
  96414. FLAC__bool got_a_frame;
  96415. FLAC__ASSERT(0 != decoder);
  96416. FLAC__ASSERT(0 != decoder->protected_);
  96417. while(1) {
  96418. switch(decoder->protected_->state) {
  96419. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96420. if(!find_metadata_(decoder))
  96421. return false; /* above function sets the status for us */
  96422. break;
  96423. case FLAC__STREAM_DECODER_READ_METADATA:
  96424. if(!read_metadata_(decoder))
  96425. return false; /* above function sets the status for us */
  96426. else
  96427. return true;
  96428. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96429. if(!frame_sync_(decoder))
  96430. return true; /* above function sets the status for us */
  96431. break;
  96432. case FLAC__STREAM_DECODER_READ_FRAME:
  96433. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  96434. return false; /* above function sets the status for us */
  96435. if(got_a_frame)
  96436. return true; /* above function sets the status for us */
  96437. break;
  96438. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96439. case FLAC__STREAM_DECODER_ABORTED:
  96440. return true;
  96441. default:
  96442. FLAC__ASSERT(0);
  96443. return false;
  96444. }
  96445. }
  96446. }
  96447. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  96448. {
  96449. FLAC__ASSERT(0 != decoder);
  96450. FLAC__ASSERT(0 != decoder->protected_);
  96451. while(1) {
  96452. switch(decoder->protected_->state) {
  96453. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96454. if(!find_metadata_(decoder))
  96455. return false; /* above function sets the status for us */
  96456. break;
  96457. case FLAC__STREAM_DECODER_READ_METADATA:
  96458. if(!read_metadata_(decoder))
  96459. return false; /* above function sets the status for us */
  96460. break;
  96461. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96462. case FLAC__STREAM_DECODER_READ_FRAME:
  96463. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96464. case FLAC__STREAM_DECODER_ABORTED:
  96465. return true;
  96466. default:
  96467. FLAC__ASSERT(0);
  96468. return false;
  96469. }
  96470. }
  96471. }
  96472. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  96473. {
  96474. FLAC__bool dummy;
  96475. FLAC__ASSERT(0 != decoder);
  96476. FLAC__ASSERT(0 != decoder->protected_);
  96477. while(1) {
  96478. switch(decoder->protected_->state) {
  96479. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96480. if(!find_metadata_(decoder))
  96481. return false; /* above function sets the status for us */
  96482. break;
  96483. case FLAC__STREAM_DECODER_READ_METADATA:
  96484. if(!read_metadata_(decoder))
  96485. return false; /* above function sets the status for us */
  96486. break;
  96487. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96488. if(!frame_sync_(decoder))
  96489. return true; /* above function sets the status for us */
  96490. break;
  96491. case FLAC__STREAM_DECODER_READ_FRAME:
  96492. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  96493. return false; /* above function sets the status for us */
  96494. break;
  96495. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96496. case FLAC__STREAM_DECODER_ABORTED:
  96497. return true;
  96498. default:
  96499. FLAC__ASSERT(0);
  96500. return false;
  96501. }
  96502. }
  96503. }
  96504. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  96505. {
  96506. FLAC__bool got_a_frame;
  96507. FLAC__ASSERT(0 != decoder);
  96508. FLAC__ASSERT(0 != decoder->protected_);
  96509. while(1) {
  96510. switch(decoder->protected_->state) {
  96511. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96512. case FLAC__STREAM_DECODER_READ_METADATA:
  96513. return false; /* above function sets the status for us */
  96514. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96515. if(!frame_sync_(decoder))
  96516. return true; /* above function sets the status for us */
  96517. break;
  96518. case FLAC__STREAM_DECODER_READ_FRAME:
  96519. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  96520. return false; /* above function sets the status for us */
  96521. if(got_a_frame)
  96522. return true; /* above function sets the status for us */
  96523. break;
  96524. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96525. case FLAC__STREAM_DECODER_ABORTED:
  96526. return true;
  96527. default:
  96528. FLAC__ASSERT(0);
  96529. return false;
  96530. }
  96531. }
  96532. }
  96533. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  96534. {
  96535. FLAC__uint64 length;
  96536. FLAC__ASSERT(0 != decoder);
  96537. if(
  96538. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  96539. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  96540. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  96541. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  96542. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  96543. )
  96544. return false;
  96545. if(0 == decoder->private_->seek_callback)
  96546. return false;
  96547. FLAC__ASSERT(decoder->private_->seek_callback);
  96548. FLAC__ASSERT(decoder->private_->tell_callback);
  96549. FLAC__ASSERT(decoder->private_->length_callback);
  96550. FLAC__ASSERT(decoder->private_->eof_callback);
  96551. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  96552. return false;
  96553. decoder->private_->is_seeking = true;
  96554. /* turn off md5 checking if a seek is attempted */
  96555. decoder->private_->do_md5_checking = false;
  96556. /* 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) */
  96557. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  96558. decoder->private_->is_seeking = false;
  96559. return false;
  96560. }
  96561. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  96562. if(
  96563. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  96564. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  96565. ) {
  96566. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  96567. /* above call sets the state for us */
  96568. decoder->private_->is_seeking = false;
  96569. return false;
  96570. }
  96571. /* check this again in case we didn't know total_samples the first time */
  96572. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96573. decoder->private_->is_seeking = false;
  96574. return false;
  96575. }
  96576. }
  96577. {
  96578. const FLAC__bool ok =
  96579. #if FLAC__HAS_OGG
  96580. decoder->private_->is_ogg?
  96581. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  96582. #endif
  96583. seek_to_absolute_sample_(decoder, length, sample)
  96584. ;
  96585. decoder->private_->is_seeking = false;
  96586. return ok;
  96587. }
  96588. }
  96589. /***********************************************************************
  96590. *
  96591. * Protected class methods
  96592. *
  96593. ***********************************************************************/
  96594. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  96595. {
  96596. FLAC__ASSERT(0 != decoder);
  96597. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96598. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  96599. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  96600. }
  96601. /***********************************************************************
  96602. *
  96603. * Private class methods
  96604. *
  96605. ***********************************************************************/
  96606. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  96607. {
  96608. #if FLAC__HAS_OGG
  96609. decoder->private_->is_ogg = false;
  96610. #endif
  96611. decoder->private_->read_callback = 0;
  96612. decoder->private_->seek_callback = 0;
  96613. decoder->private_->tell_callback = 0;
  96614. decoder->private_->length_callback = 0;
  96615. decoder->private_->eof_callback = 0;
  96616. decoder->private_->write_callback = 0;
  96617. decoder->private_->metadata_callback = 0;
  96618. decoder->private_->error_callback = 0;
  96619. decoder->private_->client_data = 0;
  96620. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96621. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  96622. decoder->private_->metadata_filter_ids_count = 0;
  96623. decoder->protected_->md5_checking = false;
  96624. #if FLAC__HAS_OGG
  96625. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  96626. #endif
  96627. }
  96628. /*
  96629. * This will forcibly set stdin to binary mode (for OSes that require it)
  96630. */
  96631. FILE *get_binary_stdin_(void)
  96632. {
  96633. /* if something breaks here it is probably due to the presence or
  96634. * absence of an underscore before the identifiers 'setmode',
  96635. * 'fileno', and/or 'O_BINARY'; check your system header files.
  96636. */
  96637. #if defined _MSC_VER || defined __MINGW32__
  96638. _setmode(_fileno(stdin), _O_BINARY);
  96639. #elif defined __CYGWIN__
  96640. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  96641. setmode(_fileno(stdin), _O_BINARY);
  96642. #elif defined __EMX__
  96643. setmode(fileno(stdin), O_BINARY);
  96644. #endif
  96645. return stdin;
  96646. }
  96647. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  96648. {
  96649. unsigned i;
  96650. FLAC__int32 *tmp;
  96651. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  96652. return true;
  96653. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  96654. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96655. if(0 != decoder->private_->output[i]) {
  96656. free(decoder->private_->output[i]-4);
  96657. decoder->private_->output[i] = 0;
  96658. }
  96659. if(0 != decoder->private_->residual_unaligned[i]) {
  96660. free(decoder->private_->residual_unaligned[i]);
  96661. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96662. }
  96663. }
  96664. for(i = 0; i < channels; i++) {
  96665. /* WATCHOUT:
  96666. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96667. * output arrays have a buffer of up to 3 zeroes in front
  96668. * (at negative indices) for alignment purposes; we use 4
  96669. * to keep the data well-aligned.
  96670. */
  96671. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  96672. if(tmp == 0) {
  96673. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96674. return false;
  96675. }
  96676. memset(tmp, 0, sizeof(FLAC__int32)*4);
  96677. decoder->private_->output[i] = tmp + 4;
  96678. /* WATCHOUT:
  96679. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  96680. */
  96681. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  96682. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96683. return false;
  96684. }
  96685. }
  96686. decoder->private_->output_capacity = size;
  96687. decoder->private_->output_channels = channels;
  96688. return true;
  96689. }
  96690. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  96691. {
  96692. size_t i;
  96693. FLAC__ASSERT(0 != decoder);
  96694. FLAC__ASSERT(0 != decoder->private_);
  96695. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  96696. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  96697. return true;
  96698. return false;
  96699. }
  96700. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  96701. {
  96702. FLAC__uint32 x;
  96703. unsigned i, id_;
  96704. FLAC__bool first = true;
  96705. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96706. for(i = id_ = 0; i < 4; ) {
  96707. if(decoder->private_->cached) {
  96708. x = (FLAC__uint32)decoder->private_->lookahead;
  96709. decoder->private_->cached = false;
  96710. }
  96711. else {
  96712. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96713. return false; /* read_callback_ sets the state for us */
  96714. }
  96715. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  96716. first = true;
  96717. i++;
  96718. id_ = 0;
  96719. continue;
  96720. }
  96721. if(x == ID3V2_TAG_[id_]) {
  96722. id_++;
  96723. i = 0;
  96724. if(id_ == 3) {
  96725. if(!skip_id3v2_tag_(decoder))
  96726. return false; /* skip_id3v2_tag_ sets the state for us */
  96727. }
  96728. continue;
  96729. }
  96730. id_ = 0;
  96731. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96732. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96733. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96734. return false; /* read_callback_ sets the state for us */
  96735. /* 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 */
  96736. /* else we have to check if the second byte is the end of a sync code */
  96737. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96738. decoder->private_->lookahead = (FLAC__byte)x;
  96739. decoder->private_->cached = true;
  96740. }
  96741. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96742. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96743. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96744. return true;
  96745. }
  96746. }
  96747. i = 0;
  96748. if(first) {
  96749. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96750. first = false;
  96751. }
  96752. }
  96753. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  96754. return true;
  96755. }
  96756. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  96757. {
  96758. FLAC__bool is_last;
  96759. FLAC__uint32 i, x, type, length;
  96760. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96761. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  96762. return false; /* read_callback_ sets the state for us */
  96763. is_last = x? true : false;
  96764. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  96765. return false; /* read_callback_ sets the state for us */
  96766. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  96767. return false; /* read_callback_ sets the state for us */
  96768. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  96769. if(!read_metadata_streaminfo_(decoder, is_last, length))
  96770. return false;
  96771. decoder->private_->has_stream_info = true;
  96772. 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))
  96773. decoder->private_->do_md5_checking = false;
  96774. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  96775. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  96776. }
  96777. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96778. if(!read_metadata_seektable_(decoder, is_last, length))
  96779. return false;
  96780. decoder->private_->has_seek_table = true;
  96781. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  96782. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  96783. }
  96784. else {
  96785. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  96786. unsigned real_length = length;
  96787. FLAC__StreamMetadata block;
  96788. block.is_last = is_last;
  96789. block.type = (FLAC__MetadataType)type;
  96790. block.length = length;
  96791. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  96792. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  96793. return false; /* read_callback_ sets the state for us */
  96794. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  96795. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  96796. return false;
  96797. }
  96798. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  96799. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  96800. skip_it = !skip_it;
  96801. }
  96802. if(skip_it) {
  96803. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96804. return false; /* read_callback_ sets the state for us */
  96805. }
  96806. else {
  96807. switch(type) {
  96808. case FLAC__METADATA_TYPE_PADDING:
  96809. /* skip the padding bytes */
  96810. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96811. return false; /* read_callback_ sets the state for us */
  96812. break;
  96813. case FLAC__METADATA_TYPE_APPLICATION:
  96814. /* remember, we read the ID already */
  96815. if(real_length > 0) {
  96816. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  96817. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96818. return false;
  96819. }
  96820. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  96821. return false; /* read_callback_ sets the state for us */
  96822. }
  96823. else
  96824. block.data.application.data = 0;
  96825. break;
  96826. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96827. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  96828. return false;
  96829. break;
  96830. case FLAC__METADATA_TYPE_CUESHEET:
  96831. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  96832. return false;
  96833. break;
  96834. case FLAC__METADATA_TYPE_PICTURE:
  96835. if(!read_metadata_picture_(decoder, &block.data.picture))
  96836. return false;
  96837. break;
  96838. case FLAC__METADATA_TYPE_STREAMINFO:
  96839. case FLAC__METADATA_TYPE_SEEKTABLE:
  96840. FLAC__ASSERT(0);
  96841. break;
  96842. default:
  96843. if(real_length > 0) {
  96844. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  96845. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96846. return false;
  96847. }
  96848. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  96849. return false; /* read_callback_ sets the state for us */
  96850. }
  96851. else
  96852. block.data.unknown.data = 0;
  96853. break;
  96854. }
  96855. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  96856. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  96857. /* now we have to free any malloc()ed data in the block */
  96858. switch(type) {
  96859. case FLAC__METADATA_TYPE_PADDING:
  96860. break;
  96861. case FLAC__METADATA_TYPE_APPLICATION:
  96862. if(0 != block.data.application.data)
  96863. free(block.data.application.data);
  96864. break;
  96865. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96866. if(0 != block.data.vorbis_comment.vendor_string.entry)
  96867. free(block.data.vorbis_comment.vendor_string.entry);
  96868. if(block.data.vorbis_comment.num_comments > 0)
  96869. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  96870. if(0 != block.data.vorbis_comment.comments[i].entry)
  96871. free(block.data.vorbis_comment.comments[i].entry);
  96872. if(0 != block.data.vorbis_comment.comments)
  96873. free(block.data.vorbis_comment.comments);
  96874. break;
  96875. case FLAC__METADATA_TYPE_CUESHEET:
  96876. if(block.data.cue_sheet.num_tracks > 0)
  96877. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  96878. if(0 != block.data.cue_sheet.tracks[i].indices)
  96879. free(block.data.cue_sheet.tracks[i].indices);
  96880. if(0 != block.data.cue_sheet.tracks)
  96881. free(block.data.cue_sheet.tracks);
  96882. break;
  96883. case FLAC__METADATA_TYPE_PICTURE:
  96884. if(0 != block.data.picture.mime_type)
  96885. free(block.data.picture.mime_type);
  96886. if(0 != block.data.picture.description)
  96887. free(block.data.picture.description);
  96888. if(0 != block.data.picture.data)
  96889. free(block.data.picture.data);
  96890. break;
  96891. case FLAC__METADATA_TYPE_STREAMINFO:
  96892. case FLAC__METADATA_TYPE_SEEKTABLE:
  96893. FLAC__ASSERT(0);
  96894. default:
  96895. if(0 != block.data.unknown.data)
  96896. free(block.data.unknown.data);
  96897. break;
  96898. }
  96899. }
  96900. }
  96901. if(is_last) {
  96902. /* if this fails, it's OK, it's just a hint for the seek routine */
  96903. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  96904. decoder->private_->first_frame_offset = 0;
  96905. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96906. }
  96907. return true;
  96908. }
  96909. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96910. {
  96911. FLAC__uint32 x;
  96912. unsigned bits, used_bits = 0;
  96913. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96914. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96915. decoder->private_->stream_info.is_last = is_last;
  96916. decoder->private_->stream_info.length = length;
  96917. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96918. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96919. return false; /* read_callback_ sets the state for us */
  96920. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96921. used_bits += bits;
  96922. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96923. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96924. return false; /* read_callback_ sets the state for us */
  96925. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96926. used_bits += bits;
  96927. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96928. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96929. return false; /* read_callback_ sets the state for us */
  96930. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96931. used_bits += bits;
  96932. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96933. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96934. return false; /* read_callback_ sets the state for us */
  96935. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96936. used_bits += bits;
  96937. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96938. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96939. return false; /* read_callback_ sets the state for us */
  96940. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96941. used_bits += bits;
  96942. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96943. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96944. return false; /* read_callback_ sets the state for us */
  96945. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96946. used_bits += bits;
  96947. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96948. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96949. return false; /* read_callback_ sets the state for us */
  96950. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96951. used_bits += bits;
  96952. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96953. 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))
  96954. return false; /* read_callback_ sets the state for us */
  96955. used_bits += bits;
  96956. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96957. return false; /* read_callback_ sets the state for us */
  96958. used_bits += 16*8;
  96959. /* skip the rest of the block */
  96960. FLAC__ASSERT(used_bits % 8 == 0);
  96961. length -= (used_bits / 8);
  96962. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96963. return false; /* read_callback_ sets the state for us */
  96964. return true;
  96965. }
  96966. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96967. {
  96968. FLAC__uint32 i, x;
  96969. FLAC__uint64 xx;
  96970. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96971. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96972. decoder->private_->seek_table.is_last = is_last;
  96973. decoder->private_->seek_table.length = length;
  96974. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96975. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96976. 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)))) {
  96977. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96978. return false;
  96979. }
  96980. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96981. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96982. return false; /* read_callback_ sets the state for us */
  96983. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96984. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96985. return false; /* read_callback_ sets the state for us */
  96986. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96987. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96988. return false; /* read_callback_ sets the state for us */
  96989. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96990. }
  96991. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96992. /* if there is a partial point left, skip over it */
  96993. if(length > 0) {
  96994. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96995. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96996. return false; /* read_callback_ sets the state for us */
  96997. }
  96998. return true;
  96999. }
  97000. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  97001. {
  97002. FLAC__uint32 i;
  97003. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97004. /* read vendor string */
  97005. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97006. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  97007. return false; /* read_callback_ sets the state for us */
  97008. if(obj->vendor_string.length > 0) {
  97009. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  97010. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97011. return false;
  97012. }
  97013. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  97014. return false; /* read_callback_ sets the state for us */
  97015. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  97016. }
  97017. else
  97018. obj->vendor_string.entry = 0;
  97019. /* read num comments */
  97020. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  97021. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  97022. return false; /* read_callback_ sets the state for us */
  97023. /* read comments */
  97024. if(obj->num_comments > 0) {
  97025. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  97026. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97027. return false;
  97028. }
  97029. for(i = 0; i < obj->num_comments; i++) {
  97030. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97031. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  97032. return false; /* read_callback_ sets the state for us */
  97033. if(obj->comments[i].length > 0) {
  97034. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  97035. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97036. return false;
  97037. }
  97038. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  97039. return false; /* read_callback_ sets the state for us */
  97040. obj->comments[i].entry[obj->comments[i].length] = '\0';
  97041. }
  97042. else
  97043. obj->comments[i].entry = 0;
  97044. }
  97045. }
  97046. else {
  97047. obj->comments = 0;
  97048. }
  97049. return true;
  97050. }
  97051. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  97052. {
  97053. FLAC__uint32 i, j, x;
  97054. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97055. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  97056. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  97057. 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))
  97058. return false; /* read_callback_ sets the state for us */
  97059. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  97060. return false; /* read_callback_ sets the state for us */
  97061. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  97062. return false; /* read_callback_ sets the state for us */
  97063. obj->is_cd = x? true : false;
  97064. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  97065. return false; /* read_callback_ sets the state for us */
  97066. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  97067. return false; /* read_callback_ sets the state for us */
  97068. obj->num_tracks = x;
  97069. if(obj->num_tracks > 0) {
  97070. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  97071. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97072. return false;
  97073. }
  97074. for(i = 0; i < obj->num_tracks; i++) {
  97075. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  97076. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  97077. return false; /* read_callback_ sets the state for us */
  97078. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  97079. return false; /* read_callback_ sets the state for us */
  97080. track->number = (FLAC__byte)x;
  97081. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  97082. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  97083. return false; /* read_callback_ sets the state for us */
  97084. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  97085. return false; /* read_callback_ sets the state for us */
  97086. track->type = x;
  97087. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  97088. return false; /* read_callback_ sets the state for us */
  97089. track->pre_emphasis = x;
  97090. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  97091. return false; /* read_callback_ sets the state for us */
  97092. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  97093. return false; /* read_callback_ sets the state for us */
  97094. track->num_indices = (FLAC__byte)x;
  97095. if(track->num_indices > 0) {
  97096. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  97097. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97098. return false;
  97099. }
  97100. for(j = 0; j < track->num_indices; j++) {
  97101. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  97102. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  97103. return false; /* read_callback_ sets the state for us */
  97104. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  97105. return false; /* read_callback_ sets the state for us */
  97106. index->number = (FLAC__byte)x;
  97107. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  97108. return false; /* read_callback_ sets the state for us */
  97109. }
  97110. }
  97111. }
  97112. }
  97113. return true;
  97114. }
  97115. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  97116. {
  97117. FLAC__uint32 x;
  97118. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97119. /* read type */
  97120. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  97121. return false; /* read_callback_ sets the state for us */
  97122. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  97123. /* read MIME type */
  97124. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  97125. return false; /* read_callback_ sets the state for us */
  97126. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  97127. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97128. return false;
  97129. }
  97130. if(x > 0) {
  97131. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  97132. return false; /* read_callback_ sets the state for us */
  97133. }
  97134. obj->mime_type[x] = '\0';
  97135. /* read description */
  97136. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  97137. return false; /* read_callback_ sets the state for us */
  97138. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  97139. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97140. return false;
  97141. }
  97142. if(x > 0) {
  97143. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  97144. return false; /* read_callback_ sets the state for us */
  97145. }
  97146. obj->description[x] = '\0';
  97147. /* read width */
  97148. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  97149. return false; /* read_callback_ sets the state for us */
  97150. /* read height */
  97151. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  97152. return false; /* read_callback_ sets the state for us */
  97153. /* read depth */
  97154. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  97155. return false; /* read_callback_ sets the state for us */
  97156. /* read colors */
  97157. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  97158. return false; /* read_callback_ sets the state for us */
  97159. /* read data */
  97160. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  97161. return false; /* read_callback_ sets the state for us */
  97162. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  97163. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97164. return false;
  97165. }
  97166. if(obj->data_length > 0) {
  97167. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  97168. return false; /* read_callback_ sets the state for us */
  97169. }
  97170. return true;
  97171. }
  97172. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  97173. {
  97174. FLAC__uint32 x;
  97175. unsigned i, skip;
  97176. /* skip the version and flags bytes */
  97177. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  97178. return false; /* read_callback_ sets the state for us */
  97179. /* get the size (in bytes) to skip */
  97180. skip = 0;
  97181. for(i = 0; i < 4; i++) {
  97182. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97183. return false; /* read_callback_ sets the state for us */
  97184. skip <<= 7;
  97185. skip |= (x & 0x7f);
  97186. }
  97187. /* skip the rest of the tag */
  97188. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  97189. return false; /* read_callback_ sets the state for us */
  97190. return true;
  97191. }
  97192. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  97193. {
  97194. FLAC__uint32 x;
  97195. FLAC__bool first = true;
  97196. /* If we know the total number of samples in the stream, stop if we've read that many. */
  97197. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  97198. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  97199. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97200. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97201. return true;
  97202. }
  97203. }
  97204. /* make sure we're byte aligned */
  97205. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97206. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97207. return false; /* read_callback_ sets the state for us */
  97208. }
  97209. while(1) {
  97210. if(decoder->private_->cached) {
  97211. x = (FLAC__uint32)decoder->private_->lookahead;
  97212. decoder->private_->cached = false;
  97213. }
  97214. else {
  97215. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97216. return false; /* read_callback_ sets the state for us */
  97217. }
  97218. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97219. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97220. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97221. return false; /* read_callback_ sets the state for us */
  97222. /* 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 */
  97223. /* else we have to check if the second byte is the end of a sync code */
  97224. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97225. decoder->private_->lookahead = (FLAC__byte)x;
  97226. decoder->private_->cached = true;
  97227. }
  97228. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97229. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97230. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97231. return true;
  97232. }
  97233. }
  97234. if(first) {
  97235. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97236. first = false;
  97237. }
  97238. }
  97239. return true;
  97240. }
  97241. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  97242. {
  97243. unsigned channel;
  97244. unsigned i;
  97245. FLAC__int32 mid, side;
  97246. unsigned frame_crc; /* the one we calculate from the input stream */
  97247. FLAC__uint32 x;
  97248. *got_a_frame = false;
  97249. /* init the CRC */
  97250. frame_crc = 0;
  97251. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  97252. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  97253. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  97254. if(!read_frame_header_(decoder))
  97255. return false;
  97256. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  97257. return true;
  97258. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  97259. return false;
  97260. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97261. /*
  97262. * first figure the correct bits-per-sample of the subframe
  97263. */
  97264. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  97265. switch(decoder->private_->frame.header.channel_assignment) {
  97266. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97267. /* no adjustment needed */
  97268. break;
  97269. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97270. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97271. if(channel == 1)
  97272. bps++;
  97273. break;
  97274. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97275. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97276. if(channel == 0)
  97277. bps++;
  97278. break;
  97279. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97280. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97281. if(channel == 1)
  97282. bps++;
  97283. break;
  97284. default:
  97285. FLAC__ASSERT(0);
  97286. }
  97287. /*
  97288. * now read it
  97289. */
  97290. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  97291. return false;
  97292. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97293. return true;
  97294. }
  97295. if(!read_zero_padding_(decoder))
  97296. return false;
  97297. 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) */
  97298. return true;
  97299. /*
  97300. * Read the frame CRC-16 from the footer and check
  97301. */
  97302. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  97303. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  97304. return false; /* read_callback_ sets the state for us */
  97305. if(frame_crc == x) {
  97306. if(do_full_decode) {
  97307. /* Undo any special channel coding */
  97308. switch(decoder->private_->frame.header.channel_assignment) {
  97309. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97310. /* do nothing */
  97311. break;
  97312. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97313. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97314. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97315. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  97316. break;
  97317. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97318. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97319. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97320. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  97321. break;
  97322. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97323. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97324. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97325. #if 1
  97326. mid = decoder->private_->output[0][i];
  97327. side = decoder->private_->output[1][i];
  97328. mid <<= 1;
  97329. mid |= (side & 1); /* i.e. if 'side' is odd... */
  97330. decoder->private_->output[0][i] = (mid + side) >> 1;
  97331. decoder->private_->output[1][i] = (mid - side) >> 1;
  97332. #else
  97333. /* OPT: without 'side' temp variable */
  97334. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  97335. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  97336. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  97337. #endif
  97338. }
  97339. break;
  97340. default:
  97341. FLAC__ASSERT(0);
  97342. break;
  97343. }
  97344. }
  97345. }
  97346. else {
  97347. /* Bad frame, emit error and zero the output signal */
  97348. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  97349. if(do_full_decode) {
  97350. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97351. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97352. }
  97353. }
  97354. }
  97355. *got_a_frame = true;
  97356. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  97357. if(decoder->private_->next_fixed_block_size)
  97358. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  97359. /* put the latest values into the public section of the decoder instance */
  97360. decoder->protected_->channels = decoder->private_->frame.header.channels;
  97361. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  97362. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  97363. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  97364. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  97365. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97366. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  97367. /* write it */
  97368. if(do_full_decode) {
  97369. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  97370. return false;
  97371. }
  97372. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97373. return true;
  97374. }
  97375. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  97376. {
  97377. FLAC__uint32 x;
  97378. FLAC__uint64 xx;
  97379. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  97380. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  97381. unsigned raw_header_len;
  97382. FLAC__bool is_unparseable = false;
  97383. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97384. /* init the raw header with the saved bits from synchronization */
  97385. raw_header[0] = decoder->private_->header_warmup[0];
  97386. raw_header[1] = decoder->private_->header_warmup[1];
  97387. raw_header_len = 2;
  97388. /* check to make sure that reserved bit is 0 */
  97389. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  97390. is_unparseable = true;
  97391. /*
  97392. * Note that along the way as we read the header, we look for a sync
  97393. * code inside. If we find one it would indicate that our original
  97394. * sync was bad since there cannot be a sync code in a valid header.
  97395. *
  97396. * Three kinds of things can go wrong when reading the frame header:
  97397. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  97398. * If we don't find a sync code, it can end up looking like we read
  97399. * a valid but unparseable header, until getting to the frame header
  97400. * CRC. Even then we could get a false positive on the CRC.
  97401. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  97402. * future encoder).
  97403. * 3) We may be on a damaged frame which appears valid but unparseable.
  97404. *
  97405. * For all these reasons, we try and read a complete frame header as
  97406. * long as it seems valid, even if unparseable, up until the frame
  97407. * header CRC.
  97408. */
  97409. /*
  97410. * read in the raw header as bytes so we can CRC it, and parse it on the way
  97411. */
  97412. for(i = 0; i < 2; i++) {
  97413. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97414. return false; /* read_callback_ sets the state for us */
  97415. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97416. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  97417. decoder->private_->lookahead = (FLAC__byte)x;
  97418. decoder->private_->cached = true;
  97419. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97420. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97421. return true;
  97422. }
  97423. raw_header[raw_header_len++] = (FLAC__byte)x;
  97424. }
  97425. switch(x = raw_header[2] >> 4) {
  97426. case 0:
  97427. is_unparseable = true;
  97428. break;
  97429. case 1:
  97430. decoder->private_->frame.header.blocksize = 192;
  97431. break;
  97432. case 2:
  97433. case 3:
  97434. case 4:
  97435. case 5:
  97436. decoder->private_->frame.header.blocksize = 576 << (x-2);
  97437. break;
  97438. case 6:
  97439. case 7:
  97440. blocksize_hint = x;
  97441. break;
  97442. case 8:
  97443. case 9:
  97444. case 10:
  97445. case 11:
  97446. case 12:
  97447. case 13:
  97448. case 14:
  97449. case 15:
  97450. decoder->private_->frame.header.blocksize = 256 << (x-8);
  97451. break;
  97452. default:
  97453. FLAC__ASSERT(0);
  97454. break;
  97455. }
  97456. switch(x = raw_header[2] & 0x0f) {
  97457. case 0:
  97458. if(decoder->private_->has_stream_info)
  97459. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  97460. else
  97461. is_unparseable = true;
  97462. break;
  97463. case 1:
  97464. decoder->private_->frame.header.sample_rate = 88200;
  97465. break;
  97466. case 2:
  97467. decoder->private_->frame.header.sample_rate = 176400;
  97468. break;
  97469. case 3:
  97470. decoder->private_->frame.header.sample_rate = 192000;
  97471. break;
  97472. case 4:
  97473. decoder->private_->frame.header.sample_rate = 8000;
  97474. break;
  97475. case 5:
  97476. decoder->private_->frame.header.sample_rate = 16000;
  97477. break;
  97478. case 6:
  97479. decoder->private_->frame.header.sample_rate = 22050;
  97480. break;
  97481. case 7:
  97482. decoder->private_->frame.header.sample_rate = 24000;
  97483. break;
  97484. case 8:
  97485. decoder->private_->frame.header.sample_rate = 32000;
  97486. break;
  97487. case 9:
  97488. decoder->private_->frame.header.sample_rate = 44100;
  97489. break;
  97490. case 10:
  97491. decoder->private_->frame.header.sample_rate = 48000;
  97492. break;
  97493. case 11:
  97494. decoder->private_->frame.header.sample_rate = 96000;
  97495. break;
  97496. case 12:
  97497. case 13:
  97498. case 14:
  97499. sample_rate_hint = x;
  97500. break;
  97501. case 15:
  97502. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97503. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97504. return true;
  97505. default:
  97506. FLAC__ASSERT(0);
  97507. }
  97508. x = (unsigned)(raw_header[3] >> 4);
  97509. if(x & 8) {
  97510. decoder->private_->frame.header.channels = 2;
  97511. switch(x & 7) {
  97512. case 0:
  97513. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  97514. break;
  97515. case 1:
  97516. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  97517. break;
  97518. case 2:
  97519. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  97520. break;
  97521. default:
  97522. is_unparseable = true;
  97523. break;
  97524. }
  97525. }
  97526. else {
  97527. decoder->private_->frame.header.channels = (unsigned)x + 1;
  97528. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  97529. }
  97530. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  97531. case 0:
  97532. if(decoder->private_->has_stream_info)
  97533. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97534. else
  97535. is_unparseable = true;
  97536. break;
  97537. case 1:
  97538. decoder->private_->frame.header.bits_per_sample = 8;
  97539. break;
  97540. case 2:
  97541. decoder->private_->frame.header.bits_per_sample = 12;
  97542. break;
  97543. case 4:
  97544. decoder->private_->frame.header.bits_per_sample = 16;
  97545. break;
  97546. case 5:
  97547. decoder->private_->frame.header.bits_per_sample = 20;
  97548. break;
  97549. case 6:
  97550. decoder->private_->frame.header.bits_per_sample = 24;
  97551. break;
  97552. case 3:
  97553. case 7:
  97554. is_unparseable = true;
  97555. break;
  97556. default:
  97557. FLAC__ASSERT(0);
  97558. break;
  97559. }
  97560. /* check to make sure that reserved bit is 0 */
  97561. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  97562. is_unparseable = true;
  97563. /* read the frame's starting sample number (or frame number as the case may be) */
  97564. if(
  97565. raw_header[1] & 0x01 ||
  97566. /*@@@ 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 */
  97567. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  97568. ) { /* variable blocksize */
  97569. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  97570. return false; /* read_callback_ sets the state for us */
  97571. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  97572. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  97573. decoder->private_->cached = true;
  97574. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97575. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97576. return true;
  97577. }
  97578. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  97579. decoder->private_->frame.header.number.sample_number = xx;
  97580. }
  97581. else { /* fixed blocksize */
  97582. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  97583. return false; /* read_callback_ sets the state for us */
  97584. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  97585. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  97586. decoder->private_->cached = true;
  97587. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97588. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97589. return true;
  97590. }
  97591. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  97592. decoder->private_->frame.header.number.frame_number = x;
  97593. }
  97594. if(blocksize_hint) {
  97595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97596. return false; /* read_callback_ sets the state for us */
  97597. raw_header[raw_header_len++] = (FLAC__byte)x;
  97598. if(blocksize_hint == 7) {
  97599. FLAC__uint32 _x;
  97600. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  97601. return false; /* read_callback_ sets the state for us */
  97602. raw_header[raw_header_len++] = (FLAC__byte)_x;
  97603. x = (x << 8) | _x;
  97604. }
  97605. decoder->private_->frame.header.blocksize = x+1;
  97606. }
  97607. if(sample_rate_hint) {
  97608. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97609. return false; /* read_callback_ sets the state for us */
  97610. raw_header[raw_header_len++] = (FLAC__byte)x;
  97611. if(sample_rate_hint != 12) {
  97612. FLAC__uint32 _x;
  97613. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  97614. return false; /* read_callback_ sets the state for us */
  97615. raw_header[raw_header_len++] = (FLAC__byte)_x;
  97616. x = (x << 8) | _x;
  97617. }
  97618. if(sample_rate_hint == 12)
  97619. decoder->private_->frame.header.sample_rate = x*1000;
  97620. else if(sample_rate_hint == 13)
  97621. decoder->private_->frame.header.sample_rate = x;
  97622. else
  97623. decoder->private_->frame.header.sample_rate = x*10;
  97624. }
  97625. /* read the CRC-8 byte */
  97626. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97627. return false; /* read_callback_ sets the state for us */
  97628. crc8 = (FLAC__byte)x;
  97629. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  97630. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97631. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97632. return true;
  97633. }
  97634. /* calculate the sample number from the frame number if needed */
  97635. decoder->private_->next_fixed_block_size = 0;
  97636. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  97637. x = decoder->private_->frame.header.number.frame_number;
  97638. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  97639. if(decoder->private_->fixed_block_size)
  97640. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  97641. else if(decoder->private_->has_stream_info) {
  97642. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  97643. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  97644. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97645. }
  97646. else
  97647. is_unparseable = true;
  97648. }
  97649. else if(x == 0) {
  97650. decoder->private_->frame.header.number.sample_number = 0;
  97651. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  97652. }
  97653. else {
  97654. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  97655. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  97656. }
  97657. }
  97658. if(is_unparseable) {
  97659. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97660. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97661. return true;
  97662. }
  97663. return true;
  97664. }
  97665. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97666. {
  97667. FLAC__uint32 x;
  97668. FLAC__bool wasted_bits;
  97669. unsigned i;
  97670. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  97671. return false; /* read_callback_ sets the state for us */
  97672. wasted_bits = (x & 1);
  97673. x &= 0xfe;
  97674. if(wasted_bits) {
  97675. unsigned u;
  97676. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  97677. return false; /* read_callback_ sets the state for us */
  97678. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  97679. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  97680. }
  97681. else
  97682. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  97683. /*
  97684. * Lots of magic numbers here
  97685. */
  97686. if(x & 0x80) {
  97687. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97688. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97689. return true;
  97690. }
  97691. else if(x == 0) {
  97692. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  97693. return false;
  97694. }
  97695. else if(x == 2) {
  97696. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  97697. return false;
  97698. }
  97699. else if(x < 16) {
  97700. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97701. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97702. return true;
  97703. }
  97704. else if(x <= 24) {
  97705. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  97706. return false;
  97707. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97708. return true;
  97709. }
  97710. else if(x < 64) {
  97711. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97712. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97713. return true;
  97714. }
  97715. else {
  97716. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  97717. return false;
  97718. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97719. return true;
  97720. }
  97721. if(wasted_bits && do_full_decode) {
  97722. x = decoder->private_->frame.subframes[channel].wasted_bits;
  97723. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97724. decoder->private_->output[channel][i] <<= x;
  97725. }
  97726. return true;
  97727. }
  97728. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97729. {
  97730. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  97731. FLAC__int32 x;
  97732. unsigned i;
  97733. FLAC__int32 *output = decoder->private_->output[channel];
  97734. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  97735. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97736. return false; /* read_callback_ sets the state for us */
  97737. subframe->value = x;
  97738. /* decode the subframe */
  97739. if(do_full_decode) {
  97740. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97741. output[i] = x;
  97742. }
  97743. return true;
  97744. }
  97745. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97746. {
  97747. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  97748. FLAC__int32 i32;
  97749. FLAC__uint32 u32;
  97750. unsigned u;
  97751. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  97752. subframe->residual = decoder->private_->residual[channel];
  97753. subframe->order = order;
  97754. /* read warm-up samples */
  97755. for(u = 0; u < order; u++) {
  97756. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97757. return false; /* read_callback_ sets the state for us */
  97758. subframe->warmup[u] = i32;
  97759. }
  97760. /* read entropy coding method info */
  97761. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97762. return false; /* read_callback_ sets the state for us */
  97763. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97764. switch(subframe->entropy_coding_method.type) {
  97765. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97766. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97767. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97768. return false; /* read_callback_ sets the state for us */
  97769. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97770. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97771. break;
  97772. default:
  97773. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97774. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97775. return true;
  97776. }
  97777. /* read residual */
  97778. switch(subframe->entropy_coding_method.type) {
  97779. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97780. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97781. 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))
  97782. return false;
  97783. break;
  97784. default:
  97785. FLAC__ASSERT(0);
  97786. }
  97787. /* decode the subframe */
  97788. if(do_full_decode) {
  97789. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97790. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  97791. }
  97792. return true;
  97793. }
  97794. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97795. {
  97796. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  97797. FLAC__int32 i32;
  97798. FLAC__uint32 u32;
  97799. unsigned u;
  97800. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  97801. subframe->residual = decoder->private_->residual[channel];
  97802. subframe->order = order;
  97803. /* read warm-up samples */
  97804. for(u = 0; u < order; u++) {
  97805. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97806. return false; /* read_callback_ sets the state for us */
  97807. subframe->warmup[u] = i32;
  97808. }
  97809. /* read qlp coeff precision */
  97810. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  97811. return false; /* read_callback_ sets the state for us */
  97812. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  97813. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97814. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97815. return true;
  97816. }
  97817. subframe->qlp_coeff_precision = u32+1;
  97818. /* read qlp shift */
  97819. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  97820. return false; /* read_callback_ sets the state for us */
  97821. subframe->quantization_level = i32;
  97822. /* read quantized lp coefficiencts */
  97823. for(u = 0; u < order; u++) {
  97824. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  97825. return false; /* read_callback_ sets the state for us */
  97826. subframe->qlp_coeff[u] = i32;
  97827. }
  97828. /* read entropy coding method info */
  97829. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97830. return false; /* read_callback_ sets the state for us */
  97831. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97832. switch(subframe->entropy_coding_method.type) {
  97833. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97834. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97835. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97836. return false; /* read_callback_ sets the state for us */
  97837. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97838. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97839. break;
  97840. default:
  97841. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97842. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97843. return true;
  97844. }
  97845. /* read residual */
  97846. switch(subframe->entropy_coding_method.type) {
  97847. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97848. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97849. 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))
  97850. return false;
  97851. break;
  97852. default:
  97853. FLAC__ASSERT(0);
  97854. }
  97855. /* decode the subframe */
  97856. if(do_full_decode) {
  97857. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97858. /*@@@@@@ technically not pessimistic enough, should be more like
  97859. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  97860. */
  97861. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  97862. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  97863. if(order <= 8)
  97864. 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);
  97865. else
  97866. 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);
  97867. }
  97868. else
  97869. 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);
  97870. else
  97871. 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);
  97872. }
  97873. return true;
  97874. }
  97875. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97876. {
  97877. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  97878. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  97879. unsigned i;
  97880. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  97881. subframe->data = residual;
  97882. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97883. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97884. return false; /* read_callback_ sets the state for us */
  97885. residual[i] = x;
  97886. }
  97887. /* decode the subframe */
  97888. if(do_full_decode)
  97889. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97890. return true;
  97891. }
  97892. 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)
  97893. {
  97894. FLAC__uint32 rice_parameter;
  97895. int i;
  97896. unsigned partition, sample, u;
  97897. const unsigned partitions = 1u << partition_order;
  97898. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  97899. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  97900. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  97901. /* sanity checks */
  97902. if(partition_order == 0) {
  97903. if(decoder->private_->frame.header.blocksize < predictor_order) {
  97904. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97905. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97906. return true;
  97907. }
  97908. }
  97909. else {
  97910. if(partition_samples < predictor_order) {
  97911. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97912. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97913. return true;
  97914. }
  97915. }
  97916. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97917. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97918. return false;
  97919. }
  97920. sample = 0;
  97921. for(partition = 0; partition < partitions; partition++) {
  97922. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97923. return false; /* read_callback_ sets the state for us */
  97924. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97925. if(rice_parameter < pesc) {
  97926. partitioned_rice_contents->raw_bits[partition] = 0;
  97927. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97928. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97929. return false; /* read_callback_ sets the state for us */
  97930. sample += u;
  97931. }
  97932. else {
  97933. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97934. return false; /* read_callback_ sets the state for us */
  97935. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97936. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97937. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97938. return false; /* read_callback_ sets the state for us */
  97939. residual[sample] = i;
  97940. }
  97941. }
  97942. }
  97943. return true;
  97944. }
  97945. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97946. {
  97947. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97948. FLAC__uint32 zero = 0;
  97949. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97950. return false; /* read_callback_ sets the state for us */
  97951. if(zero != 0) {
  97952. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97953. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97954. }
  97955. }
  97956. return true;
  97957. }
  97958. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97959. {
  97960. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97961. if(
  97962. #if FLAC__HAS_OGG
  97963. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97964. !decoder->private_->is_ogg &&
  97965. #endif
  97966. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97967. ) {
  97968. *bytes = 0;
  97969. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97970. return false;
  97971. }
  97972. else if(*bytes > 0) {
  97973. /* While seeking, it is possible for our seek to land in the
  97974. * middle of audio data that looks exactly like a frame header
  97975. * from a future version of an encoder. When that happens, our
  97976. * error callback will get an
  97977. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97978. * unparseable_frame_count. But there is a remote possibility
  97979. * that it is properly synced at such a "future-codec frame",
  97980. * so to make sure, we wait to see many "unparseable" errors in
  97981. * a row before bailing out.
  97982. */
  97983. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97984. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97985. return false;
  97986. }
  97987. else {
  97988. const FLAC__StreamDecoderReadStatus status =
  97989. #if FLAC__HAS_OGG
  97990. decoder->private_->is_ogg?
  97991. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97992. #endif
  97993. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97994. ;
  97995. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97996. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97997. return false;
  97998. }
  97999. else if(*bytes == 0) {
  98000. if(
  98001. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  98002. (
  98003. #if FLAC__HAS_OGG
  98004. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  98005. !decoder->private_->is_ogg &&
  98006. #endif
  98007. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  98008. )
  98009. ) {
  98010. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  98011. return false;
  98012. }
  98013. else
  98014. return true;
  98015. }
  98016. else
  98017. return true;
  98018. }
  98019. }
  98020. else {
  98021. /* abort to avoid a deadlock */
  98022. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98023. return false;
  98024. }
  98025. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  98026. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  98027. * and at the same time hit the end of the stream (for example, seeking
  98028. * to a point that is after the beginning of the last Ogg page). There
  98029. * is no way to report an Ogg sync loss through the callbacks (see note
  98030. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  98031. * So to keep the decoder from stopping at this point we gate the call
  98032. * to the eof_callback and let the Ogg decoder aspect set the
  98033. * end-of-stream state when it is needed.
  98034. */
  98035. }
  98036. #if FLAC__HAS_OGG
  98037. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  98038. {
  98039. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  98040. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  98041. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98042. /* we don't really have a way to handle lost sync via read
  98043. * callback so we'll let it pass and let the underlying
  98044. * FLAC decoder catch the error
  98045. */
  98046. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  98047. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98048. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  98049. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98050. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  98051. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  98052. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  98053. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  98054. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  98055. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98056. default:
  98057. FLAC__ASSERT(0);
  98058. /* double protection */
  98059. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98060. }
  98061. }
  98062. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98063. {
  98064. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  98065. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  98066. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  98067. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  98068. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  98069. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  98070. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  98071. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98072. default:
  98073. /* double protection: */
  98074. FLAC__ASSERT(0);
  98075. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98076. }
  98077. }
  98078. #endif
  98079. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  98080. {
  98081. if(decoder->private_->is_seeking) {
  98082. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  98083. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  98084. FLAC__uint64 target_sample = decoder->private_->target_sample;
  98085. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98086. #if FLAC__HAS_OGG
  98087. decoder->private_->got_a_frame = true;
  98088. #endif
  98089. decoder->private_->last_frame = *frame; /* save the frame */
  98090. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  98091. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  98092. /* kick out of seek mode */
  98093. decoder->private_->is_seeking = false;
  98094. /* shift out the samples before target_sample */
  98095. if(delta > 0) {
  98096. unsigned channel;
  98097. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  98098. for(channel = 0; channel < frame->header.channels; channel++)
  98099. newbuffer[channel] = buffer[channel] + delta;
  98100. decoder->private_->last_frame.header.blocksize -= delta;
  98101. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  98102. /* write the relevant samples */
  98103. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  98104. }
  98105. else {
  98106. /* write the relevant samples */
  98107. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98108. }
  98109. }
  98110. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  98111. }
  98112. /*
  98113. * If we never got STREAMINFO, turn off MD5 checking to save
  98114. * cycles since we don't have a sum to compare to anyway
  98115. */
  98116. if(!decoder->private_->has_stream_info)
  98117. decoder->private_->do_md5_checking = false;
  98118. if(decoder->private_->do_md5_checking) {
  98119. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  98120. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  98121. }
  98122. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98123. }
  98124. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  98125. {
  98126. if(!decoder->private_->is_seeking)
  98127. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  98128. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  98129. decoder->private_->unparseable_frame_count++;
  98130. }
  98131. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98132. {
  98133. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  98134. FLAC__int64 pos = -1;
  98135. int i;
  98136. unsigned approx_bytes_per_frame;
  98137. FLAC__bool first_seek = true;
  98138. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  98139. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  98140. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98141. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  98142. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  98143. /* take these from the current frame in case they've changed mid-stream */
  98144. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  98145. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  98146. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  98147. /* use values from stream info if we didn't decode a frame */
  98148. if(channels == 0)
  98149. channels = decoder->private_->stream_info.data.stream_info.channels;
  98150. if(bps == 0)
  98151. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98152. /* we are just guessing here */
  98153. if(max_framesize > 0)
  98154. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  98155. /*
  98156. * Check if it's a known fixed-blocksize stream. Note that though
  98157. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  98158. * never get a STREAMINFO block when decoding so the value of
  98159. * min_blocksize might be zero.
  98160. */
  98161. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  98162. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  98163. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  98164. }
  98165. else
  98166. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  98167. /*
  98168. * First, we set an upper and lower bound on where in the
  98169. * stream we will search. For now we assume the worst case
  98170. * scenario, which is our best guess at the beginning of
  98171. * the first frame and end of the stream.
  98172. */
  98173. lower_bound = first_frame_offset;
  98174. lower_bound_sample = 0;
  98175. upper_bound = stream_length;
  98176. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  98177. /*
  98178. * Now we refine the bounds if we have a seektable with
  98179. * suitable points. Note that according to the spec they
  98180. * must be ordered by ascending sample number.
  98181. *
  98182. * Note: to protect against invalid seek tables we will ignore points
  98183. * that have frame_samples==0 or sample_number>=total_samples
  98184. */
  98185. if(seek_table) {
  98186. FLAC__uint64 new_lower_bound = lower_bound;
  98187. FLAC__uint64 new_upper_bound = upper_bound;
  98188. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  98189. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  98190. /* find the closest seek point <= target_sample, if it exists */
  98191. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  98192. if(
  98193. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98194. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98195. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98196. seek_table->points[i].sample_number <= target_sample
  98197. )
  98198. break;
  98199. }
  98200. if(i >= 0) { /* i.e. we found a suitable seek point... */
  98201. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98202. new_lower_bound_sample = seek_table->points[i].sample_number;
  98203. }
  98204. /* find the closest seek point > target_sample, if it exists */
  98205. for(i = 0; i < (int)seek_table->num_points; i++) {
  98206. if(
  98207. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98208. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98209. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98210. seek_table->points[i].sample_number > target_sample
  98211. )
  98212. break;
  98213. }
  98214. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  98215. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98216. new_upper_bound_sample = seek_table->points[i].sample_number;
  98217. }
  98218. /* final protection against unsorted seek tables; keep original values if bogus */
  98219. if(new_upper_bound >= new_lower_bound) {
  98220. lower_bound = new_lower_bound;
  98221. upper_bound = new_upper_bound;
  98222. lower_bound_sample = new_lower_bound_sample;
  98223. upper_bound_sample = new_upper_bound_sample;
  98224. }
  98225. }
  98226. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  98227. /* there are 2 insidious ways that the following equality occurs, which
  98228. * we need to fix:
  98229. * 1) total_samples is 0 (unknown) and target_sample is 0
  98230. * 2) total_samples is 0 (unknown) and target_sample happens to be
  98231. * exactly equal to the last seek point in the seek table; this
  98232. * means there is no seek point above it, and upper_bound_samples
  98233. * remains equal to the estimate (of target_samples) we made above
  98234. * in either case it does not hurt to move upper_bound_sample up by 1
  98235. */
  98236. if(upper_bound_sample == lower_bound_sample)
  98237. upper_bound_sample++;
  98238. decoder->private_->target_sample = target_sample;
  98239. while(1) {
  98240. /* check if the bounds are still ok */
  98241. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  98242. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98243. return false;
  98244. }
  98245. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98246. #if defined _MSC_VER || defined __MINGW32__
  98247. /* with VC++ you have to spoon feed it the casting */
  98248. 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;
  98249. #else
  98250. 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;
  98251. #endif
  98252. #else
  98253. /* a little less accurate: */
  98254. if(upper_bound - lower_bound < 0xffffffff)
  98255. 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;
  98256. else /* @@@ WATCHOUT, ~2TB limit */
  98257. 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;
  98258. #endif
  98259. if(pos >= (FLAC__int64)upper_bound)
  98260. pos = (FLAC__int64)upper_bound - 1;
  98261. if(pos < (FLAC__int64)lower_bound)
  98262. pos = (FLAC__int64)lower_bound;
  98263. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98264. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98265. return false;
  98266. }
  98267. if(!FLAC__stream_decoder_flush(decoder)) {
  98268. /* above call sets the state for us */
  98269. return false;
  98270. }
  98271. /* Now we need to get a frame. First we need to reset our
  98272. * unparseable_frame_count; if we get too many unparseable
  98273. * frames in a row, the read callback will return
  98274. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  98275. * FLAC__stream_decoder_process_single() to return false.
  98276. */
  98277. decoder->private_->unparseable_frame_count = 0;
  98278. if(!FLAC__stream_decoder_process_single(decoder)) {
  98279. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98280. return false;
  98281. }
  98282. /* our write callback will change the state when it gets to the target frame */
  98283. /* 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 */
  98284. #if 0
  98285. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  98286. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  98287. break;
  98288. #endif
  98289. if(!decoder->private_->is_seeking)
  98290. break;
  98291. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98292. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98293. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  98294. if (pos == (FLAC__int64)lower_bound) {
  98295. /* can't move back any more than the first frame, something is fatally wrong */
  98296. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98297. return false;
  98298. }
  98299. /* our last move backwards wasn't big enough, try again */
  98300. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  98301. continue;
  98302. }
  98303. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  98304. first_seek = false;
  98305. /* make sure we are not seeking in corrupted stream */
  98306. if (this_frame_sample < lower_bound_sample) {
  98307. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98308. return false;
  98309. }
  98310. /* we need to narrow the search */
  98311. if(target_sample < this_frame_sample) {
  98312. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98313. /*@@@@@@ what will decode position be if at end of stream? */
  98314. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  98315. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98316. return false;
  98317. }
  98318. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  98319. }
  98320. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  98321. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98322. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  98323. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98324. return false;
  98325. }
  98326. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  98327. }
  98328. }
  98329. return true;
  98330. }
  98331. #if FLAC__HAS_OGG
  98332. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98333. {
  98334. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  98335. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  98336. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  98337. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  98338. FLAC__bool did_a_seek;
  98339. unsigned iteration = 0;
  98340. /* In the first iterations, we will calculate the target byte position
  98341. * by the distance from the target sample to left_sample and
  98342. * right_sample (let's call it "proportional search"). After that, we
  98343. * will switch to binary search.
  98344. */
  98345. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  98346. /* We will switch to a linear search once our current sample is less
  98347. * than this number of samples ahead of the target sample
  98348. */
  98349. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  98350. /* If the total number of samples is unknown, use a large value, and
  98351. * force binary search immediately.
  98352. */
  98353. if(right_sample == 0) {
  98354. right_sample = (FLAC__uint64)(-1);
  98355. BINARY_SEARCH_AFTER_ITERATION = 0;
  98356. }
  98357. decoder->private_->target_sample = target_sample;
  98358. for( ; ; iteration++) {
  98359. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  98360. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  98361. pos = (right_pos + left_pos) / 2;
  98362. }
  98363. else {
  98364. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98365. #if defined _MSC_VER || defined __MINGW32__
  98366. /* with MSVC you have to spoon feed it the casting */
  98367. 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));
  98368. #else
  98369. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  98370. #endif
  98371. #else
  98372. /* a little less accurate: */
  98373. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  98374. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  98375. else /* @@@ WATCHOUT, ~2TB limit */
  98376. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  98377. #endif
  98378. /* @@@ TODO: might want to limit pos to some distance
  98379. * before EOF, to make sure we land before the last frame,
  98380. * thereby getting a this_frame_sample and so having a better
  98381. * estimate.
  98382. */
  98383. }
  98384. /* physical seek */
  98385. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98386. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98387. return false;
  98388. }
  98389. if(!FLAC__stream_decoder_flush(decoder)) {
  98390. /* above call sets the state for us */
  98391. return false;
  98392. }
  98393. did_a_seek = true;
  98394. }
  98395. else
  98396. did_a_seek = false;
  98397. decoder->private_->got_a_frame = false;
  98398. if(!FLAC__stream_decoder_process_single(decoder)) {
  98399. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98400. return false;
  98401. }
  98402. if(!decoder->private_->got_a_frame) {
  98403. if(did_a_seek) {
  98404. /* this can happen if we seek to a point after the last frame; we drop
  98405. * to binary search right away in this case to avoid any wasted
  98406. * iterations of proportional search.
  98407. */
  98408. right_pos = pos;
  98409. BINARY_SEARCH_AFTER_ITERATION = 0;
  98410. }
  98411. else {
  98412. /* this can probably only happen if total_samples is unknown and the
  98413. * target_sample is past the end of the stream
  98414. */
  98415. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98416. return false;
  98417. }
  98418. }
  98419. /* our write callback will change the state when it gets to the target frame */
  98420. else if(!decoder->private_->is_seeking) {
  98421. break;
  98422. }
  98423. else {
  98424. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98425. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98426. if (did_a_seek) {
  98427. if (this_frame_sample <= target_sample) {
  98428. /* The 'equal' case should not happen, since
  98429. * FLAC__stream_decoder_process_single()
  98430. * should recognize that it has hit the
  98431. * target sample and we would exit through
  98432. * the 'break' above.
  98433. */
  98434. FLAC__ASSERT(this_frame_sample != target_sample);
  98435. left_sample = this_frame_sample;
  98436. /* sanity check to avoid infinite loop */
  98437. if (left_pos == pos) {
  98438. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98439. return false;
  98440. }
  98441. left_pos = pos;
  98442. }
  98443. else if(this_frame_sample > target_sample) {
  98444. right_sample = this_frame_sample;
  98445. /* sanity check to avoid infinite loop */
  98446. if (right_pos == pos) {
  98447. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98448. return false;
  98449. }
  98450. right_pos = pos;
  98451. }
  98452. }
  98453. }
  98454. }
  98455. return true;
  98456. }
  98457. #endif
  98458. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98459. {
  98460. (void)client_data;
  98461. if(*bytes > 0) {
  98462. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  98463. if(ferror(decoder->private_->file))
  98464. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98465. else if(*bytes == 0)
  98466. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98467. else
  98468. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98469. }
  98470. else
  98471. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  98472. }
  98473. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  98474. {
  98475. (void)client_data;
  98476. if(decoder->private_->file == stdin)
  98477. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  98478. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  98479. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  98480. else
  98481. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  98482. }
  98483. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  98484. {
  98485. off_t pos;
  98486. (void)client_data;
  98487. if(decoder->private_->file == stdin)
  98488. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  98489. else if((pos = ftello(decoder->private_->file)) < 0)
  98490. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  98491. else {
  98492. *absolute_byte_offset = (FLAC__uint64)pos;
  98493. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  98494. }
  98495. }
  98496. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  98497. {
  98498. struct stat filestats;
  98499. (void)client_data;
  98500. if(decoder->private_->file == stdin)
  98501. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  98502. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  98503. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  98504. else {
  98505. *stream_length = (FLAC__uint64)filestats.st_size;
  98506. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  98507. }
  98508. }
  98509. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  98510. {
  98511. (void)client_data;
  98512. return feof(decoder->private_->file)? true : false;
  98513. }
  98514. #endif
  98515. /*** End of inlined file: stream_decoder.c ***/
  98516. /*** Start of inlined file: stream_encoder.c ***/
  98517. /*** Start of inlined file: juce_FlacHeader.h ***/
  98518. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98519. // tasks..
  98520. #define VERSION "1.2.1"
  98521. #define FLAC__NO_DLL 1
  98522. #if JUCE_MSVC
  98523. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98524. #endif
  98525. #if JUCE_MAC
  98526. #define FLAC__SYS_DARWIN 1
  98527. #endif
  98528. /*** End of inlined file: juce_FlacHeader.h ***/
  98529. #if JUCE_USE_FLAC
  98530. #if HAVE_CONFIG_H
  98531. # include <config.h>
  98532. #endif
  98533. #if defined _MSC_VER || defined __MINGW32__
  98534. #include <io.h> /* for _setmode() */
  98535. #include <fcntl.h> /* for _O_BINARY */
  98536. #endif
  98537. #if defined __CYGWIN__ || defined __EMX__
  98538. #include <io.h> /* for setmode(), O_BINARY */
  98539. #include <fcntl.h> /* for _O_BINARY */
  98540. #endif
  98541. #include <limits.h>
  98542. #include <stdio.h>
  98543. #include <stdlib.h> /* for malloc() */
  98544. #include <string.h> /* for memcpy() */
  98545. #include <sys/types.h> /* for off_t */
  98546. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98547. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98548. #define fseeko fseek
  98549. #define ftello ftell
  98550. #endif
  98551. #endif
  98552. /*** Start of inlined file: stream_encoder.h ***/
  98553. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  98554. #define FLAC__PROTECTED__STREAM_ENCODER_H
  98555. #if FLAC__HAS_OGG
  98556. #include "private/ogg_encoder_aspect.h"
  98557. #endif
  98558. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98559. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  98560. typedef enum {
  98561. FLAC__APODIZATION_BARTLETT,
  98562. FLAC__APODIZATION_BARTLETT_HANN,
  98563. FLAC__APODIZATION_BLACKMAN,
  98564. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  98565. FLAC__APODIZATION_CONNES,
  98566. FLAC__APODIZATION_FLATTOP,
  98567. FLAC__APODIZATION_GAUSS,
  98568. FLAC__APODIZATION_HAMMING,
  98569. FLAC__APODIZATION_HANN,
  98570. FLAC__APODIZATION_KAISER_BESSEL,
  98571. FLAC__APODIZATION_NUTTALL,
  98572. FLAC__APODIZATION_RECTANGLE,
  98573. FLAC__APODIZATION_TRIANGLE,
  98574. FLAC__APODIZATION_TUKEY,
  98575. FLAC__APODIZATION_WELCH
  98576. } FLAC__ApodizationFunction;
  98577. typedef struct {
  98578. FLAC__ApodizationFunction type;
  98579. union {
  98580. struct {
  98581. FLAC__real stddev;
  98582. } gauss;
  98583. struct {
  98584. FLAC__real p;
  98585. } tukey;
  98586. } parameters;
  98587. } FLAC__ApodizationSpecification;
  98588. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98589. typedef struct FLAC__StreamEncoderProtected {
  98590. FLAC__StreamEncoderState state;
  98591. FLAC__bool verify;
  98592. FLAC__bool streamable_subset;
  98593. FLAC__bool do_md5;
  98594. FLAC__bool do_mid_side_stereo;
  98595. FLAC__bool loose_mid_side_stereo;
  98596. unsigned channels;
  98597. unsigned bits_per_sample;
  98598. unsigned sample_rate;
  98599. unsigned blocksize;
  98600. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98601. unsigned num_apodizations;
  98602. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  98603. #endif
  98604. unsigned max_lpc_order;
  98605. unsigned qlp_coeff_precision;
  98606. FLAC__bool do_qlp_coeff_prec_search;
  98607. FLAC__bool do_exhaustive_model_search;
  98608. FLAC__bool do_escape_coding;
  98609. unsigned min_residual_partition_order;
  98610. unsigned max_residual_partition_order;
  98611. unsigned rice_parameter_search_dist;
  98612. FLAC__uint64 total_samples_estimate;
  98613. FLAC__StreamMetadata **metadata;
  98614. unsigned num_metadata_blocks;
  98615. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  98616. #if FLAC__HAS_OGG
  98617. FLAC__OggEncoderAspect ogg_encoder_aspect;
  98618. #endif
  98619. } FLAC__StreamEncoderProtected;
  98620. #endif
  98621. /*** End of inlined file: stream_encoder.h ***/
  98622. #if FLAC__HAS_OGG
  98623. #include "include/private/ogg_helper.h"
  98624. #include "include/private/ogg_mapping.h"
  98625. #endif
  98626. /*** Start of inlined file: stream_encoder_framing.h ***/
  98627. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  98628. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  98629. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  98630. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  98631. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98632. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98633. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98634. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98635. #endif
  98636. /*** End of inlined file: stream_encoder_framing.h ***/
  98637. /*** Start of inlined file: window.h ***/
  98638. #ifndef FLAC__PRIVATE__WINDOW_H
  98639. #define FLAC__PRIVATE__WINDOW_H
  98640. #ifdef HAVE_CONFIG_H
  98641. #include <config.h>
  98642. #endif
  98643. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98644. /*
  98645. * FLAC__window_*()
  98646. * --------------------------------------------------------------------
  98647. * Calculates window coefficients according to different apodization
  98648. * functions.
  98649. *
  98650. * OUT window[0,L-1]
  98651. * IN L (number of points in window)
  98652. */
  98653. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  98654. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  98655. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  98656. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  98657. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  98658. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  98659. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  98660. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  98661. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  98662. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  98663. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  98664. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  98665. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  98666. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  98667. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  98668. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98669. #endif
  98670. /*** End of inlined file: window.h ***/
  98671. #ifndef FLaC__INLINE
  98672. #define FLaC__INLINE
  98673. #endif
  98674. #ifdef min
  98675. #undef min
  98676. #endif
  98677. #define min(x,y) ((x)<(y)?(x):(y))
  98678. #ifdef max
  98679. #undef max
  98680. #endif
  98681. #define max(x,y) ((x)>(y)?(x):(y))
  98682. /* Exact Rice codeword length calculation is off by default. The simple
  98683. * (and fast) estimation (of how many bits a residual value will be
  98684. * encoded with) in this encoder is very good, almost always yielding
  98685. * compression within 0.1% of exact calculation.
  98686. */
  98687. #undef EXACT_RICE_BITS_CALCULATION
  98688. /* Rice parameter searching is off by default. The simple (and fast)
  98689. * parameter estimation in this encoder is very good, almost always
  98690. * yielding compression within 0.1% of the optimal parameters.
  98691. */
  98692. #undef ENABLE_RICE_PARAMETER_SEARCH
  98693. typedef struct {
  98694. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  98695. unsigned size; /* of each data[] in samples */
  98696. unsigned tail;
  98697. } verify_input_fifo;
  98698. typedef struct {
  98699. const FLAC__byte *data;
  98700. unsigned capacity;
  98701. unsigned bytes;
  98702. } verify_output;
  98703. typedef enum {
  98704. ENCODER_IN_MAGIC = 0,
  98705. ENCODER_IN_METADATA = 1,
  98706. ENCODER_IN_AUDIO = 2
  98707. } EncoderStateHint;
  98708. static struct CompressionLevels {
  98709. FLAC__bool do_mid_side_stereo;
  98710. FLAC__bool loose_mid_side_stereo;
  98711. unsigned max_lpc_order;
  98712. unsigned qlp_coeff_precision;
  98713. FLAC__bool do_qlp_coeff_prec_search;
  98714. FLAC__bool do_escape_coding;
  98715. FLAC__bool do_exhaustive_model_search;
  98716. unsigned min_residual_partition_order;
  98717. unsigned max_residual_partition_order;
  98718. unsigned rice_parameter_search_dist;
  98719. } compression_levels_[] = {
  98720. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  98721. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  98722. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  98723. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  98724. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  98725. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  98726. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  98727. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  98728. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  98729. };
  98730. /***********************************************************************
  98731. *
  98732. * Private class method prototypes
  98733. *
  98734. ***********************************************************************/
  98735. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  98736. static void free_(FLAC__StreamEncoder *encoder);
  98737. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  98738. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  98739. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  98740. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  98741. #if FLAC__HAS_OGG
  98742. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  98743. #endif
  98744. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  98745. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  98746. static FLAC__bool process_subframe_(
  98747. FLAC__StreamEncoder *encoder,
  98748. unsigned min_partition_order,
  98749. unsigned max_partition_order,
  98750. const FLAC__FrameHeader *frame_header,
  98751. unsigned subframe_bps,
  98752. const FLAC__int32 integer_signal[],
  98753. FLAC__Subframe *subframe[2],
  98754. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  98755. FLAC__int32 *residual[2],
  98756. unsigned *best_subframe,
  98757. unsigned *best_bits
  98758. );
  98759. static FLAC__bool add_subframe_(
  98760. FLAC__StreamEncoder *encoder,
  98761. unsigned blocksize,
  98762. unsigned subframe_bps,
  98763. const FLAC__Subframe *subframe,
  98764. FLAC__BitWriter *frame
  98765. );
  98766. static unsigned evaluate_constant_subframe_(
  98767. FLAC__StreamEncoder *encoder,
  98768. const FLAC__int32 signal,
  98769. unsigned blocksize,
  98770. unsigned subframe_bps,
  98771. FLAC__Subframe *subframe
  98772. );
  98773. static unsigned evaluate_fixed_subframe_(
  98774. FLAC__StreamEncoder *encoder,
  98775. const FLAC__int32 signal[],
  98776. FLAC__int32 residual[],
  98777. FLAC__uint64 abs_residual_partition_sums[],
  98778. unsigned raw_bits_per_partition[],
  98779. unsigned blocksize,
  98780. unsigned subframe_bps,
  98781. unsigned order,
  98782. unsigned rice_parameter,
  98783. unsigned rice_parameter_limit,
  98784. unsigned min_partition_order,
  98785. unsigned max_partition_order,
  98786. FLAC__bool do_escape_coding,
  98787. unsigned rice_parameter_search_dist,
  98788. FLAC__Subframe *subframe,
  98789. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98790. );
  98791. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98792. static unsigned evaluate_lpc_subframe_(
  98793. FLAC__StreamEncoder *encoder,
  98794. const FLAC__int32 signal[],
  98795. FLAC__int32 residual[],
  98796. FLAC__uint64 abs_residual_partition_sums[],
  98797. unsigned raw_bits_per_partition[],
  98798. const FLAC__real lp_coeff[],
  98799. unsigned blocksize,
  98800. unsigned subframe_bps,
  98801. unsigned order,
  98802. unsigned qlp_coeff_precision,
  98803. unsigned rice_parameter,
  98804. unsigned rice_parameter_limit,
  98805. unsigned min_partition_order,
  98806. unsigned max_partition_order,
  98807. FLAC__bool do_escape_coding,
  98808. unsigned rice_parameter_search_dist,
  98809. FLAC__Subframe *subframe,
  98810. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98811. );
  98812. #endif
  98813. static unsigned evaluate_verbatim_subframe_(
  98814. FLAC__StreamEncoder *encoder,
  98815. const FLAC__int32 signal[],
  98816. unsigned blocksize,
  98817. unsigned subframe_bps,
  98818. FLAC__Subframe *subframe
  98819. );
  98820. static unsigned find_best_partition_order_(
  98821. struct FLAC__StreamEncoderPrivate *private_,
  98822. const FLAC__int32 residual[],
  98823. FLAC__uint64 abs_residual_partition_sums[],
  98824. unsigned raw_bits_per_partition[],
  98825. unsigned residual_samples,
  98826. unsigned predictor_order,
  98827. unsigned rice_parameter,
  98828. unsigned rice_parameter_limit,
  98829. unsigned min_partition_order,
  98830. unsigned max_partition_order,
  98831. unsigned bps,
  98832. FLAC__bool do_escape_coding,
  98833. unsigned rice_parameter_search_dist,
  98834. FLAC__EntropyCodingMethod *best_ecm
  98835. );
  98836. static void precompute_partition_info_sums_(
  98837. const FLAC__int32 residual[],
  98838. FLAC__uint64 abs_residual_partition_sums[],
  98839. unsigned residual_samples,
  98840. unsigned predictor_order,
  98841. unsigned min_partition_order,
  98842. unsigned max_partition_order,
  98843. unsigned bps
  98844. );
  98845. static void precompute_partition_info_escapes_(
  98846. const FLAC__int32 residual[],
  98847. unsigned raw_bits_per_partition[],
  98848. unsigned residual_samples,
  98849. unsigned predictor_order,
  98850. unsigned min_partition_order,
  98851. unsigned max_partition_order
  98852. );
  98853. static FLAC__bool set_partitioned_rice_(
  98854. #ifdef EXACT_RICE_BITS_CALCULATION
  98855. const FLAC__int32 residual[],
  98856. #endif
  98857. const FLAC__uint64 abs_residual_partition_sums[],
  98858. const unsigned raw_bits_per_partition[],
  98859. const unsigned residual_samples,
  98860. const unsigned predictor_order,
  98861. const unsigned suggested_rice_parameter,
  98862. const unsigned rice_parameter_limit,
  98863. const unsigned rice_parameter_search_dist,
  98864. const unsigned partition_order,
  98865. const FLAC__bool search_for_escapes,
  98866. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  98867. unsigned *bits
  98868. );
  98869. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  98870. /* verify-related routines: */
  98871. static void append_to_verify_fifo_(
  98872. verify_input_fifo *fifo,
  98873. const FLAC__int32 * const input[],
  98874. unsigned input_offset,
  98875. unsigned channels,
  98876. unsigned wide_samples
  98877. );
  98878. static void append_to_verify_fifo_interleaved_(
  98879. verify_input_fifo *fifo,
  98880. const FLAC__int32 input[],
  98881. unsigned input_offset,
  98882. unsigned channels,
  98883. unsigned wide_samples
  98884. );
  98885. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98886. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  98887. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  98888. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  98889. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98890. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98891. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98892. 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);
  98893. static FILE *get_binary_stdout_(void);
  98894. /***********************************************************************
  98895. *
  98896. * Private class data
  98897. *
  98898. ***********************************************************************/
  98899. typedef struct FLAC__StreamEncoderPrivate {
  98900. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  98901. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  98902. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  98903. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98904. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  98905. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  98906. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  98907. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  98908. #endif
  98909. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  98910. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  98911. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98912. FLAC__int32 *residual_workspace_mid_side[2][2];
  98913. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  98914. FLAC__Subframe subframe_workspace_mid_side[2][2];
  98915. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98916. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  98917. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  98918. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  98919. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98920. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  98921. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  98922. unsigned best_subframe_mid_side[2];
  98923. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  98924. unsigned best_subframe_bits_mid_side[2];
  98925. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  98926. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  98927. FLAC__BitWriter *frame; /* the current frame being worked on */
  98928. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  98929. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  98930. FLAC__ChannelAssignment last_channel_assignment;
  98931. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  98932. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  98933. unsigned current_sample_number;
  98934. unsigned current_frame_number;
  98935. FLAC__MD5Context md5context;
  98936. FLAC__CPUInfo cpuinfo;
  98937. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98938. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98939. #else
  98940. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98941. #endif
  98942. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98943. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  98944. 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[]);
  98945. 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[]);
  98946. 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[]);
  98947. #endif
  98948. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  98949. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  98950. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  98951. FLAC__bool disable_constant_subframes;
  98952. FLAC__bool disable_fixed_subframes;
  98953. FLAC__bool disable_verbatim_subframes;
  98954. #if FLAC__HAS_OGG
  98955. FLAC__bool is_ogg;
  98956. #endif
  98957. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  98958. FLAC__StreamEncoderSeekCallback seek_callback;
  98959. FLAC__StreamEncoderTellCallback tell_callback;
  98960. FLAC__StreamEncoderWriteCallback write_callback;
  98961. FLAC__StreamEncoderMetadataCallback metadata_callback;
  98962. FLAC__StreamEncoderProgressCallback progress_callback;
  98963. void *client_data;
  98964. unsigned first_seekpoint_to_check;
  98965. FILE *file; /* only used when encoding to a file */
  98966. FLAC__uint64 bytes_written;
  98967. FLAC__uint64 samples_written;
  98968. unsigned frames_written;
  98969. unsigned total_frames_estimate;
  98970. /* unaligned (original) pointers to allocated data */
  98971. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  98972. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  98973. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98974. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  98975. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  98976. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  98977. FLAC__real *windowed_signal_unaligned;
  98978. #endif
  98979. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  98980. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  98981. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  98982. unsigned *raw_bits_per_partition_unaligned;
  98983. /*
  98984. * These fields have been moved here from private function local
  98985. * declarations merely to save stack space during encoding.
  98986. */
  98987. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98988. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  98989. #endif
  98990. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  98991. /*
  98992. * The data for the verify section
  98993. */
  98994. struct {
  98995. FLAC__StreamDecoder *decoder;
  98996. EncoderStateHint state_hint;
  98997. FLAC__bool needs_magic_hack;
  98998. verify_input_fifo input_fifo;
  98999. verify_output output;
  99000. struct {
  99001. FLAC__uint64 absolute_sample;
  99002. unsigned frame_number;
  99003. unsigned channel;
  99004. unsigned sample;
  99005. FLAC__int32 expected;
  99006. FLAC__int32 got;
  99007. } error_stats;
  99008. } verify;
  99009. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  99010. } FLAC__StreamEncoderPrivate;
  99011. /***********************************************************************
  99012. *
  99013. * Public static class data
  99014. *
  99015. ***********************************************************************/
  99016. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  99017. "FLAC__STREAM_ENCODER_OK",
  99018. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  99019. "FLAC__STREAM_ENCODER_OGG_ERROR",
  99020. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  99021. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  99022. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  99023. "FLAC__STREAM_ENCODER_IO_ERROR",
  99024. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  99025. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  99026. };
  99027. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  99028. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  99029. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  99030. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99031. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  99032. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  99033. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  99034. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  99035. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  99036. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  99037. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  99038. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  99039. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  99040. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  99041. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  99042. };
  99043. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  99044. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  99045. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  99046. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  99047. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  99048. };
  99049. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  99050. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  99051. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  99052. };
  99053. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  99054. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  99055. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  99056. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  99057. };
  99058. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  99059. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  99060. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  99061. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  99062. };
  99063. /* Number of samples that will be overread to watch for end of stream. By
  99064. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  99065. * always try to read blocksize+1 samples before encoding a block, so that
  99066. * even if the stream has a total sample count that is an integral multiple
  99067. * of the blocksize, we will still notice when we are encoding the last
  99068. * block. This is needed, for example, to correctly set the end-of-stream
  99069. * marker in Ogg FLAC.
  99070. *
  99071. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  99072. * not really any reason to change it.
  99073. */
  99074. static const unsigned OVERREAD_ = 1;
  99075. /***********************************************************************
  99076. *
  99077. * Class constructor/destructor
  99078. *
  99079. */
  99080. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  99081. {
  99082. FLAC__StreamEncoder *encoder;
  99083. unsigned i;
  99084. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99085. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  99086. if(encoder == 0) {
  99087. return 0;
  99088. }
  99089. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  99090. if(encoder->protected_ == 0) {
  99091. free(encoder);
  99092. return 0;
  99093. }
  99094. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  99095. if(encoder->private_ == 0) {
  99096. free(encoder->protected_);
  99097. free(encoder);
  99098. return 0;
  99099. }
  99100. encoder->private_->frame = FLAC__bitwriter_new();
  99101. if(encoder->private_->frame == 0) {
  99102. free(encoder->private_);
  99103. free(encoder->protected_);
  99104. free(encoder);
  99105. return 0;
  99106. }
  99107. encoder->private_->file = 0;
  99108. set_defaults_enc(encoder);
  99109. encoder->private_->is_being_deleted = false;
  99110. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99111. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  99112. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  99113. }
  99114. for(i = 0; i < 2; i++) {
  99115. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  99116. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  99117. }
  99118. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99119. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  99120. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  99121. }
  99122. for(i = 0; i < 2; i++) {
  99123. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  99124. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  99125. }
  99126. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99127. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99128. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99129. }
  99130. for(i = 0; i < 2; i++) {
  99131. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99132. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99133. }
  99134. for(i = 0; i < 2; i++)
  99135. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  99136. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99137. return encoder;
  99138. }
  99139. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  99140. {
  99141. unsigned i;
  99142. FLAC__ASSERT(0 != encoder);
  99143. FLAC__ASSERT(0 != encoder->protected_);
  99144. FLAC__ASSERT(0 != encoder->private_);
  99145. FLAC__ASSERT(0 != encoder->private_->frame);
  99146. encoder->private_->is_being_deleted = true;
  99147. (void)FLAC__stream_encoder_finish(encoder);
  99148. if(0 != encoder->private_->verify.decoder)
  99149. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  99150. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99151. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99152. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99153. }
  99154. for(i = 0; i < 2; i++) {
  99155. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99156. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99157. }
  99158. for(i = 0; i < 2; i++)
  99159. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  99160. FLAC__bitwriter_delete(encoder->private_->frame);
  99161. free(encoder->private_);
  99162. free(encoder->protected_);
  99163. free(encoder);
  99164. }
  99165. /***********************************************************************
  99166. *
  99167. * Public class methods
  99168. *
  99169. ***********************************************************************/
  99170. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  99171. FLAC__StreamEncoder *encoder,
  99172. FLAC__StreamEncoderReadCallback read_callback,
  99173. FLAC__StreamEncoderWriteCallback write_callback,
  99174. FLAC__StreamEncoderSeekCallback seek_callback,
  99175. FLAC__StreamEncoderTellCallback tell_callback,
  99176. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99177. void *client_data,
  99178. FLAC__bool is_ogg
  99179. )
  99180. {
  99181. unsigned i;
  99182. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  99183. FLAC__ASSERT(0 != encoder);
  99184. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99185. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99186. #if !FLAC__HAS_OGG
  99187. if(is_ogg)
  99188. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99189. #endif
  99190. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  99191. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  99192. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  99193. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  99194. if(encoder->protected_->channels != 2) {
  99195. encoder->protected_->do_mid_side_stereo = false;
  99196. encoder->protected_->loose_mid_side_stereo = false;
  99197. }
  99198. else if(!encoder->protected_->do_mid_side_stereo)
  99199. encoder->protected_->loose_mid_side_stereo = false;
  99200. if(encoder->protected_->bits_per_sample >= 32)
  99201. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  99202. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  99203. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  99204. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  99205. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  99206. if(encoder->protected_->blocksize == 0) {
  99207. if(encoder->protected_->max_lpc_order == 0)
  99208. encoder->protected_->blocksize = 1152;
  99209. else
  99210. encoder->protected_->blocksize = 4096;
  99211. }
  99212. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  99213. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  99214. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  99215. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  99216. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  99217. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  99218. if(encoder->protected_->qlp_coeff_precision == 0) {
  99219. if(encoder->protected_->bits_per_sample < 16) {
  99220. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  99221. /* @@@ until then we'll make a guess */
  99222. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  99223. }
  99224. else if(encoder->protected_->bits_per_sample == 16) {
  99225. if(encoder->protected_->blocksize <= 192)
  99226. encoder->protected_->qlp_coeff_precision = 7;
  99227. else if(encoder->protected_->blocksize <= 384)
  99228. encoder->protected_->qlp_coeff_precision = 8;
  99229. else if(encoder->protected_->blocksize <= 576)
  99230. encoder->protected_->qlp_coeff_precision = 9;
  99231. else if(encoder->protected_->blocksize <= 1152)
  99232. encoder->protected_->qlp_coeff_precision = 10;
  99233. else if(encoder->protected_->blocksize <= 2304)
  99234. encoder->protected_->qlp_coeff_precision = 11;
  99235. else if(encoder->protected_->blocksize <= 4608)
  99236. encoder->protected_->qlp_coeff_precision = 12;
  99237. else
  99238. encoder->protected_->qlp_coeff_precision = 13;
  99239. }
  99240. else {
  99241. if(encoder->protected_->blocksize <= 384)
  99242. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  99243. else if(encoder->protected_->blocksize <= 1152)
  99244. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  99245. else
  99246. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99247. }
  99248. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  99249. }
  99250. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  99251. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  99252. if(encoder->protected_->streamable_subset) {
  99253. if(
  99254. encoder->protected_->blocksize != 192 &&
  99255. encoder->protected_->blocksize != 576 &&
  99256. encoder->protected_->blocksize != 1152 &&
  99257. encoder->protected_->blocksize != 2304 &&
  99258. encoder->protected_->blocksize != 4608 &&
  99259. encoder->protected_->blocksize != 256 &&
  99260. encoder->protected_->blocksize != 512 &&
  99261. encoder->protected_->blocksize != 1024 &&
  99262. encoder->protected_->blocksize != 2048 &&
  99263. encoder->protected_->blocksize != 4096 &&
  99264. encoder->protected_->blocksize != 8192 &&
  99265. encoder->protected_->blocksize != 16384
  99266. )
  99267. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99268. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  99269. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99270. if(
  99271. encoder->protected_->bits_per_sample != 8 &&
  99272. encoder->protected_->bits_per_sample != 12 &&
  99273. encoder->protected_->bits_per_sample != 16 &&
  99274. encoder->protected_->bits_per_sample != 20 &&
  99275. encoder->protected_->bits_per_sample != 24
  99276. )
  99277. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99278. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  99279. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99280. if(
  99281. encoder->protected_->sample_rate <= 48000 &&
  99282. (
  99283. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  99284. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  99285. )
  99286. ) {
  99287. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99288. }
  99289. }
  99290. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99291. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  99292. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  99293. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  99294. #if FLAC__HAS_OGG
  99295. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  99296. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  99297. unsigned i;
  99298. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  99299. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99300. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  99301. for( ; i > 0; i--)
  99302. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  99303. encoder->protected_->metadata[0] = vc;
  99304. break;
  99305. }
  99306. }
  99307. }
  99308. #endif
  99309. /* keep track of any SEEKTABLE block */
  99310. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  99311. unsigned i;
  99312. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99313. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99314. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  99315. break; /* take only the first one */
  99316. }
  99317. }
  99318. }
  99319. /* validate metadata */
  99320. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  99321. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99322. metadata_has_seektable = false;
  99323. metadata_has_vorbis_comment = false;
  99324. metadata_picture_has_type1 = false;
  99325. metadata_picture_has_type2 = false;
  99326. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99327. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  99328. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  99329. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99330. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99331. if(metadata_has_seektable) /* only one is allowed */
  99332. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99333. metadata_has_seektable = true;
  99334. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  99335. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99336. }
  99337. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99338. if(metadata_has_vorbis_comment) /* only one is allowed */
  99339. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99340. metadata_has_vorbis_comment = true;
  99341. }
  99342. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  99343. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  99344. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99345. }
  99346. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  99347. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  99348. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99349. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  99350. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  99351. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99352. metadata_picture_has_type1 = true;
  99353. /* standard icon must be 32x32 pixel PNG */
  99354. if(
  99355. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  99356. (
  99357. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  99358. m->data.picture.width != 32 ||
  99359. m->data.picture.height != 32
  99360. )
  99361. )
  99362. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99363. }
  99364. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  99365. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  99366. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99367. metadata_picture_has_type2 = true;
  99368. }
  99369. }
  99370. }
  99371. encoder->private_->input_capacity = 0;
  99372. for(i = 0; i < encoder->protected_->channels; i++) {
  99373. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  99374. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99375. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  99376. #endif
  99377. }
  99378. for(i = 0; i < 2; i++) {
  99379. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  99380. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99381. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  99382. #endif
  99383. }
  99384. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99385. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  99386. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  99387. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  99388. #endif
  99389. for(i = 0; i < encoder->protected_->channels; i++) {
  99390. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  99391. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  99392. encoder->private_->best_subframe[i] = 0;
  99393. }
  99394. for(i = 0; i < 2; i++) {
  99395. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  99396. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  99397. encoder->private_->best_subframe_mid_side[i] = 0;
  99398. }
  99399. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  99400. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  99401. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99402. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  99403. #else
  99404. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  99405. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  99406. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  99407. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  99408. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  99409. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  99410. 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);
  99411. #endif
  99412. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  99413. encoder->private_->loose_mid_side_stereo_frames = 1;
  99414. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99415. encoder->private_->current_sample_number = 0;
  99416. encoder->private_->current_frame_number = 0;
  99417. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  99418. 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? */
  99419. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  99420. /*
  99421. * get the CPU info and set the function pointers
  99422. */
  99423. FLAC__cpu_info(&encoder->private_->cpuinfo);
  99424. /* first default to the non-asm routines */
  99425. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99426. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  99427. #endif
  99428. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  99429. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99430. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99431. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  99432. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99433. #endif
  99434. /* now override with asm where appropriate */
  99435. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99436. # ifndef FLAC__NO_ASM
  99437. if(encoder->private_->cpuinfo.use_asm) {
  99438. # ifdef FLAC__CPU_IA32
  99439. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99440. # ifdef FLAC__HAS_NASM
  99441. if(encoder->private_->cpuinfo.data.ia32.sse) {
  99442. if(encoder->protected_->max_lpc_order < 4)
  99443. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  99444. else if(encoder->protected_->max_lpc_order < 8)
  99445. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  99446. else if(encoder->protected_->max_lpc_order < 12)
  99447. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  99448. else
  99449. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99450. }
  99451. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  99452. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  99453. else
  99454. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99455. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  99456. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99457. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  99458. }
  99459. else {
  99460. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99461. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99462. }
  99463. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  99464. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  99465. # endif /* FLAC__HAS_NASM */
  99466. # endif /* FLAC__CPU_IA32 */
  99467. }
  99468. # endif /* !FLAC__NO_ASM */
  99469. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  99470. /* finally override based on wide-ness if necessary */
  99471. if(encoder->private_->use_wide_by_block) {
  99472. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  99473. }
  99474. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  99475. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  99476. #if FLAC__HAS_OGG
  99477. encoder->private_->is_ogg = is_ogg;
  99478. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  99479. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99480. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99481. }
  99482. #endif
  99483. encoder->private_->read_callback = read_callback;
  99484. encoder->private_->write_callback = write_callback;
  99485. encoder->private_->seek_callback = seek_callback;
  99486. encoder->private_->tell_callback = tell_callback;
  99487. encoder->private_->metadata_callback = metadata_callback;
  99488. encoder->private_->client_data = client_data;
  99489. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  99490. /* the above function sets the state for us in case of an error */
  99491. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99492. }
  99493. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  99494. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99495. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99496. }
  99497. /*
  99498. * Set up the verify stuff if necessary
  99499. */
  99500. if(encoder->protected_->verify) {
  99501. /*
  99502. * First, set up the fifo which will hold the
  99503. * original signal to compare against
  99504. */
  99505. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  99506. for(i = 0; i < encoder->protected_->channels; i++) {
  99507. 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))) {
  99508. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99509. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99510. }
  99511. }
  99512. encoder->private_->verify.input_fifo.tail = 0;
  99513. /*
  99514. * Now set up a stream decoder for verification
  99515. */
  99516. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  99517. if(0 == encoder->private_->verify.decoder) {
  99518. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99519. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99520. }
  99521. 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) {
  99522. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99523. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99524. }
  99525. }
  99526. encoder->private_->verify.error_stats.absolute_sample = 0;
  99527. encoder->private_->verify.error_stats.frame_number = 0;
  99528. encoder->private_->verify.error_stats.channel = 0;
  99529. encoder->private_->verify.error_stats.sample = 0;
  99530. encoder->private_->verify.error_stats.expected = 0;
  99531. encoder->private_->verify.error_stats.got = 0;
  99532. /*
  99533. * These must be done before we write any metadata, because that
  99534. * calls the write_callback, which uses these values.
  99535. */
  99536. encoder->private_->first_seekpoint_to_check = 0;
  99537. encoder->private_->samples_written = 0;
  99538. encoder->protected_->streaminfo_offset = 0;
  99539. encoder->protected_->seektable_offset = 0;
  99540. encoder->protected_->audio_offset = 0;
  99541. /*
  99542. * write the stream header
  99543. */
  99544. if(encoder->protected_->verify)
  99545. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  99546. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  99547. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99548. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99549. }
  99550. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99551. /* the above function sets the state for us in case of an error */
  99552. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99553. }
  99554. /*
  99555. * write the STREAMINFO metadata block
  99556. */
  99557. if(encoder->protected_->verify)
  99558. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  99559. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  99560. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  99561. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  99562. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  99563. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  99564. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  99565. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  99566. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  99567. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  99568. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  99569. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  99570. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  99571. if(encoder->protected_->do_md5)
  99572. FLAC__MD5Init(&encoder->private_->md5context);
  99573. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  99574. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99575. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99576. }
  99577. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99578. /* the above function sets the state for us in case of an error */
  99579. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99580. }
  99581. /*
  99582. * Now that the STREAMINFO block is written, we can init this to an
  99583. * absurdly-high value...
  99584. */
  99585. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  99586. /* ... and clear this to 0 */
  99587. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  99588. /*
  99589. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  99590. * if not, we will write an empty one (FLAC__add_metadata_block()
  99591. * automatically supplies the vendor string).
  99592. *
  99593. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  99594. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  99595. * true it will have already insured that the metadata list is properly
  99596. * ordered.)
  99597. */
  99598. if(!metadata_has_vorbis_comment) {
  99599. FLAC__StreamMetadata vorbis_comment;
  99600. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  99601. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  99602. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  99603. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  99604. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  99605. vorbis_comment.data.vorbis_comment.num_comments = 0;
  99606. vorbis_comment.data.vorbis_comment.comments = 0;
  99607. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  99608. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99609. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99610. }
  99611. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99612. /* the above function sets the state for us in case of an error */
  99613. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99614. }
  99615. }
  99616. /*
  99617. * write the user's metadata blocks
  99618. */
  99619. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99620. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  99621. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  99622. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99623. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99624. }
  99625. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99626. /* the above function sets the state for us in case of an error */
  99627. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99628. }
  99629. }
  99630. /* now that all the metadata is written, we save the stream offset */
  99631. 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 */
  99632. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99633. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99634. }
  99635. if(encoder->protected_->verify)
  99636. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  99637. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  99638. }
  99639. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  99640. FLAC__StreamEncoder *encoder,
  99641. FLAC__StreamEncoderWriteCallback write_callback,
  99642. FLAC__StreamEncoderSeekCallback seek_callback,
  99643. FLAC__StreamEncoderTellCallback tell_callback,
  99644. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99645. void *client_data
  99646. )
  99647. {
  99648. return init_stream_internal_enc(
  99649. encoder,
  99650. /*read_callback=*/0,
  99651. write_callback,
  99652. seek_callback,
  99653. tell_callback,
  99654. metadata_callback,
  99655. client_data,
  99656. /*is_ogg=*/false
  99657. );
  99658. }
  99659. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  99660. FLAC__StreamEncoder *encoder,
  99661. FLAC__StreamEncoderReadCallback read_callback,
  99662. FLAC__StreamEncoderWriteCallback write_callback,
  99663. FLAC__StreamEncoderSeekCallback seek_callback,
  99664. FLAC__StreamEncoderTellCallback tell_callback,
  99665. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99666. void *client_data
  99667. )
  99668. {
  99669. return init_stream_internal_enc(
  99670. encoder,
  99671. read_callback,
  99672. write_callback,
  99673. seek_callback,
  99674. tell_callback,
  99675. metadata_callback,
  99676. client_data,
  99677. /*is_ogg=*/true
  99678. );
  99679. }
  99680. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  99681. FLAC__StreamEncoder *encoder,
  99682. FILE *file,
  99683. FLAC__StreamEncoderProgressCallback progress_callback,
  99684. void *client_data,
  99685. FLAC__bool is_ogg
  99686. )
  99687. {
  99688. FLAC__StreamEncoderInitStatus init_status;
  99689. FLAC__ASSERT(0 != encoder);
  99690. FLAC__ASSERT(0 != file);
  99691. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99692. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99693. /* double protection */
  99694. if(file == 0) {
  99695. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99696. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99697. }
  99698. /*
  99699. * To make sure that our file does not go unclosed after an error, we
  99700. * must assign the FILE pointer before any further error can occur in
  99701. * this routine.
  99702. */
  99703. if(file == stdout)
  99704. file = get_binary_stdout_(); /* just to be safe */
  99705. encoder->private_->file = file;
  99706. encoder->private_->progress_callback = progress_callback;
  99707. encoder->private_->bytes_written = 0;
  99708. encoder->private_->samples_written = 0;
  99709. encoder->private_->frames_written = 0;
  99710. init_status = init_stream_internal_enc(
  99711. encoder,
  99712. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  99713. file_write_callback_,
  99714. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  99715. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  99716. /*metadata_callback=*/0,
  99717. client_data,
  99718. is_ogg
  99719. );
  99720. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  99721. /* the above function sets the state for us in case of an error */
  99722. return init_status;
  99723. }
  99724. {
  99725. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99726. FLAC__ASSERT(blocksize != 0);
  99727. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  99728. }
  99729. return init_status;
  99730. }
  99731. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  99732. FLAC__StreamEncoder *encoder,
  99733. FILE *file,
  99734. FLAC__StreamEncoderProgressCallback progress_callback,
  99735. void *client_data
  99736. )
  99737. {
  99738. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  99739. }
  99740. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  99741. FLAC__StreamEncoder *encoder,
  99742. FILE *file,
  99743. FLAC__StreamEncoderProgressCallback progress_callback,
  99744. void *client_data
  99745. )
  99746. {
  99747. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  99748. }
  99749. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  99750. FLAC__StreamEncoder *encoder,
  99751. const char *filename,
  99752. FLAC__StreamEncoderProgressCallback progress_callback,
  99753. void *client_data,
  99754. FLAC__bool is_ogg
  99755. )
  99756. {
  99757. FILE *file;
  99758. FLAC__ASSERT(0 != encoder);
  99759. /*
  99760. * To make sure that our file does not go unclosed after an error, we
  99761. * have to do the same entrance checks here that are later performed
  99762. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  99763. */
  99764. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99765. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99766. file = filename? fopen(filename, "w+b") : stdout;
  99767. if(file == 0) {
  99768. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99769. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99770. }
  99771. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  99772. }
  99773. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  99774. FLAC__StreamEncoder *encoder,
  99775. const char *filename,
  99776. FLAC__StreamEncoderProgressCallback progress_callback,
  99777. void *client_data
  99778. )
  99779. {
  99780. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  99781. }
  99782. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  99783. FLAC__StreamEncoder *encoder,
  99784. const char *filename,
  99785. FLAC__StreamEncoderProgressCallback progress_callback,
  99786. void *client_data
  99787. )
  99788. {
  99789. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  99790. }
  99791. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  99792. {
  99793. FLAC__bool error = false;
  99794. FLAC__ASSERT(0 != encoder);
  99795. FLAC__ASSERT(0 != encoder->private_);
  99796. FLAC__ASSERT(0 != encoder->protected_);
  99797. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  99798. return true;
  99799. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  99800. if(encoder->private_->current_sample_number != 0) {
  99801. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  99802. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  99803. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  99804. error = true;
  99805. }
  99806. }
  99807. if(encoder->protected_->do_md5)
  99808. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  99809. if(!encoder->private_->is_being_deleted) {
  99810. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  99811. if(encoder->private_->seek_callback) {
  99812. #if FLAC__HAS_OGG
  99813. if(encoder->private_->is_ogg)
  99814. update_ogg_metadata_(encoder);
  99815. else
  99816. #endif
  99817. update_metadata_(encoder);
  99818. /* check if an error occurred while updating metadata */
  99819. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  99820. error = true;
  99821. }
  99822. if(encoder->private_->metadata_callback)
  99823. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  99824. }
  99825. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  99826. if(!error)
  99827. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99828. error = true;
  99829. }
  99830. }
  99831. if(0 != encoder->private_->file) {
  99832. if(encoder->private_->file != stdout)
  99833. fclose(encoder->private_->file);
  99834. encoder->private_->file = 0;
  99835. }
  99836. #if FLAC__HAS_OGG
  99837. if(encoder->private_->is_ogg)
  99838. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  99839. #endif
  99840. free_(encoder);
  99841. set_defaults_enc(encoder);
  99842. if(!error)
  99843. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99844. return !error;
  99845. }
  99846. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long 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. #if FLAC__HAS_OGG
  99854. /* can't check encoder->private_->is_ogg since that's not set until init time */
  99855. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  99856. return true;
  99857. #else
  99858. (void)value;
  99859. return false;
  99860. #endif
  99861. }
  99862. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99863. {
  99864. FLAC__ASSERT(0 != encoder);
  99865. FLAC__ASSERT(0 != encoder->private_);
  99866. FLAC__ASSERT(0 != encoder->protected_);
  99867. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99868. return false;
  99869. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99870. encoder->protected_->verify = value;
  99871. #endif
  99872. return true;
  99873. }
  99874. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99875. {
  99876. FLAC__ASSERT(0 != encoder);
  99877. FLAC__ASSERT(0 != encoder->private_);
  99878. FLAC__ASSERT(0 != encoder->protected_);
  99879. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99880. return false;
  99881. encoder->protected_->streamable_subset = value;
  99882. return true;
  99883. }
  99884. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99885. {
  99886. FLAC__ASSERT(0 != encoder);
  99887. FLAC__ASSERT(0 != encoder->private_);
  99888. FLAC__ASSERT(0 != encoder->protected_);
  99889. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99890. return false;
  99891. encoder->protected_->do_md5 = value;
  99892. return true;
  99893. }
  99894. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  99895. {
  99896. FLAC__ASSERT(0 != encoder);
  99897. FLAC__ASSERT(0 != encoder->private_);
  99898. FLAC__ASSERT(0 != encoder->protected_);
  99899. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99900. return false;
  99901. encoder->protected_->channels = value;
  99902. return true;
  99903. }
  99904. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  99905. {
  99906. FLAC__ASSERT(0 != encoder);
  99907. FLAC__ASSERT(0 != encoder->private_);
  99908. FLAC__ASSERT(0 != encoder->protected_);
  99909. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99910. return false;
  99911. encoder->protected_->bits_per_sample = value;
  99912. return true;
  99913. }
  99914. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  99915. {
  99916. FLAC__ASSERT(0 != encoder);
  99917. FLAC__ASSERT(0 != encoder->private_);
  99918. FLAC__ASSERT(0 != encoder->protected_);
  99919. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99920. return false;
  99921. encoder->protected_->sample_rate = value;
  99922. return true;
  99923. }
  99924. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  99925. {
  99926. FLAC__bool ok = true;
  99927. FLAC__ASSERT(0 != encoder);
  99928. FLAC__ASSERT(0 != encoder->private_);
  99929. FLAC__ASSERT(0 != encoder->protected_);
  99930. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99931. return false;
  99932. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  99933. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  99934. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  99935. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  99936. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99937. #if 0
  99938. /* was: */
  99939. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  99940. /* but it's too hard to specify the string in a locale-specific way */
  99941. #else
  99942. encoder->protected_->num_apodizations = 1;
  99943. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99944. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99945. #endif
  99946. #endif
  99947. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  99948. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  99949. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  99950. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  99951. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  99952. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  99953. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  99954. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  99955. return ok;
  99956. }
  99957. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  99958. {
  99959. FLAC__ASSERT(0 != encoder);
  99960. FLAC__ASSERT(0 != encoder->private_);
  99961. FLAC__ASSERT(0 != encoder->protected_);
  99962. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99963. return false;
  99964. encoder->protected_->blocksize = value;
  99965. return true;
  99966. }
  99967. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99968. {
  99969. FLAC__ASSERT(0 != encoder);
  99970. FLAC__ASSERT(0 != encoder->private_);
  99971. FLAC__ASSERT(0 != encoder->protected_);
  99972. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99973. return false;
  99974. encoder->protected_->do_mid_side_stereo = value;
  99975. return true;
  99976. }
  99977. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99978. {
  99979. FLAC__ASSERT(0 != encoder);
  99980. FLAC__ASSERT(0 != encoder->private_);
  99981. FLAC__ASSERT(0 != encoder->protected_);
  99982. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99983. return false;
  99984. encoder->protected_->loose_mid_side_stereo = value;
  99985. return true;
  99986. }
  99987. /*@@@@add to tests*/
  99988. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  99989. {
  99990. FLAC__ASSERT(0 != encoder);
  99991. FLAC__ASSERT(0 != encoder->private_);
  99992. FLAC__ASSERT(0 != encoder->protected_);
  99993. FLAC__ASSERT(0 != specification);
  99994. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99995. return false;
  99996. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  99997. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  99998. #else
  99999. encoder->protected_->num_apodizations = 0;
  100000. while(1) {
  100001. const char *s = strchr(specification, ';');
  100002. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  100003. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  100004. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  100005. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  100006. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  100007. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  100008. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  100009. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  100010. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  100011. else if(n==6 && 0 == strncmp("connes" , specification, n))
  100012. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  100013. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  100014. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  100015. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  100016. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  100017. if (stddev > 0.0 && stddev <= 0.5) {
  100018. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  100019. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  100020. }
  100021. }
  100022. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  100023. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  100024. else if(n==4 && 0 == strncmp("hann" , specification, n))
  100025. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  100026. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  100027. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  100028. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  100029. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  100030. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  100031. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  100032. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  100033. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  100034. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  100035. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  100036. if (p >= 0.0 && p <= 1.0) {
  100037. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  100038. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  100039. }
  100040. }
  100041. else if(n==5 && 0 == strncmp("welch" , specification, n))
  100042. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  100043. if (encoder->protected_->num_apodizations == 32)
  100044. break;
  100045. if (s)
  100046. specification = s+1;
  100047. else
  100048. break;
  100049. }
  100050. if(encoder->protected_->num_apodizations == 0) {
  100051. encoder->protected_->num_apodizations = 1;
  100052. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100053. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100054. }
  100055. #endif
  100056. return true;
  100057. }
  100058. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  100059. {
  100060. FLAC__ASSERT(0 != encoder);
  100061. FLAC__ASSERT(0 != encoder->private_);
  100062. FLAC__ASSERT(0 != encoder->protected_);
  100063. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100064. return false;
  100065. encoder->protected_->max_lpc_order = value;
  100066. return true;
  100067. }
  100068. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  100069. {
  100070. FLAC__ASSERT(0 != encoder);
  100071. FLAC__ASSERT(0 != encoder->private_);
  100072. FLAC__ASSERT(0 != encoder->protected_);
  100073. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100074. return false;
  100075. encoder->protected_->qlp_coeff_precision = value;
  100076. return true;
  100077. }
  100078. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100079. {
  100080. FLAC__ASSERT(0 != encoder);
  100081. FLAC__ASSERT(0 != encoder->private_);
  100082. FLAC__ASSERT(0 != encoder->protected_);
  100083. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100084. return false;
  100085. encoder->protected_->do_qlp_coeff_prec_search = value;
  100086. return true;
  100087. }
  100088. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100089. {
  100090. FLAC__ASSERT(0 != encoder);
  100091. FLAC__ASSERT(0 != encoder->private_);
  100092. FLAC__ASSERT(0 != encoder->protected_);
  100093. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100094. return false;
  100095. #if 0
  100096. /*@@@ deprecated: */
  100097. encoder->protected_->do_escape_coding = value;
  100098. #else
  100099. (void)value;
  100100. #endif
  100101. return true;
  100102. }
  100103. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100104. {
  100105. FLAC__ASSERT(0 != encoder);
  100106. FLAC__ASSERT(0 != encoder->private_);
  100107. FLAC__ASSERT(0 != encoder->protected_);
  100108. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100109. return false;
  100110. encoder->protected_->do_exhaustive_model_search = value;
  100111. return true;
  100112. }
  100113. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100114. {
  100115. FLAC__ASSERT(0 != encoder);
  100116. FLAC__ASSERT(0 != encoder->private_);
  100117. FLAC__ASSERT(0 != encoder->protected_);
  100118. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100119. return false;
  100120. encoder->protected_->min_residual_partition_order = value;
  100121. return true;
  100122. }
  100123. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100124. {
  100125. FLAC__ASSERT(0 != encoder);
  100126. FLAC__ASSERT(0 != encoder->private_);
  100127. FLAC__ASSERT(0 != encoder->protected_);
  100128. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100129. return false;
  100130. encoder->protected_->max_residual_partition_order = value;
  100131. return true;
  100132. }
  100133. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  100134. {
  100135. FLAC__ASSERT(0 != encoder);
  100136. FLAC__ASSERT(0 != encoder->private_);
  100137. FLAC__ASSERT(0 != encoder->protected_);
  100138. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100139. return false;
  100140. #if 0
  100141. /*@@@ deprecated: */
  100142. encoder->protected_->rice_parameter_search_dist = value;
  100143. #else
  100144. (void)value;
  100145. #endif
  100146. return true;
  100147. }
  100148. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  100149. {
  100150. FLAC__ASSERT(0 != encoder);
  100151. FLAC__ASSERT(0 != encoder->private_);
  100152. FLAC__ASSERT(0 != encoder->protected_);
  100153. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100154. return false;
  100155. encoder->protected_->total_samples_estimate = value;
  100156. return true;
  100157. }
  100158. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  100159. {
  100160. FLAC__ASSERT(0 != encoder);
  100161. FLAC__ASSERT(0 != encoder->private_);
  100162. FLAC__ASSERT(0 != encoder->protected_);
  100163. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100164. return false;
  100165. if(0 == metadata)
  100166. num_blocks = 0;
  100167. if(0 == num_blocks)
  100168. metadata = 0;
  100169. /* realloc() does not do exactly what we want so... */
  100170. if(encoder->protected_->metadata) {
  100171. free(encoder->protected_->metadata);
  100172. encoder->protected_->metadata = 0;
  100173. encoder->protected_->num_metadata_blocks = 0;
  100174. }
  100175. if(num_blocks) {
  100176. FLAC__StreamMetadata **m;
  100177. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  100178. return false;
  100179. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  100180. encoder->protected_->metadata = m;
  100181. encoder->protected_->num_metadata_blocks = num_blocks;
  100182. }
  100183. #if FLAC__HAS_OGG
  100184. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  100185. return false;
  100186. #endif
  100187. return true;
  100188. }
  100189. /*
  100190. * These three functions are not static, but not publically exposed in
  100191. * include/FLAC/ either. They are used by the test suite.
  100192. */
  100193. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100194. {
  100195. FLAC__ASSERT(0 != encoder);
  100196. FLAC__ASSERT(0 != encoder->private_);
  100197. FLAC__ASSERT(0 != encoder->protected_);
  100198. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100199. return false;
  100200. encoder->private_->disable_constant_subframes = value;
  100201. return true;
  100202. }
  100203. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100204. {
  100205. FLAC__ASSERT(0 != encoder);
  100206. FLAC__ASSERT(0 != encoder->private_);
  100207. FLAC__ASSERT(0 != encoder->protected_);
  100208. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100209. return false;
  100210. encoder->private_->disable_fixed_subframes = value;
  100211. return true;
  100212. }
  100213. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100214. {
  100215. FLAC__ASSERT(0 != encoder);
  100216. FLAC__ASSERT(0 != encoder->private_);
  100217. FLAC__ASSERT(0 != encoder->protected_);
  100218. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100219. return false;
  100220. encoder->private_->disable_verbatim_subframes = value;
  100221. return true;
  100222. }
  100223. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  100224. {
  100225. FLAC__ASSERT(0 != encoder);
  100226. FLAC__ASSERT(0 != encoder->private_);
  100227. FLAC__ASSERT(0 != encoder->protected_);
  100228. return encoder->protected_->state;
  100229. }
  100230. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  100231. {
  100232. FLAC__ASSERT(0 != encoder);
  100233. FLAC__ASSERT(0 != encoder->private_);
  100234. FLAC__ASSERT(0 != encoder->protected_);
  100235. if(encoder->protected_->verify)
  100236. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  100237. else
  100238. return FLAC__STREAM_DECODER_UNINITIALIZED;
  100239. }
  100240. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  100241. {
  100242. FLAC__ASSERT(0 != encoder);
  100243. FLAC__ASSERT(0 != encoder->private_);
  100244. FLAC__ASSERT(0 != encoder->protected_);
  100245. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  100246. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  100247. else
  100248. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  100249. }
  100250. 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)
  100251. {
  100252. FLAC__ASSERT(0 != encoder);
  100253. FLAC__ASSERT(0 != encoder->private_);
  100254. FLAC__ASSERT(0 != encoder->protected_);
  100255. if(0 != absolute_sample)
  100256. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  100257. if(0 != frame_number)
  100258. *frame_number = encoder->private_->verify.error_stats.frame_number;
  100259. if(0 != channel)
  100260. *channel = encoder->private_->verify.error_stats.channel;
  100261. if(0 != sample)
  100262. *sample = encoder->private_->verify.error_stats.sample;
  100263. if(0 != expected)
  100264. *expected = encoder->private_->verify.error_stats.expected;
  100265. if(0 != got)
  100266. *got = encoder->private_->verify.error_stats.got;
  100267. }
  100268. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  100269. {
  100270. FLAC__ASSERT(0 != encoder);
  100271. FLAC__ASSERT(0 != encoder->private_);
  100272. FLAC__ASSERT(0 != encoder->protected_);
  100273. return encoder->protected_->verify;
  100274. }
  100275. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  100276. {
  100277. FLAC__ASSERT(0 != encoder);
  100278. FLAC__ASSERT(0 != encoder->private_);
  100279. FLAC__ASSERT(0 != encoder->protected_);
  100280. return encoder->protected_->streamable_subset;
  100281. }
  100282. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  100283. {
  100284. FLAC__ASSERT(0 != encoder);
  100285. FLAC__ASSERT(0 != encoder->private_);
  100286. FLAC__ASSERT(0 != encoder->protected_);
  100287. return encoder->protected_->do_md5;
  100288. }
  100289. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  100290. {
  100291. FLAC__ASSERT(0 != encoder);
  100292. FLAC__ASSERT(0 != encoder->private_);
  100293. FLAC__ASSERT(0 != encoder->protected_);
  100294. return encoder->protected_->channels;
  100295. }
  100296. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  100297. {
  100298. FLAC__ASSERT(0 != encoder);
  100299. FLAC__ASSERT(0 != encoder->private_);
  100300. FLAC__ASSERT(0 != encoder->protected_);
  100301. return encoder->protected_->bits_per_sample;
  100302. }
  100303. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  100304. {
  100305. FLAC__ASSERT(0 != encoder);
  100306. FLAC__ASSERT(0 != encoder->private_);
  100307. FLAC__ASSERT(0 != encoder->protected_);
  100308. return encoder->protected_->sample_rate;
  100309. }
  100310. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  100311. {
  100312. FLAC__ASSERT(0 != encoder);
  100313. FLAC__ASSERT(0 != encoder->private_);
  100314. FLAC__ASSERT(0 != encoder->protected_);
  100315. return encoder->protected_->blocksize;
  100316. }
  100317. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100318. {
  100319. FLAC__ASSERT(0 != encoder);
  100320. FLAC__ASSERT(0 != encoder->private_);
  100321. FLAC__ASSERT(0 != encoder->protected_);
  100322. return encoder->protected_->do_mid_side_stereo;
  100323. }
  100324. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100325. {
  100326. FLAC__ASSERT(0 != encoder);
  100327. FLAC__ASSERT(0 != encoder->private_);
  100328. FLAC__ASSERT(0 != encoder->protected_);
  100329. return encoder->protected_->loose_mid_side_stereo;
  100330. }
  100331. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  100332. {
  100333. FLAC__ASSERT(0 != encoder);
  100334. FLAC__ASSERT(0 != encoder->private_);
  100335. FLAC__ASSERT(0 != encoder->protected_);
  100336. return encoder->protected_->max_lpc_order;
  100337. }
  100338. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  100339. {
  100340. FLAC__ASSERT(0 != encoder);
  100341. FLAC__ASSERT(0 != encoder->private_);
  100342. FLAC__ASSERT(0 != encoder->protected_);
  100343. return encoder->protected_->qlp_coeff_precision;
  100344. }
  100345. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  100346. {
  100347. FLAC__ASSERT(0 != encoder);
  100348. FLAC__ASSERT(0 != encoder->private_);
  100349. FLAC__ASSERT(0 != encoder->protected_);
  100350. return encoder->protected_->do_qlp_coeff_prec_search;
  100351. }
  100352. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  100353. {
  100354. FLAC__ASSERT(0 != encoder);
  100355. FLAC__ASSERT(0 != encoder->private_);
  100356. FLAC__ASSERT(0 != encoder->protected_);
  100357. return encoder->protected_->do_escape_coding;
  100358. }
  100359. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  100360. {
  100361. FLAC__ASSERT(0 != encoder);
  100362. FLAC__ASSERT(0 != encoder->private_);
  100363. FLAC__ASSERT(0 != encoder->protected_);
  100364. return encoder->protected_->do_exhaustive_model_search;
  100365. }
  100366. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100367. {
  100368. FLAC__ASSERT(0 != encoder);
  100369. FLAC__ASSERT(0 != encoder->private_);
  100370. FLAC__ASSERT(0 != encoder->protected_);
  100371. return encoder->protected_->min_residual_partition_order;
  100372. }
  100373. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100374. {
  100375. FLAC__ASSERT(0 != encoder);
  100376. FLAC__ASSERT(0 != encoder->private_);
  100377. FLAC__ASSERT(0 != encoder->protected_);
  100378. return encoder->protected_->max_residual_partition_order;
  100379. }
  100380. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  100381. {
  100382. FLAC__ASSERT(0 != encoder);
  100383. FLAC__ASSERT(0 != encoder->private_);
  100384. FLAC__ASSERT(0 != encoder->protected_);
  100385. return encoder->protected_->rice_parameter_search_dist;
  100386. }
  100387. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  100388. {
  100389. FLAC__ASSERT(0 != encoder);
  100390. FLAC__ASSERT(0 != encoder->private_);
  100391. FLAC__ASSERT(0 != encoder->protected_);
  100392. return encoder->protected_->total_samples_estimate;
  100393. }
  100394. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  100395. {
  100396. unsigned i, j = 0, channel;
  100397. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100398. FLAC__ASSERT(0 != encoder);
  100399. FLAC__ASSERT(0 != encoder->private_);
  100400. FLAC__ASSERT(0 != encoder->protected_);
  100401. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100402. do {
  100403. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  100404. if(encoder->protected_->verify)
  100405. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  100406. for(channel = 0; channel < channels; channel++)
  100407. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  100408. if(encoder->protected_->do_mid_side_stereo) {
  100409. FLAC__ASSERT(channels == 2);
  100410. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100411. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100412. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  100413. 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' ! */
  100414. }
  100415. }
  100416. else
  100417. j += n;
  100418. encoder->private_->current_sample_number += n;
  100419. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100420. if(encoder->private_->current_sample_number > blocksize) {
  100421. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  100422. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100423. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100424. return false;
  100425. /* move unprocessed overread samples to beginnings of arrays */
  100426. for(channel = 0; channel < channels; channel++)
  100427. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100428. if(encoder->protected_->do_mid_side_stereo) {
  100429. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100430. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100431. }
  100432. encoder->private_->current_sample_number = 1;
  100433. }
  100434. } while(j < samples);
  100435. return true;
  100436. }
  100437. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  100438. {
  100439. unsigned i, j, k, channel;
  100440. FLAC__int32 x, mid, side;
  100441. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100442. FLAC__ASSERT(0 != encoder);
  100443. FLAC__ASSERT(0 != encoder->private_);
  100444. FLAC__ASSERT(0 != encoder->protected_);
  100445. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100446. j = k = 0;
  100447. /*
  100448. * we have several flavors of the same basic loop, optimized for
  100449. * different conditions:
  100450. */
  100451. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  100452. /*
  100453. * stereo coding: unroll channel loop
  100454. */
  100455. do {
  100456. if(encoder->protected_->verify)
  100457. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100458. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100459. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100460. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  100461. x = buffer[k++];
  100462. encoder->private_->integer_signal[1][i] = x;
  100463. mid += x;
  100464. side -= x;
  100465. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  100466. encoder->private_->integer_signal_mid_side[1][i] = side;
  100467. encoder->private_->integer_signal_mid_side[0][i] = mid;
  100468. }
  100469. encoder->private_->current_sample_number = i;
  100470. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100471. if(i > blocksize) {
  100472. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100473. return false;
  100474. /* move unprocessed overread samples to beginnings of arrays */
  100475. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100476. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100477. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  100478. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  100479. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100480. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100481. encoder->private_->current_sample_number = 1;
  100482. }
  100483. } while(j < samples);
  100484. }
  100485. else {
  100486. /*
  100487. * independent channel coding: buffer each channel in inner loop
  100488. */
  100489. do {
  100490. if(encoder->protected_->verify)
  100491. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100492. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100493. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100494. for(channel = 0; channel < channels; channel++)
  100495. encoder->private_->integer_signal[channel][i] = buffer[k++];
  100496. }
  100497. encoder->private_->current_sample_number = i;
  100498. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100499. if(i > blocksize) {
  100500. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100501. return false;
  100502. /* move unprocessed overread samples to beginnings of arrays */
  100503. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100504. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100505. for(channel = 0; channel < channels; channel++)
  100506. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100507. encoder->private_->current_sample_number = 1;
  100508. }
  100509. } while(j < samples);
  100510. }
  100511. return true;
  100512. }
  100513. /***********************************************************************
  100514. *
  100515. * Private class methods
  100516. *
  100517. ***********************************************************************/
  100518. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  100519. {
  100520. FLAC__ASSERT(0 != encoder);
  100521. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  100522. encoder->protected_->verify = true;
  100523. #else
  100524. encoder->protected_->verify = false;
  100525. #endif
  100526. encoder->protected_->streamable_subset = true;
  100527. encoder->protected_->do_md5 = true;
  100528. encoder->protected_->do_mid_side_stereo = false;
  100529. encoder->protected_->loose_mid_side_stereo = false;
  100530. encoder->protected_->channels = 2;
  100531. encoder->protected_->bits_per_sample = 16;
  100532. encoder->protected_->sample_rate = 44100;
  100533. encoder->protected_->blocksize = 0;
  100534. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100535. encoder->protected_->num_apodizations = 1;
  100536. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100537. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100538. #endif
  100539. encoder->protected_->max_lpc_order = 0;
  100540. encoder->protected_->qlp_coeff_precision = 0;
  100541. encoder->protected_->do_qlp_coeff_prec_search = false;
  100542. encoder->protected_->do_exhaustive_model_search = false;
  100543. encoder->protected_->do_escape_coding = false;
  100544. encoder->protected_->min_residual_partition_order = 0;
  100545. encoder->protected_->max_residual_partition_order = 0;
  100546. encoder->protected_->rice_parameter_search_dist = 0;
  100547. encoder->protected_->total_samples_estimate = 0;
  100548. encoder->protected_->metadata = 0;
  100549. encoder->protected_->num_metadata_blocks = 0;
  100550. encoder->private_->seek_table = 0;
  100551. encoder->private_->disable_constant_subframes = false;
  100552. encoder->private_->disable_fixed_subframes = false;
  100553. encoder->private_->disable_verbatim_subframes = false;
  100554. #if FLAC__HAS_OGG
  100555. encoder->private_->is_ogg = false;
  100556. #endif
  100557. encoder->private_->read_callback = 0;
  100558. encoder->private_->write_callback = 0;
  100559. encoder->private_->seek_callback = 0;
  100560. encoder->private_->tell_callback = 0;
  100561. encoder->private_->metadata_callback = 0;
  100562. encoder->private_->progress_callback = 0;
  100563. encoder->private_->client_data = 0;
  100564. #if FLAC__HAS_OGG
  100565. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  100566. #endif
  100567. }
  100568. void free_(FLAC__StreamEncoder *encoder)
  100569. {
  100570. unsigned i, channel;
  100571. FLAC__ASSERT(0 != encoder);
  100572. if(encoder->protected_->metadata) {
  100573. free(encoder->protected_->metadata);
  100574. encoder->protected_->metadata = 0;
  100575. encoder->protected_->num_metadata_blocks = 0;
  100576. }
  100577. for(i = 0; i < encoder->protected_->channels; i++) {
  100578. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  100579. free(encoder->private_->integer_signal_unaligned[i]);
  100580. encoder->private_->integer_signal_unaligned[i] = 0;
  100581. }
  100582. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100583. if(0 != encoder->private_->real_signal_unaligned[i]) {
  100584. free(encoder->private_->real_signal_unaligned[i]);
  100585. encoder->private_->real_signal_unaligned[i] = 0;
  100586. }
  100587. #endif
  100588. }
  100589. for(i = 0; i < 2; i++) {
  100590. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  100591. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  100592. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  100593. }
  100594. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100595. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  100596. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  100597. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  100598. }
  100599. #endif
  100600. }
  100601. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100602. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  100603. if(0 != encoder->private_->window_unaligned[i]) {
  100604. free(encoder->private_->window_unaligned[i]);
  100605. encoder->private_->window_unaligned[i] = 0;
  100606. }
  100607. }
  100608. if(0 != encoder->private_->windowed_signal_unaligned) {
  100609. free(encoder->private_->windowed_signal_unaligned);
  100610. encoder->private_->windowed_signal_unaligned = 0;
  100611. }
  100612. #endif
  100613. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100614. for(i = 0; i < 2; i++) {
  100615. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  100616. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  100617. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  100618. }
  100619. }
  100620. }
  100621. for(channel = 0; channel < 2; channel++) {
  100622. for(i = 0; i < 2; i++) {
  100623. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  100624. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  100625. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  100626. }
  100627. }
  100628. }
  100629. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  100630. free(encoder->private_->abs_residual_partition_sums_unaligned);
  100631. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  100632. }
  100633. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  100634. free(encoder->private_->raw_bits_per_partition_unaligned);
  100635. encoder->private_->raw_bits_per_partition_unaligned = 0;
  100636. }
  100637. if(encoder->protected_->verify) {
  100638. for(i = 0; i < encoder->protected_->channels; i++) {
  100639. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  100640. free(encoder->private_->verify.input_fifo.data[i]);
  100641. encoder->private_->verify.input_fifo.data[i] = 0;
  100642. }
  100643. }
  100644. }
  100645. FLAC__bitwriter_free(encoder->private_->frame);
  100646. }
  100647. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  100648. {
  100649. FLAC__bool ok;
  100650. unsigned i, channel;
  100651. FLAC__ASSERT(new_blocksize > 0);
  100652. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100653. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  100654. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  100655. if(new_blocksize <= encoder->private_->input_capacity)
  100656. return true;
  100657. ok = true;
  100658. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  100659. * requires that the input arrays (in our case the integer signals)
  100660. * have a buffer of up to 3 zeroes in front (at negative indices) for
  100661. * alignment purposes; we use 4 in front to keep the data well-aligned.
  100662. */
  100663. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  100664. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  100665. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  100666. encoder->private_->integer_signal[i] += 4;
  100667. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100668. #if 0 /* @@@ currently unused */
  100669. if(encoder->protected_->max_lpc_order > 0)
  100670. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  100671. #endif
  100672. #endif
  100673. }
  100674. for(i = 0; ok && i < 2; i++) {
  100675. 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]);
  100676. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  100677. encoder->private_->integer_signal_mid_side[i] += 4;
  100678. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100679. #if 0 /* @@@ currently unused */
  100680. if(encoder->protected_->max_lpc_order > 0)
  100681. 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]);
  100682. #endif
  100683. #endif
  100684. }
  100685. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100686. if(ok && encoder->protected_->max_lpc_order > 0) {
  100687. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  100688. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  100689. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  100690. }
  100691. #endif
  100692. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  100693. for(i = 0; ok && i < 2; i++) {
  100694. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  100695. }
  100696. }
  100697. for(channel = 0; ok && channel < 2; channel++) {
  100698. for(i = 0; ok && i < 2; i++) {
  100699. 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]);
  100700. }
  100701. }
  100702. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  100703. /*@@@ 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) */
  100704. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  100705. if(encoder->protected_->do_escape_coding)
  100706. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  100707. /* now adjust the windows if the blocksize has changed */
  100708. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100709. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  100710. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  100711. switch(encoder->protected_->apodizations[i].type) {
  100712. case FLAC__APODIZATION_BARTLETT:
  100713. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  100714. break;
  100715. case FLAC__APODIZATION_BARTLETT_HANN:
  100716. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  100717. break;
  100718. case FLAC__APODIZATION_BLACKMAN:
  100719. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  100720. break;
  100721. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  100722. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  100723. break;
  100724. case FLAC__APODIZATION_CONNES:
  100725. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  100726. break;
  100727. case FLAC__APODIZATION_FLATTOP:
  100728. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  100729. break;
  100730. case FLAC__APODIZATION_GAUSS:
  100731. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  100732. break;
  100733. case FLAC__APODIZATION_HAMMING:
  100734. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  100735. break;
  100736. case FLAC__APODIZATION_HANN:
  100737. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100738. break;
  100739. case FLAC__APODIZATION_KAISER_BESSEL:
  100740. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  100741. break;
  100742. case FLAC__APODIZATION_NUTTALL:
  100743. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  100744. break;
  100745. case FLAC__APODIZATION_RECTANGLE:
  100746. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  100747. break;
  100748. case FLAC__APODIZATION_TRIANGLE:
  100749. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  100750. break;
  100751. case FLAC__APODIZATION_TUKEY:
  100752. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  100753. break;
  100754. case FLAC__APODIZATION_WELCH:
  100755. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  100756. break;
  100757. default:
  100758. FLAC__ASSERT(0);
  100759. /* double protection */
  100760. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100761. break;
  100762. }
  100763. }
  100764. }
  100765. #endif
  100766. if(ok)
  100767. encoder->private_->input_capacity = new_blocksize;
  100768. else
  100769. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100770. return ok;
  100771. }
  100772. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  100773. {
  100774. const FLAC__byte *buffer;
  100775. size_t bytes;
  100776. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100777. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  100778. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100779. return false;
  100780. }
  100781. if(encoder->protected_->verify) {
  100782. encoder->private_->verify.output.data = buffer;
  100783. encoder->private_->verify.output.bytes = bytes;
  100784. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  100785. encoder->private_->verify.needs_magic_hack = true;
  100786. }
  100787. else {
  100788. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  100789. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100790. FLAC__bitwriter_clear(encoder->private_->frame);
  100791. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  100792. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100793. return false;
  100794. }
  100795. }
  100796. }
  100797. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100798. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100799. FLAC__bitwriter_clear(encoder->private_->frame);
  100800. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100801. return false;
  100802. }
  100803. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100804. FLAC__bitwriter_clear(encoder->private_->frame);
  100805. if(samples > 0) {
  100806. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  100807. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  100808. }
  100809. return true;
  100810. }
  100811. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  100812. {
  100813. FLAC__StreamEncoderWriteStatus status;
  100814. FLAC__uint64 output_position = 0;
  100815. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  100816. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  100817. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100818. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100819. }
  100820. /*
  100821. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  100822. */
  100823. if(samples == 0) {
  100824. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  100825. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  100826. encoder->protected_->streaminfo_offset = output_position;
  100827. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  100828. encoder->protected_->seektable_offset = output_position;
  100829. }
  100830. /*
  100831. * Mark the current seek point if hit (if audio_offset == 0 that
  100832. * means we're still writing metadata and haven't hit the first
  100833. * frame yet)
  100834. */
  100835. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  100836. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100837. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  100838. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  100839. FLAC__uint64 test_sample;
  100840. unsigned i;
  100841. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  100842. test_sample = encoder->private_->seek_table->points[i].sample_number;
  100843. if(test_sample > frame_last_sample) {
  100844. break;
  100845. }
  100846. else if(test_sample >= frame_first_sample) {
  100847. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  100848. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  100849. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  100850. encoder->private_->first_seekpoint_to_check++;
  100851. /* DO NOT: "break;" and here's why:
  100852. * The seektable template may contain more than one target
  100853. * sample for any given frame; we will keep looping, generating
  100854. * duplicate seekpoints for them, and we'll clean it up later,
  100855. * just before writing the seektable back to the metadata.
  100856. */
  100857. }
  100858. else {
  100859. encoder->private_->first_seekpoint_to_check++;
  100860. }
  100861. }
  100862. }
  100863. #if FLAC__HAS_OGG
  100864. if(encoder->private_->is_ogg) {
  100865. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  100866. &encoder->protected_->ogg_encoder_aspect,
  100867. buffer,
  100868. bytes,
  100869. samples,
  100870. encoder->private_->current_frame_number,
  100871. is_last_block,
  100872. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  100873. encoder,
  100874. encoder->private_->client_data
  100875. );
  100876. }
  100877. else
  100878. #endif
  100879. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  100880. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100881. encoder->private_->bytes_written += bytes;
  100882. encoder->private_->samples_written += samples;
  100883. /* we keep a high watermark on the number of frames written because
  100884. * when the encoder goes back to write metadata, 'current_frame'
  100885. * will drop back to 0.
  100886. */
  100887. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  100888. }
  100889. else
  100890. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100891. return status;
  100892. }
  100893. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100894. void update_metadata_(const FLAC__StreamEncoder *encoder)
  100895. {
  100896. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100897. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100898. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100899. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100900. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100901. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  100902. FLAC__StreamEncoderSeekStatus seek_status;
  100903. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100904. /* All this is based on intimate knowledge of the stream header
  100905. * layout, but a change to the header format that would break this
  100906. * would also break all streams encoded in the previous format.
  100907. */
  100908. /*
  100909. * Write MD5 signature
  100910. */
  100911. {
  100912. const unsigned md5_offset =
  100913. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100914. (
  100915. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100916. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100917. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100918. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100919. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100920. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100921. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100922. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100923. ) / 8;
  100924. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100925. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100926. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100927. return;
  100928. }
  100929. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100930. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100931. return;
  100932. }
  100933. }
  100934. /*
  100935. * Write total samples
  100936. */
  100937. {
  100938. const unsigned total_samples_byte_offset =
  100939. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100940. (
  100941. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100942. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100943. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100944. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100945. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100946. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100947. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100948. - 4
  100949. ) / 8;
  100950. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  100951. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100952. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100953. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100954. b[4] = (FLAC__byte)(samples & 0xFF);
  100955. 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) {
  100956. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100957. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100958. return;
  100959. }
  100960. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100961. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100962. return;
  100963. }
  100964. }
  100965. /*
  100966. * Write min/max framesize
  100967. */
  100968. {
  100969. const unsigned min_framesize_offset =
  100970. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100971. (
  100972. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100973. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100974. ) / 8;
  100975. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100976. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100977. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100978. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100979. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100980. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100981. 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) {
  100982. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100983. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100984. return;
  100985. }
  100986. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100987. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100988. return;
  100989. }
  100990. }
  100991. /*
  100992. * Write seektable
  100993. */
  100994. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100995. unsigned i;
  100996. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100997. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100998. 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) {
  100999. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101000. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101001. return;
  101002. }
  101003. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  101004. FLAC__uint64 xx;
  101005. unsigned x;
  101006. xx = encoder->private_->seek_table->points[i].sample_number;
  101007. b[7] = (FLAC__byte)xx; xx >>= 8;
  101008. b[6] = (FLAC__byte)xx; xx >>= 8;
  101009. b[5] = (FLAC__byte)xx; xx >>= 8;
  101010. b[4] = (FLAC__byte)xx; xx >>= 8;
  101011. b[3] = (FLAC__byte)xx; xx >>= 8;
  101012. b[2] = (FLAC__byte)xx; xx >>= 8;
  101013. b[1] = (FLAC__byte)xx; xx >>= 8;
  101014. b[0] = (FLAC__byte)xx; xx >>= 8;
  101015. xx = encoder->private_->seek_table->points[i].stream_offset;
  101016. b[15] = (FLAC__byte)xx; xx >>= 8;
  101017. b[14] = (FLAC__byte)xx; xx >>= 8;
  101018. b[13] = (FLAC__byte)xx; xx >>= 8;
  101019. b[12] = (FLAC__byte)xx; xx >>= 8;
  101020. b[11] = (FLAC__byte)xx; xx >>= 8;
  101021. b[10] = (FLAC__byte)xx; xx >>= 8;
  101022. b[9] = (FLAC__byte)xx; xx >>= 8;
  101023. b[8] = (FLAC__byte)xx; xx >>= 8;
  101024. x = encoder->private_->seek_table->points[i].frame_samples;
  101025. b[17] = (FLAC__byte)x; x >>= 8;
  101026. b[16] = (FLAC__byte)x; x >>= 8;
  101027. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101028. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101029. return;
  101030. }
  101031. }
  101032. }
  101033. }
  101034. #if FLAC__HAS_OGG
  101035. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101036. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  101037. {
  101038. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  101039. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  101040. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  101041. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  101042. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  101043. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  101044. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  101045. FLAC__STREAM_SYNC_LENGTH
  101046. ;
  101047. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101048. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101049. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101050. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101051. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101052. ogg_page page;
  101053. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101054. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  101055. /* Pre-check that client supports seeking, since we don't want the
  101056. * ogg_helper code to ever have to deal with this condition.
  101057. */
  101058. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  101059. return;
  101060. /* All this is based on intimate knowledge of the stream header
  101061. * layout, but a change to the header format that would break this
  101062. * would also break all streams encoded in the previous format.
  101063. */
  101064. /**
  101065. ** Write STREAMINFO stats
  101066. **/
  101067. simple_ogg_page__init(&page);
  101068. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101069. simple_ogg_page__clear(&page);
  101070. return; /* state already set */
  101071. }
  101072. /*
  101073. * Write MD5 signature
  101074. */
  101075. {
  101076. const unsigned md5_offset =
  101077. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101078. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101079. (
  101080. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101081. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101082. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101083. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101084. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101085. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101086. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101087. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101088. ) / 8;
  101089. if(md5_offset + 16 > (unsigned)page.body_len) {
  101090. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101091. simple_ogg_page__clear(&page);
  101092. return;
  101093. }
  101094. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  101095. }
  101096. /*
  101097. * Write total samples
  101098. */
  101099. {
  101100. const unsigned total_samples_byte_offset =
  101101. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101102. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101103. (
  101104. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101105. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101106. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101107. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101108. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101109. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101110. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101111. - 4
  101112. ) / 8;
  101113. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  101114. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101115. simple_ogg_page__clear(&page);
  101116. return;
  101117. }
  101118. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  101119. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  101120. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101121. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101122. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101123. b[4] = (FLAC__byte)(samples & 0xFF);
  101124. memcpy(page.body + total_samples_byte_offset, b, 5);
  101125. }
  101126. /*
  101127. * Write min/max framesize
  101128. */
  101129. {
  101130. const unsigned min_framesize_offset =
  101131. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101132. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101133. (
  101134. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101135. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101136. ) / 8;
  101137. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  101138. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101139. simple_ogg_page__clear(&page);
  101140. return;
  101141. }
  101142. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101143. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101144. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101145. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101146. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101147. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101148. memcpy(page.body + min_framesize_offset, b, 6);
  101149. }
  101150. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101151. simple_ogg_page__clear(&page);
  101152. return; /* state already set */
  101153. }
  101154. simple_ogg_page__clear(&page);
  101155. /*
  101156. * Write seektable
  101157. */
  101158. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101159. unsigned i;
  101160. FLAC__byte *p;
  101161. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101162. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101163. simple_ogg_page__init(&page);
  101164. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101165. simple_ogg_page__clear(&page);
  101166. return; /* state already set */
  101167. }
  101168. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  101169. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101170. simple_ogg_page__clear(&page);
  101171. return;
  101172. }
  101173. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  101174. FLAC__uint64 xx;
  101175. unsigned x;
  101176. xx = encoder->private_->seek_table->points[i].sample_number;
  101177. b[7] = (FLAC__byte)xx; xx >>= 8;
  101178. b[6] = (FLAC__byte)xx; xx >>= 8;
  101179. b[5] = (FLAC__byte)xx; xx >>= 8;
  101180. b[4] = (FLAC__byte)xx; xx >>= 8;
  101181. b[3] = (FLAC__byte)xx; xx >>= 8;
  101182. b[2] = (FLAC__byte)xx; xx >>= 8;
  101183. b[1] = (FLAC__byte)xx; xx >>= 8;
  101184. b[0] = (FLAC__byte)xx; xx >>= 8;
  101185. xx = encoder->private_->seek_table->points[i].stream_offset;
  101186. b[15] = (FLAC__byte)xx; xx >>= 8;
  101187. b[14] = (FLAC__byte)xx; xx >>= 8;
  101188. b[13] = (FLAC__byte)xx; xx >>= 8;
  101189. b[12] = (FLAC__byte)xx; xx >>= 8;
  101190. b[11] = (FLAC__byte)xx; xx >>= 8;
  101191. b[10] = (FLAC__byte)xx; xx >>= 8;
  101192. b[9] = (FLAC__byte)xx; xx >>= 8;
  101193. b[8] = (FLAC__byte)xx; xx >>= 8;
  101194. x = encoder->private_->seek_table->points[i].frame_samples;
  101195. b[17] = (FLAC__byte)x; x >>= 8;
  101196. b[16] = (FLAC__byte)x; x >>= 8;
  101197. memcpy(p, b, 18);
  101198. }
  101199. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101200. simple_ogg_page__clear(&page);
  101201. return; /* state already set */
  101202. }
  101203. simple_ogg_page__clear(&page);
  101204. }
  101205. }
  101206. #endif
  101207. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  101208. {
  101209. FLAC__uint16 crc;
  101210. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101211. /*
  101212. * Accumulate raw signal to the MD5 signature
  101213. */
  101214. 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)) {
  101215. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101216. return false;
  101217. }
  101218. /*
  101219. * Process the frame header and subframes into the frame bitbuffer
  101220. */
  101221. if(!process_subframes_(encoder, is_fractional_block)) {
  101222. /* the above function sets the state for us in case of an error */
  101223. return false;
  101224. }
  101225. /*
  101226. * Zero-pad the frame to a byte_boundary
  101227. */
  101228. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  101229. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101230. return false;
  101231. }
  101232. /*
  101233. * CRC-16 the whole thing
  101234. */
  101235. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101236. if(
  101237. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  101238. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  101239. ) {
  101240. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101241. return false;
  101242. }
  101243. /*
  101244. * Write it
  101245. */
  101246. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  101247. /* the above function sets the state for us in case of an error */
  101248. return false;
  101249. }
  101250. /*
  101251. * Get ready for the next frame
  101252. */
  101253. encoder->private_->current_sample_number = 0;
  101254. encoder->private_->current_frame_number++;
  101255. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  101256. return true;
  101257. }
  101258. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  101259. {
  101260. FLAC__FrameHeader frame_header;
  101261. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  101262. FLAC__bool do_independent, do_mid_side;
  101263. /*
  101264. * Calculate the min,max Rice partition orders
  101265. */
  101266. if(is_fractional_block) {
  101267. max_partition_order = 0;
  101268. }
  101269. else {
  101270. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  101271. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  101272. }
  101273. min_partition_order = min(min_partition_order, max_partition_order);
  101274. /*
  101275. * Setup the frame
  101276. */
  101277. frame_header.blocksize = encoder->protected_->blocksize;
  101278. frame_header.sample_rate = encoder->protected_->sample_rate;
  101279. frame_header.channels = encoder->protected_->channels;
  101280. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  101281. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  101282. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101283. frame_header.number.frame_number = encoder->private_->current_frame_number;
  101284. /*
  101285. * Figure out what channel assignments to try
  101286. */
  101287. if(encoder->protected_->do_mid_side_stereo) {
  101288. if(encoder->protected_->loose_mid_side_stereo) {
  101289. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  101290. do_independent = true;
  101291. do_mid_side = true;
  101292. }
  101293. else {
  101294. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  101295. do_mid_side = !do_independent;
  101296. }
  101297. }
  101298. else {
  101299. do_independent = true;
  101300. do_mid_side = true;
  101301. }
  101302. }
  101303. else {
  101304. do_independent = true;
  101305. do_mid_side = false;
  101306. }
  101307. FLAC__ASSERT(do_independent || do_mid_side);
  101308. /*
  101309. * Check for wasted bits; set effective bps for each subframe
  101310. */
  101311. if(do_independent) {
  101312. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101313. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  101314. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  101315. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  101316. }
  101317. }
  101318. if(do_mid_side) {
  101319. FLAC__ASSERT(encoder->protected_->channels == 2);
  101320. for(channel = 0; channel < 2; channel++) {
  101321. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  101322. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  101323. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  101324. }
  101325. }
  101326. /*
  101327. * First do a normal encoding pass of each independent channel
  101328. */
  101329. if(do_independent) {
  101330. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101331. if(!
  101332. process_subframe_(
  101333. encoder,
  101334. min_partition_order,
  101335. max_partition_order,
  101336. &frame_header,
  101337. encoder->private_->subframe_bps[channel],
  101338. encoder->private_->integer_signal[channel],
  101339. encoder->private_->subframe_workspace_ptr[channel],
  101340. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  101341. encoder->private_->residual_workspace[channel],
  101342. encoder->private_->best_subframe+channel,
  101343. encoder->private_->best_subframe_bits+channel
  101344. )
  101345. )
  101346. return false;
  101347. }
  101348. }
  101349. /*
  101350. * Now do mid and side channels if requested
  101351. */
  101352. if(do_mid_side) {
  101353. FLAC__ASSERT(encoder->protected_->channels == 2);
  101354. for(channel = 0; channel < 2; channel++) {
  101355. if(!
  101356. process_subframe_(
  101357. encoder,
  101358. min_partition_order,
  101359. max_partition_order,
  101360. &frame_header,
  101361. encoder->private_->subframe_bps_mid_side[channel],
  101362. encoder->private_->integer_signal_mid_side[channel],
  101363. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  101364. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  101365. encoder->private_->residual_workspace_mid_side[channel],
  101366. encoder->private_->best_subframe_mid_side+channel,
  101367. encoder->private_->best_subframe_bits_mid_side+channel
  101368. )
  101369. )
  101370. return false;
  101371. }
  101372. }
  101373. /*
  101374. * Compose the frame bitbuffer
  101375. */
  101376. if(do_mid_side) {
  101377. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  101378. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  101379. FLAC__ChannelAssignment channel_assignment;
  101380. FLAC__ASSERT(encoder->protected_->channels == 2);
  101381. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  101382. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  101383. }
  101384. else {
  101385. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  101386. unsigned min_bits;
  101387. int ca;
  101388. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  101389. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  101390. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  101391. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  101392. FLAC__ASSERT(do_independent && do_mid_side);
  101393. /* We have to figure out which channel assignent results in the smallest frame */
  101394. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  101395. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  101396. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  101397. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  101398. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101399. min_bits = bits[channel_assignment];
  101400. for(ca = 1; ca <= 3; ca++) {
  101401. if(bits[ca] < min_bits) {
  101402. min_bits = bits[ca];
  101403. channel_assignment = (FLAC__ChannelAssignment)ca;
  101404. }
  101405. }
  101406. }
  101407. frame_header.channel_assignment = channel_assignment;
  101408. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101409. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101410. return false;
  101411. }
  101412. switch(channel_assignment) {
  101413. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101414. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101415. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101416. break;
  101417. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101418. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101419. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101420. break;
  101421. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101422. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101423. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101424. break;
  101425. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101426. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  101427. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101428. break;
  101429. default:
  101430. FLAC__ASSERT(0);
  101431. }
  101432. switch(channel_assignment) {
  101433. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101434. left_bps = encoder->private_->subframe_bps [0];
  101435. right_bps = encoder->private_->subframe_bps [1];
  101436. break;
  101437. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101438. left_bps = encoder->private_->subframe_bps [0];
  101439. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101440. break;
  101441. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101442. left_bps = encoder->private_->subframe_bps_mid_side[1];
  101443. right_bps = encoder->private_->subframe_bps [1];
  101444. break;
  101445. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101446. left_bps = encoder->private_->subframe_bps_mid_side[0];
  101447. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101448. break;
  101449. default:
  101450. FLAC__ASSERT(0);
  101451. }
  101452. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  101453. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  101454. return false;
  101455. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  101456. return false;
  101457. }
  101458. else {
  101459. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101460. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101461. return false;
  101462. }
  101463. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101464. 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)) {
  101465. /* the above function sets the state for us in case of an error */
  101466. return false;
  101467. }
  101468. }
  101469. }
  101470. if(encoder->protected_->loose_mid_side_stereo) {
  101471. encoder->private_->loose_mid_side_stereo_frame_count++;
  101472. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  101473. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  101474. }
  101475. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  101476. return true;
  101477. }
  101478. FLAC__bool process_subframe_(
  101479. FLAC__StreamEncoder *encoder,
  101480. unsigned min_partition_order,
  101481. unsigned max_partition_order,
  101482. const FLAC__FrameHeader *frame_header,
  101483. unsigned subframe_bps,
  101484. const FLAC__int32 integer_signal[],
  101485. FLAC__Subframe *subframe[2],
  101486. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101487. FLAC__int32 *residual[2],
  101488. unsigned *best_subframe,
  101489. unsigned *best_bits
  101490. )
  101491. {
  101492. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101493. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101494. #else
  101495. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101496. #endif
  101497. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101498. FLAC__double lpc_residual_bits_per_sample;
  101499. 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 */
  101500. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  101501. unsigned min_lpc_order, max_lpc_order, lpc_order;
  101502. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  101503. #endif
  101504. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  101505. unsigned rice_parameter;
  101506. unsigned _candidate_bits, _best_bits;
  101507. unsigned _best_subframe;
  101508. /* only use RICE2 partitions if stream bps > 16 */
  101509. 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;
  101510. FLAC__ASSERT(frame_header->blocksize > 0);
  101511. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  101512. _best_subframe = 0;
  101513. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  101514. _best_bits = UINT_MAX;
  101515. else
  101516. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  101517. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  101518. unsigned signal_is_constant = false;
  101519. 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);
  101520. /* check for constant subframe */
  101521. if(
  101522. !encoder->private_->disable_constant_subframes &&
  101523. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101524. fixed_residual_bits_per_sample[1] == 0.0
  101525. #else
  101526. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  101527. #endif
  101528. ) {
  101529. /* the above means it's possible all samples are the same value; now double-check it: */
  101530. unsigned i;
  101531. signal_is_constant = true;
  101532. for(i = 1; i < frame_header->blocksize; i++) {
  101533. if(integer_signal[0] != integer_signal[i]) {
  101534. signal_is_constant = false;
  101535. break;
  101536. }
  101537. }
  101538. }
  101539. if(signal_is_constant) {
  101540. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  101541. if(_candidate_bits < _best_bits) {
  101542. _best_subframe = !_best_subframe;
  101543. _best_bits = _candidate_bits;
  101544. }
  101545. }
  101546. else {
  101547. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  101548. /* encode fixed */
  101549. if(encoder->protected_->do_exhaustive_model_search) {
  101550. min_fixed_order = 0;
  101551. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  101552. }
  101553. else {
  101554. min_fixed_order = max_fixed_order = guess_fixed_order;
  101555. }
  101556. if(max_fixed_order >= frame_header->blocksize)
  101557. max_fixed_order = frame_header->blocksize - 1;
  101558. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  101559. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101560. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  101561. continue; /* don't even try */
  101562. 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 */
  101563. #else
  101564. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  101565. continue; /* don't even try */
  101566. 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 */
  101567. #endif
  101568. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  101569. if(rice_parameter >= rice_parameter_limit) {
  101570. #ifdef DEBUG_VERBOSE
  101571. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  101572. #endif
  101573. rice_parameter = rice_parameter_limit - 1;
  101574. }
  101575. _candidate_bits =
  101576. evaluate_fixed_subframe_(
  101577. encoder,
  101578. integer_signal,
  101579. residual[!_best_subframe],
  101580. encoder->private_->abs_residual_partition_sums,
  101581. encoder->private_->raw_bits_per_partition,
  101582. frame_header->blocksize,
  101583. subframe_bps,
  101584. fixed_order,
  101585. rice_parameter,
  101586. rice_parameter_limit,
  101587. min_partition_order,
  101588. max_partition_order,
  101589. encoder->protected_->do_escape_coding,
  101590. encoder->protected_->rice_parameter_search_dist,
  101591. subframe[!_best_subframe],
  101592. partitioned_rice_contents[!_best_subframe]
  101593. );
  101594. if(_candidate_bits < _best_bits) {
  101595. _best_subframe = !_best_subframe;
  101596. _best_bits = _candidate_bits;
  101597. }
  101598. }
  101599. }
  101600. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101601. /* encode lpc */
  101602. if(encoder->protected_->max_lpc_order > 0) {
  101603. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  101604. max_lpc_order = frame_header->blocksize-1;
  101605. else
  101606. max_lpc_order = encoder->protected_->max_lpc_order;
  101607. if(max_lpc_order > 0) {
  101608. unsigned a;
  101609. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  101610. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  101611. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  101612. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  101613. if(autoc[0] != 0.0) {
  101614. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  101615. if(encoder->protected_->do_exhaustive_model_search) {
  101616. min_lpc_order = 1;
  101617. }
  101618. else {
  101619. const unsigned guess_lpc_order =
  101620. FLAC__lpc_compute_best_order(
  101621. lpc_error,
  101622. max_lpc_order,
  101623. frame_header->blocksize,
  101624. subframe_bps + (
  101625. encoder->protected_->do_qlp_coeff_prec_search?
  101626. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  101627. encoder->protected_->qlp_coeff_precision
  101628. )
  101629. );
  101630. min_lpc_order = max_lpc_order = guess_lpc_order;
  101631. }
  101632. if(max_lpc_order >= frame_header->blocksize)
  101633. max_lpc_order = frame_header->blocksize - 1;
  101634. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  101635. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  101636. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  101637. continue; /* don't even try */
  101638. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  101639. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  101640. if(rice_parameter >= rice_parameter_limit) {
  101641. #ifdef DEBUG_VERBOSE
  101642. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  101643. #endif
  101644. rice_parameter = rice_parameter_limit - 1;
  101645. }
  101646. if(encoder->protected_->do_qlp_coeff_prec_search) {
  101647. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  101648. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  101649. if(subframe_bps <= 17) {
  101650. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  101651. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  101652. }
  101653. else
  101654. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101655. }
  101656. else {
  101657. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  101658. }
  101659. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  101660. _candidate_bits =
  101661. evaluate_lpc_subframe_(
  101662. encoder,
  101663. integer_signal,
  101664. residual[!_best_subframe],
  101665. encoder->private_->abs_residual_partition_sums,
  101666. encoder->private_->raw_bits_per_partition,
  101667. encoder->private_->lp_coeff[lpc_order-1],
  101668. frame_header->blocksize,
  101669. subframe_bps,
  101670. lpc_order,
  101671. qlp_coeff_precision,
  101672. rice_parameter,
  101673. rice_parameter_limit,
  101674. min_partition_order,
  101675. max_partition_order,
  101676. encoder->protected_->do_escape_coding,
  101677. encoder->protected_->rice_parameter_search_dist,
  101678. subframe[!_best_subframe],
  101679. partitioned_rice_contents[!_best_subframe]
  101680. );
  101681. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  101682. if(_candidate_bits < _best_bits) {
  101683. _best_subframe = !_best_subframe;
  101684. _best_bits = _candidate_bits;
  101685. }
  101686. }
  101687. }
  101688. }
  101689. }
  101690. }
  101691. }
  101692. }
  101693. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101694. }
  101695. }
  101696. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  101697. if(_best_bits == UINT_MAX) {
  101698. FLAC__ASSERT(_best_subframe == 0);
  101699. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  101700. }
  101701. *best_subframe = _best_subframe;
  101702. *best_bits = _best_bits;
  101703. return true;
  101704. }
  101705. FLAC__bool add_subframe_(
  101706. FLAC__StreamEncoder *encoder,
  101707. unsigned blocksize,
  101708. unsigned subframe_bps,
  101709. const FLAC__Subframe *subframe,
  101710. FLAC__BitWriter *frame
  101711. )
  101712. {
  101713. switch(subframe->type) {
  101714. case FLAC__SUBFRAME_TYPE_CONSTANT:
  101715. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  101716. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101717. return false;
  101718. }
  101719. break;
  101720. case FLAC__SUBFRAME_TYPE_FIXED:
  101721. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  101722. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101723. return false;
  101724. }
  101725. break;
  101726. case FLAC__SUBFRAME_TYPE_LPC:
  101727. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  101728. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101729. return false;
  101730. }
  101731. break;
  101732. case FLAC__SUBFRAME_TYPE_VERBATIM:
  101733. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  101734. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101735. return false;
  101736. }
  101737. break;
  101738. default:
  101739. FLAC__ASSERT(0);
  101740. }
  101741. return true;
  101742. }
  101743. #define SPOTCHECK_ESTIMATE 0
  101744. #if SPOTCHECK_ESTIMATE
  101745. static void spotcheck_subframe_estimate_(
  101746. FLAC__StreamEncoder *encoder,
  101747. unsigned blocksize,
  101748. unsigned subframe_bps,
  101749. const FLAC__Subframe *subframe,
  101750. unsigned estimate
  101751. )
  101752. {
  101753. FLAC__bool ret;
  101754. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  101755. if(frame == 0) {
  101756. fprintf(stderr, "EST: can't allocate frame\n");
  101757. return;
  101758. }
  101759. if(!FLAC__bitwriter_init(frame)) {
  101760. fprintf(stderr, "EST: can't init frame\n");
  101761. return;
  101762. }
  101763. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  101764. FLAC__ASSERT(ret);
  101765. {
  101766. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  101767. if(estimate != actual)
  101768. 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);
  101769. }
  101770. FLAC__bitwriter_delete(frame);
  101771. }
  101772. #endif
  101773. unsigned evaluate_constant_subframe_(
  101774. FLAC__StreamEncoder *encoder,
  101775. const FLAC__int32 signal,
  101776. unsigned blocksize,
  101777. unsigned subframe_bps,
  101778. FLAC__Subframe *subframe
  101779. )
  101780. {
  101781. unsigned estimate;
  101782. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101783. subframe->data.constant.value = signal;
  101784. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  101785. #if SPOTCHECK_ESTIMATE
  101786. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101787. #else
  101788. (void)encoder, (void)blocksize;
  101789. #endif
  101790. return estimate;
  101791. }
  101792. unsigned evaluate_fixed_subframe_(
  101793. FLAC__StreamEncoder *encoder,
  101794. const FLAC__int32 signal[],
  101795. FLAC__int32 residual[],
  101796. FLAC__uint64 abs_residual_partition_sums[],
  101797. unsigned raw_bits_per_partition[],
  101798. unsigned blocksize,
  101799. unsigned subframe_bps,
  101800. unsigned order,
  101801. unsigned rice_parameter,
  101802. unsigned rice_parameter_limit,
  101803. unsigned min_partition_order,
  101804. unsigned max_partition_order,
  101805. FLAC__bool do_escape_coding,
  101806. unsigned rice_parameter_search_dist,
  101807. FLAC__Subframe *subframe,
  101808. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101809. )
  101810. {
  101811. unsigned i, residual_bits, estimate;
  101812. const unsigned residual_samples = blocksize - order;
  101813. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  101814. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  101815. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101816. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101817. subframe->data.fixed.residual = residual;
  101818. residual_bits =
  101819. find_best_partition_order_(
  101820. encoder->private_,
  101821. residual,
  101822. abs_residual_partition_sums,
  101823. raw_bits_per_partition,
  101824. residual_samples,
  101825. order,
  101826. rice_parameter,
  101827. rice_parameter_limit,
  101828. min_partition_order,
  101829. max_partition_order,
  101830. subframe_bps,
  101831. do_escape_coding,
  101832. rice_parameter_search_dist,
  101833. &subframe->data.fixed.entropy_coding_method
  101834. );
  101835. subframe->data.fixed.order = order;
  101836. for(i = 0; i < order; i++)
  101837. subframe->data.fixed.warmup[i] = signal[i];
  101838. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  101839. #if SPOTCHECK_ESTIMATE
  101840. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101841. #endif
  101842. return estimate;
  101843. }
  101844. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101845. unsigned evaluate_lpc_subframe_(
  101846. FLAC__StreamEncoder *encoder,
  101847. const FLAC__int32 signal[],
  101848. FLAC__int32 residual[],
  101849. FLAC__uint64 abs_residual_partition_sums[],
  101850. unsigned raw_bits_per_partition[],
  101851. const FLAC__real lp_coeff[],
  101852. unsigned blocksize,
  101853. unsigned subframe_bps,
  101854. unsigned order,
  101855. unsigned qlp_coeff_precision,
  101856. unsigned rice_parameter,
  101857. unsigned rice_parameter_limit,
  101858. unsigned min_partition_order,
  101859. unsigned max_partition_order,
  101860. FLAC__bool do_escape_coding,
  101861. unsigned rice_parameter_search_dist,
  101862. FLAC__Subframe *subframe,
  101863. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101864. )
  101865. {
  101866. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  101867. unsigned i, residual_bits, estimate;
  101868. int quantization, ret;
  101869. const unsigned residual_samples = blocksize - order;
  101870. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  101871. if(subframe_bps <= 16) {
  101872. FLAC__ASSERT(order > 0);
  101873. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  101874. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  101875. }
  101876. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  101877. if(ret != 0)
  101878. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  101879. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101880. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  101881. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101882. else
  101883. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101884. else
  101885. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101886. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  101887. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101888. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101889. subframe->data.lpc.residual = residual;
  101890. residual_bits =
  101891. find_best_partition_order_(
  101892. encoder->private_,
  101893. residual,
  101894. abs_residual_partition_sums,
  101895. raw_bits_per_partition,
  101896. residual_samples,
  101897. order,
  101898. rice_parameter,
  101899. rice_parameter_limit,
  101900. min_partition_order,
  101901. max_partition_order,
  101902. subframe_bps,
  101903. do_escape_coding,
  101904. rice_parameter_search_dist,
  101905. &subframe->data.lpc.entropy_coding_method
  101906. );
  101907. subframe->data.lpc.order = order;
  101908. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  101909. subframe->data.lpc.quantization_level = quantization;
  101910. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  101911. for(i = 0; i < order; i++)
  101912. subframe->data.lpc.warmup[i] = signal[i];
  101913. 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;
  101914. #if SPOTCHECK_ESTIMATE
  101915. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101916. #endif
  101917. return estimate;
  101918. }
  101919. #endif
  101920. unsigned evaluate_verbatim_subframe_(
  101921. FLAC__StreamEncoder *encoder,
  101922. const FLAC__int32 signal[],
  101923. unsigned blocksize,
  101924. unsigned subframe_bps,
  101925. FLAC__Subframe *subframe
  101926. )
  101927. {
  101928. unsigned estimate;
  101929. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101930. subframe->data.verbatim.data = signal;
  101931. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  101932. #if SPOTCHECK_ESTIMATE
  101933. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101934. #else
  101935. (void)encoder;
  101936. #endif
  101937. return estimate;
  101938. }
  101939. unsigned find_best_partition_order_(
  101940. FLAC__StreamEncoderPrivate *private_,
  101941. const FLAC__int32 residual[],
  101942. FLAC__uint64 abs_residual_partition_sums[],
  101943. unsigned raw_bits_per_partition[],
  101944. unsigned residual_samples,
  101945. unsigned predictor_order,
  101946. unsigned rice_parameter,
  101947. unsigned rice_parameter_limit,
  101948. unsigned min_partition_order,
  101949. unsigned max_partition_order,
  101950. unsigned bps,
  101951. FLAC__bool do_escape_coding,
  101952. unsigned rice_parameter_search_dist,
  101953. FLAC__EntropyCodingMethod *best_ecm
  101954. )
  101955. {
  101956. unsigned residual_bits, best_residual_bits = 0;
  101957. unsigned best_parameters_index = 0;
  101958. unsigned best_partition_order = 0;
  101959. const unsigned blocksize = residual_samples + predictor_order;
  101960. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  101961. min_partition_order = min(min_partition_order, max_partition_order);
  101962. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  101963. if(do_escape_coding)
  101964. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  101965. {
  101966. int partition_order;
  101967. unsigned sum;
  101968. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  101969. if(!
  101970. set_partitioned_rice_(
  101971. #ifdef EXACT_RICE_BITS_CALCULATION
  101972. residual,
  101973. #endif
  101974. abs_residual_partition_sums+sum,
  101975. raw_bits_per_partition+sum,
  101976. residual_samples,
  101977. predictor_order,
  101978. rice_parameter,
  101979. rice_parameter_limit,
  101980. rice_parameter_search_dist,
  101981. (unsigned)partition_order,
  101982. do_escape_coding,
  101983. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  101984. &residual_bits
  101985. )
  101986. )
  101987. {
  101988. FLAC__ASSERT(best_residual_bits != 0);
  101989. break;
  101990. }
  101991. sum += 1u << partition_order;
  101992. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  101993. best_residual_bits = residual_bits;
  101994. best_parameters_index = !best_parameters_index;
  101995. best_partition_order = partition_order;
  101996. }
  101997. }
  101998. }
  101999. best_ecm->data.partitioned_rice.order = best_partition_order;
  102000. {
  102001. /*
  102002. * We are allowed to de-const the pointer based on our special
  102003. * knowledge; it is const to the outside world.
  102004. */
  102005. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  102006. unsigned partition;
  102007. /* save best parameters and raw_bits */
  102008. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  102009. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  102010. if(do_escape_coding)
  102011. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  102012. /*
  102013. * Now need to check if the type should be changed to
  102014. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  102015. * size of the rice parameters.
  102016. */
  102017. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  102018. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  102019. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  102020. break;
  102021. }
  102022. }
  102023. }
  102024. return best_residual_bits;
  102025. }
  102026. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102027. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  102028. const FLAC__int32 residual[],
  102029. FLAC__uint64 abs_residual_partition_sums[],
  102030. unsigned blocksize,
  102031. unsigned predictor_order,
  102032. unsigned min_partition_order,
  102033. unsigned max_partition_order
  102034. );
  102035. #endif
  102036. void precompute_partition_info_sums_(
  102037. const FLAC__int32 residual[],
  102038. FLAC__uint64 abs_residual_partition_sums[],
  102039. unsigned residual_samples,
  102040. unsigned predictor_order,
  102041. unsigned min_partition_order,
  102042. unsigned max_partition_order,
  102043. unsigned bps
  102044. )
  102045. {
  102046. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  102047. unsigned partitions = 1u << max_partition_order;
  102048. FLAC__ASSERT(default_partition_samples > predictor_order);
  102049. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102050. /* slightly pessimistic but still catches all common cases */
  102051. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102052. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102053. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  102054. return;
  102055. }
  102056. #endif
  102057. /* first do max_partition_order */
  102058. {
  102059. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  102060. /* slightly pessimistic but still catches all common cases */
  102061. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102062. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102063. FLAC__uint32 abs_residual_partition_sum;
  102064. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102065. end += default_partition_samples;
  102066. abs_residual_partition_sum = 0;
  102067. for( ; residual_sample < end; residual_sample++)
  102068. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102069. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102070. }
  102071. }
  102072. else { /* have to pessimistically use 64 bits for accumulator */
  102073. FLAC__uint64 abs_residual_partition_sum;
  102074. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102075. end += default_partition_samples;
  102076. abs_residual_partition_sum = 0;
  102077. for( ; residual_sample < end; residual_sample++)
  102078. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102079. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102080. }
  102081. }
  102082. }
  102083. /* now merge partitions for lower orders */
  102084. {
  102085. unsigned from_partition = 0, to_partition = partitions;
  102086. int partition_order;
  102087. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  102088. unsigned i;
  102089. partitions >>= 1;
  102090. for(i = 0; i < partitions; i++) {
  102091. abs_residual_partition_sums[to_partition++] =
  102092. abs_residual_partition_sums[from_partition ] +
  102093. abs_residual_partition_sums[from_partition+1];
  102094. from_partition += 2;
  102095. }
  102096. }
  102097. }
  102098. }
  102099. void precompute_partition_info_escapes_(
  102100. const FLAC__int32 residual[],
  102101. unsigned raw_bits_per_partition[],
  102102. unsigned residual_samples,
  102103. unsigned predictor_order,
  102104. unsigned min_partition_order,
  102105. unsigned max_partition_order
  102106. )
  102107. {
  102108. int partition_order;
  102109. unsigned from_partition, to_partition = 0;
  102110. const unsigned blocksize = residual_samples + predictor_order;
  102111. /* first do max_partition_order */
  102112. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  102113. FLAC__int32 r;
  102114. FLAC__uint32 rmax;
  102115. unsigned partition, partition_sample, partition_samples, residual_sample;
  102116. const unsigned partitions = 1u << partition_order;
  102117. const unsigned default_partition_samples = blocksize >> partition_order;
  102118. FLAC__ASSERT(default_partition_samples > predictor_order);
  102119. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102120. partition_samples = default_partition_samples;
  102121. if(partition == 0)
  102122. partition_samples -= predictor_order;
  102123. rmax = 0;
  102124. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  102125. r = residual[residual_sample++];
  102126. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  102127. if(r < 0)
  102128. rmax |= ~r;
  102129. else
  102130. rmax |= r;
  102131. }
  102132. /* now we know all residual values are in the range [-rmax-1,rmax] */
  102133. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  102134. }
  102135. to_partition = partitions;
  102136. break; /*@@@ yuck, should remove the 'for' loop instead */
  102137. }
  102138. /* now merge partitions for lower orders */
  102139. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  102140. unsigned m;
  102141. unsigned i;
  102142. const unsigned partitions = 1u << partition_order;
  102143. for(i = 0; i < partitions; i++) {
  102144. m = raw_bits_per_partition[from_partition];
  102145. from_partition++;
  102146. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  102147. from_partition++;
  102148. to_partition++;
  102149. }
  102150. }
  102151. }
  102152. #ifdef EXACT_RICE_BITS_CALCULATION
  102153. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102154. const unsigned rice_parameter,
  102155. const unsigned partition_samples,
  102156. const FLAC__int32 *residual
  102157. )
  102158. {
  102159. unsigned i, partition_bits =
  102160. 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 */
  102161. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  102162. ;
  102163. for(i = 0; i < partition_samples; i++)
  102164. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  102165. return partition_bits;
  102166. }
  102167. #else
  102168. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102169. const unsigned rice_parameter,
  102170. const unsigned partition_samples,
  102171. const FLAC__uint64 abs_residual_partition_sum
  102172. )
  102173. {
  102174. return
  102175. 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 */
  102176. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  102177. (
  102178. rice_parameter?
  102179. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  102180. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  102181. )
  102182. - (partition_samples >> 1)
  102183. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  102184. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  102185. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  102186. * So the subtraction term tries to guess how many extra bits were contributed.
  102187. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  102188. */
  102189. ;
  102190. }
  102191. #endif
  102192. FLAC__bool set_partitioned_rice_(
  102193. #ifdef EXACT_RICE_BITS_CALCULATION
  102194. const FLAC__int32 residual[],
  102195. #endif
  102196. const FLAC__uint64 abs_residual_partition_sums[],
  102197. const unsigned raw_bits_per_partition[],
  102198. const unsigned residual_samples,
  102199. const unsigned predictor_order,
  102200. const unsigned suggested_rice_parameter,
  102201. const unsigned rice_parameter_limit,
  102202. const unsigned rice_parameter_search_dist,
  102203. const unsigned partition_order,
  102204. const FLAC__bool search_for_escapes,
  102205. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102206. unsigned *bits
  102207. )
  102208. {
  102209. unsigned rice_parameter, partition_bits;
  102210. unsigned best_partition_bits, best_rice_parameter = 0;
  102211. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  102212. unsigned *parameters, *raw_bits;
  102213. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102214. unsigned min_rice_parameter, max_rice_parameter;
  102215. #else
  102216. (void)rice_parameter_search_dist;
  102217. #endif
  102218. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102219. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102220. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  102221. parameters = partitioned_rice_contents->parameters;
  102222. raw_bits = partitioned_rice_contents->raw_bits;
  102223. if(partition_order == 0) {
  102224. best_partition_bits = (unsigned)(-1);
  102225. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102226. if(rice_parameter_search_dist) {
  102227. if(suggested_rice_parameter < rice_parameter_search_dist)
  102228. min_rice_parameter = 0;
  102229. else
  102230. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  102231. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  102232. if(max_rice_parameter >= rice_parameter_limit) {
  102233. #ifdef DEBUG_VERBOSE
  102234. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  102235. #endif
  102236. max_rice_parameter = rice_parameter_limit - 1;
  102237. }
  102238. }
  102239. else
  102240. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  102241. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102242. #else
  102243. rice_parameter = suggested_rice_parameter;
  102244. #endif
  102245. #ifdef EXACT_RICE_BITS_CALCULATION
  102246. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  102247. #else
  102248. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  102249. #endif
  102250. if(partition_bits < best_partition_bits) {
  102251. best_rice_parameter = rice_parameter;
  102252. best_partition_bits = partition_bits;
  102253. }
  102254. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102255. }
  102256. #endif
  102257. if(search_for_escapes) {
  102258. 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;
  102259. if(partition_bits <= best_partition_bits) {
  102260. raw_bits[0] = raw_bits_per_partition[0];
  102261. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102262. best_partition_bits = partition_bits;
  102263. }
  102264. else
  102265. raw_bits[0] = 0;
  102266. }
  102267. parameters[0] = best_rice_parameter;
  102268. bits_ += best_partition_bits;
  102269. }
  102270. else {
  102271. unsigned partition, residual_sample;
  102272. unsigned partition_samples;
  102273. FLAC__uint64 mean, k;
  102274. const unsigned partitions = 1u << partition_order;
  102275. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102276. partition_samples = (residual_samples+predictor_order) >> partition_order;
  102277. if(partition == 0) {
  102278. if(partition_samples <= predictor_order)
  102279. return false;
  102280. else
  102281. partition_samples -= predictor_order;
  102282. }
  102283. mean = abs_residual_partition_sums[partition];
  102284. /* we are basically calculating the size in bits of the
  102285. * average residual magnitude in the partition:
  102286. * rice_parameter = floor(log2(mean/partition_samples))
  102287. * 'mean' is not a good name for the variable, it is
  102288. * actually the sum of magnitudes of all residual values
  102289. * in the partition, so the actual mean is
  102290. * mean/partition_samples
  102291. */
  102292. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  102293. ;
  102294. if(rice_parameter >= rice_parameter_limit) {
  102295. #ifdef DEBUG_VERBOSE
  102296. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  102297. #endif
  102298. rice_parameter = rice_parameter_limit - 1;
  102299. }
  102300. best_partition_bits = (unsigned)(-1);
  102301. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102302. if(rice_parameter_search_dist) {
  102303. if(rice_parameter < rice_parameter_search_dist)
  102304. min_rice_parameter = 0;
  102305. else
  102306. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  102307. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  102308. if(max_rice_parameter >= rice_parameter_limit) {
  102309. #ifdef DEBUG_VERBOSE
  102310. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  102311. #endif
  102312. max_rice_parameter = rice_parameter_limit - 1;
  102313. }
  102314. }
  102315. else
  102316. min_rice_parameter = max_rice_parameter = rice_parameter;
  102317. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102318. #endif
  102319. #ifdef EXACT_RICE_BITS_CALCULATION
  102320. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  102321. #else
  102322. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  102323. #endif
  102324. if(partition_bits < best_partition_bits) {
  102325. best_rice_parameter = rice_parameter;
  102326. best_partition_bits = partition_bits;
  102327. }
  102328. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102329. }
  102330. #endif
  102331. if(search_for_escapes) {
  102332. 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;
  102333. if(partition_bits <= best_partition_bits) {
  102334. raw_bits[partition] = raw_bits_per_partition[partition];
  102335. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102336. best_partition_bits = partition_bits;
  102337. }
  102338. else
  102339. raw_bits[partition] = 0;
  102340. }
  102341. parameters[partition] = best_rice_parameter;
  102342. bits_ += best_partition_bits;
  102343. residual_sample += partition_samples;
  102344. }
  102345. }
  102346. *bits = bits_;
  102347. return true;
  102348. }
  102349. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  102350. {
  102351. unsigned i, shift;
  102352. FLAC__int32 x = 0;
  102353. for(i = 0; i < samples && !(x&1); i++)
  102354. x |= signal[i];
  102355. if(x == 0) {
  102356. shift = 0;
  102357. }
  102358. else {
  102359. for(shift = 0; !(x&1); shift++)
  102360. x >>= 1;
  102361. }
  102362. if(shift > 0) {
  102363. for(i = 0; i < samples; i++)
  102364. signal[i] >>= shift;
  102365. }
  102366. return shift;
  102367. }
  102368. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102369. {
  102370. unsigned channel;
  102371. for(channel = 0; channel < channels; channel++)
  102372. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  102373. fifo->tail += wide_samples;
  102374. FLAC__ASSERT(fifo->tail <= fifo->size);
  102375. }
  102376. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102377. {
  102378. unsigned channel;
  102379. unsigned sample, wide_sample;
  102380. unsigned tail = fifo->tail;
  102381. sample = input_offset * channels;
  102382. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  102383. for(channel = 0; channel < channels; channel++)
  102384. fifo->data[channel][tail] = input[sample++];
  102385. tail++;
  102386. }
  102387. fifo->tail = tail;
  102388. FLAC__ASSERT(fifo->tail <= fifo->size);
  102389. }
  102390. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102391. {
  102392. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102393. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  102394. (void)decoder;
  102395. if(encoder->private_->verify.needs_magic_hack) {
  102396. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  102397. *bytes = FLAC__STREAM_SYNC_LENGTH;
  102398. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  102399. encoder->private_->verify.needs_magic_hack = false;
  102400. }
  102401. else {
  102402. if(encoded_bytes == 0) {
  102403. /*
  102404. * If we get here, a FIFO underflow has occurred,
  102405. * which means there is a bug somewhere.
  102406. */
  102407. FLAC__ASSERT(0);
  102408. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102409. }
  102410. else if(encoded_bytes < *bytes)
  102411. *bytes = encoded_bytes;
  102412. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  102413. encoder->private_->verify.output.data += *bytes;
  102414. encoder->private_->verify.output.bytes -= *bytes;
  102415. }
  102416. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102417. }
  102418. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  102419. {
  102420. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  102421. unsigned channel;
  102422. const unsigned channels = frame->header.channels;
  102423. const unsigned blocksize = frame->header.blocksize;
  102424. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  102425. (void)decoder;
  102426. for(channel = 0; channel < channels; channel++) {
  102427. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  102428. unsigned i, sample = 0;
  102429. FLAC__int32 expect = 0, got = 0;
  102430. for(i = 0; i < blocksize; i++) {
  102431. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  102432. sample = i;
  102433. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  102434. got = (FLAC__int32)buffer[channel][i];
  102435. break;
  102436. }
  102437. }
  102438. FLAC__ASSERT(i < blocksize);
  102439. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102440. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  102441. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  102442. encoder->private_->verify.error_stats.channel = channel;
  102443. encoder->private_->verify.error_stats.sample = sample;
  102444. encoder->private_->verify.error_stats.expected = expect;
  102445. encoder->private_->verify.error_stats.got = got;
  102446. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102447. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  102448. }
  102449. }
  102450. /* dequeue the frame from the fifo */
  102451. encoder->private_->verify.input_fifo.tail -= blocksize;
  102452. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  102453. for(channel = 0; channel < channels; channel++)
  102454. 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]));
  102455. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102456. }
  102457. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  102458. {
  102459. (void)decoder, (void)metadata, (void)client_data;
  102460. }
  102461. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  102462. {
  102463. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102464. (void)decoder, (void)status;
  102465. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102466. }
  102467. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102468. {
  102469. (void)client_data;
  102470. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  102471. if (*bytes == 0) {
  102472. if (feof(encoder->private_->file))
  102473. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  102474. else if (ferror(encoder->private_->file))
  102475. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  102476. }
  102477. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  102478. }
  102479. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102480. {
  102481. (void)client_data;
  102482. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102483. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  102484. else
  102485. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  102486. }
  102487. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102488. {
  102489. off_t offset;
  102490. (void)client_data;
  102491. offset = ftello(encoder->private_->file);
  102492. if(offset < 0) {
  102493. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  102494. }
  102495. else {
  102496. *absolute_byte_offset = (FLAC__uint64)offset;
  102497. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  102498. }
  102499. }
  102500. #ifdef FLAC__VALGRIND_TESTING
  102501. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  102502. {
  102503. size_t ret = fwrite(ptr, size, nmemb, stream);
  102504. if(!ferror(stream))
  102505. fflush(stream);
  102506. return ret;
  102507. }
  102508. #else
  102509. #define local__fwrite fwrite
  102510. #endif
  102511. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  102512. {
  102513. (void)client_data, (void)current_frame;
  102514. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  102515. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  102516. #if FLAC__HAS_OGG
  102517. /* We would like to be able to use 'samples > 0' in the
  102518. * clause here but currently because of the nature of our
  102519. * Ogg writing implementation, 'samples' is always 0 (see
  102520. * ogg_encoder_aspect.c). The downside is extra progress
  102521. * callbacks.
  102522. */
  102523. encoder->private_->is_ogg? true :
  102524. #endif
  102525. samples > 0
  102526. );
  102527. if(call_it) {
  102528. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  102529. * because at this point in the callback chain, the stats
  102530. * have not been updated. Only after we return and control
  102531. * gets back to write_frame_() are the stats updated
  102532. */
  102533. 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);
  102534. }
  102535. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  102536. }
  102537. else
  102538. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102539. }
  102540. /*
  102541. * This will forcibly set stdout to binary mode (for OSes that require it)
  102542. */
  102543. FILE *get_binary_stdout_(void)
  102544. {
  102545. /* if something breaks here it is probably due to the presence or
  102546. * absence of an underscore before the identifiers 'setmode',
  102547. * 'fileno', and/or 'O_BINARY'; check your system header files.
  102548. */
  102549. #if defined _MSC_VER || defined __MINGW32__
  102550. _setmode(_fileno(stdout), _O_BINARY);
  102551. #elif defined __CYGWIN__
  102552. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  102553. setmode(_fileno(stdout), _O_BINARY);
  102554. #elif defined __EMX__
  102555. setmode(fileno(stdout), O_BINARY);
  102556. #endif
  102557. return stdout;
  102558. }
  102559. #endif
  102560. /*** End of inlined file: stream_encoder.c ***/
  102561. /*** Start of inlined file: stream_encoder_framing.c ***/
  102562. /*** Start of inlined file: juce_FlacHeader.h ***/
  102563. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102564. // tasks..
  102565. #define VERSION "1.2.1"
  102566. #define FLAC__NO_DLL 1
  102567. #if JUCE_MSVC
  102568. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102569. #endif
  102570. #if JUCE_MAC
  102571. #define FLAC__SYS_DARWIN 1
  102572. #endif
  102573. /*** End of inlined file: juce_FlacHeader.h ***/
  102574. #if JUCE_USE_FLAC
  102575. #if HAVE_CONFIG_H
  102576. # include <config.h>
  102577. #endif
  102578. #include <stdio.h>
  102579. #include <string.h> /* for strlen() */
  102580. #ifdef max
  102581. #undef max
  102582. #endif
  102583. #define max(x,y) ((x)>(y)?(x):(y))
  102584. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  102585. 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);
  102586. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  102587. {
  102588. unsigned i, j;
  102589. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  102590. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  102591. return false;
  102592. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  102593. return false;
  102594. /*
  102595. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  102596. */
  102597. i = metadata->length;
  102598. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102599. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  102600. i -= metadata->data.vorbis_comment.vendor_string.length;
  102601. i += vendor_string_length;
  102602. }
  102603. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  102604. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  102605. return false;
  102606. switch(metadata->type) {
  102607. case FLAC__METADATA_TYPE_STREAMINFO:
  102608. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  102609. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  102610. return false;
  102611. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  102612. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  102613. return false;
  102614. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  102615. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  102616. return false;
  102617. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  102618. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  102619. return false;
  102620. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  102621. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  102622. return false;
  102623. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  102624. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  102625. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  102626. return false;
  102627. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  102628. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102629. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  102630. return false;
  102631. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  102632. return false;
  102633. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  102634. return false;
  102635. break;
  102636. case FLAC__METADATA_TYPE_PADDING:
  102637. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  102638. return false;
  102639. break;
  102640. case FLAC__METADATA_TYPE_APPLICATION:
  102641. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  102642. return false;
  102643. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  102644. return false;
  102645. break;
  102646. case FLAC__METADATA_TYPE_SEEKTABLE:
  102647. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  102648. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  102649. return false;
  102650. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  102651. return false;
  102652. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  102653. return false;
  102654. }
  102655. break;
  102656. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  102657. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  102658. return false;
  102659. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  102660. return false;
  102661. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  102662. return false;
  102663. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  102664. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  102665. return false;
  102666. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  102667. return false;
  102668. }
  102669. break;
  102670. case FLAC__METADATA_TYPE_CUESHEET:
  102671. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  102672. 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))
  102673. return false;
  102674. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  102675. return false;
  102676. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  102677. return false;
  102678. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  102679. return false;
  102680. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  102681. return false;
  102682. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  102683. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  102684. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  102685. return false;
  102686. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  102687. return false;
  102688. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  102689. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  102690. return false;
  102691. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  102692. return false;
  102693. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  102694. return false;
  102695. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  102696. return false;
  102697. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  102698. return false;
  102699. for(j = 0; j < track->num_indices; j++) {
  102700. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  102701. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  102702. return false;
  102703. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  102704. return false;
  102705. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  102706. return false;
  102707. }
  102708. }
  102709. break;
  102710. case FLAC__METADATA_TYPE_PICTURE:
  102711. {
  102712. size_t len;
  102713. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  102714. return false;
  102715. len = strlen(metadata->data.picture.mime_type);
  102716. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  102717. return false;
  102718. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  102719. return false;
  102720. len = strlen((const char *)metadata->data.picture.description);
  102721. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  102722. return false;
  102723. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  102724. return false;
  102725. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  102726. return false;
  102727. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  102728. return false;
  102729. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  102730. return false;
  102731. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  102732. return false;
  102733. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  102734. return false;
  102735. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  102736. return false;
  102737. }
  102738. break;
  102739. default:
  102740. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  102741. return false;
  102742. break;
  102743. }
  102744. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102745. return true;
  102746. }
  102747. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  102748. {
  102749. unsigned u, blocksize_hint, sample_rate_hint;
  102750. FLAC__byte crc;
  102751. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102752. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  102753. return false;
  102754. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  102755. return false;
  102756. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  102757. return false;
  102758. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  102759. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  102760. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  102761. blocksize_hint = 0;
  102762. switch(header->blocksize) {
  102763. case 192: u = 1; break;
  102764. case 576: u = 2; break;
  102765. case 1152: u = 3; break;
  102766. case 2304: u = 4; break;
  102767. case 4608: u = 5; break;
  102768. case 256: u = 8; break;
  102769. case 512: u = 9; break;
  102770. case 1024: u = 10; break;
  102771. case 2048: u = 11; break;
  102772. case 4096: u = 12; break;
  102773. case 8192: u = 13; break;
  102774. case 16384: u = 14; break;
  102775. case 32768: u = 15; break;
  102776. default:
  102777. if(header->blocksize <= 0x100)
  102778. blocksize_hint = u = 6;
  102779. else
  102780. blocksize_hint = u = 7;
  102781. break;
  102782. }
  102783. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  102784. return false;
  102785. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  102786. sample_rate_hint = 0;
  102787. switch(header->sample_rate) {
  102788. case 88200: u = 1; break;
  102789. case 176400: u = 2; break;
  102790. case 192000: u = 3; break;
  102791. case 8000: u = 4; break;
  102792. case 16000: u = 5; break;
  102793. case 22050: u = 6; break;
  102794. case 24000: u = 7; break;
  102795. case 32000: u = 8; break;
  102796. case 44100: u = 9; break;
  102797. case 48000: u = 10; break;
  102798. case 96000: u = 11; break;
  102799. default:
  102800. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  102801. sample_rate_hint = u = 12;
  102802. else if(header->sample_rate % 10 == 0)
  102803. sample_rate_hint = u = 14;
  102804. else if(header->sample_rate <= 0xffff)
  102805. sample_rate_hint = u = 13;
  102806. else
  102807. u = 0;
  102808. break;
  102809. }
  102810. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  102811. return false;
  102812. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  102813. switch(header->channel_assignment) {
  102814. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  102815. u = header->channels - 1;
  102816. break;
  102817. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  102818. FLAC__ASSERT(header->channels == 2);
  102819. u = 8;
  102820. break;
  102821. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  102822. FLAC__ASSERT(header->channels == 2);
  102823. u = 9;
  102824. break;
  102825. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  102826. FLAC__ASSERT(header->channels == 2);
  102827. u = 10;
  102828. break;
  102829. default:
  102830. FLAC__ASSERT(0);
  102831. }
  102832. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  102833. return false;
  102834. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102835. switch(header->bits_per_sample) {
  102836. case 8 : u = 1; break;
  102837. case 12: u = 2; break;
  102838. case 16: u = 4; break;
  102839. case 20: u = 5; break;
  102840. case 24: u = 6; break;
  102841. default: u = 0; break;
  102842. }
  102843. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  102844. return false;
  102845. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  102846. return false;
  102847. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  102848. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  102849. return false;
  102850. }
  102851. else {
  102852. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  102853. return false;
  102854. }
  102855. if(blocksize_hint)
  102856. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  102857. return false;
  102858. switch(sample_rate_hint) {
  102859. case 12:
  102860. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  102861. return false;
  102862. break;
  102863. case 13:
  102864. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  102865. return false;
  102866. break;
  102867. case 14:
  102868. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  102869. return false;
  102870. break;
  102871. }
  102872. /* write the CRC */
  102873. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  102874. return false;
  102875. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  102876. return false;
  102877. return true;
  102878. }
  102879. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102880. {
  102881. FLAC__bool ok;
  102882. ok =
  102883. 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) &&
  102884. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  102885. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  102886. ;
  102887. return ok;
  102888. }
  102889. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102890. {
  102891. unsigned i;
  102892. 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))
  102893. return false;
  102894. if(wasted_bits)
  102895. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102896. return false;
  102897. for(i = 0; i < subframe->order; i++)
  102898. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102899. return false;
  102900. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102901. return false;
  102902. switch(subframe->entropy_coding_method.type) {
  102903. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102904. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102905. if(!add_residual_partitioned_rice_(
  102906. bw,
  102907. subframe->residual,
  102908. residual_samples,
  102909. subframe->order,
  102910. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102911. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102912. subframe->entropy_coding_method.data.partitioned_rice.order,
  102913. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102914. ))
  102915. return false;
  102916. break;
  102917. default:
  102918. FLAC__ASSERT(0);
  102919. }
  102920. return true;
  102921. }
  102922. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102923. {
  102924. unsigned i;
  102925. 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))
  102926. return false;
  102927. if(wasted_bits)
  102928. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102929. return false;
  102930. for(i = 0; i < subframe->order; i++)
  102931. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102932. return false;
  102933. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  102934. return false;
  102935. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  102936. return false;
  102937. for(i = 0; i < subframe->order; i++)
  102938. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  102939. return false;
  102940. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102941. return false;
  102942. switch(subframe->entropy_coding_method.type) {
  102943. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102944. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102945. if(!add_residual_partitioned_rice_(
  102946. bw,
  102947. subframe->residual,
  102948. residual_samples,
  102949. subframe->order,
  102950. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102951. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102952. subframe->entropy_coding_method.data.partitioned_rice.order,
  102953. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102954. ))
  102955. return false;
  102956. break;
  102957. default:
  102958. FLAC__ASSERT(0);
  102959. }
  102960. return true;
  102961. }
  102962. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102963. {
  102964. unsigned i;
  102965. const FLAC__int32 *signal = subframe->data;
  102966. 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))
  102967. return false;
  102968. if(wasted_bits)
  102969. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102970. return false;
  102971. for(i = 0; i < samples; i++)
  102972. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  102973. return false;
  102974. return true;
  102975. }
  102976. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  102977. {
  102978. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  102979. return false;
  102980. switch(method->type) {
  102981. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102982. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102983. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102984. return false;
  102985. break;
  102986. default:
  102987. FLAC__ASSERT(0);
  102988. }
  102989. return true;
  102990. }
  102991. 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)
  102992. {
  102993. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  102994. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  102995. if(partition_order == 0) {
  102996. unsigned i;
  102997. if(raw_bits[0] == 0) {
  102998. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  102999. return false;
  103000. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  103001. return false;
  103002. }
  103003. else {
  103004. FLAC__ASSERT(rice_parameters[0] == 0);
  103005. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103006. return false;
  103007. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103008. return false;
  103009. for(i = 0; i < residual_samples; i++) {
  103010. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  103011. return false;
  103012. }
  103013. }
  103014. return true;
  103015. }
  103016. else {
  103017. unsigned i, j, k = 0, k_last = 0;
  103018. unsigned partition_samples;
  103019. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  103020. for(i = 0; i < (1u<<partition_order); i++) {
  103021. partition_samples = default_partition_samples;
  103022. if(i == 0)
  103023. partition_samples -= predictor_order;
  103024. k += partition_samples;
  103025. if(raw_bits[i] == 0) {
  103026. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  103027. return false;
  103028. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  103029. return false;
  103030. }
  103031. else {
  103032. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103033. return false;
  103034. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103035. return false;
  103036. for(j = k_last; j < k; j++) {
  103037. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  103038. return false;
  103039. }
  103040. }
  103041. k_last = k;
  103042. }
  103043. return true;
  103044. }
  103045. }
  103046. #endif
  103047. /*** End of inlined file: stream_encoder_framing.c ***/
  103048. /*** Start of inlined file: window_flac.c ***/
  103049. /*** Start of inlined file: juce_FlacHeader.h ***/
  103050. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103051. // tasks..
  103052. #define VERSION "1.2.1"
  103053. #define FLAC__NO_DLL 1
  103054. #if JUCE_MSVC
  103055. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103056. #endif
  103057. #if JUCE_MAC
  103058. #define FLAC__SYS_DARWIN 1
  103059. #endif
  103060. /*** End of inlined file: juce_FlacHeader.h ***/
  103061. #if JUCE_USE_FLAC
  103062. #if HAVE_CONFIG_H
  103063. # include <config.h>
  103064. #endif
  103065. #include <math.h>
  103066. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103067. #ifndef M_PI
  103068. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  103069. #define M_PI 3.14159265358979323846
  103070. #endif
  103071. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  103072. {
  103073. const FLAC__int32 N = L - 1;
  103074. FLAC__int32 n;
  103075. if (L & 1) {
  103076. for (n = 0; n <= N/2; n++)
  103077. window[n] = 2.0f * n / (float)N;
  103078. for (; n <= N; n++)
  103079. window[n] = 2.0f - 2.0f * n / (float)N;
  103080. }
  103081. else {
  103082. for (n = 0; n <= L/2-1; n++)
  103083. window[n] = 2.0f * n / (float)N;
  103084. for (; n <= N; n++)
  103085. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  103086. }
  103087. }
  103088. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  103089. {
  103090. const FLAC__int32 N = L - 1;
  103091. FLAC__int32 n;
  103092. for (n = 0; n < L; n++)
  103093. 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)));
  103094. }
  103095. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  103096. {
  103097. const FLAC__int32 N = L - 1;
  103098. FLAC__int32 n;
  103099. for (n = 0; n < L; n++)
  103100. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  103101. }
  103102. /* 4-term -92dB side-lobe */
  103103. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  103104. {
  103105. const FLAC__int32 N = L - 1;
  103106. FLAC__int32 n;
  103107. for (n = 0; n <= N; n++)
  103108. 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));
  103109. }
  103110. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  103111. {
  103112. const FLAC__int32 N = L - 1;
  103113. const double N2 = (double)N / 2.;
  103114. FLAC__int32 n;
  103115. for (n = 0; n <= N; n++) {
  103116. double k = ((double)n - N2) / N2;
  103117. k = 1.0f - k * k;
  103118. window[n] = (FLAC__real)(k * k);
  103119. }
  103120. }
  103121. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  103122. {
  103123. const FLAC__int32 N = L - 1;
  103124. FLAC__int32 n;
  103125. for (n = 0; n < L; n++)
  103126. 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));
  103127. }
  103128. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  103129. {
  103130. const FLAC__int32 N = L - 1;
  103131. const double N2 = (double)N / 2.;
  103132. FLAC__int32 n;
  103133. for (n = 0; n <= N; n++) {
  103134. const double k = ((double)n - N2) / (stddev * N2);
  103135. window[n] = (FLAC__real)exp(-0.5f * k * k);
  103136. }
  103137. }
  103138. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  103139. {
  103140. const FLAC__int32 N = L - 1;
  103141. FLAC__int32 n;
  103142. for (n = 0; n < L; n++)
  103143. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  103144. }
  103145. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  103146. {
  103147. const FLAC__int32 N = L - 1;
  103148. FLAC__int32 n;
  103149. for (n = 0; n < L; n++)
  103150. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  103151. }
  103152. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  103153. {
  103154. const FLAC__int32 N = L - 1;
  103155. FLAC__int32 n;
  103156. for (n = 0; n < L; n++)
  103157. 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));
  103158. }
  103159. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  103160. {
  103161. const FLAC__int32 N = L - 1;
  103162. FLAC__int32 n;
  103163. for (n = 0; n < L; n++)
  103164. 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));
  103165. }
  103166. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  103167. {
  103168. FLAC__int32 n;
  103169. for (n = 0; n < L; n++)
  103170. window[n] = 1.0f;
  103171. }
  103172. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  103173. {
  103174. FLAC__int32 n;
  103175. if (L & 1) {
  103176. for (n = 1; n <= L+1/2; n++)
  103177. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  103178. for (; n <= L; n++)
  103179. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  103180. }
  103181. else {
  103182. for (n = 1; n <= L/2; n++)
  103183. window[n-1] = 2.0f * n / (float)L;
  103184. for (; n <= L; n++)
  103185. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  103186. }
  103187. }
  103188. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  103189. {
  103190. if (p <= 0.0)
  103191. FLAC__window_rectangle(window, L);
  103192. else if (p >= 1.0)
  103193. FLAC__window_hann(window, L);
  103194. else {
  103195. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  103196. FLAC__int32 n;
  103197. /* start with rectangle... */
  103198. FLAC__window_rectangle(window, L);
  103199. /* ...replace ends with hann */
  103200. if (Np > 0) {
  103201. for (n = 0; n <= Np; n++) {
  103202. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  103203. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  103204. }
  103205. }
  103206. }
  103207. }
  103208. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  103209. {
  103210. const FLAC__int32 N = L - 1;
  103211. const double N2 = (double)N / 2.;
  103212. FLAC__int32 n;
  103213. for (n = 0; n <= N; n++) {
  103214. const double k = ((double)n - N2) / N2;
  103215. window[n] = (FLAC__real)(1.0f - k * k);
  103216. }
  103217. }
  103218. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  103219. #endif
  103220. /*** End of inlined file: window_flac.c ***/
  103221. #else
  103222. #include <FLAC/all.h>
  103223. #endif
  103224. }
  103225. #undef max
  103226. #undef min
  103227. #ifdef _MSC_VER
  103228. #pragma warning (pop)
  103229. #endif
  103230. BEGIN_JUCE_NAMESPACE
  103231. static const char* const flacFormatName = "FLAC file";
  103232. static const char* const flacExtensions[] = { ".flac", 0 };
  103233. class FlacReader : public AudioFormatReader
  103234. {
  103235. public:
  103236. FlacReader (InputStream* const in)
  103237. : AudioFormatReader (in, TRANS (flacFormatName)),
  103238. reservoir (2, 0),
  103239. reservoirStart (0),
  103240. samplesInReservoir (0),
  103241. scanningForLength (false)
  103242. {
  103243. using namespace FlacNamespace;
  103244. lengthInSamples = 0;
  103245. decoder = FLAC__stream_decoder_new();
  103246. ok = FLAC__stream_decoder_init_stream (decoder,
  103247. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  103248. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  103249. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  103250. if (ok)
  103251. {
  103252. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103253. if (lengthInSamples == 0 && sampleRate > 0)
  103254. {
  103255. // the length hasn't been stored in the metadata, so we'll need to
  103256. // work it out the length the hard way, by scanning the whole file..
  103257. scanningForLength = true;
  103258. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  103259. scanningForLength = false;
  103260. const int64 tempLength = lengthInSamples;
  103261. FLAC__stream_decoder_reset (decoder);
  103262. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103263. lengthInSamples = tempLength;
  103264. }
  103265. }
  103266. }
  103267. ~FlacReader()
  103268. {
  103269. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  103270. }
  103271. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  103272. {
  103273. sampleRate = info.sample_rate;
  103274. bitsPerSample = info.bits_per_sample;
  103275. lengthInSamples = (unsigned int) info.total_samples;
  103276. numChannels = info.channels;
  103277. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  103278. }
  103279. // returns the number of samples read
  103280. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  103281. int64 startSampleInFile, int numSamples)
  103282. {
  103283. using namespace FlacNamespace;
  103284. if (! ok)
  103285. return false;
  103286. while (numSamples > 0)
  103287. {
  103288. if (startSampleInFile >= reservoirStart
  103289. && startSampleInFile < reservoirStart + samplesInReservoir)
  103290. {
  103291. const int num = (int) jmin ((int64) numSamples,
  103292. reservoirStart + samplesInReservoir - startSampleInFile);
  103293. jassert (num > 0);
  103294. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  103295. if (destSamples[i] != 0)
  103296. memcpy (destSamples[i] + startOffsetInDestBuffer,
  103297. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  103298. sizeof (int) * num);
  103299. startOffsetInDestBuffer += num;
  103300. startSampleInFile += num;
  103301. numSamples -= num;
  103302. }
  103303. else
  103304. {
  103305. if (startSampleInFile >= (int) lengthInSamples)
  103306. {
  103307. samplesInReservoir = 0;
  103308. }
  103309. else if (startSampleInFile < reservoirStart
  103310. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  103311. {
  103312. // had some problems with flac crashing if the read pos is aligned more
  103313. // accurately than this. Probably fixed in newer versions of the library, though.
  103314. reservoirStart = (int) (startSampleInFile & ~511);
  103315. samplesInReservoir = 0;
  103316. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  103317. }
  103318. else
  103319. {
  103320. reservoirStart += samplesInReservoir;
  103321. samplesInReservoir = 0;
  103322. FLAC__stream_decoder_process_single (decoder);
  103323. }
  103324. if (samplesInReservoir == 0)
  103325. break;
  103326. }
  103327. }
  103328. if (numSamples > 0)
  103329. {
  103330. for (int i = numDestChannels; --i >= 0;)
  103331. if (destSamples[i] != 0)
  103332. zeromem (destSamples[i] + startOffsetInDestBuffer,
  103333. sizeof (int) * numSamples);
  103334. }
  103335. return true;
  103336. }
  103337. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  103338. {
  103339. if (scanningForLength)
  103340. {
  103341. lengthInSamples += numSamples;
  103342. }
  103343. else
  103344. {
  103345. if (numSamples > reservoir.getNumSamples())
  103346. reservoir.setSize (numChannels, numSamples, false, false, true);
  103347. const int bitsToShift = 32 - bitsPerSample;
  103348. for (int i = 0; i < (int) numChannels; ++i)
  103349. {
  103350. const FlacNamespace::FLAC__int32* src = buffer[i];
  103351. int n = i;
  103352. while (src == 0 && n > 0)
  103353. src = buffer [--n];
  103354. if (src != 0)
  103355. {
  103356. int* dest = (int*) reservoir.getSampleData(i);
  103357. for (int j = 0; j < numSamples; ++j)
  103358. dest[j] = src[j] << bitsToShift;
  103359. }
  103360. }
  103361. samplesInReservoir = numSamples;
  103362. }
  103363. }
  103364. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  103365. {
  103366. using namespace FlacNamespace;
  103367. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  103368. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  103369. }
  103370. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  103371. {
  103372. using namespace FlacNamespace;
  103373. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  103374. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  103375. }
  103376. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  103377. {
  103378. using namespace FlacNamespace;
  103379. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  103380. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  103381. }
  103382. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  103383. {
  103384. using namespace FlacNamespace;
  103385. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  103386. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  103387. }
  103388. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  103389. {
  103390. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  103391. }
  103392. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  103393. const FlacNamespace::FLAC__Frame* frame,
  103394. const FlacNamespace::FLAC__int32* const buffer[],
  103395. void* client_data)
  103396. {
  103397. using namespace FlacNamespace;
  103398. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  103399. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  103400. }
  103401. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  103402. const FlacNamespace::FLAC__StreamMetadata* metadata,
  103403. void* client_data)
  103404. {
  103405. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  103406. }
  103407. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  103408. {
  103409. }
  103410. juce_UseDebuggingNewOperator
  103411. private:
  103412. FlacNamespace::FLAC__StreamDecoder* decoder;
  103413. AudioSampleBuffer reservoir;
  103414. int reservoirStart, samplesInReservoir;
  103415. bool ok, scanningForLength;
  103416. FlacReader (const FlacReader&);
  103417. FlacReader& operator= (const FlacReader&);
  103418. };
  103419. class FlacWriter : public AudioFormatWriter
  103420. {
  103421. public:
  103422. FlacWriter (OutputStream* const out,
  103423. const double sampleRate_,
  103424. const int numChannels_,
  103425. const int bitsPerSample_)
  103426. : AudioFormatWriter (out, TRANS (flacFormatName),
  103427. sampleRate_,
  103428. numChannels_,
  103429. bitsPerSample_)
  103430. {
  103431. using namespace FlacNamespace;
  103432. encoder = FLAC__stream_encoder_new();
  103433. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  103434. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  103435. FLAC__stream_encoder_set_channels (encoder, numChannels);
  103436. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  103437. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  103438. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  103439. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  103440. ok = FLAC__stream_encoder_init_stream (encoder,
  103441. encodeWriteCallback, encodeSeekCallback,
  103442. encodeTellCallback, encodeMetadataCallback,
  103443. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103444. }
  103445. ~FlacWriter()
  103446. {
  103447. if (ok)
  103448. {
  103449. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  103450. output->flush();
  103451. }
  103452. else
  103453. {
  103454. output = 0; // to stop the base class deleting this, as it needs to be returned
  103455. // to the caller of createWriter()
  103456. }
  103457. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  103458. }
  103459. bool write (const int** samplesToWrite, int numSamples)
  103460. {
  103461. using namespace FlacNamespace;
  103462. if (! ok)
  103463. return false;
  103464. int* buf[3];
  103465. const int bitsToShift = 32 - bitsPerSample;
  103466. if (bitsToShift > 0)
  103467. {
  103468. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  103469. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  103470. buf[0] = (int*) temp.getData();
  103471. buf[1] = buf[0] + numSamples;
  103472. buf[2] = 0;
  103473. for (int i = numChannelsToWrite; --i >= 0;)
  103474. {
  103475. if (samplesToWrite[i] != 0)
  103476. {
  103477. for (int j = 0; j < numSamples; ++j)
  103478. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  103479. }
  103480. }
  103481. samplesToWrite = (const int**) buf;
  103482. }
  103483. return FLAC__stream_encoder_process (encoder,
  103484. (const FLAC__int32**) samplesToWrite,
  103485. numSamples) != 0;
  103486. }
  103487. bool writeData (const void* const data, const int size) const
  103488. {
  103489. return output->write (data, size);
  103490. }
  103491. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  103492. {
  103493. using namespace FlacNamespace;
  103494. b += bytes;
  103495. for (int i = 0; i < bytes; ++i)
  103496. {
  103497. *(--b) = (FLAC__byte) (val & 0xff);
  103498. val >>= 8;
  103499. }
  103500. }
  103501. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  103502. {
  103503. using namespace FlacNamespace;
  103504. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  103505. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  103506. const unsigned int channelsMinus1 = info.channels - 1;
  103507. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  103508. packUint32 (info.min_blocksize, buffer, 2);
  103509. packUint32 (info.max_blocksize, buffer + 2, 2);
  103510. packUint32 (info.min_framesize, buffer + 4, 3);
  103511. packUint32 (info.max_framesize, buffer + 7, 3);
  103512. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  103513. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  103514. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  103515. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  103516. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  103517. memcpy (buffer + 18, info.md5sum, 16);
  103518. const bool seekOk = output->setPosition (4);
  103519. (void) seekOk;
  103520. // if this fails, you've given it an output stream that can't seek! It needs
  103521. // to be able to seek back to write the header
  103522. jassert (seekOk);
  103523. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  103524. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  103525. }
  103526. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  103527. const FlacNamespace::FLAC__byte buffer[],
  103528. size_t bytes,
  103529. unsigned int /*samples*/,
  103530. unsigned int /*current_frame*/,
  103531. void* client_data)
  103532. {
  103533. using namespace FlacNamespace;
  103534. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  103535. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  103536. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103537. }
  103538. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  103539. {
  103540. using namespace FlacNamespace;
  103541. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  103542. }
  103543. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  103544. {
  103545. using namespace FlacNamespace;
  103546. if (client_data == 0)
  103547. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  103548. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  103549. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  103550. }
  103551. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  103552. {
  103553. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  103554. }
  103555. juce_UseDebuggingNewOperator
  103556. bool ok;
  103557. private:
  103558. FlacNamespace::FLAC__StreamEncoder* encoder;
  103559. MemoryBlock temp;
  103560. FlacWriter (const FlacWriter&);
  103561. FlacWriter& operator= (const FlacWriter&);
  103562. };
  103563. FlacAudioFormat::FlacAudioFormat()
  103564. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  103565. {
  103566. }
  103567. FlacAudioFormat::~FlacAudioFormat()
  103568. {
  103569. }
  103570. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  103571. {
  103572. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  103573. return Array <int> (rates);
  103574. }
  103575. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  103576. {
  103577. const int depths[] = { 16, 24, 0 };
  103578. return Array <int> (depths);
  103579. }
  103580. bool FlacAudioFormat::canDoStereo()
  103581. {
  103582. return true;
  103583. }
  103584. bool FlacAudioFormat::canDoMono()
  103585. {
  103586. return true;
  103587. }
  103588. bool FlacAudioFormat::isCompressed()
  103589. {
  103590. return true;
  103591. }
  103592. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  103593. const bool deleteStreamIfOpeningFails)
  103594. {
  103595. ScopedPointer<FlacReader> r (new FlacReader (in));
  103596. if (r->sampleRate != 0)
  103597. return r.release();
  103598. if (! deleteStreamIfOpeningFails)
  103599. r->input = 0;
  103600. return 0;
  103601. }
  103602. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  103603. double sampleRate,
  103604. unsigned int numberOfChannels,
  103605. int bitsPerSample,
  103606. const StringPairArray& /*metadataValues*/,
  103607. int /*qualityOptionIndex*/)
  103608. {
  103609. if (getPossibleBitDepths().contains (bitsPerSample))
  103610. {
  103611. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  103612. if (w->ok)
  103613. return w.release();
  103614. }
  103615. return 0;
  103616. }
  103617. END_JUCE_NAMESPACE
  103618. #endif
  103619. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  103620. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  103621. #if JUCE_USE_OGGVORBIS
  103622. #if JUCE_MAC
  103623. #define __MACOSX__ 1
  103624. #endif
  103625. namespace OggVorbisNamespace
  103626. {
  103627. #if JUCE_INCLUDE_OGGVORBIS_CODE
  103628. /*** Start of inlined file: vorbisenc.h ***/
  103629. #ifndef _OV_ENC_H_
  103630. #define _OV_ENC_H_
  103631. #ifdef __cplusplus
  103632. extern "C"
  103633. {
  103634. #endif /* __cplusplus */
  103635. /*** Start of inlined file: codec.h ***/
  103636. #ifndef _vorbis_codec_h_
  103637. #define _vorbis_codec_h_
  103638. #ifdef __cplusplus
  103639. extern "C"
  103640. {
  103641. #endif /* __cplusplus */
  103642. /*** Start of inlined file: ogg.h ***/
  103643. #ifndef _OGG_H
  103644. #define _OGG_H
  103645. #ifdef __cplusplus
  103646. extern "C" {
  103647. #endif
  103648. /*** Start of inlined file: os_types.h ***/
  103649. #ifndef _OS_TYPES_H
  103650. #define _OS_TYPES_H
  103651. /* make it easy on the folks that want to compile the libs with a
  103652. different malloc than stdlib */
  103653. #define _ogg_malloc malloc
  103654. #define _ogg_calloc calloc
  103655. #define _ogg_realloc realloc
  103656. #define _ogg_free free
  103657. #if defined(_WIN32)
  103658. # if defined(__CYGWIN__)
  103659. # include <_G_config.h>
  103660. typedef _G_int64_t ogg_int64_t;
  103661. typedef _G_int32_t ogg_int32_t;
  103662. typedef _G_uint32_t ogg_uint32_t;
  103663. typedef _G_int16_t ogg_int16_t;
  103664. typedef _G_uint16_t ogg_uint16_t;
  103665. # elif defined(__MINGW32__)
  103666. typedef short ogg_int16_t;
  103667. typedef unsigned short ogg_uint16_t;
  103668. typedef int ogg_int32_t;
  103669. typedef unsigned int ogg_uint32_t;
  103670. typedef long long ogg_int64_t;
  103671. typedef unsigned long long ogg_uint64_t;
  103672. # elif defined(__MWERKS__)
  103673. typedef long long ogg_int64_t;
  103674. typedef int ogg_int32_t;
  103675. typedef unsigned int ogg_uint32_t;
  103676. typedef short ogg_int16_t;
  103677. typedef unsigned short ogg_uint16_t;
  103678. # else
  103679. /* MSVC/Borland */
  103680. typedef __int64 ogg_int64_t;
  103681. typedef __int32 ogg_int32_t;
  103682. typedef unsigned __int32 ogg_uint32_t;
  103683. typedef __int16 ogg_int16_t;
  103684. typedef unsigned __int16 ogg_uint16_t;
  103685. # endif
  103686. #elif defined(__MACOS__)
  103687. # include <sys/types.h>
  103688. typedef SInt16 ogg_int16_t;
  103689. typedef UInt16 ogg_uint16_t;
  103690. typedef SInt32 ogg_int32_t;
  103691. typedef UInt32 ogg_uint32_t;
  103692. typedef SInt64 ogg_int64_t;
  103693. #elif defined(__MACOSX__) /* MacOS X Framework build */
  103694. # include <sys/types.h>
  103695. typedef int16_t ogg_int16_t;
  103696. typedef u_int16_t ogg_uint16_t;
  103697. typedef int32_t ogg_int32_t;
  103698. typedef u_int32_t ogg_uint32_t;
  103699. typedef int64_t ogg_int64_t;
  103700. #elif defined(__BEOS__)
  103701. /* Be */
  103702. # include <inttypes.h>
  103703. typedef int16_t ogg_int16_t;
  103704. typedef u_int16_t ogg_uint16_t;
  103705. typedef int32_t ogg_int32_t;
  103706. typedef u_int32_t ogg_uint32_t;
  103707. typedef int64_t ogg_int64_t;
  103708. #elif defined (__EMX__)
  103709. /* OS/2 GCC */
  103710. typedef short ogg_int16_t;
  103711. typedef unsigned short ogg_uint16_t;
  103712. typedef int ogg_int32_t;
  103713. typedef unsigned int ogg_uint32_t;
  103714. typedef long long ogg_int64_t;
  103715. #elif defined (DJGPP)
  103716. /* DJGPP */
  103717. typedef short ogg_int16_t;
  103718. typedef int ogg_int32_t;
  103719. typedef unsigned int ogg_uint32_t;
  103720. typedef long long ogg_int64_t;
  103721. #elif defined(R5900)
  103722. /* PS2 EE */
  103723. typedef long ogg_int64_t;
  103724. typedef int ogg_int32_t;
  103725. typedef unsigned ogg_uint32_t;
  103726. typedef short ogg_int16_t;
  103727. #elif defined(__SYMBIAN32__)
  103728. /* Symbian GCC */
  103729. typedef signed short ogg_int16_t;
  103730. typedef unsigned short ogg_uint16_t;
  103731. typedef signed int ogg_int32_t;
  103732. typedef unsigned int ogg_uint32_t;
  103733. typedef long long int ogg_int64_t;
  103734. #else
  103735. # include <sys/types.h>
  103736. /*** Start of inlined file: config_types.h ***/
  103737. #ifndef __CONFIG_TYPES_H__
  103738. #define __CONFIG_TYPES_H__
  103739. typedef int16_t ogg_int16_t;
  103740. typedef unsigned short ogg_uint16_t;
  103741. typedef int32_t ogg_int32_t;
  103742. typedef unsigned int ogg_uint32_t;
  103743. typedef int64_t ogg_int64_t;
  103744. #endif
  103745. /*** End of inlined file: config_types.h ***/
  103746. #endif
  103747. #endif /* _OS_TYPES_H */
  103748. /*** End of inlined file: os_types.h ***/
  103749. typedef struct {
  103750. long endbyte;
  103751. int endbit;
  103752. unsigned char *buffer;
  103753. unsigned char *ptr;
  103754. long storage;
  103755. } oggpack_buffer;
  103756. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  103757. typedef struct {
  103758. unsigned char *header;
  103759. long header_len;
  103760. unsigned char *body;
  103761. long body_len;
  103762. } ogg_page;
  103763. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  103764. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  103765. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  103766. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  103767. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  103768. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  103769. }
  103770. /* ogg_stream_state contains the current encode/decode state of a logical
  103771. Ogg bitstream **********************************************************/
  103772. typedef struct {
  103773. unsigned char *body_data; /* bytes from packet bodies */
  103774. long body_storage; /* storage elements allocated */
  103775. long body_fill; /* elements stored; fill mark */
  103776. long body_returned; /* elements of fill returned */
  103777. int *lacing_vals; /* The values that will go to the segment table */
  103778. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  103779. this way, but it is simple coupled to the
  103780. lacing fifo */
  103781. long lacing_storage;
  103782. long lacing_fill;
  103783. long lacing_packet;
  103784. long lacing_returned;
  103785. unsigned char header[282]; /* working space for header encode */
  103786. int header_fill;
  103787. int e_o_s; /* set when we have buffered the last packet in the
  103788. logical bitstream */
  103789. int b_o_s; /* set after we've written the initial page
  103790. of a logical bitstream */
  103791. long serialno;
  103792. long pageno;
  103793. ogg_int64_t packetno; /* sequence number for decode; the framing
  103794. knows where there's a hole in the data,
  103795. but we need coupling so that the codec
  103796. (which is in a seperate abstraction
  103797. layer) also knows about the gap */
  103798. ogg_int64_t granulepos;
  103799. } ogg_stream_state;
  103800. /* ogg_packet is used to encapsulate the data and metadata belonging
  103801. to a single raw Ogg/Vorbis packet *************************************/
  103802. typedef struct {
  103803. unsigned char *packet;
  103804. long bytes;
  103805. long b_o_s;
  103806. long e_o_s;
  103807. ogg_int64_t granulepos;
  103808. ogg_int64_t packetno; /* sequence number for decode; the framing
  103809. knows where there's a hole in the data,
  103810. but we need coupling so that the codec
  103811. (which is in a seperate abstraction
  103812. layer) also knows about the gap */
  103813. } ogg_packet;
  103814. typedef struct {
  103815. unsigned char *data;
  103816. int storage;
  103817. int fill;
  103818. int returned;
  103819. int unsynced;
  103820. int headerbytes;
  103821. int bodybytes;
  103822. } ogg_sync_state;
  103823. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  103824. extern void oggpack_writeinit(oggpack_buffer *b);
  103825. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  103826. extern void oggpack_writealign(oggpack_buffer *b);
  103827. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  103828. extern void oggpack_reset(oggpack_buffer *b);
  103829. extern void oggpack_writeclear(oggpack_buffer *b);
  103830. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103831. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  103832. extern long oggpack_look(oggpack_buffer *b,int bits);
  103833. extern long oggpack_look1(oggpack_buffer *b);
  103834. extern void oggpack_adv(oggpack_buffer *b,int bits);
  103835. extern void oggpack_adv1(oggpack_buffer *b);
  103836. extern long oggpack_read(oggpack_buffer *b,int bits);
  103837. extern long oggpack_read1(oggpack_buffer *b);
  103838. extern long oggpack_bytes(oggpack_buffer *b);
  103839. extern long oggpack_bits(oggpack_buffer *b);
  103840. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  103841. extern void oggpackB_writeinit(oggpack_buffer *b);
  103842. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  103843. extern void oggpackB_writealign(oggpack_buffer *b);
  103844. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  103845. extern void oggpackB_reset(oggpack_buffer *b);
  103846. extern void oggpackB_writeclear(oggpack_buffer *b);
  103847. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103848. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  103849. extern long oggpackB_look(oggpack_buffer *b,int bits);
  103850. extern long oggpackB_look1(oggpack_buffer *b);
  103851. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  103852. extern void oggpackB_adv1(oggpack_buffer *b);
  103853. extern long oggpackB_read(oggpack_buffer *b,int bits);
  103854. extern long oggpackB_read1(oggpack_buffer *b);
  103855. extern long oggpackB_bytes(oggpack_buffer *b);
  103856. extern long oggpackB_bits(oggpack_buffer *b);
  103857. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  103858. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  103859. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  103860. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  103861. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  103862. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  103863. extern int ogg_sync_init(ogg_sync_state *oy);
  103864. extern int ogg_sync_clear(ogg_sync_state *oy);
  103865. extern int ogg_sync_reset(ogg_sync_state *oy);
  103866. extern int ogg_sync_destroy(ogg_sync_state *oy);
  103867. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  103868. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  103869. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  103870. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  103871. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  103872. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  103873. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  103874. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  103875. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  103876. extern int ogg_stream_clear(ogg_stream_state *os);
  103877. extern int ogg_stream_reset(ogg_stream_state *os);
  103878. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  103879. extern int ogg_stream_destroy(ogg_stream_state *os);
  103880. extern int ogg_stream_eos(ogg_stream_state *os);
  103881. extern void ogg_page_checksum_set(ogg_page *og);
  103882. extern int ogg_page_version(ogg_page *og);
  103883. extern int ogg_page_continued(ogg_page *og);
  103884. extern int ogg_page_bos(ogg_page *og);
  103885. extern int ogg_page_eos(ogg_page *og);
  103886. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  103887. extern int ogg_page_serialno(ogg_page *og);
  103888. extern long ogg_page_pageno(ogg_page *og);
  103889. extern int ogg_page_packets(ogg_page *og);
  103890. extern void ogg_packet_clear(ogg_packet *op);
  103891. #ifdef __cplusplus
  103892. }
  103893. #endif
  103894. #endif /* _OGG_H */
  103895. /*** End of inlined file: ogg.h ***/
  103896. typedef struct vorbis_info{
  103897. int version;
  103898. int channels;
  103899. long rate;
  103900. /* The below bitrate declarations are *hints*.
  103901. Combinations of the three values carry the following implications:
  103902. all three set to the same value:
  103903. implies a fixed rate bitstream
  103904. only nominal set:
  103905. implies a VBR stream that averages the nominal bitrate. No hard
  103906. upper/lower limit
  103907. upper and or lower set:
  103908. implies a VBR bitstream that obeys the bitrate limits. nominal
  103909. may also be set to give a nominal rate.
  103910. none set:
  103911. the coder does not care to speculate.
  103912. */
  103913. long bitrate_upper;
  103914. long bitrate_nominal;
  103915. long bitrate_lower;
  103916. long bitrate_window;
  103917. void *codec_setup;
  103918. } vorbis_info;
  103919. /* vorbis_dsp_state buffers the current vorbis audio
  103920. analysis/synthesis state. The DSP state belongs to a specific
  103921. logical bitstream ****************************************************/
  103922. typedef struct vorbis_dsp_state{
  103923. int analysisp;
  103924. vorbis_info *vi;
  103925. float **pcm;
  103926. float **pcmret;
  103927. int pcm_storage;
  103928. int pcm_current;
  103929. int pcm_returned;
  103930. int preextrapolate;
  103931. int eofflag;
  103932. long lW;
  103933. long W;
  103934. long nW;
  103935. long centerW;
  103936. ogg_int64_t granulepos;
  103937. ogg_int64_t sequence;
  103938. ogg_int64_t glue_bits;
  103939. ogg_int64_t time_bits;
  103940. ogg_int64_t floor_bits;
  103941. ogg_int64_t res_bits;
  103942. void *backend_state;
  103943. } vorbis_dsp_state;
  103944. typedef struct vorbis_block{
  103945. /* necessary stream state for linking to the framing abstraction */
  103946. float **pcm; /* this is a pointer into local storage */
  103947. oggpack_buffer opb;
  103948. long lW;
  103949. long W;
  103950. long nW;
  103951. int pcmend;
  103952. int mode;
  103953. int eofflag;
  103954. ogg_int64_t granulepos;
  103955. ogg_int64_t sequence;
  103956. vorbis_dsp_state *vd; /* For read-only access of configuration */
  103957. /* local storage to avoid remallocing; it's up to the mapping to
  103958. structure it */
  103959. void *localstore;
  103960. long localtop;
  103961. long localalloc;
  103962. long totaluse;
  103963. struct alloc_chain *reap;
  103964. /* bitmetrics for the frame */
  103965. long glue_bits;
  103966. long time_bits;
  103967. long floor_bits;
  103968. long res_bits;
  103969. void *internal;
  103970. } vorbis_block;
  103971. /* vorbis_block is a single block of data to be processed as part of
  103972. the analysis/synthesis stream; it belongs to a specific logical
  103973. bitstream, but is independant from other vorbis_blocks belonging to
  103974. that logical bitstream. *************************************************/
  103975. struct alloc_chain{
  103976. void *ptr;
  103977. struct alloc_chain *next;
  103978. };
  103979. /* vorbis_info contains all the setup information specific to the
  103980. specific compression/decompression mode in progress (eg,
  103981. psychoacoustic settings, channel setup, options, codebook
  103982. etc). vorbis_info and substructures are in backends.h.
  103983. *********************************************************************/
  103984. /* the comments are not part of vorbis_info so that vorbis_info can be
  103985. static storage */
  103986. typedef struct vorbis_comment{
  103987. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  103988. whatever vendor is set to in encode */
  103989. char **user_comments;
  103990. int *comment_lengths;
  103991. int comments;
  103992. char *vendor;
  103993. } vorbis_comment;
  103994. /* libvorbis encodes in two abstraction layers; first we perform DSP
  103995. and produce a packet (see docs/analysis.txt). The packet is then
  103996. coded into a framed OggSquish bitstream by the second layer (see
  103997. docs/framing.txt). Decode is the reverse process; we sync/frame
  103998. the bitstream and extract individual packets, then decode the
  103999. packet back into PCM audio.
  104000. The extra framing/packetizing is used in streaming formats, such as
  104001. files. Over the net (such as with UDP), the framing and
  104002. packetization aren't necessary as they're provided by the transport
  104003. and the streaming layer is not used */
  104004. /* Vorbis PRIMITIVES: general ***************************************/
  104005. extern void vorbis_info_init(vorbis_info *vi);
  104006. extern void vorbis_info_clear(vorbis_info *vi);
  104007. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  104008. extern void vorbis_comment_init(vorbis_comment *vc);
  104009. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  104010. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  104011. const char *tag, char *contents);
  104012. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  104013. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  104014. extern void vorbis_comment_clear(vorbis_comment *vc);
  104015. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  104016. extern int vorbis_block_clear(vorbis_block *vb);
  104017. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  104018. extern double vorbis_granule_time(vorbis_dsp_state *v,
  104019. ogg_int64_t granulepos);
  104020. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  104021. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104022. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  104023. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  104024. vorbis_comment *vc,
  104025. ogg_packet *op,
  104026. ogg_packet *op_comm,
  104027. ogg_packet *op_code);
  104028. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  104029. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  104030. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  104031. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  104032. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104033. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  104034. ogg_packet *op);
  104035. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  104036. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  104037. ogg_packet *op);
  104038. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104039. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  104040. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  104041. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  104042. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  104043. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  104044. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  104045. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  104046. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  104047. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  104048. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  104049. /* Vorbis ERRORS and return codes ***********************************/
  104050. #define OV_FALSE -1
  104051. #define OV_EOF -2
  104052. #define OV_HOLE -3
  104053. #define OV_EREAD -128
  104054. #define OV_EFAULT -129
  104055. #define OV_EIMPL -130
  104056. #define OV_EINVAL -131
  104057. #define OV_ENOTVORBIS -132
  104058. #define OV_EBADHEADER -133
  104059. #define OV_EVERSION -134
  104060. #define OV_ENOTAUDIO -135
  104061. #define OV_EBADPACKET -136
  104062. #define OV_EBADLINK -137
  104063. #define OV_ENOSEEK -138
  104064. #ifdef __cplusplus
  104065. }
  104066. #endif /* __cplusplus */
  104067. #endif
  104068. /*** End of inlined file: codec.h ***/
  104069. extern int vorbis_encode_init(vorbis_info *vi,
  104070. long channels,
  104071. long rate,
  104072. long max_bitrate,
  104073. long nominal_bitrate,
  104074. long min_bitrate);
  104075. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  104076. long channels,
  104077. long rate,
  104078. long max_bitrate,
  104079. long nominal_bitrate,
  104080. long min_bitrate);
  104081. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  104082. long channels,
  104083. long rate,
  104084. float quality /* quality level from 0. (lo) to 1. (hi) */
  104085. );
  104086. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  104087. long channels,
  104088. long rate,
  104089. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  104090. );
  104091. extern int vorbis_encode_setup_init(vorbis_info *vi);
  104092. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  104093. /* deprecated rate management supported only for compatability */
  104094. #define OV_ECTL_RATEMANAGE_GET 0x10
  104095. #define OV_ECTL_RATEMANAGE_SET 0x11
  104096. #define OV_ECTL_RATEMANAGE_AVG 0x12
  104097. #define OV_ECTL_RATEMANAGE_HARD 0x13
  104098. struct ovectl_ratemanage_arg {
  104099. int management_active;
  104100. long bitrate_hard_min;
  104101. long bitrate_hard_max;
  104102. double bitrate_hard_window;
  104103. long bitrate_av_lo;
  104104. long bitrate_av_hi;
  104105. double bitrate_av_window;
  104106. double bitrate_av_window_center;
  104107. };
  104108. /* new rate setup */
  104109. #define OV_ECTL_RATEMANAGE2_GET 0x14
  104110. #define OV_ECTL_RATEMANAGE2_SET 0x15
  104111. struct ovectl_ratemanage2_arg {
  104112. int management_active;
  104113. long bitrate_limit_min_kbps;
  104114. long bitrate_limit_max_kbps;
  104115. long bitrate_limit_reservoir_bits;
  104116. double bitrate_limit_reservoir_bias;
  104117. long bitrate_average_kbps;
  104118. double bitrate_average_damping;
  104119. };
  104120. #define OV_ECTL_LOWPASS_GET 0x20
  104121. #define OV_ECTL_LOWPASS_SET 0x21
  104122. #define OV_ECTL_IBLOCK_GET 0x30
  104123. #define OV_ECTL_IBLOCK_SET 0x31
  104124. #ifdef __cplusplus
  104125. }
  104126. #endif /* __cplusplus */
  104127. #endif
  104128. /*** End of inlined file: vorbisenc.h ***/
  104129. /*** Start of inlined file: vorbisfile.h ***/
  104130. #ifndef _OV_FILE_H_
  104131. #define _OV_FILE_H_
  104132. #ifdef __cplusplus
  104133. extern "C"
  104134. {
  104135. #endif /* __cplusplus */
  104136. #include <stdio.h>
  104137. /* The function prototypes for the callbacks are basically the same as for
  104138. * the stdio functions fread, fseek, fclose, ftell.
  104139. * The one difference is that the FILE * arguments have been replaced with
  104140. * a void * - this is to be used as a pointer to whatever internal data these
  104141. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  104142. *
  104143. * If you use other functions, check the docs for these functions and return
  104144. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  104145. * unseekable
  104146. */
  104147. typedef struct {
  104148. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  104149. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  104150. int (*close_func) (void *datasource);
  104151. long (*tell_func) (void *datasource);
  104152. } ov_callbacks;
  104153. #define NOTOPEN 0
  104154. #define PARTOPEN 1
  104155. #define OPENED 2
  104156. #define STREAMSET 3
  104157. #define INITSET 4
  104158. typedef struct OggVorbis_File {
  104159. void *datasource; /* Pointer to a FILE *, etc. */
  104160. int seekable;
  104161. ogg_int64_t offset;
  104162. ogg_int64_t end;
  104163. ogg_sync_state oy;
  104164. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  104165. stream appears */
  104166. int links;
  104167. ogg_int64_t *offsets;
  104168. ogg_int64_t *dataoffsets;
  104169. long *serialnos;
  104170. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  104171. compatability; x2 size, stores both
  104172. beginning and end values */
  104173. vorbis_info *vi;
  104174. vorbis_comment *vc;
  104175. /* Decoding working state local storage */
  104176. ogg_int64_t pcm_offset;
  104177. int ready_state;
  104178. long current_serialno;
  104179. int current_link;
  104180. double bittrack;
  104181. double samptrack;
  104182. ogg_stream_state os; /* take physical pages, weld into a logical
  104183. stream of packets */
  104184. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  104185. vorbis_block vb; /* local working space for packet->PCM decode */
  104186. ov_callbacks callbacks;
  104187. } OggVorbis_File;
  104188. extern int ov_clear(OggVorbis_File *vf);
  104189. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104190. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  104191. char *initial, long ibytes, ov_callbacks callbacks);
  104192. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104193. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  104194. char *initial, long ibytes, ov_callbacks callbacks);
  104195. extern int ov_test_open(OggVorbis_File *vf);
  104196. extern long ov_bitrate(OggVorbis_File *vf,int i);
  104197. extern long ov_bitrate_instant(OggVorbis_File *vf);
  104198. extern long ov_streams(OggVorbis_File *vf);
  104199. extern long ov_seekable(OggVorbis_File *vf);
  104200. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  104201. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  104202. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  104203. extern double ov_time_total(OggVorbis_File *vf,int i);
  104204. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104205. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104206. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  104207. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  104208. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  104209. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104210. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104211. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104212. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  104213. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  104214. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  104215. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  104216. extern double ov_time_tell(OggVorbis_File *vf);
  104217. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  104218. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  104219. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  104220. int *bitstream);
  104221. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  104222. int bigendianp,int word,int sgned,int *bitstream);
  104223. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  104224. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  104225. extern int ov_halfrate_p(OggVorbis_File *vf);
  104226. #ifdef __cplusplus
  104227. }
  104228. #endif /* __cplusplus */
  104229. #endif
  104230. /*** End of inlined file: vorbisfile.h ***/
  104231. /*** Start of inlined file: bitwise.c ***/
  104232. /* We're 'LSb' endian; if we write a word but read individual bits,
  104233. then we'll read the lsb first */
  104234. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  104235. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104236. // tasks..
  104237. #if JUCE_MSVC
  104238. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104239. #endif
  104240. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  104241. #if JUCE_USE_OGGVORBIS
  104242. #include <string.h>
  104243. #include <stdlib.h>
  104244. #define BUFFER_INCREMENT 256
  104245. static const unsigned long mask[]=
  104246. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  104247. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  104248. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  104249. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  104250. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  104251. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  104252. 0x3fffffff,0x7fffffff,0xffffffff };
  104253. static const unsigned int mask8B[]=
  104254. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  104255. void oggpack_writeinit(oggpack_buffer *b){
  104256. memset(b,0,sizeof(*b));
  104257. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  104258. b->buffer[0]='\0';
  104259. b->storage=BUFFER_INCREMENT;
  104260. }
  104261. void oggpackB_writeinit(oggpack_buffer *b){
  104262. oggpack_writeinit(b);
  104263. }
  104264. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  104265. long bytes=bits>>3;
  104266. bits-=bytes*8;
  104267. b->ptr=b->buffer+bytes;
  104268. b->endbit=bits;
  104269. b->endbyte=bytes;
  104270. *b->ptr&=mask[bits];
  104271. }
  104272. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  104273. long bytes=bits>>3;
  104274. bits-=bytes*8;
  104275. b->ptr=b->buffer+bytes;
  104276. b->endbit=bits;
  104277. b->endbyte=bytes;
  104278. *b->ptr&=mask8B[bits];
  104279. }
  104280. /* Takes only up to 32 bits. */
  104281. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  104282. if(b->endbyte+4>=b->storage){
  104283. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104284. b->storage+=BUFFER_INCREMENT;
  104285. b->ptr=b->buffer+b->endbyte;
  104286. }
  104287. value&=mask[bits];
  104288. bits+=b->endbit;
  104289. b->ptr[0]|=value<<b->endbit;
  104290. if(bits>=8){
  104291. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  104292. if(bits>=16){
  104293. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  104294. if(bits>=24){
  104295. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  104296. if(bits>=32){
  104297. if(b->endbit)
  104298. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  104299. else
  104300. b->ptr[4]=0;
  104301. }
  104302. }
  104303. }
  104304. }
  104305. b->endbyte+=bits/8;
  104306. b->ptr+=bits/8;
  104307. b->endbit=bits&7;
  104308. }
  104309. /* Takes only up to 32 bits. */
  104310. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  104311. if(b->endbyte+4>=b->storage){
  104312. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104313. b->storage+=BUFFER_INCREMENT;
  104314. b->ptr=b->buffer+b->endbyte;
  104315. }
  104316. value=(value&mask[bits])<<(32-bits);
  104317. bits+=b->endbit;
  104318. b->ptr[0]|=value>>(24+b->endbit);
  104319. if(bits>=8){
  104320. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  104321. if(bits>=16){
  104322. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  104323. if(bits>=24){
  104324. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  104325. if(bits>=32){
  104326. if(b->endbit)
  104327. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  104328. else
  104329. b->ptr[4]=0;
  104330. }
  104331. }
  104332. }
  104333. }
  104334. b->endbyte+=bits/8;
  104335. b->ptr+=bits/8;
  104336. b->endbit=bits&7;
  104337. }
  104338. void oggpack_writealign(oggpack_buffer *b){
  104339. int bits=8-b->endbit;
  104340. if(bits<8)
  104341. oggpack_write(b,0,bits);
  104342. }
  104343. void oggpackB_writealign(oggpack_buffer *b){
  104344. int bits=8-b->endbit;
  104345. if(bits<8)
  104346. oggpackB_write(b,0,bits);
  104347. }
  104348. static void oggpack_writecopy_helper(oggpack_buffer *b,
  104349. void *source,
  104350. long bits,
  104351. void (*w)(oggpack_buffer *,
  104352. unsigned long,
  104353. int),
  104354. int msb){
  104355. unsigned char *ptr=(unsigned char *)source;
  104356. long bytes=bits/8;
  104357. bits-=bytes*8;
  104358. if(b->endbit){
  104359. int i;
  104360. /* unaligned copy. Do it the hard way. */
  104361. for(i=0;i<bytes;i++)
  104362. w(b,(unsigned long)(ptr[i]),8);
  104363. }else{
  104364. /* aligned block copy */
  104365. if(b->endbyte+bytes+1>=b->storage){
  104366. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  104367. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  104368. b->ptr=b->buffer+b->endbyte;
  104369. }
  104370. memmove(b->ptr,source,bytes);
  104371. b->ptr+=bytes;
  104372. b->endbyte+=bytes;
  104373. *b->ptr=0;
  104374. }
  104375. if(bits){
  104376. if(msb)
  104377. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  104378. else
  104379. w(b,(unsigned long)(ptr[bytes]),bits);
  104380. }
  104381. }
  104382. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  104383. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  104384. }
  104385. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  104386. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  104387. }
  104388. void oggpack_reset(oggpack_buffer *b){
  104389. b->ptr=b->buffer;
  104390. b->buffer[0]=0;
  104391. b->endbit=b->endbyte=0;
  104392. }
  104393. void oggpackB_reset(oggpack_buffer *b){
  104394. oggpack_reset(b);
  104395. }
  104396. void oggpack_writeclear(oggpack_buffer *b){
  104397. _ogg_free(b->buffer);
  104398. memset(b,0,sizeof(*b));
  104399. }
  104400. void oggpackB_writeclear(oggpack_buffer *b){
  104401. oggpack_writeclear(b);
  104402. }
  104403. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  104404. memset(b,0,sizeof(*b));
  104405. b->buffer=b->ptr=buf;
  104406. b->storage=bytes;
  104407. }
  104408. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  104409. oggpack_readinit(b,buf,bytes);
  104410. }
  104411. /* Read in bits without advancing the bitptr; bits <= 32 */
  104412. long oggpack_look(oggpack_buffer *b,int bits){
  104413. unsigned long ret;
  104414. unsigned long m=mask[bits];
  104415. bits+=b->endbit;
  104416. if(b->endbyte+4>=b->storage){
  104417. /* not the main path */
  104418. if(b->endbyte*8+bits>b->storage*8)return(-1);
  104419. }
  104420. ret=b->ptr[0]>>b->endbit;
  104421. if(bits>8){
  104422. ret|=b->ptr[1]<<(8-b->endbit);
  104423. if(bits>16){
  104424. ret|=b->ptr[2]<<(16-b->endbit);
  104425. if(bits>24){
  104426. ret|=b->ptr[3]<<(24-b->endbit);
  104427. if(bits>32 && b->endbit)
  104428. ret|=b->ptr[4]<<(32-b->endbit);
  104429. }
  104430. }
  104431. }
  104432. return(m&ret);
  104433. }
  104434. /* Read in bits without advancing the bitptr; bits <= 32 */
  104435. long oggpackB_look(oggpack_buffer *b,int bits){
  104436. unsigned long ret;
  104437. int m=32-bits;
  104438. bits+=b->endbit;
  104439. if(b->endbyte+4>=b->storage){
  104440. /* not the main path */
  104441. if(b->endbyte*8+bits>b->storage*8)return(-1);
  104442. }
  104443. ret=b->ptr[0]<<(24+b->endbit);
  104444. if(bits>8){
  104445. ret|=b->ptr[1]<<(16+b->endbit);
  104446. if(bits>16){
  104447. ret|=b->ptr[2]<<(8+b->endbit);
  104448. if(bits>24){
  104449. ret|=b->ptr[3]<<(b->endbit);
  104450. if(bits>32 && b->endbit)
  104451. ret|=b->ptr[4]>>(8-b->endbit);
  104452. }
  104453. }
  104454. }
  104455. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  104456. }
  104457. long oggpack_look1(oggpack_buffer *b){
  104458. if(b->endbyte>=b->storage)return(-1);
  104459. return((b->ptr[0]>>b->endbit)&1);
  104460. }
  104461. long oggpackB_look1(oggpack_buffer *b){
  104462. if(b->endbyte>=b->storage)return(-1);
  104463. return((b->ptr[0]>>(7-b->endbit))&1);
  104464. }
  104465. void oggpack_adv(oggpack_buffer *b,int bits){
  104466. bits+=b->endbit;
  104467. b->ptr+=bits/8;
  104468. b->endbyte+=bits/8;
  104469. b->endbit=bits&7;
  104470. }
  104471. void oggpackB_adv(oggpack_buffer *b,int bits){
  104472. oggpack_adv(b,bits);
  104473. }
  104474. void oggpack_adv1(oggpack_buffer *b){
  104475. if(++(b->endbit)>7){
  104476. b->endbit=0;
  104477. b->ptr++;
  104478. b->endbyte++;
  104479. }
  104480. }
  104481. void oggpackB_adv1(oggpack_buffer *b){
  104482. oggpack_adv1(b);
  104483. }
  104484. /* bits <= 32 */
  104485. long oggpack_read(oggpack_buffer *b,int bits){
  104486. long ret;
  104487. unsigned long m=mask[bits];
  104488. bits+=b->endbit;
  104489. if(b->endbyte+4>=b->storage){
  104490. /* not the main path */
  104491. ret=-1L;
  104492. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  104493. }
  104494. ret=b->ptr[0]>>b->endbit;
  104495. if(bits>8){
  104496. ret|=b->ptr[1]<<(8-b->endbit);
  104497. if(bits>16){
  104498. ret|=b->ptr[2]<<(16-b->endbit);
  104499. if(bits>24){
  104500. ret|=b->ptr[3]<<(24-b->endbit);
  104501. if(bits>32 && b->endbit){
  104502. ret|=b->ptr[4]<<(32-b->endbit);
  104503. }
  104504. }
  104505. }
  104506. }
  104507. ret&=m;
  104508. overflow:
  104509. b->ptr+=bits/8;
  104510. b->endbyte+=bits/8;
  104511. b->endbit=bits&7;
  104512. return(ret);
  104513. }
  104514. /* bits <= 32 */
  104515. long oggpackB_read(oggpack_buffer *b,int bits){
  104516. long ret;
  104517. long m=32-bits;
  104518. bits+=b->endbit;
  104519. if(b->endbyte+4>=b->storage){
  104520. /* not the main path */
  104521. ret=-1L;
  104522. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  104523. }
  104524. ret=b->ptr[0]<<(24+b->endbit);
  104525. if(bits>8){
  104526. ret|=b->ptr[1]<<(16+b->endbit);
  104527. if(bits>16){
  104528. ret|=b->ptr[2]<<(8+b->endbit);
  104529. if(bits>24){
  104530. ret|=b->ptr[3]<<(b->endbit);
  104531. if(bits>32 && b->endbit)
  104532. ret|=b->ptr[4]>>(8-b->endbit);
  104533. }
  104534. }
  104535. }
  104536. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  104537. overflow:
  104538. b->ptr+=bits/8;
  104539. b->endbyte+=bits/8;
  104540. b->endbit=bits&7;
  104541. return(ret);
  104542. }
  104543. long oggpack_read1(oggpack_buffer *b){
  104544. long ret;
  104545. if(b->endbyte>=b->storage){
  104546. /* not the main path */
  104547. ret=-1L;
  104548. goto overflow;
  104549. }
  104550. ret=(b->ptr[0]>>b->endbit)&1;
  104551. overflow:
  104552. b->endbit++;
  104553. if(b->endbit>7){
  104554. b->endbit=0;
  104555. b->ptr++;
  104556. b->endbyte++;
  104557. }
  104558. return(ret);
  104559. }
  104560. long oggpackB_read1(oggpack_buffer *b){
  104561. long ret;
  104562. if(b->endbyte>=b->storage){
  104563. /* not the main path */
  104564. ret=-1L;
  104565. goto overflow;
  104566. }
  104567. ret=(b->ptr[0]>>(7-b->endbit))&1;
  104568. overflow:
  104569. b->endbit++;
  104570. if(b->endbit>7){
  104571. b->endbit=0;
  104572. b->ptr++;
  104573. b->endbyte++;
  104574. }
  104575. return(ret);
  104576. }
  104577. long oggpack_bytes(oggpack_buffer *b){
  104578. return(b->endbyte+(b->endbit+7)/8);
  104579. }
  104580. long oggpack_bits(oggpack_buffer *b){
  104581. return(b->endbyte*8+b->endbit);
  104582. }
  104583. long oggpackB_bytes(oggpack_buffer *b){
  104584. return oggpack_bytes(b);
  104585. }
  104586. long oggpackB_bits(oggpack_buffer *b){
  104587. return oggpack_bits(b);
  104588. }
  104589. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  104590. return(b->buffer);
  104591. }
  104592. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  104593. return oggpack_get_buffer(b);
  104594. }
  104595. /* Self test of the bitwise routines; everything else is based on
  104596. them, so they damned well better be solid. */
  104597. #ifdef _V_SELFTEST
  104598. #include <stdio.h>
  104599. static int ilog(unsigned int v){
  104600. int ret=0;
  104601. while(v){
  104602. ret++;
  104603. v>>=1;
  104604. }
  104605. return(ret);
  104606. }
  104607. oggpack_buffer o;
  104608. oggpack_buffer r;
  104609. void report(char *in){
  104610. fprintf(stderr,"%s",in);
  104611. exit(1);
  104612. }
  104613. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  104614. long bytes,i;
  104615. unsigned char *buffer;
  104616. oggpack_reset(&o);
  104617. for(i=0;i<vals;i++)
  104618. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  104619. buffer=oggpack_get_buffer(&o);
  104620. bytes=oggpack_bytes(&o);
  104621. if(bytes!=compsize)report("wrong number of bytes!\n");
  104622. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  104623. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  104624. report("wrote incorrect value!\n");
  104625. }
  104626. oggpack_readinit(&r,buffer,bytes);
  104627. for(i=0;i<vals;i++){
  104628. int tbit=bits?bits:ilog(b[i]);
  104629. if(oggpack_look(&r,tbit)==-1)
  104630. report("out of data!\n");
  104631. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  104632. report("looked at incorrect value!\n");
  104633. if(tbit==1)
  104634. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  104635. report("looked at single bit incorrect value!\n");
  104636. if(tbit==1){
  104637. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  104638. report("read incorrect single bit value!\n");
  104639. }else{
  104640. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  104641. report("read incorrect value!\n");
  104642. }
  104643. }
  104644. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104645. }
  104646. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  104647. long bytes,i;
  104648. unsigned char *buffer;
  104649. oggpackB_reset(&o);
  104650. for(i=0;i<vals;i++)
  104651. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  104652. buffer=oggpackB_get_buffer(&o);
  104653. bytes=oggpackB_bytes(&o);
  104654. if(bytes!=compsize)report("wrong number of bytes!\n");
  104655. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  104656. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  104657. report("wrote incorrect value!\n");
  104658. }
  104659. oggpackB_readinit(&r,buffer,bytes);
  104660. for(i=0;i<vals;i++){
  104661. int tbit=bits?bits:ilog(b[i]);
  104662. if(oggpackB_look(&r,tbit)==-1)
  104663. report("out of data!\n");
  104664. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  104665. report("looked at incorrect value!\n");
  104666. if(tbit==1)
  104667. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  104668. report("looked at single bit incorrect value!\n");
  104669. if(tbit==1){
  104670. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  104671. report("read incorrect single bit value!\n");
  104672. }else{
  104673. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  104674. report("read incorrect value!\n");
  104675. }
  104676. }
  104677. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104678. }
  104679. int main(void){
  104680. unsigned char *buffer;
  104681. long bytes,i;
  104682. static unsigned long testbuffer1[]=
  104683. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  104684. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  104685. int test1size=43;
  104686. static unsigned long testbuffer2[]=
  104687. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  104688. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  104689. 85525151,0,12321,1,349528352};
  104690. int test2size=21;
  104691. static unsigned long testbuffer3[]=
  104692. {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,
  104693. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  104694. int test3size=56;
  104695. static unsigned long large[]=
  104696. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  104697. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  104698. 85525151,0,12321,1,2146528352};
  104699. int onesize=33;
  104700. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  104701. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  104702. 223,4};
  104703. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  104704. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  104705. 245,251,128};
  104706. int twosize=6;
  104707. static int two[6]={61,255,255,251,231,29};
  104708. static int twoB[6]={247,63,255,253,249,120};
  104709. int threesize=54;
  104710. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  104711. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  104712. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  104713. 100,52,4,14,18,86,77,1};
  104714. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  104715. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  104716. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  104717. 200,20,254,4,58,106,176,144,0};
  104718. int foursize=38;
  104719. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  104720. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  104721. 28,2,133,0,1};
  104722. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  104723. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  104724. 129,10,4,32};
  104725. int fivesize=45;
  104726. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  104727. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  104728. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  104729. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  104730. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  104731. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  104732. int sixsize=7;
  104733. static int six[7]={17,177,170,242,169,19,148};
  104734. static int sixB[7]={136,141,85,79,149,200,41};
  104735. /* Test read/write together */
  104736. /* Later we test against pregenerated bitstreams */
  104737. oggpack_writeinit(&o);
  104738. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  104739. cliptest(testbuffer1,test1size,0,one,onesize);
  104740. fprintf(stderr,"ok.");
  104741. fprintf(stderr,"\nNull bit call (LSb): ");
  104742. cliptest(testbuffer3,test3size,0,two,twosize);
  104743. fprintf(stderr,"ok.");
  104744. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  104745. cliptest(testbuffer2,test2size,0,three,threesize);
  104746. fprintf(stderr,"ok.");
  104747. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  104748. oggpack_reset(&o);
  104749. for(i=0;i<test2size;i++)
  104750. oggpack_write(&o,large[i],32);
  104751. buffer=oggpack_get_buffer(&o);
  104752. bytes=oggpack_bytes(&o);
  104753. oggpack_readinit(&r,buffer,bytes);
  104754. for(i=0;i<test2size;i++){
  104755. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  104756. if(oggpack_look(&r,32)!=large[i]){
  104757. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  104758. oggpack_look(&r,32),large[i]);
  104759. report("read incorrect value!\n");
  104760. }
  104761. oggpack_adv(&r,32);
  104762. }
  104763. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104764. fprintf(stderr,"ok.");
  104765. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  104766. cliptest(testbuffer1,test1size,7,four,foursize);
  104767. fprintf(stderr,"ok.");
  104768. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  104769. cliptest(testbuffer2,test2size,17,five,fivesize);
  104770. fprintf(stderr,"ok.");
  104771. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  104772. cliptest(testbuffer3,test3size,1,six,sixsize);
  104773. fprintf(stderr,"ok.");
  104774. fprintf(stderr,"\nTesting read past end (LSb): ");
  104775. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104776. for(i=0;i<64;i++){
  104777. if(oggpack_read(&r,1)!=0){
  104778. fprintf(stderr,"failed; got -1 prematurely.\n");
  104779. exit(1);
  104780. }
  104781. }
  104782. if(oggpack_look(&r,1)!=-1 ||
  104783. oggpack_read(&r,1)!=-1){
  104784. fprintf(stderr,"failed; read past end without -1.\n");
  104785. exit(1);
  104786. }
  104787. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104788. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  104789. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104790. exit(1);
  104791. }
  104792. if(oggpack_look(&r,18)!=0 ||
  104793. oggpack_look(&r,18)!=0){
  104794. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104795. exit(1);
  104796. }
  104797. if(oggpack_look(&r,19)!=-1 ||
  104798. oggpack_look(&r,19)!=-1){
  104799. fprintf(stderr,"failed; read past end without -1.\n");
  104800. exit(1);
  104801. }
  104802. if(oggpack_look(&r,32)!=-1 ||
  104803. oggpack_look(&r,32)!=-1){
  104804. fprintf(stderr,"failed; read past end without -1.\n");
  104805. exit(1);
  104806. }
  104807. oggpack_writeclear(&o);
  104808. fprintf(stderr,"ok.\n");
  104809. /********** lazy, cut-n-paste retest with MSb packing ***********/
  104810. /* Test read/write together */
  104811. /* Later we test against pregenerated bitstreams */
  104812. oggpackB_writeinit(&o);
  104813. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  104814. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  104815. fprintf(stderr,"ok.");
  104816. fprintf(stderr,"\nNull bit call (MSb): ");
  104817. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  104818. fprintf(stderr,"ok.");
  104819. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  104820. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  104821. fprintf(stderr,"ok.");
  104822. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  104823. oggpackB_reset(&o);
  104824. for(i=0;i<test2size;i++)
  104825. oggpackB_write(&o,large[i],32);
  104826. buffer=oggpackB_get_buffer(&o);
  104827. bytes=oggpackB_bytes(&o);
  104828. oggpackB_readinit(&r,buffer,bytes);
  104829. for(i=0;i<test2size;i++){
  104830. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  104831. if(oggpackB_look(&r,32)!=large[i]){
  104832. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  104833. oggpackB_look(&r,32),large[i]);
  104834. report("read incorrect value!\n");
  104835. }
  104836. oggpackB_adv(&r,32);
  104837. }
  104838. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104839. fprintf(stderr,"ok.");
  104840. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  104841. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  104842. fprintf(stderr,"ok.");
  104843. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  104844. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  104845. fprintf(stderr,"ok.");
  104846. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  104847. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  104848. fprintf(stderr,"ok.");
  104849. fprintf(stderr,"\nTesting read past end (MSb): ");
  104850. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104851. for(i=0;i<64;i++){
  104852. if(oggpackB_read(&r,1)!=0){
  104853. fprintf(stderr,"failed; got -1 prematurely.\n");
  104854. exit(1);
  104855. }
  104856. }
  104857. if(oggpackB_look(&r,1)!=-1 ||
  104858. oggpackB_read(&r,1)!=-1){
  104859. fprintf(stderr,"failed; read past end without -1.\n");
  104860. exit(1);
  104861. }
  104862. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104863. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  104864. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104865. exit(1);
  104866. }
  104867. if(oggpackB_look(&r,18)!=0 ||
  104868. oggpackB_look(&r,18)!=0){
  104869. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104870. exit(1);
  104871. }
  104872. if(oggpackB_look(&r,19)!=-1 ||
  104873. oggpackB_look(&r,19)!=-1){
  104874. fprintf(stderr,"failed; read past end without -1.\n");
  104875. exit(1);
  104876. }
  104877. if(oggpackB_look(&r,32)!=-1 ||
  104878. oggpackB_look(&r,32)!=-1){
  104879. fprintf(stderr,"failed; read past end without -1.\n");
  104880. exit(1);
  104881. }
  104882. oggpackB_writeclear(&o);
  104883. fprintf(stderr,"ok.\n\n");
  104884. return(0);
  104885. }
  104886. #endif /* _V_SELFTEST */
  104887. #undef BUFFER_INCREMENT
  104888. #endif
  104889. /*** End of inlined file: bitwise.c ***/
  104890. /*** Start of inlined file: framing.c ***/
  104891. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  104892. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104893. // tasks..
  104894. #if JUCE_MSVC
  104895. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104896. #endif
  104897. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  104898. #if JUCE_USE_OGGVORBIS
  104899. #include <stdlib.h>
  104900. #include <string.h>
  104901. /* A complete description of Ogg framing exists in docs/framing.html */
  104902. int ogg_page_version(ogg_page *og){
  104903. return((int)(og->header[4]));
  104904. }
  104905. int ogg_page_continued(ogg_page *og){
  104906. return((int)(og->header[5]&0x01));
  104907. }
  104908. int ogg_page_bos(ogg_page *og){
  104909. return((int)(og->header[5]&0x02));
  104910. }
  104911. int ogg_page_eos(ogg_page *og){
  104912. return((int)(og->header[5]&0x04));
  104913. }
  104914. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  104915. unsigned char *page=og->header;
  104916. ogg_int64_t granulepos=page[13]&(0xff);
  104917. granulepos= (granulepos<<8)|(page[12]&0xff);
  104918. granulepos= (granulepos<<8)|(page[11]&0xff);
  104919. granulepos= (granulepos<<8)|(page[10]&0xff);
  104920. granulepos= (granulepos<<8)|(page[9]&0xff);
  104921. granulepos= (granulepos<<8)|(page[8]&0xff);
  104922. granulepos= (granulepos<<8)|(page[7]&0xff);
  104923. granulepos= (granulepos<<8)|(page[6]&0xff);
  104924. return(granulepos);
  104925. }
  104926. int ogg_page_serialno(ogg_page *og){
  104927. return(og->header[14] |
  104928. (og->header[15]<<8) |
  104929. (og->header[16]<<16) |
  104930. (og->header[17]<<24));
  104931. }
  104932. long ogg_page_pageno(ogg_page *og){
  104933. return(og->header[18] |
  104934. (og->header[19]<<8) |
  104935. (og->header[20]<<16) |
  104936. (og->header[21]<<24));
  104937. }
  104938. /* returns the number of packets that are completed on this page (if
  104939. the leading packet is begun on a previous page, but ends on this
  104940. page, it's counted */
  104941. /* NOTE:
  104942. If a page consists of a packet begun on a previous page, and a new
  104943. packet begun (but not completed) on this page, the return will be:
  104944. ogg_page_packets(page) ==1,
  104945. ogg_page_continued(page) !=0
  104946. If a page happens to be a single packet that was begun on a
  104947. previous page, and spans to the next page (in the case of a three or
  104948. more page packet), the return will be:
  104949. ogg_page_packets(page) ==0,
  104950. ogg_page_continued(page) !=0
  104951. */
  104952. int ogg_page_packets(ogg_page *og){
  104953. int i,n=og->header[26],count=0;
  104954. for(i=0;i<n;i++)
  104955. if(og->header[27+i]<255)count++;
  104956. return(count);
  104957. }
  104958. #if 0
  104959. /* helper to initialize lookup for direct-table CRC (illustrative; we
  104960. use the static init below) */
  104961. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  104962. int i;
  104963. unsigned long r;
  104964. r = index << 24;
  104965. for (i=0; i<8; i++)
  104966. if (r & 0x80000000UL)
  104967. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  104968. polynomial, although we use an
  104969. unreflected alg and an init/final
  104970. of 0, not 0xffffffff */
  104971. else
  104972. r<<=1;
  104973. return (r & 0xffffffffUL);
  104974. }
  104975. #endif
  104976. static const ogg_uint32_t crc_lookup[256]={
  104977. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  104978. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  104979. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  104980. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  104981. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  104982. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  104983. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  104984. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  104985. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  104986. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  104987. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  104988. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  104989. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  104990. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  104991. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  104992. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  104993. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  104994. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  104995. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  104996. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  104997. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  104998. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  104999. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  105000. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  105001. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  105002. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  105003. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  105004. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  105005. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  105006. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  105007. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  105008. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  105009. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  105010. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  105011. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  105012. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  105013. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  105014. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  105015. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  105016. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  105017. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  105018. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  105019. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  105020. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  105021. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  105022. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  105023. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  105024. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  105025. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  105026. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  105027. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  105028. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  105029. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  105030. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  105031. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  105032. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  105033. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  105034. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  105035. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  105036. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  105037. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  105038. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  105039. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  105040. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  105041. /* init the encode/decode logical stream state */
  105042. int ogg_stream_init(ogg_stream_state *os,int serialno){
  105043. if(os){
  105044. memset(os,0,sizeof(*os));
  105045. os->body_storage=16*1024;
  105046. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  105047. os->lacing_storage=1024;
  105048. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  105049. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  105050. os->serialno=serialno;
  105051. return(0);
  105052. }
  105053. return(-1);
  105054. }
  105055. /* _clear does not free os, only the non-flat storage within */
  105056. int ogg_stream_clear(ogg_stream_state *os){
  105057. if(os){
  105058. if(os->body_data)_ogg_free(os->body_data);
  105059. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  105060. if(os->granule_vals)_ogg_free(os->granule_vals);
  105061. memset(os,0,sizeof(*os));
  105062. }
  105063. return(0);
  105064. }
  105065. int ogg_stream_destroy(ogg_stream_state *os){
  105066. if(os){
  105067. ogg_stream_clear(os);
  105068. _ogg_free(os);
  105069. }
  105070. return(0);
  105071. }
  105072. /* Helpers for ogg_stream_encode; this keeps the structure and
  105073. what's happening fairly clear */
  105074. static void _os_body_expand(ogg_stream_state *os,int needed){
  105075. if(os->body_storage<=os->body_fill+needed){
  105076. os->body_storage+=(needed+1024);
  105077. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  105078. }
  105079. }
  105080. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  105081. if(os->lacing_storage<=os->lacing_fill+needed){
  105082. os->lacing_storage+=(needed+32);
  105083. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  105084. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  105085. }
  105086. }
  105087. /* checksum the page */
  105088. /* Direct table CRC; note that this will be faster in the future if we
  105089. perform the checksum silmultaneously with other copies */
  105090. void ogg_page_checksum_set(ogg_page *og){
  105091. if(og){
  105092. ogg_uint32_t crc_reg=0;
  105093. int i;
  105094. /* safety; needed for API behavior, but not framing code */
  105095. og->header[22]=0;
  105096. og->header[23]=0;
  105097. og->header[24]=0;
  105098. og->header[25]=0;
  105099. for(i=0;i<og->header_len;i++)
  105100. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  105101. for(i=0;i<og->body_len;i++)
  105102. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  105103. og->header[22]=(unsigned char)(crc_reg&0xff);
  105104. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  105105. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  105106. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  105107. }
  105108. }
  105109. /* submit data to the internal buffer of the framing engine */
  105110. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  105111. int lacing_vals=op->bytes/255+1,i;
  105112. if(os->body_returned){
  105113. /* advance packet data according to the body_returned pointer. We
  105114. had to keep it around to return a pointer into the buffer last
  105115. call */
  105116. os->body_fill-=os->body_returned;
  105117. if(os->body_fill)
  105118. memmove(os->body_data,os->body_data+os->body_returned,
  105119. os->body_fill);
  105120. os->body_returned=0;
  105121. }
  105122. /* make sure we have the buffer storage */
  105123. _os_body_expand(os,op->bytes);
  105124. _os_lacing_expand(os,lacing_vals);
  105125. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  105126. the liability of overly clean abstraction for the time being. It
  105127. will actually be fairly easy to eliminate the extra copy in the
  105128. future */
  105129. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  105130. os->body_fill+=op->bytes;
  105131. /* Store lacing vals for this packet */
  105132. for(i=0;i<lacing_vals-1;i++){
  105133. os->lacing_vals[os->lacing_fill+i]=255;
  105134. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  105135. }
  105136. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  105137. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  105138. /* flag the first segment as the beginning of the packet */
  105139. os->lacing_vals[os->lacing_fill]|= 0x100;
  105140. os->lacing_fill+=lacing_vals;
  105141. /* for the sake of completeness */
  105142. os->packetno++;
  105143. if(op->e_o_s)os->e_o_s=1;
  105144. return(0);
  105145. }
  105146. /* This will flush remaining packets into a page (returning nonzero),
  105147. even if there is not enough data to trigger a flush normally
  105148. (undersized page). If there are no packets or partial packets to
  105149. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  105150. try to flush a normal sized page like ogg_stream_pageout; a call to
  105151. ogg_stream_flush does not guarantee that all packets have flushed.
  105152. Only a return value of 0 from ogg_stream_flush indicates all packet
  105153. data is flushed into pages.
  105154. since ogg_stream_flush will flush the last page in a stream even if
  105155. it's undersized, you almost certainly want to use ogg_stream_pageout
  105156. (and *not* ogg_stream_flush) unless you specifically need to flush
  105157. an page regardless of size in the middle of a stream. */
  105158. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  105159. int i;
  105160. int vals=0;
  105161. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  105162. int bytes=0;
  105163. long acc=0;
  105164. ogg_int64_t granule_pos=-1;
  105165. if(maxvals==0)return(0);
  105166. /* construct a page */
  105167. /* decide how many segments to include */
  105168. /* If this is the initial header case, the first page must only include
  105169. the initial header packet */
  105170. if(os->b_o_s==0){ /* 'initial header page' case */
  105171. granule_pos=0;
  105172. for(vals=0;vals<maxvals;vals++){
  105173. if((os->lacing_vals[vals]&0x0ff)<255){
  105174. vals++;
  105175. break;
  105176. }
  105177. }
  105178. }else{
  105179. for(vals=0;vals<maxvals;vals++){
  105180. if(acc>4096)break;
  105181. acc+=os->lacing_vals[vals]&0x0ff;
  105182. if((os->lacing_vals[vals]&0xff)<255)
  105183. granule_pos=os->granule_vals[vals];
  105184. }
  105185. }
  105186. /* construct the header in temp storage */
  105187. memcpy(os->header,"OggS",4);
  105188. /* stream structure version */
  105189. os->header[4]=0x00;
  105190. /* continued packet flag? */
  105191. os->header[5]=0x00;
  105192. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  105193. /* first page flag? */
  105194. if(os->b_o_s==0)os->header[5]|=0x02;
  105195. /* last page flag? */
  105196. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  105197. os->b_o_s=1;
  105198. /* 64 bits of PCM position */
  105199. for(i=6;i<14;i++){
  105200. os->header[i]=(unsigned char)(granule_pos&0xff);
  105201. granule_pos>>=8;
  105202. }
  105203. /* 32 bits of stream serial number */
  105204. {
  105205. long serialno=os->serialno;
  105206. for(i=14;i<18;i++){
  105207. os->header[i]=(unsigned char)(serialno&0xff);
  105208. serialno>>=8;
  105209. }
  105210. }
  105211. /* 32 bits of page counter (we have both counter and page header
  105212. because this val can roll over) */
  105213. if(os->pageno==-1)os->pageno=0; /* because someone called
  105214. stream_reset; this would be a
  105215. strange thing to do in an
  105216. encode stream, but it has
  105217. plausible uses */
  105218. {
  105219. long pageno=os->pageno++;
  105220. for(i=18;i<22;i++){
  105221. os->header[i]=(unsigned char)(pageno&0xff);
  105222. pageno>>=8;
  105223. }
  105224. }
  105225. /* zero for computation; filled in later */
  105226. os->header[22]=0;
  105227. os->header[23]=0;
  105228. os->header[24]=0;
  105229. os->header[25]=0;
  105230. /* segment table */
  105231. os->header[26]=(unsigned char)(vals&0xff);
  105232. for(i=0;i<vals;i++)
  105233. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  105234. /* set pointers in the ogg_page struct */
  105235. og->header=os->header;
  105236. og->header_len=os->header_fill=vals+27;
  105237. og->body=os->body_data+os->body_returned;
  105238. og->body_len=bytes;
  105239. /* advance the lacing data and set the body_returned pointer */
  105240. os->lacing_fill-=vals;
  105241. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  105242. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  105243. os->body_returned+=bytes;
  105244. /* calculate the checksum */
  105245. ogg_page_checksum_set(og);
  105246. /* done */
  105247. return(1);
  105248. }
  105249. /* This constructs pages from buffered packet segments. The pointers
  105250. returned are to static buffers; do not free. The returned buffers are
  105251. good only until the next call (using the same ogg_stream_state) */
  105252. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  105253. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  105254. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  105255. os->lacing_fill>=255 || /* 'segment table full' case */
  105256. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  105257. return(ogg_stream_flush(os,og));
  105258. }
  105259. /* not enough data to construct a page and not end of stream */
  105260. return(0);
  105261. }
  105262. int ogg_stream_eos(ogg_stream_state *os){
  105263. return os->e_o_s;
  105264. }
  105265. /* DECODING PRIMITIVES: packet streaming layer **********************/
  105266. /* This has two layers to place more of the multi-serialno and paging
  105267. control in the application's hands. First, we expose a data buffer
  105268. using ogg_sync_buffer(). The app either copies into the
  105269. buffer, or passes it directly to read(), etc. We then call
  105270. ogg_sync_wrote() to tell how many bytes we just added.
  105271. Pages are returned (pointers into the buffer in ogg_sync_state)
  105272. by ogg_sync_pageout(). The page is then submitted to
  105273. ogg_stream_pagein() along with the appropriate
  105274. ogg_stream_state* (ie, matching serialno). We then get raw
  105275. packets out calling ogg_stream_packetout() with a
  105276. ogg_stream_state. */
  105277. /* initialize the struct to a known state */
  105278. int ogg_sync_init(ogg_sync_state *oy){
  105279. if(oy){
  105280. memset(oy,0,sizeof(*oy));
  105281. }
  105282. return(0);
  105283. }
  105284. /* clear non-flat storage within */
  105285. int ogg_sync_clear(ogg_sync_state *oy){
  105286. if(oy){
  105287. if(oy->data)_ogg_free(oy->data);
  105288. ogg_sync_init(oy);
  105289. }
  105290. return(0);
  105291. }
  105292. int ogg_sync_destroy(ogg_sync_state *oy){
  105293. if(oy){
  105294. ogg_sync_clear(oy);
  105295. _ogg_free(oy);
  105296. }
  105297. return(0);
  105298. }
  105299. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  105300. /* first, clear out any space that has been previously returned */
  105301. if(oy->returned){
  105302. oy->fill-=oy->returned;
  105303. if(oy->fill>0)
  105304. memmove(oy->data,oy->data+oy->returned,oy->fill);
  105305. oy->returned=0;
  105306. }
  105307. if(size>oy->storage-oy->fill){
  105308. /* We need to extend the internal buffer */
  105309. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  105310. if(oy->data)
  105311. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  105312. else
  105313. oy->data=(unsigned char*) _ogg_malloc(newsize);
  105314. oy->storage=newsize;
  105315. }
  105316. /* expose a segment at least as large as requested at the fill mark */
  105317. return((char *)oy->data+oy->fill);
  105318. }
  105319. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  105320. if(oy->fill+bytes>oy->storage)return(-1);
  105321. oy->fill+=bytes;
  105322. return(0);
  105323. }
  105324. /* sync the stream. This is meant to be useful for finding page
  105325. boundaries.
  105326. return values for this:
  105327. -n) skipped n bytes
  105328. 0) page not ready; more data (no bytes skipped)
  105329. n) page synced at current location; page length n bytes
  105330. */
  105331. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  105332. unsigned char *page=oy->data+oy->returned;
  105333. unsigned char *next;
  105334. long bytes=oy->fill-oy->returned;
  105335. if(oy->headerbytes==0){
  105336. int headerbytes,i;
  105337. if(bytes<27)return(0); /* not enough for a header */
  105338. /* verify capture pattern */
  105339. if(memcmp(page,"OggS",4))goto sync_fail;
  105340. headerbytes=page[26]+27;
  105341. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  105342. /* count up body length in the segment table */
  105343. for(i=0;i<page[26];i++)
  105344. oy->bodybytes+=page[27+i];
  105345. oy->headerbytes=headerbytes;
  105346. }
  105347. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  105348. /* The whole test page is buffered. Verify the checksum */
  105349. {
  105350. /* Grab the checksum bytes, set the header field to zero */
  105351. char chksum[4];
  105352. ogg_page log;
  105353. memcpy(chksum,page+22,4);
  105354. memset(page+22,0,4);
  105355. /* set up a temp page struct and recompute the checksum */
  105356. log.header=page;
  105357. log.header_len=oy->headerbytes;
  105358. log.body=page+oy->headerbytes;
  105359. log.body_len=oy->bodybytes;
  105360. ogg_page_checksum_set(&log);
  105361. /* Compare */
  105362. if(memcmp(chksum,page+22,4)){
  105363. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  105364. at all) */
  105365. /* replace the computed checksum with the one actually read in */
  105366. memcpy(page+22,chksum,4);
  105367. /* Bad checksum. Lose sync */
  105368. goto sync_fail;
  105369. }
  105370. }
  105371. /* yes, have a whole page all ready to go */
  105372. {
  105373. unsigned char *page=oy->data+oy->returned;
  105374. long bytes;
  105375. if(og){
  105376. og->header=page;
  105377. og->header_len=oy->headerbytes;
  105378. og->body=page+oy->headerbytes;
  105379. og->body_len=oy->bodybytes;
  105380. }
  105381. oy->unsynced=0;
  105382. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  105383. oy->headerbytes=0;
  105384. oy->bodybytes=0;
  105385. return(bytes);
  105386. }
  105387. sync_fail:
  105388. oy->headerbytes=0;
  105389. oy->bodybytes=0;
  105390. /* search for possible capture */
  105391. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  105392. if(!next)
  105393. next=oy->data+oy->fill;
  105394. oy->returned=next-oy->data;
  105395. return(-(next-page));
  105396. }
  105397. /* sync the stream and get a page. Keep trying until we find a page.
  105398. Supress 'sync errors' after reporting the first.
  105399. return values:
  105400. -1) recapture (hole in data)
  105401. 0) need more data
  105402. 1) page returned
  105403. Returns pointers into buffered data; invalidated by next call to
  105404. _stream, _clear, _init, or _buffer */
  105405. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  105406. /* all we need to do is verify a page at the head of the stream
  105407. buffer. If it doesn't verify, we look for the next potential
  105408. frame */
  105409. for(;;){
  105410. long ret=ogg_sync_pageseek(oy,og);
  105411. if(ret>0){
  105412. /* have a page */
  105413. return(1);
  105414. }
  105415. if(ret==0){
  105416. /* need more data */
  105417. return(0);
  105418. }
  105419. /* head did not start a synced page... skipped some bytes */
  105420. if(!oy->unsynced){
  105421. oy->unsynced=1;
  105422. return(-1);
  105423. }
  105424. /* loop. keep looking */
  105425. }
  105426. }
  105427. /* add the incoming page to the stream state; we decompose the page
  105428. into packet segments here as well. */
  105429. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  105430. unsigned char *header=og->header;
  105431. unsigned char *body=og->body;
  105432. long bodysize=og->body_len;
  105433. int segptr=0;
  105434. int version=ogg_page_version(og);
  105435. int continued=ogg_page_continued(og);
  105436. int bos=ogg_page_bos(og);
  105437. int eos=ogg_page_eos(og);
  105438. ogg_int64_t granulepos=ogg_page_granulepos(og);
  105439. int serialno=ogg_page_serialno(og);
  105440. long pageno=ogg_page_pageno(og);
  105441. int segments=header[26];
  105442. /* clean up 'returned data' */
  105443. {
  105444. long lr=os->lacing_returned;
  105445. long br=os->body_returned;
  105446. /* body data */
  105447. if(br){
  105448. os->body_fill-=br;
  105449. if(os->body_fill)
  105450. memmove(os->body_data,os->body_data+br,os->body_fill);
  105451. os->body_returned=0;
  105452. }
  105453. if(lr){
  105454. /* segment table */
  105455. if(os->lacing_fill-lr){
  105456. memmove(os->lacing_vals,os->lacing_vals+lr,
  105457. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  105458. memmove(os->granule_vals,os->granule_vals+lr,
  105459. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  105460. }
  105461. os->lacing_fill-=lr;
  105462. os->lacing_packet-=lr;
  105463. os->lacing_returned=0;
  105464. }
  105465. }
  105466. /* check the serial number */
  105467. if(serialno!=os->serialno)return(-1);
  105468. if(version>0)return(-1);
  105469. _os_lacing_expand(os,segments+1);
  105470. /* are we in sequence? */
  105471. if(pageno!=os->pageno){
  105472. int i;
  105473. /* unroll previous partial packet (if any) */
  105474. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  105475. os->body_fill-=os->lacing_vals[i]&0xff;
  105476. os->lacing_fill=os->lacing_packet;
  105477. /* make a note of dropped data in segment table */
  105478. if(os->pageno!=-1){
  105479. os->lacing_vals[os->lacing_fill++]=0x400;
  105480. os->lacing_packet++;
  105481. }
  105482. }
  105483. /* are we a 'continued packet' page? If so, we may need to skip
  105484. some segments */
  105485. if(continued){
  105486. if(os->lacing_fill<1 ||
  105487. os->lacing_vals[os->lacing_fill-1]==0x400){
  105488. bos=0;
  105489. for(;segptr<segments;segptr++){
  105490. int val=header[27+segptr];
  105491. body+=val;
  105492. bodysize-=val;
  105493. if(val<255){
  105494. segptr++;
  105495. break;
  105496. }
  105497. }
  105498. }
  105499. }
  105500. if(bodysize){
  105501. _os_body_expand(os,bodysize);
  105502. memcpy(os->body_data+os->body_fill,body,bodysize);
  105503. os->body_fill+=bodysize;
  105504. }
  105505. {
  105506. int saved=-1;
  105507. while(segptr<segments){
  105508. int val=header[27+segptr];
  105509. os->lacing_vals[os->lacing_fill]=val;
  105510. os->granule_vals[os->lacing_fill]=-1;
  105511. if(bos){
  105512. os->lacing_vals[os->lacing_fill]|=0x100;
  105513. bos=0;
  105514. }
  105515. if(val<255)saved=os->lacing_fill;
  105516. os->lacing_fill++;
  105517. segptr++;
  105518. if(val<255)os->lacing_packet=os->lacing_fill;
  105519. }
  105520. /* set the granulepos on the last granuleval of the last full packet */
  105521. if(saved!=-1){
  105522. os->granule_vals[saved]=granulepos;
  105523. }
  105524. }
  105525. if(eos){
  105526. os->e_o_s=1;
  105527. if(os->lacing_fill>0)
  105528. os->lacing_vals[os->lacing_fill-1]|=0x200;
  105529. }
  105530. os->pageno=pageno+1;
  105531. return(0);
  105532. }
  105533. /* clear things to an initial state. Good to call, eg, before seeking */
  105534. int ogg_sync_reset(ogg_sync_state *oy){
  105535. oy->fill=0;
  105536. oy->returned=0;
  105537. oy->unsynced=0;
  105538. oy->headerbytes=0;
  105539. oy->bodybytes=0;
  105540. return(0);
  105541. }
  105542. int ogg_stream_reset(ogg_stream_state *os){
  105543. os->body_fill=0;
  105544. os->body_returned=0;
  105545. os->lacing_fill=0;
  105546. os->lacing_packet=0;
  105547. os->lacing_returned=0;
  105548. os->header_fill=0;
  105549. os->e_o_s=0;
  105550. os->b_o_s=0;
  105551. os->pageno=-1;
  105552. os->packetno=0;
  105553. os->granulepos=0;
  105554. return(0);
  105555. }
  105556. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  105557. ogg_stream_reset(os);
  105558. os->serialno=serialno;
  105559. return(0);
  105560. }
  105561. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  105562. /* The last part of decode. We have the stream broken into packet
  105563. segments. Now we need to group them into packets (or return the
  105564. out of sync markers) */
  105565. int ptr=os->lacing_returned;
  105566. if(os->lacing_packet<=ptr)return(0);
  105567. if(os->lacing_vals[ptr]&0x400){
  105568. /* we need to tell the codec there's a gap; it might need to
  105569. handle previous packet dependencies. */
  105570. os->lacing_returned++;
  105571. os->packetno++;
  105572. return(-1);
  105573. }
  105574. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  105575. to ask if there's a whole packet
  105576. waiting */
  105577. /* Gather the whole packet. We'll have no holes or a partial packet */
  105578. {
  105579. int size=os->lacing_vals[ptr]&0xff;
  105580. int bytes=size;
  105581. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  105582. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  105583. while(size==255){
  105584. int val=os->lacing_vals[++ptr];
  105585. size=val&0xff;
  105586. if(val&0x200)eos=0x200;
  105587. bytes+=size;
  105588. }
  105589. if(op){
  105590. op->e_o_s=eos;
  105591. op->b_o_s=bos;
  105592. op->packet=os->body_data+os->body_returned;
  105593. op->packetno=os->packetno;
  105594. op->granulepos=os->granule_vals[ptr];
  105595. op->bytes=bytes;
  105596. }
  105597. if(adv){
  105598. os->body_returned+=bytes;
  105599. os->lacing_returned=ptr+1;
  105600. os->packetno++;
  105601. }
  105602. }
  105603. return(1);
  105604. }
  105605. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  105606. return _packetout(os,op,1);
  105607. }
  105608. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  105609. return _packetout(os,op,0);
  105610. }
  105611. void ogg_packet_clear(ogg_packet *op) {
  105612. _ogg_free(op->packet);
  105613. memset(op, 0, sizeof(*op));
  105614. }
  105615. #ifdef _V_SELFTEST
  105616. #include <stdio.h>
  105617. ogg_stream_state os_en, os_de;
  105618. ogg_sync_state oy;
  105619. void checkpacket(ogg_packet *op,int len, int no, int pos){
  105620. long j;
  105621. static int sequence=0;
  105622. static int lastno=0;
  105623. if(op->bytes!=len){
  105624. fprintf(stderr,"incorrect packet length!\n");
  105625. exit(1);
  105626. }
  105627. if(op->granulepos!=pos){
  105628. fprintf(stderr,"incorrect packet position!\n");
  105629. exit(1);
  105630. }
  105631. /* packet number just follows sequence/gap; adjust the input number
  105632. for that */
  105633. if(no==0){
  105634. sequence=0;
  105635. }else{
  105636. sequence++;
  105637. if(no>lastno+1)
  105638. sequence++;
  105639. }
  105640. lastno=no;
  105641. if(op->packetno!=sequence){
  105642. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  105643. (long)(op->packetno),sequence);
  105644. exit(1);
  105645. }
  105646. /* Test data */
  105647. for(j=0;j<op->bytes;j++)
  105648. if(op->packet[j]!=((j+no)&0xff)){
  105649. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  105650. j,op->packet[j],(j+no)&0xff);
  105651. exit(1);
  105652. }
  105653. }
  105654. void check_page(unsigned char *data,const int *header,ogg_page *og){
  105655. long j;
  105656. /* Test data */
  105657. for(j=0;j<og->body_len;j++)
  105658. if(og->body[j]!=data[j]){
  105659. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  105660. j,data[j],og->body[j]);
  105661. exit(1);
  105662. }
  105663. /* Test header */
  105664. for(j=0;j<og->header_len;j++){
  105665. if(og->header[j]!=header[j]){
  105666. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  105667. for(j=0;j<header[26]+27;j++)
  105668. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  105669. fprintf(stderr,"\n");
  105670. exit(1);
  105671. }
  105672. }
  105673. if(og->header_len!=header[26]+27){
  105674. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  105675. og->header_len,header[26]+27);
  105676. exit(1);
  105677. }
  105678. }
  105679. void print_header(ogg_page *og){
  105680. int j;
  105681. fprintf(stderr,"\nHEADER:\n");
  105682. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  105683. og->header[0],og->header[1],og->header[2],og->header[3],
  105684. (int)og->header[4],(int)og->header[5]);
  105685. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  105686. (og->header[9]<<24)|(og->header[8]<<16)|
  105687. (og->header[7]<<8)|og->header[6],
  105688. (og->header[17]<<24)|(og->header[16]<<16)|
  105689. (og->header[15]<<8)|og->header[14],
  105690. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  105691. (og->header[19]<<8)|og->header[18]);
  105692. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  105693. (int)og->header[22],(int)og->header[23],
  105694. (int)og->header[24],(int)og->header[25],
  105695. (int)og->header[26]);
  105696. for(j=27;j<og->header_len;j++)
  105697. fprintf(stderr,"%d ",(int)og->header[j]);
  105698. fprintf(stderr,")\n\n");
  105699. }
  105700. void copy_page(ogg_page *og){
  105701. unsigned char *temp=_ogg_malloc(og->header_len);
  105702. memcpy(temp,og->header,og->header_len);
  105703. og->header=temp;
  105704. temp=_ogg_malloc(og->body_len);
  105705. memcpy(temp,og->body,og->body_len);
  105706. og->body=temp;
  105707. }
  105708. void free_page(ogg_page *og){
  105709. _ogg_free (og->header);
  105710. _ogg_free (og->body);
  105711. }
  105712. void error(void){
  105713. fprintf(stderr,"error!\n");
  105714. exit(1);
  105715. }
  105716. /* 17 only */
  105717. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  105718. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105719. 0x01,0x02,0x03,0x04,0,0,0,0,
  105720. 0x15,0xed,0xec,0x91,
  105721. 1,
  105722. 17};
  105723. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  105724. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105725. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105726. 0x01,0x02,0x03,0x04,0,0,0,0,
  105727. 0x59,0x10,0x6c,0x2c,
  105728. 1,
  105729. 17};
  105730. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105731. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  105732. 0x01,0x02,0x03,0x04,1,0,0,0,
  105733. 0x89,0x33,0x85,0xce,
  105734. 13,
  105735. 254,255,0,255,1,255,245,255,255,0,
  105736. 255,255,90};
  105737. /* nil packets; beginning,middle,end */
  105738. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105739. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105740. 0x01,0x02,0x03,0x04,0,0,0,0,
  105741. 0xff,0x7b,0x23,0x17,
  105742. 1,
  105743. 0};
  105744. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105745. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  105746. 0x01,0x02,0x03,0x04,1,0,0,0,
  105747. 0x5c,0x3f,0x66,0xcb,
  105748. 17,
  105749. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  105750. 255,255,90,0};
  105751. /* large initial packet */
  105752. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105753. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105754. 0x01,0x02,0x03,0x04,0,0,0,0,
  105755. 0x01,0x27,0x31,0xaa,
  105756. 18,
  105757. 255,255,255,255,255,255,255,255,
  105758. 255,255,255,255,255,255,255,255,255,10};
  105759. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105760. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105761. 0x01,0x02,0x03,0x04,1,0,0,0,
  105762. 0x7f,0x4e,0x8a,0xd2,
  105763. 4,
  105764. 255,4,255,0};
  105765. /* continuing packet test */
  105766. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105767. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105768. 0x01,0x02,0x03,0x04,0,0,0,0,
  105769. 0xff,0x7b,0x23,0x17,
  105770. 1,
  105771. 0};
  105772. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105773. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105774. 0x01,0x02,0x03,0x04,1,0,0,0,
  105775. 0x54,0x05,0x51,0xc8,
  105776. 17,
  105777. 255,255,255,255,255,255,255,255,
  105778. 255,255,255,255,255,255,255,255,255};
  105779. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105780. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  105781. 0x01,0x02,0x03,0x04,2,0,0,0,
  105782. 0xc8,0xc3,0xcb,0xed,
  105783. 5,
  105784. 10,255,4,255,0};
  105785. /* page with the 255 segment limit */
  105786. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105787. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105788. 0x01,0x02,0x03,0x04,0,0,0,0,
  105789. 0xff,0x7b,0x23,0x17,
  105790. 1,
  105791. 0};
  105792. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105793. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  105794. 0x01,0x02,0x03,0x04,1,0,0,0,
  105795. 0xed,0x2a,0x2e,0xa7,
  105796. 255,
  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,10,
  105813. 10,10,10,10,10,10,10,10,
  105814. 10,10,10,10,10,10,10,10,
  105815. 10,10,10,10,10,10,10,10,
  105816. 10,10,10,10,10,10,10,10,
  105817. 10,10,10,10,10,10,10,10,
  105818. 10,10,10,10,10,10,10,10,
  105819. 10,10,10,10,10,10,10,10,
  105820. 10,10,10,10,10,10,10,10,
  105821. 10,10,10,10,10,10,10,10,
  105822. 10,10,10,10,10,10,10,10,
  105823. 10,10,10,10,10,10,10,10,
  105824. 10,10,10,10,10,10,10,10,
  105825. 10,10,10,10,10,10,10,10,
  105826. 10,10,10,10,10,10,10,10,
  105827. 10,10,10,10,10,10,10,10,
  105828. 10,10,10,10,10,10,10};
  105829. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105830. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  105831. 0x01,0x02,0x03,0x04,2,0,0,0,
  105832. 0x6c,0x3b,0x82,0x3d,
  105833. 1,
  105834. 50};
  105835. /* packet that overspans over an entire page */
  105836. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105837. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105838. 0x01,0x02,0x03,0x04,0,0,0,0,
  105839. 0xff,0x7b,0x23,0x17,
  105840. 1,
  105841. 0};
  105842. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105843. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105844. 0x01,0x02,0x03,0x04,1,0,0,0,
  105845. 0x3c,0xd9,0x4d,0x3f,
  105846. 17,
  105847. 100,255,255,255,255,255,255,255,255,
  105848. 255,255,255,255,255,255,255,255};
  105849. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  105850. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105851. 0x01,0x02,0x03,0x04,2,0,0,0,
  105852. 0x01,0xd2,0xe5,0xe5,
  105853. 17,
  105854. 255,255,255,255,255,255,255,255,
  105855. 255,255,255,255,255,255,255,255,255};
  105856. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105857. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  105858. 0x01,0x02,0x03,0x04,3,0,0,0,
  105859. 0xef,0xdd,0x88,0xde,
  105860. 7,
  105861. 255,255,75,255,4,255,0};
  105862. /* packet that overspans over an entire page */
  105863. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105864. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105865. 0x01,0x02,0x03,0x04,0,0,0,0,
  105866. 0xff,0x7b,0x23,0x17,
  105867. 1,
  105868. 0};
  105869. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105870. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105871. 0x01,0x02,0x03,0x04,1,0,0,0,
  105872. 0x3c,0xd9,0x4d,0x3f,
  105873. 17,
  105874. 100,255,255,255,255,255,255,255,255,
  105875. 255,255,255,255,255,255,255,255};
  105876. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105877. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105878. 0x01,0x02,0x03,0x04,2,0,0,0,
  105879. 0xd4,0xe0,0x60,0xe5,
  105880. 1,0};
  105881. void test_pack(const int *pl, const int **headers, int byteskip,
  105882. int pageskip, int packetskip){
  105883. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  105884. long inptr=0;
  105885. long outptr=0;
  105886. long deptr=0;
  105887. long depacket=0;
  105888. long granule_pos=7,pageno=0;
  105889. int i,j,packets,pageout=pageskip;
  105890. int eosflag=0;
  105891. int bosflag=0;
  105892. int byteskipcount=0;
  105893. ogg_stream_reset(&os_en);
  105894. ogg_stream_reset(&os_de);
  105895. ogg_sync_reset(&oy);
  105896. for(packets=0;packets<packetskip;packets++)
  105897. depacket+=pl[packets];
  105898. for(packets=0;;packets++)if(pl[packets]==-1)break;
  105899. for(i=0;i<packets;i++){
  105900. /* construct a test packet */
  105901. ogg_packet op;
  105902. int len=pl[i];
  105903. op.packet=data+inptr;
  105904. op.bytes=len;
  105905. op.e_o_s=(pl[i+1]<0?1:0);
  105906. op.granulepos=granule_pos;
  105907. granule_pos+=1024;
  105908. for(j=0;j<len;j++)data[inptr++]=i+j;
  105909. /* submit the test packet */
  105910. ogg_stream_packetin(&os_en,&op);
  105911. /* retrieve any finished pages */
  105912. {
  105913. ogg_page og;
  105914. while(ogg_stream_pageout(&os_en,&og)){
  105915. /* We have a page. Check it carefully */
  105916. fprintf(stderr,"%ld, ",pageno);
  105917. if(headers[pageno]==NULL){
  105918. fprintf(stderr,"coded too many pages!\n");
  105919. exit(1);
  105920. }
  105921. check_page(data+outptr,headers[pageno],&og);
  105922. outptr+=og.body_len;
  105923. pageno++;
  105924. if(pageskip){
  105925. bosflag=1;
  105926. pageskip--;
  105927. deptr+=og.body_len;
  105928. }
  105929. /* have a complete page; submit it to sync/decode */
  105930. {
  105931. ogg_page og_de;
  105932. ogg_packet op_de,op_de2;
  105933. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  105934. char *next=buf;
  105935. byteskipcount+=og.header_len;
  105936. if(byteskipcount>byteskip){
  105937. memcpy(next,og.header,byteskipcount-byteskip);
  105938. next+=byteskipcount-byteskip;
  105939. byteskipcount=byteskip;
  105940. }
  105941. byteskipcount+=og.body_len;
  105942. if(byteskipcount>byteskip){
  105943. memcpy(next,og.body,byteskipcount-byteskip);
  105944. next+=byteskipcount-byteskip;
  105945. byteskipcount=byteskip;
  105946. }
  105947. ogg_sync_wrote(&oy,next-buf);
  105948. while(1){
  105949. int ret=ogg_sync_pageout(&oy,&og_de);
  105950. if(ret==0)break;
  105951. if(ret<0)continue;
  105952. /* got a page. Happy happy. Verify that it's good. */
  105953. fprintf(stderr,"(%ld), ",pageout);
  105954. check_page(data+deptr,headers[pageout],&og_de);
  105955. deptr+=og_de.body_len;
  105956. pageout++;
  105957. /* submit it to deconstitution */
  105958. ogg_stream_pagein(&os_de,&og_de);
  105959. /* packets out? */
  105960. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  105961. ogg_stream_packetpeek(&os_de,NULL);
  105962. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  105963. /* verify peek and out match */
  105964. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  105965. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  105966. depacket);
  105967. exit(1);
  105968. }
  105969. /* verify the packet! */
  105970. /* check data */
  105971. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  105972. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  105973. depacket);
  105974. exit(1);
  105975. }
  105976. /* check bos flag */
  105977. if(bosflag==0 && op_de.b_o_s==0){
  105978. fprintf(stderr,"b_o_s flag not set on packet!\n");
  105979. exit(1);
  105980. }
  105981. if(bosflag && op_de.b_o_s){
  105982. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  105983. exit(1);
  105984. }
  105985. bosflag=1;
  105986. depacket+=op_de.bytes;
  105987. /* check eos flag */
  105988. if(eosflag){
  105989. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  105990. exit(1);
  105991. }
  105992. if(op_de.e_o_s)eosflag=1;
  105993. /* check granulepos flag */
  105994. if(op_de.granulepos!=-1){
  105995. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  105996. }
  105997. }
  105998. }
  105999. }
  106000. }
  106001. }
  106002. }
  106003. _ogg_free(data);
  106004. if(headers[pageno]!=NULL){
  106005. fprintf(stderr,"did not write last page!\n");
  106006. exit(1);
  106007. }
  106008. if(headers[pageout]!=NULL){
  106009. fprintf(stderr,"did not decode last page!\n");
  106010. exit(1);
  106011. }
  106012. if(inptr!=outptr){
  106013. fprintf(stderr,"encoded page data incomplete!\n");
  106014. exit(1);
  106015. }
  106016. if(inptr!=deptr){
  106017. fprintf(stderr,"decoded page data incomplete!\n");
  106018. exit(1);
  106019. }
  106020. if(inptr!=depacket){
  106021. fprintf(stderr,"decoded packet data incomplete!\n");
  106022. exit(1);
  106023. }
  106024. if(!eosflag){
  106025. fprintf(stderr,"Never got a packet with EOS set!\n");
  106026. exit(1);
  106027. }
  106028. fprintf(stderr,"ok.\n");
  106029. }
  106030. int main(void){
  106031. ogg_stream_init(&os_en,0x04030201);
  106032. ogg_stream_init(&os_de,0x04030201);
  106033. ogg_sync_init(&oy);
  106034. /* Exercise each code path in the framing code. Also verify that
  106035. the checksums are working. */
  106036. {
  106037. /* 17 only */
  106038. const int packets[]={17, -1};
  106039. const int *headret[]={head1_0,NULL};
  106040. fprintf(stderr,"testing single page encoding... ");
  106041. test_pack(packets,headret,0,0,0);
  106042. }
  106043. {
  106044. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106045. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  106046. const int *headret[]={head1_1,head2_1,NULL};
  106047. fprintf(stderr,"testing basic page encoding... ");
  106048. test_pack(packets,headret,0,0,0);
  106049. }
  106050. {
  106051. /* nil packets; beginning,middle,end */
  106052. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  106053. const int *headret[]={head1_2,head2_2,NULL};
  106054. fprintf(stderr,"testing basic nil packets... ");
  106055. test_pack(packets,headret,0,0,0);
  106056. }
  106057. {
  106058. /* large initial packet */
  106059. const int packets[]={4345,259,255,-1};
  106060. const int *headret[]={head1_3,head2_3,NULL};
  106061. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  106062. test_pack(packets,headret,0,0,0);
  106063. }
  106064. {
  106065. /* continuing packet test */
  106066. const int packets[]={0,4345,259,255,-1};
  106067. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  106068. fprintf(stderr,"testing single packet page span... ");
  106069. test_pack(packets,headret,0,0,0);
  106070. }
  106071. /* page with the 255 segment limit */
  106072. {
  106073. const int packets[]={0,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,10,
  106089. 10,10,10,10,10,10,10,10,
  106090. 10,10,10,10,10,10,10,10,
  106091. 10,10,10,10,10,10,10,10,
  106092. 10,10,10,10,10,10,10,10,
  106093. 10,10,10,10,10,10,10,10,
  106094. 10,10,10,10,10,10,10,10,
  106095. 10,10,10,10,10,10,10,10,
  106096. 10,10,10,10,10,10,10,10,
  106097. 10,10,10,10,10,10,10,10,
  106098. 10,10,10,10,10,10,10,10,
  106099. 10,10,10,10,10,10,10,10,
  106100. 10,10,10,10,10,10,10,10,
  106101. 10,10,10,10,10,10,10,10,
  106102. 10,10,10,10,10,10,10,10,
  106103. 10,10,10,10,10,10,10,10,
  106104. 10,10,10,10,10,10,10,50,-1};
  106105. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  106106. fprintf(stderr,"testing max packet segments... ");
  106107. test_pack(packets,headret,0,0,0);
  106108. }
  106109. {
  106110. /* packet that overspans over an entire page */
  106111. const int packets[]={0,100,9000,259,255,-1};
  106112. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106113. fprintf(stderr,"testing very large packets... ");
  106114. test_pack(packets,headret,0,0,0);
  106115. }
  106116. {
  106117. /* test for the libogg 1.1.1 resync in large continuation bug
  106118. found by Josh Coalson) */
  106119. const int packets[]={0,100,9000,259,255,-1};
  106120. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106121. fprintf(stderr,"testing continuation resync in very large packets... ");
  106122. test_pack(packets,headret,100,2,3);
  106123. }
  106124. {
  106125. /* term only page. why not? */
  106126. const int packets[]={0,100,4080,-1};
  106127. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  106128. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  106129. test_pack(packets,headret,0,0,0);
  106130. }
  106131. {
  106132. /* build a bunch of pages for testing */
  106133. unsigned char *data=_ogg_malloc(1024*1024);
  106134. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  106135. int inptr=0,i,j;
  106136. ogg_page og[5];
  106137. ogg_stream_reset(&os_en);
  106138. for(i=0;pl[i]!=-1;i++){
  106139. ogg_packet op;
  106140. int len=pl[i];
  106141. op.packet=data+inptr;
  106142. op.bytes=len;
  106143. op.e_o_s=(pl[i+1]<0?1:0);
  106144. op.granulepos=(i+1)*1000;
  106145. for(j=0;j<len;j++)data[inptr++]=i+j;
  106146. ogg_stream_packetin(&os_en,&op);
  106147. }
  106148. _ogg_free(data);
  106149. /* retrieve finished pages */
  106150. for(i=0;i<5;i++){
  106151. if(ogg_stream_pageout(&os_en,&og[i])==0){
  106152. fprintf(stderr,"Too few pages output building sync tests!\n");
  106153. exit(1);
  106154. }
  106155. copy_page(&og[i]);
  106156. }
  106157. /* Test lost pages on pagein/packetout: no rollback */
  106158. {
  106159. ogg_page temp;
  106160. ogg_packet test;
  106161. fprintf(stderr,"Testing loss of pages... ");
  106162. ogg_sync_reset(&oy);
  106163. ogg_stream_reset(&os_de);
  106164. for(i=0;i<5;i++){
  106165. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106166. og[i].header_len);
  106167. ogg_sync_wrote(&oy,og[i].header_len);
  106168. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106169. ogg_sync_wrote(&oy,og[i].body_len);
  106170. }
  106171. ogg_sync_pageout(&oy,&temp);
  106172. ogg_stream_pagein(&os_de,&temp);
  106173. ogg_sync_pageout(&oy,&temp);
  106174. ogg_stream_pagein(&os_de,&temp);
  106175. ogg_sync_pageout(&oy,&temp);
  106176. /* skip */
  106177. ogg_sync_pageout(&oy,&temp);
  106178. ogg_stream_pagein(&os_de,&temp);
  106179. /* do we get the expected results/packets? */
  106180. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106181. checkpacket(&test,0,0,0);
  106182. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106183. checkpacket(&test,100,1,-1);
  106184. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106185. checkpacket(&test,4079,2,3000);
  106186. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106187. fprintf(stderr,"Error: loss of page did not return error\n");
  106188. exit(1);
  106189. }
  106190. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106191. checkpacket(&test,76,5,-1);
  106192. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106193. checkpacket(&test,34,6,-1);
  106194. fprintf(stderr,"ok.\n");
  106195. }
  106196. /* Test lost pages on pagein/packetout: rollback with continuation */
  106197. {
  106198. ogg_page temp;
  106199. ogg_packet test;
  106200. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  106201. ogg_sync_reset(&oy);
  106202. ogg_stream_reset(&os_de);
  106203. for(i=0;i<5;i++){
  106204. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106205. og[i].header_len);
  106206. ogg_sync_wrote(&oy,og[i].header_len);
  106207. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106208. ogg_sync_wrote(&oy,og[i].body_len);
  106209. }
  106210. ogg_sync_pageout(&oy,&temp);
  106211. ogg_stream_pagein(&os_de,&temp);
  106212. ogg_sync_pageout(&oy,&temp);
  106213. ogg_stream_pagein(&os_de,&temp);
  106214. ogg_sync_pageout(&oy,&temp);
  106215. ogg_stream_pagein(&os_de,&temp);
  106216. ogg_sync_pageout(&oy,&temp);
  106217. /* skip */
  106218. ogg_sync_pageout(&oy,&temp);
  106219. ogg_stream_pagein(&os_de,&temp);
  106220. /* do we get the expected results/packets? */
  106221. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106222. checkpacket(&test,0,0,0);
  106223. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106224. checkpacket(&test,100,1,-1);
  106225. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106226. checkpacket(&test,4079,2,3000);
  106227. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106228. checkpacket(&test,2956,3,4000);
  106229. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106230. fprintf(stderr,"Error: loss of page did not return error\n");
  106231. exit(1);
  106232. }
  106233. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106234. checkpacket(&test,300,13,14000);
  106235. fprintf(stderr,"ok.\n");
  106236. }
  106237. /* the rest only test sync */
  106238. {
  106239. ogg_page og_de;
  106240. /* Test fractional page inputs: incomplete capture */
  106241. fprintf(stderr,"Testing sync on partial inputs... ");
  106242. ogg_sync_reset(&oy);
  106243. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106244. 3);
  106245. ogg_sync_wrote(&oy,3);
  106246. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106247. /* Test fractional page inputs: incomplete fixed header */
  106248. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  106249. 20);
  106250. ogg_sync_wrote(&oy,20);
  106251. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106252. /* Test fractional page inputs: incomplete header */
  106253. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  106254. 5);
  106255. ogg_sync_wrote(&oy,5);
  106256. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106257. /* Test fractional page inputs: incomplete body */
  106258. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  106259. og[1].header_len-28);
  106260. ogg_sync_wrote(&oy,og[1].header_len-28);
  106261. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106262. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  106263. ogg_sync_wrote(&oy,1000);
  106264. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106265. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  106266. og[1].body_len-1000);
  106267. ogg_sync_wrote(&oy,og[1].body_len-1000);
  106268. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106269. fprintf(stderr,"ok.\n");
  106270. }
  106271. /* Test fractional page inputs: page + incomplete capture */
  106272. {
  106273. ogg_page og_de;
  106274. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  106275. ogg_sync_reset(&oy);
  106276. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106277. og[1].header_len);
  106278. ogg_sync_wrote(&oy,og[1].header_len);
  106279. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106280. og[1].body_len);
  106281. ogg_sync_wrote(&oy,og[1].body_len);
  106282. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106283. 20);
  106284. ogg_sync_wrote(&oy,20);
  106285. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106286. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106287. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  106288. og[1].header_len-20);
  106289. ogg_sync_wrote(&oy,og[1].header_len-20);
  106290. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106291. og[1].body_len);
  106292. ogg_sync_wrote(&oy,og[1].body_len);
  106293. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106294. fprintf(stderr,"ok.\n");
  106295. }
  106296. /* Test recapture: garbage + page */
  106297. {
  106298. ogg_page og_de;
  106299. fprintf(stderr,"Testing search for capture... ");
  106300. ogg_sync_reset(&oy);
  106301. /* 'garbage' */
  106302. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106303. og[1].body_len);
  106304. ogg_sync_wrote(&oy,og[1].body_len);
  106305. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106306. og[1].header_len);
  106307. ogg_sync_wrote(&oy,og[1].header_len);
  106308. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106309. og[1].body_len);
  106310. ogg_sync_wrote(&oy,og[1].body_len);
  106311. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106312. 20);
  106313. ogg_sync_wrote(&oy,20);
  106314. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106315. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106316. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106317. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  106318. og[2].header_len-20);
  106319. ogg_sync_wrote(&oy,og[2].header_len-20);
  106320. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106321. og[2].body_len);
  106322. ogg_sync_wrote(&oy,og[2].body_len);
  106323. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106324. fprintf(stderr,"ok.\n");
  106325. }
  106326. /* Test recapture: page + garbage + page */
  106327. {
  106328. ogg_page og_de;
  106329. fprintf(stderr,"Testing recapture... ");
  106330. ogg_sync_reset(&oy);
  106331. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106332. og[1].header_len);
  106333. ogg_sync_wrote(&oy,og[1].header_len);
  106334. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106335. og[1].body_len);
  106336. ogg_sync_wrote(&oy,og[1].body_len);
  106337. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106338. og[2].header_len);
  106339. ogg_sync_wrote(&oy,og[2].header_len);
  106340. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106341. og[2].header_len);
  106342. ogg_sync_wrote(&oy,og[2].header_len);
  106343. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106344. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106345. og[2].body_len-5);
  106346. ogg_sync_wrote(&oy,og[2].body_len-5);
  106347. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  106348. og[3].header_len);
  106349. ogg_sync_wrote(&oy,og[3].header_len);
  106350. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  106351. og[3].body_len);
  106352. ogg_sync_wrote(&oy,og[3].body_len);
  106353. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106354. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106355. fprintf(stderr,"ok.\n");
  106356. }
  106357. /* Free page data that was previously copied */
  106358. {
  106359. for(i=0;i<5;i++){
  106360. free_page(&og[i]);
  106361. }
  106362. }
  106363. }
  106364. return(0);
  106365. }
  106366. #endif
  106367. #endif
  106368. /*** End of inlined file: framing.c ***/
  106369. /*** Start of inlined file: analysis.c ***/
  106370. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106371. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106372. // tasks..
  106373. #if JUCE_MSVC
  106374. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106375. #endif
  106376. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106377. #if JUCE_USE_OGGVORBIS
  106378. #include <stdio.h>
  106379. #include <string.h>
  106380. #include <math.h>
  106381. /*** Start of inlined file: codec_internal.h ***/
  106382. #ifndef _V_CODECI_H_
  106383. #define _V_CODECI_H_
  106384. /*** Start of inlined file: envelope.h ***/
  106385. #ifndef _V_ENVELOPE_
  106386. #define _V_ENVELOPE_
  106387. /*** Start of inlined file: mdct.h ***/
  106388. #ifndef _OGG_mdct_H_
  106389. #define _OGG_mdct_H_
  106390. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  106391. #ifdef MDCT_INTEGERIZED
  106392. #define DATA_TYPE int
  106393. #define REG_TYPE register int
  106394. #define TRIGBITS 14
  106395. #define cPI3_8 6270
  106396. #define cPI2_8 11585
  106397. #define cPI1_8 15137
  106398. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  106399. #define MULT_NORM(x) ((x)>>TRIGBITS)
  106400. #define HALVE(x) ((x)>>1)
  106401. #else
  106402. #define DATA_TYPE float
  106403. #define REG_TYPE float
  106404. #define cPI3_8 .38268343236508977175F
  106405. #define cPI2_8 .70710678118654752441F
  106406. #define cPI1_8 .92387953251128675613F
  106407. #define FLOAT_CONV(x) (x)
  106408. #define MULT_NORM(x) (x)
  106409. #define HALVE(x) ((x)*.5f)
  106410. #endif
  106411. typedef struct {
  106412. int n;
  106413. int log2n;
  106414. DATA_TYPE *trig;
  106415. int *bitrev;
  106416. DATA_TYPE scale;
  106417. } mdct_lookup;
  106418. extern void mdct_init(mdct_lookup *lookup,int n);
  106419. extern void mdct_clear(mdct_lookup *l);
  106420. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  106421. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  106422. #endif
  106423. /*** End of inlined file: mdct.h ***/
  106424. #define VE_PRE 16
  106425. #define VE_WIN 4
  106426. #define VE_POST 2
  106427. #define VE_AMP (VE_PRE+VE_POST-1)
  106428. #define VE_BANDS 7
  106429. #define VE_NEARDC 15
  106430. #define VE_MINSTRETCH 2 /* a bit less than short block */
  106431. #define VE_MAXSTRETCH 12 /* one-third full block */
  106432. typedef struct {
  106433. float ampbuf[VE_AMP];
  106434. int ampptr;
  106435. float nearDC[VE_NEARDC];
  106436. float nearDC_acc;
  106437. float nearDC_partialacc;
  106438. int nearptr;
  106439. } envelope_filter_state;
  106440. typedef struct {
  106441. int begin;
  106442. int end;
  106443. float *window;
  106444. float total;
  106445. } envelope_band;
  106446. typedef struct {
  106447. int ch;
  106448. int winlength;
  106449. int searchstep;
  106450. float minenergy;
  106451. mdct_lookup mdct;
  106452. float *mdct_win;
  106453. envelope_band band[VE_BANDS];
  106454. envelope_filter_state *filter;
  106455. int stretch;
  106456. int *mark;
  106457. long storage;
  106458. long current;
  106459. long curmark;
  106460. long cursor;
  106461. } envelope_lookup;
  106462. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  106463. extern void _ve_envelope_clear(envelope_lookup *e);
  106464. extern long _ve_envelope_search(vorbis_dsp_state *v);
  106465. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  106466. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  106467. #endif
  106468. /*** End of inlined file: envelope.h ***/
  106469. /*** Start of inlined file: codebook.h ***/
  106470. #ifndef _V_CODEBOOK_H_
  106471. #define _V_CODEBOOK_H_
  106472. /* This structure encapsulates huffman and VQ style encoding books; it
  106473. doesn't do anything specific to either.
  106474. valuelist/quantlist are nonNULL (and q_* significant) only if
  106475. there's entry->value mapping to be done.
  106476. If encode-side mapping must be done (and thus the entry needs to be
  106477. hunted), the auxiliary encode pointer will point to a decision
  106478. tree. This is true of both VQ and huffman, but is mostly useful
  106479. with VQ.
  106480. */
  106481. typedef struct static_codebook{
  106482. long dim; /* codebook dimensions (elements per vector) */
  106483. long entries; /* codebook entries */
  106484. long *lengthlist; /* codeword lengths in bits */
  106485. /* mapping ***************************************************************/
  106486. int maptype; /* 0=none
  106487. 1=implicitly populated values from map column
  106488. 2=listed arbitrary values */
  106489. /* The below does a linear, single monotonic sequence mapping. */
  106490. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  106491. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  106492. int q_quant; /* bits: 0 < quant <= 16 */
  106493. int q_sequencep; /* bitflag */
  106494. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  106495. map == 2: list of dim*entries quantized entry vals
  106496. */
  106497. /* encode helpers ********************************************************/
  106498. struct encode_aux_nearestmatch *nearest_tree;
  106499. struct encode_aux_threshmatch *thresh_tree;
  106500. struct encode_aux_pigeonhole *pigeon_tree;
  106501. int allocedp;
  106502. } static_codebook;
  106503. /* this structures an arbitrary trained book to quickly find the
  106504. nearest cell match */
  106505. typedef struct encode_aux_nearestmatch{
  106506. /* pre-calculated partitioning tree */
  106507. long *ptr0;
  106508. long *ptr1;
  106509. long *p; /* decision points (each is an entry) */
  106510. long *q; /* decision points (each is an entry) */
  106511. long aux; /* number of tree entries */
  106512. long alloc;
  106513. } encode_aux_nearestmatch;
  106514. /* assumes a maptype of 1; encode side only, so that's OK */
  106515. typedef struct encode_aux_threshmatch{
  106516. float *quantthresh;
  106517. long *quantmap;
  106518. int quantvals;
  106519. int threshvals;
  106520. } encode_aux_threshmatch;
  106521. typedef struct encode_aux_pigeonhole{
  106522. float min;
  106523. float del;
  106524. int mapentries;
  106525. int quantvals;
  106526. long *pigeonmap;
  106527. long fittotal;
  106528. long *fitlist;
  106529. long *fitmap;
  106530. long *fitlength;
  106531. } encode_aux_pigeonhole;
  106532. typedef struct codebook{
  106533. long dim; /* codebook dimensions (elements per vector) */
  106534. long entries; /* codebook entries */
  106535. long used_entries; /* populated codebook entries */
  106536. const static_codebook *c;
  106537. /* for encode, the below are entry-ordered, fully populated */
  106538. /* for decode, the below are ordered by bitreversed codeword and only
  106539. used entries are populated */
  106540. float *valuelist; /* list of dim*entries actual entry values */
  106541. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  106542. int *dec_index; /* only used if sparseness collapsed */
  106543. char *dec_codelengths;
  106544. ogg_uint32_t *dec_firsttable;
  106545. int dec_firsttablen;
  106546. int dec_maxlength;
  106547. } codebook;
  106548. extern void vorbis_staticbook_clear(static_codebook *b);
  106549. extern void vorbis_staticbook_destroy(static_codebook *b);
  106550. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  106551. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  106552. extern void vorbis_book_clear(codebook *b);
  106553. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  106554. extern float *_book_logdist(const static_codebook *b,float *vals);
  106555. extern float _float32_unpack(long val);
  106556. extern long _float32_pack(float val);
  106557. extern int _best(codebook *book, float *a, int step);
  106558. extern int _ilog(unsigned int v);
  106559. extern long _book_maptype1_quantvals(const static_codebook *b);
  106560. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  106561. extern long vorbis_book_codeword(codebook *book,int entry);
  106562. extern long vorbis_book_codelen(codebook *book,int entry);
  106563. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  106564. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  106565. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  106566. extern int vorbis_book_errorv(codebook *book, float *a);
  106567. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  106568. oggpack_buffer *b);
  106569. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  106570. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  106571. oggpack_buffer *b,int n);
  106572. extern long vorbis_book_decodev_set(codebook *book, float *a,
  106573. oggpack_buffer *b,int n);
  106574. extern long vorbis_book_decodev_add(codebook *book, float *a,
  106575. oggpack_buffer *b,int n);
  106576. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  106577. long off,int ch,
  106578. oggpack_buffer *b,int n);
  106579. #endif
  106580. /*** End of inlined file: codebook.h ***/
  106581. #define BLOCKTYPE_IMPULSE 0
  106582. #define BLOCKTYPE_PADDING 1
  106583. #define BLOCKTYPE_TRANSITION 0
  106584. #define BLOCKTYPE_LONG 1
  106585. #define PACKETBLOBS 15
  106586. typedef struct vorbis_block_internal{
  106587. float **pcmdelay; /* this is a pointer into local storage */
  106588. float ampmax;
  106589. int blocktype;
  106590. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  106591. blob [PACKETBLOBS/2] points to
  106592. the oggpack_buffer in the
  106593. main vorbis_block */
  106594. } vorbis_block_internal;
  106595. typedef void vorbis_look_floor;
  106596. typedef void vorbis_look_residue;
  106597. typedef void vorbis_look_transform;
  106598. /* mode ************************************************************/
  106599. typedef struct {
  106600. int blockflag;
  106601. int windowtype;
  106602. int transformtype;
  106603. int mapping;
  106604. } vorbis_info_mode;
  106605. typedef void vorbis_info_floor;
  106606. typedef void vorbis_info_residue;
  106607. typedef void vorbis_info_mapping;
  106608. /*** Start of inlined file: psy.h ***/
  106609. #ifndef _V_PSY_H_
  106610. #define _V_PSY_H_
  106611. /*** Start of inlined file: smallft.h ***/
  106612. #ifndef _V_SMFT_H_
  106613. #define _V_SMFT_H_
  106614. typedef struct {
  106615. int n;
  106616. float *trigcache;
  106617. int *splitcache;
  106618. } drft_lookup;
  106619. extern void drft_forward(drft_lookup *l,float *data);
  106620. extern void drft_backward(drft_lookup *l,float *data);
  106621. extern void drft_init(drft_lookup *l,int n);
  106622. extern void drft_clear(drft_lookup *l);
  106623. #endif
  106624. /*** End of inlined file: smallft.h ***/
  106625. /*** Start of inlined file: backends.h ***/
  106626. /* this is exposed up here because we need it for static modes.
  106627. Lookups for each backend aren't exposed because there's no reason
  106628. to do so */
  106629. #ifndef _vorbis_backend_h_
  106630. #define _vorbis_backend_h_
  106631. /* this would all be simpler/shorter with templates, but.... */
  106632. /* Floor backend generic *****************************************/
  106633. typedef struct{
  106634. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  106635. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  106636. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  106637. void (*free_info) (vorbis_info_floor *);
  106638. void (*free_look) (vorbis_look_floor *);
  106639. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  106640. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  106641. void *buffer,float *);
  106642. } vorbis_func_floor;
  106643. typedef struct{
  106644. int order;
  106645. long rate;
  106646. long barkmap;
  106647. int ampbits;
  106648. int ampdB;
  106649. int numbooks; /* <= 16 */
  106650. int books[16];
  106651. float lessthan; /* encode-only config setting hacks for libvorbis */
  106652. float greaterthan; /* encode-only config setting hacks for libvorbis */
  106653. } vorbis_info_floor0;
  106654. #define VIF_POSIT 63
  106655. #define VIF_CLASS 16
  106656. #define VIF_PARTS 31
  106657. typedef struct{
  106658. int partitions; /* 0 to 31 */
  106659. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  106660. int class_dim[VIF_CLASS]; /* 1 to 8 */
  106661. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  106662. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  106663. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  106664. int mult; /* 1 2 3 or 4 */
  106665. int postlist[VIF_POSIT+2]; /* first two implicit */
  106666. /* encode side analysis parameters */
  106667. float maxover;
  106668. float maxunder;
  106669. float maxerr;
  106670. float twofitweight;
  106671. float twofitatten;
  106672. int n;
  106673. } vorbis_info_floor1;
  106674. /* Residue backend generic *****************************************/
  106675. typedef struct{
  106676. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  106677. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  106678. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  106679. vorbis_info_residue *);
  106680. void (*free_info) (vorbis_info_residue *);
  106681. void (*free_look) (vorbis_look_residue *);
  106682. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  106683. float **,int *,int);
  106684. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  106685. vorbis_look_residue *,
  106686. float **,float **,int *,int,long **);
  106687. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  106688. float **,int *,int);
  106689. } vorbis_func_residue;
  106690. typedef struct vorbis_info_residue0{
  106691. /* block-partitioned VQ coded straight residue */
  106692. long begin;
  106693. long end;
  106694. /* first stage (lossless partitioning) */
  106695. int grouping; /* group n vectors per partition */
  106696. int partitions; /* possible codebooks for a partition */
  106697. int groupbook; /* huffbook for partitioning */
  106698. int secondstages[64]; /* expanded out to pointers in lookup */
  106699. int booklist[256]; /* list of second stage books */
  106700. float classmetric1[64];
  106701. float classmetric2[64];
  106702. } vorbis_info_residue0;
  106703. /* Mapping backend generic *****************************************/
  106704. typedef struct{
  106705. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  106706. oggpack_buffer *);
  106707. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  106708. void (*free_info) (vorbis_info_mapping *);
  106709. int (*forward) (struct vorbis_block *vb);
  106710. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  106711. } vorbis_func_mapping;
  106712. typedef struct vorbis_info_mapping0{
  106713. int submaps; /* <= 16 */
  106714. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  106715. int floorsubmap[16]; /* [mux] submap to floors */
  106716. int residuesubmap[16]; /* [mux] submap to residue */
  106717. int coupling_steps;
  106718. int coupling_mag[256];
  106719. int coupling_ang[256];
  106720. } vorbis_info_mapping0;
  106721. #endif
  106722. /*** End of inlined file: backends.h ***/
  106723. #ifndef EHMER_MAX
  106724. #define EHMER_MAX 56
  106725. #endif
  106726. /* psychoacoustic setup ********************************************/
  106727. #define P_BANDS 17 /* 62Hz to 16kHz */
  106728. #define P_LEVELS 8 /* 30dB to 100dB */
  106729. #define P_LEVEL_0 30. /* 30 dB */
  106730. #define P_NOISECURVES 3
  106731. #define NOISE_COMPAND_LEVELS 40
  106732. typedef struct vorbis_info_psy{
  106733. int blockflag;
  106734. float ath_adjatt;
  106735. float ath_maxatt;
  106736. float tone_masteratt[P_NOISECURVES];
  106737. float tone_centerboost;
  106738. float tone_decay;
  106739. float tone_abs_limit;
  106740. float toneatt[P_BANDS];
  106741. int noisemaskp;
  106742. float noisemaxsupp;
  106743. float noisewindowlo;
  106744. float noisewindowhi;
  106745. int noisewindowlomin;
  106746. int noisewindowhimin;
  106747. int noisewindowfixed;
  106748. float noiseoff[P_NOISECURVES][P_BANDS];
  106749. float noisecompand[NOISE_COMPAND_LEVELS];
  106750. float max_curve_dB;
  106751. int normal_channel_p;
  106752. int normal_point_p;
  106753. int normal_start;
  106754. int normal_partition;
  106755. double normal_thresh;
  106756. } vorbis_info_psy;
  106757. typedef struct{
  106758. int eighth_octave_lines;
  106759. /* for block long/short tuning; encode only */
  106760. float preecho_thresh[VE_BANDS];
  106761. float postecho_thresh[VE_BANDS];
  106762. float stretch_penalty;
  106763. float preecho_minenergy;
  106764. float ampmax_att_per_sec;
  106765. /* channel coupling config */
  106766. int coupling_pkHz[PACKETBLOBS];
  106767. int coupling_pointlimit[2][PACKETBLOBS];
  106768. int coupling_prepointamp[PACKETBLOBS];
  106769. int coupling_postpointamp[PACKETBLOBS];
  106770. int sliding_lowpass[2][PACKETBLOBS];
  106771. } vorbis_info_psy_global;
  106772. typedef struct {
  106773. float ampmax;
  106774. int channels;
  106775. vorbis_info_psy_global *gi;
  106776. int coupling_pointlimit[2][P_NOISECURVES];
  106777. } vorbis_look_psy_global;
  106778. typedef struct {
  106779. int n;
  106780. struct vorbis_info_psy *vi;
  106781. float ***tonecurves;
  106782. float **noiseoffset;
  106783. float *ath;
  106784. long *octave; /* in n.ocshift format */
  106785. long *bark;
  106786. long firstoc;
  106787. long shiftoc;
  106788. int eighth_octave_lines; /* power of two, please */
  106789. int total_octave_lines;
  106790. long rate; /* cache it */
  106791. float m_val; /* Masking compensation value */
  106792. } vorbis_look_psy;
  106793. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  106794. vorbis_info_psy_global *gi,int n,long rate);
  106795. extern void _vp_psy_clear(vorbis_look_psy *p);
  106796. extern void *_vi_psy_dup(void *source);
  106797. extern void _vi_psy_free(vorbis_info_psy *i);
  106798. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  106799. extern void _vp_remove_floor(vorbis_look_psy *p,
  106800. float *mdct,
  106801. int *icodedflr,
  106802. float *residue,
  106803. int sliding_lowpass);
  106804. extern void _vp_noisemask(vorbis_look_psy *p,
  106805. float *logmdct,
  106806. float *logmask);
  106807. extern void _vp_tonemask(vorbis_look_psy *p,
  106808. float *logfft,
  106809. float *logmask,
  106810. float global_specmax,
  106811. float local_specmax);
  106812. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  106813. float *noise,
  106814. float *tone,
  106815. int offset_select,
  106816. float *logmask,
  106817. float *mdct,
  106818. float *logmdct);
  106819. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  106820. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  106821. vorbis_info_psy_global *g,
  106822. vorbis_look_psy *p,
  106823. vorbis_info_mapping0 *vi,
  106824. float **mdct);
  106825. extern void _vp_couple(int blobno,
  106826. vorbis_info_psy_global *g,
  106827. vorbis_look_psy *p,
  106828. vorbis_info_mapping0 *vi,
  106829. float **res,
  106830. float **mag_memo,
  106831. int **mag_sort,
  106832. int **ifloor,
  106833. int *nonzero,
  106834. int sliding_lowpass);
  106835. extern void _vp_noise_normalize(vorbis_look_psy *p,
  106836. float *in,float *out,int *sortedindex);
  106837. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  106838. float *magnitudes,int *sortedindex);
  106839. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  106840. vorbis_look_psy *p,
  106841. vorbis_info_mapping0 *vi,
  106842. float **mags);
  106843. extern void hf_reduction(vorbis_info_psy_global *g,
  106844. vorbis_look_psy *p,
  106845. vorbis_info_mapping0 *vi,
  106846. float **mdct);
  106847. #endif
  106848. /*** End of inlined file: psy.h ***/
  106849. /*** Start of inlined file: bitrate.h ***/
  106850. #ifndef _V_BITRATE_H_
  106851. #define _V_BITRATE_H_
  106852. /*** Start of inlined file: os.h ***/
  106853. #ifndef _OS_H
  106854. #define _OS_H
  106855. /********************************************************************
  106856. * *
  106857. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  106858. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  106859. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  106860. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  106861. * *
  106862. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  106863. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  106864. * *
  106865. ********************************************************************
  106866. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  106867. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  106868. ********************************************************************/
  106869. #ifdef HAVE_CONFIG_H
  106870. #include "config.h"
  106871. #endif
  106872. #include <math.h>
  106873. /*** Start of inlined file: misc.h ***/
  106874. #ifndef _V_RANDOM_H_
  106875. #define _V_RANDOM_H_
  106876. extern int analysis_noisy;
  106877. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  106878. extern void _vorbis_block_ripcord(vorbis_block *vb);
  106879. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106880. ogg_int64_t off);
  106881. #ifdef DEBUG_MALLOC
  106882. #define _VDBG_GRAPHFILE "malloc.m"
  106883. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  106884. extern void _VDBG_free(void *ptr,char *file,long line);
  106885. #ifndef MISC_C
  106886. #undef _ogg_malloc
  106887. #undef _ogg_calloc
  106888. #undef _ogg_realloc
  106889. #undef _ogg_free
  106890. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  106891. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  106892. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  106893. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  106894. #endif
  106895. #endif
  106896. #endif
  106897. /*** End of inlined file: misc.h ***/
  106898. #ifndef _V_IFDEFJAIL_H_
  106899. # define _V_IFDEFJAIL_H_
  106900. # ifdef __GNUC__
  106901. # define STIN static __inline__
  106902. # elif _WIN32
  106903. # define STIN static __inline
  106904. # else
  106905. # define STIN static
  106906. # endif
  106907. #ifdef DJGPP
  106908. # define rint(x) (floor((x)+0.5f))
  106909. #endif
  106910. #ifndef M_PI
  106911. # define M_PI (3.1415926536f)
  106912. #endif
  106913. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  106914. # include <malloc.h>
  106915. # define rint(x) (floor((x)+0.5f))
  106916. # define NO_FLOAT_MATH_LIB
  106917. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  106918. #endif
  106919. #if defined(__SYMBIAN32__) && defined(__WINS__)
  106920. void *_alloca(size_t size);
  106921. # define alloca _alloca
  106922. #endif
  106923. #ifndef FAST_HYPOT
  106924. # define FAST_HYPOT hypot
  106925. #endif
  106926. #endif
  106927. #ifdef HAVE_ALLOCA_H
  106928. # include <alloca.h>
  106929. #endif
  106930. #ifdef USE_MEMORY_H
  106931. # include <memory.h>
  106932. #endif
  106933. #ifndef min
  106934. # define min(x,y) ((x)>(y)?(y):(x))
  106935. #endif
  106936. #ifndef max
  106937. # define max(x,y) ((x)<(y)?(y):(x))
  106938. #endif
  106939. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  106940. # define VORBIS_FPU_CONTROL
  106941. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  106942. Because of encapsulation constraints (GCC can't see inside the asm
  106943. block and so we end up doing stupid things like a store/load that
  106944. is collectively a noop), we do it this way */
  106945. /* we must set up the fpu before this works!! */
  106946. typedef ogg_int16_t vorbis_fpu_control;
  106947. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106948. ogg_int16_t ret;
  106949. ogg_int16_t temp;
  106950. __asm__ __volatile__("fnstcw %0\n\t"
  106951. "movw %0,%%dx\n\t"
  106952. "orw $62463,%%dx\n\t"
  106953. "movw %%dx,%1\n\t"
  106954. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  106955. *fpu=ret;
  106956. }
  106957. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106958. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  106959. }
  106960. /* assumes the FPU is in round mode! */
  106961. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  106962. we get extra fst/fld to
  106963. truncate precision */
  106964. int i;
  106965. __asm__("fistl %0": "=m"(i) : "t"(f));
  106966. return(i);
  106967. }
  106968. #endif
  106969. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  106970. # define VORBIS_FPU_CONTROL
  106971. typedef ogg_int16_t vorbis_fpu_control;
  106972. static __inline int vorbis_ftoi(double f){
  106973. int i;
  106974. __asm{
  106975. fld f
  106976. fistp i
  106977. }
  106978. return i;
  106979. }
  106980. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106981. }
  106982. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106983. }
  106984. #endif
  106985. #ifndef VORBIS_FPU_CONTROL
  106986. typedef int vorbis_fpu_control;
  106987. static int vorbis_ftoi(double f){
  106988. return (int)(f+.5);
  106989. }
  106990. /* We don't have special code for this compiler/arch, so do it the slow way */
  106991. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  106992. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  106993. #endif
  106994. #endif /* _OS_H */
  106995. /*** End of inlined file: os.h ***/
  106996. /* encode side bitrate tracking */
  106997. typedef struct bitrate_manager_state {
  106998. int managed;
  106999. long avg_reservoir;
  107000. long minmax_reservoir;
  107001. long avg_bitsper;
  107002. long min_bitsper;
  107003. long max_bitsper;
  107004. long short_per_long;
  107005. double avgfloat;
  107006. vorbis_block *vb;
  107007. int choice;
  107008. } bitrate_manager_state;
  107009. typedef struct bitrate_manager_info{
  107010. long avg_rate;
  107011. long min_rate;
  107012. long max_rate;
  107013. long reservoir_bits;
  107014. double reservoir_bias;
  107015. double slew_damp;
  107016. } bitrate_manager_info;
  107017. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  107018. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  107019. extern int vorbis_bitrate_managed(vorbis_block *vb);
  107020. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107021. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  107022. #endif
  107023. /*** End of inlined file: bitrate.h ***/
  107024. static int ilog(unsigned int v){
  107025. int ret=0;
  107026. while(v){
  107027. ret++;
  107028. v>>=1;
  107029. }
  107030. return(ret);
  107031. }
  107032. static int ilog2(unsigned int v){
  107033. int ret=0;
  107034. if(v)--v;
  107035. while(v){
  107036. ret++;
  107037. v>>=1;
  107038. }
  107039. return(ret);
  107040. }
  107041. typedef struct private_state {
  107042. /* local lookup storage */
  107043. envelope_lookup *ve; /* envelope lookup */
  107044. int window[2];
  107045. vorbis_look_transform **transform[2]; /* block, type */
  107046. drft_lookup fft_look[2];
  107047. int modebits;
  107048. vorbis_look_floor **flr;
  107049. vorbis_look_residue **residue;
  107050. vorbis_look_psy *psy;
  107051. vorbis_look_psy_global *psy_g_look;
  107052. /* local storage, only used on the encoding side. This way the
  107053. application does not need to worry about freeing some packets'
  107054. memory and not others'; packet storage is always tracked.
  107055. Cleared next call to a _dsp_ function */
  107056. unsigned char *header;
  107057. unsigned char *header1;
  107058. unsigned char *header2;
  107059. bitrate_manager_state bms;
  107060. ogg_int64_t sample_count;
  107061. } private_state;
  107062. /* codec_setup_info contains all the setup information specific to the
  107063. specific compression/decompression mode in progress (eg,
  107064. psychoacoustic settings, channel setup, options, codebook
  107065. etc).
  107066. *********************************************************************/
  107067. /*** Start of inlined file: highlevel.h ***/
  107068. typedef struct highlevel_byblocktype {
  107069. double tone_mask_setting;
  107070. double tone_peaklimit_setting;
  107071. double noise_bias_setting;
  107072. double noise_compand_setting;
  107073. } highlevel_byblocktype;
  107074. typedef struct highlevel_encode_setup {
  107075. void *setup;
  107076. int set_in_stone;
  107077. double base_setting;
  107078. double long_setting;
  107079. double short_setting;
  107080. double impulse_noisetune;
  107081. int managed;
  107082. long bitrate_min;
  107083. long bitrate_av;
  107084. double bitrate_av_damp;
  107085. long bitrate_max;
  107086. long bitrate_reservoir;
  107087. double bitrate_reservoir_bias;
  107088. int impulse_block_p;
  107089. int noise_normalize_p;
  107090. double stereo_point_setting;
  107091. double lowpass_kHz;
  107092. double ath_floating_dB;
  107093. double ath_absolute_dB;
  107094. double amplitude_track_dBpersec;
  107095. double trigger_setting;
  107096. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  107097. } highlevel_encode_setup;
  107098. /*** End of inlined file: highlevel.h ***/
  107099. typedef struct codec_setup_info {
  107100. /* Vorbis supports only short and long blocks, but allows the
  107101. encoder to choose the sizes */
  107102. long blocksizes[2];
  107103. /* modes are the primary means of supporting on-the-fly different
  107104. blocksizes, different channel mappings (LR or M/A),
  107105. different residue backends, etc. Each mode consists of a
  107106. blocksize flag and a mapping (along with the mapping setup */
  107107. int modes;
  107108. int maps;
  107109. int floors;
  107110. int residues;
  107111. int books;
  107112. int psys; /* encode only */
  107113. vorbis_info_mode *mode_param[64];
  107114. int map_type[64];
  107115. vorbis_info_mapping *map_param[64];
  107116. int floor_type[64];
  107117. vorbis_info_floor *floor_param[64];
  107118. int residue_type[64];
  107119. vorbis_info_residue *residue_param[64];
  107120. static_codebook *book_param[256];
  107121. codebook *fullbooks;
  107122. vorbis_info_psy *psy_param[4]; /* encode only */
  107123. vorbis_info_psy_global psy_g_param;
  107124. bitrate_manager_info bi;
  107125. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  107126. highly redundant structure, but
  107127. improves clarity of program flow. */
  107128. int halfrate_flag; /* painless downsample for decode */
  107129. } codec_setup_info;
  107130. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  107131. extern void _vp_global_free(vorbis_look_psy_global *look);
  107132. #endif
  107133. /*** End of inlined file: codec_internal.h ***/
  107134. /*** Start of inlined file: registry.h ***/
  107135. #ifndef _V_REG_H_
  107136. #define _V_REG_H_
  107137. #define VI_TRANSFORMB 1
  107138. #define VI_WINDOWB 1
  107139. #define VI_TIMEB 1
  107140. #define VI_FLOORB 2
  107141. #define VI_RESB 3
  107142. #define VI_MAPB 1
  107143. extern vorbis_func_floor *_floor_P[];
  107144. extern vorbis_func_residue *_residue_P[];
  107145. extern vorbis_func_mapping *_mapping_P[];
  107146. #endif
  107147. /*** End of inlined file: registry.h ***/
  107148. /*** Start of inlined file: scales.h ***/
  107149. #ifndef _V_SCALES_H_
  107150. #define _V_SCALES_H_
  107151. #include <math.h>
  107152. /* 20log10(x) */
  107153. #define VORBIS_IEEE_FLOAT32 1
  107154. #ifdef VORBIS_IEEE_FLOAT32
  107155. static float unitnorm(float x){
  107156. union {
  107157. ogg_uint32_t i;
  107158. float f;
  107159. } ix;
  107160. ix.f = x;
  107161. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  107162. return ix.f;
  107163. }
  107164. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  107165. static float todB(const float *x){
  107166. union {
  107167. ogg_uint32_t i;
  107168. float f;
  107169. } ix;
  107170. ix.f = *x;
  107171. ix.i = ix.i&0x7fffffff;
  107172. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  107173. }
  107174. #define todB_nn(x) todB(x)
  107175. #else
  107176. static float unitnorm(float x){
  107177. if(x<0)return(-1.f);
  107178. return(1.f);
  107179. }
  107180. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  107181. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  107182. #endif
  107183. #define fromdB(x) (exp((x)*.11512925f))
  107184. /* The bark scale equations are approximations, since the original
  107185. table was somewhat hand rolled. The below are chosen to have the
  107186. best possible fit to the rolled tables, thus their somewhat odd
  107187. appearance (these are more accurate and over a longer range than
  107188. the oft-quoted bark equations found in the texts I have). The
  107189. approximations are valid from 0 - 30kHz (nyquist) or so.
  107190. all f in Hz, z in Bark */
  107191. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  107192. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  107193. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  107194. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  107195. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  107196. 0.0 */
  107197. #define toOC(n) (log(n)*1.442695f-5.965784f)
  107198. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  107199. #endif
  107200. /*** End of inlined file: scales.h ***/
  107201. int analysis_noisy=1;
  107202. /* decides between modes, dispatches to the appropriate mapping. */
  107203. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  107204. int ret,i;
  107205. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107206. vb->glue_bits=0;
  107207. vb->time_bits=0;
  107208. vb->floor_bits=0;
  107209. vb->res_bits=0;
  107210. /* first things first. Make sure encode is ready */
  107211. for(i=0;i<PACKETBLOBS;i++)
  107212. oggpack_reset(vbi->packetblob[i]);
  107213. /* we only have one mapping type (0), and we let the mapping code
  107214. itself figure out what soft mode to use. This allows easier
  107215. bitrate management */
  107216. if((ret=_mapping_P[0]->forward(vb)))
  107217. return(ret);
  107218. if(op){
  107219. if(vorbis_bitrate_managed(vb))
  107220. /* The app is using a bitmanaged mode... but not using the
  107221. bitrate management interface. */
  107222. return(OV_EINVAL);
  107223. op->packet=oggpack_get_buffer(&vb->opb);
  107224. op->bytes=oggpack_bytes(&vb->opb);
  107225. op->b_o_s=0;
  107226. op->e_o_s=vb->eofflag;
  107227. op->granulepos=vb->granulepos;
  107228. op->packetno=vb->sequence; /* for sake of completeness */
  107229. }
  107230. return(0);
  107231. }
  107232. /* there was no great place to put this.... */
  107233. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  107234. int j;
  107235. FILE *of;
  107236. char buffer[80];
  107237. /* if(i==5870){*/
  107238. sprintf(buffer,"%s_%d.m",base,i);
  107239. of=fopen(buffer,"w");
  107240. if(!of)perror("failed to open data dump file");
  107241. for(j=0;j<n;j++){
  107242. if(bark){
  107243. float b=toBARK((4000.f*j/n)+.25);
  107244. fprintf(of,"%f ",b);
  107245. }else
  107246. if(off!=0)
  107247. fprintf(of,"%f ",(double)(j+off)/8000.);
  107248. else
  107249. fprintf(of,"%f ",(double)j);
  107250. if(dB){
  107251. float val;
  107252. if(v[j]==0.)
  107253. val=-140.;
  107254. else
  107255. val=todB(v+j);
  107256. fprintf(of,"%f\n",val);
  107257. }else{
  107258. fprintf(of,"%f\n",v[j]);
  107259. }
  107260. }
  107261. fclose(of);
  107262. /* } */
  107263. }
  107264. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107265. ogg_int64_t off){
  107266. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  107267. }
  107268. #endif
  107269. /*** End of inlined file: analysis.c ***/
  107270. /*** Start of inlined file: bitrate.c ***/
  107271. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107272. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107273. // tasks..
  107274. #if JUCE_MSVC
  107275. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107276. #endif
  107277. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107278. #if JUCE_USE_OGGVORBIS
  107279. #include <stdlib.h>
  107280. #include <string.h>
  107281. #include <math.h>
  107282. /* compute bitrate tracking setup */
  107283. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  107284. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107285. bitrate_manager_info *bi=&ci->bi;
  107286. memset(bm,0,sizeof(*bm));
  107287. if(bi && (bi->reservoir_bits>0)){
  107288. long ratesamples=vi->rate;
  107289. int halfsamples=ci->blocksizes[0]>>1;
  107290. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  107291. bm->managed=1;
  107292. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  107293. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  107294. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  107295. bm->avgfloat=PACKETBLOBS/2;
  107296. /* not a necessary fix, but one that leads to a more balanced
  107297. typical initialization */
  107298. {
  107299. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107300. bm->minmax_reservoir=desired_fill;
  107301. bm->avg_reservoir=desired_fill;
  107302. }
  107303. }
  107304. }
  107305. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  107306. memset(bm,0,sizeof(*bm));
  107307. return;
  107308. }
  107309. int vorbis_bitrate_managed(vorbis_block *vb){
  107310. vorbis_dsp_state *vd=vb->vd;
  107311. private_state *b=(private_state*)vd->backend_state;
  107312. bitrate_manager_state *bm=&b->bms;
  107313. if(bm && bm->managed)return(1);
  107314. return(0);
  107315. }
  107316. /* finish taking in the block we just processed */
  107317. int vorbis_bitrate_addblock(vorbis_block *vb){
  107318. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107319. vorbis_dsp_state *vd=vb->vd;
  107320. private_state *b=(private_state*)vd->backend_state;
  107321. bitrate_manager_state *bm=&b->bms;
  107322. vorbis_info *vi=vd->vi;
  107323. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107324. bitrate_manager_info *bi=&ci->bi;
  107325. int choice=rint(bm->avgfloat);
  107326. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107327. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  107328. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  107329. int samples=ci->blocksizes[vb->W]>>1;
  107330. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107331. if(!bm->managed){
  107332. /* not a bitrate managed stream, but for API simplicity, we'll
  107333. buffer the packet to keep the code path clean */
  107334. if(bm->vb)return(-1); /* one has been submitted without
  107335. being claimed */
  107336. bm->vb=vb;
  107337. return(0);
  107338. }
  107339. bm->vb=vb;
  107340. /* look ahead for avg floater */
  107341. if(bm->avg_bitsper>0){
  107342. double slew=0.;
  107343. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107344. double slewlimit= 15./bi->slew_damp;
  107345. /* choosing a new floater:
  107346. if we're over target, we slew down
  107347. if we're under target, we slew up
  107348. choose slew as follows: look through packetblobs of this frame
  107349. and set slew as the first in the appropriate direction that
  107350. gives us the slew we want. This may mean no slew if delta is
  107351. already favorable.
  107352. Then limit slew to slew max */
  107353. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107354. while(choice>0 && this_bits>avg_target_bits &&
  107355. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107356. choice--;
  107357. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107358. }
  107359. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  107360. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  107361. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  107362. choice++;
  107363. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107364. }
  107365. }
  107366. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  107367. if(slew<-slewlimit)slew=-slewlimit;
  107368. if(slew>slewlimit)slew=slewlimit;
  107369. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  107370. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107371. }
  107372. /* enforce min(if used) on the current floater (if used) */
  107373. if(bm->min_bitsper>0){
  107374. /* do we need to force the bitrate up? */
  107375. if(this_bits<min_target_bits){
  107376. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  107377. choice++;
  107378. if(choice>=PACKETBLOBS)break;
  107379. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107380. }
  107381. }
  107382. }
  107383. /* enforce max (if used) on the current floater (if used) */
  107384. if(bm->max_bitsper>0){
  107385. /* do we need to force the bitrate down? */
  107386. if(this_bits>max_target_bits){
  107387. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  107388. choice--;
  107389. if(choice<0)break;
  107390. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107391. }
  107392. }
  107393. }
  107394. /* Choice of packetblobs now made based on floater, and min/max
  107395. requirements. Now boundary check extreme choices */
  107396. if(choice<0){
  107397. /* choosing a smaller packetblob is insufficient to trim bitrate.
  107398. frame will need to be truncated */
  107399. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  107400. bm->choice=choice=0;
  107401. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  107402. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  107403. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107404. }
  107405. }else{
  107406. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  107407. if(choice>=PACKETBLOBS)
  107408. choice=PACKETBLOBS-1;
  107409. bm->choice=choice;
  107410. /* prop up bitrate according to demand. pad this frame out with zeroes */
  107411. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  107412. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  107413. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107414. }
  107415. /* now we have the final packet and the final packet size. Update statistics */
  107416. /* min and max reservoir */
  107417. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  107418. if(max_target_bits>0 && this_bits>max_target_bits){
  107419. bm->minmax_reservoir+=(this_bits-max_target_bits);
  107420. }else if(min_target_bits>0 && this_bits<min_target_bits){
  107421. bm->minmax_reservoir+=(this_bits-min_target_bits);
  107422. }else{
  107423. /* inbetween; we want to take reservoir toward but not past desired_fill */
  107424. if(bm->minmax_reservoir>desired_fill){
  107425. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  107426. bm->minmax_reservoir+=(this_bits-max_target_bits);
  107427. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  107428. }else{
  107429. bm->minmax_reservoir=desired_fill;
  107430. }
  107431. }else{
  107432. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  107433. bm->minmax_reservoir+=(this_bits-min_target_bits);
  107434. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  107435. }else{
  107436. bm->minmax_reservoir=desired_fill;
  107437. }
  107438. }
  107439. }
  107440. }
  107441. /* avg reservoir */
  107442. if(bm->avg_bitsper>0){
  107443. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107444. bm->avg_reservoir+=this_bits-avg_target_bits;
  107445. }
  107446. return(0);
  107447. }
  107448. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  107449. private_state *b=(private_state*)vd->backend_state;
  107450. bitrate_manager_state *bm=&b->bms;
  107451. vorbis_block *vb=bm->vb;
  107452. int choice=PACKETBLOBS/2;
  107453. if(!vb)return 0;
  107454. if(op){
  107455. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107456. if(vorbis_bitrate_managed(vb))
  107457. choice=bm->choice;
  107458. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  107459. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  107460. op->b_o_s=0;
  107461. op->e_o_s=vb->eofflag;
  107462. op->granulepos=vb->granulepos;
  107463. op->packetno=vb->sequence; /* for sake of completeness */
  107464. }
  107465. bm->vb=0;
  107466. return(1);
  107467. }
  107468. #endif
  107469. /*** End of inlined file: bitrate.c ***/
  107470. /*** Start of inlined file: block.c ***/
  107471. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107472. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107473. // tasks..
  107474. #if JUCE_MSVC
  107475. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107476. #endif
  107477. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107478. #if JUCE_USE_OGGVORBIS
  107479. #include <stdio.h>
  107480. #include <stdlib.h>
  107481. #include <string.h>
  107482. /*** Start of inlined file: window.h ***/
  107483. #ifndef _V_WINDOW_
  107484. #define _V_WINDOW_
  107485. extern float *_vorbis_window_get(int n);
  107486. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  107487. int lW,int W,int nW);
  107488. #endif
  107489. /*** End of inlined file: window.h ***/
  107490. /*** Start of inlined file: lpc.h ***/
  107491. #ifndef _V_LPC_H_
  107492. #define _V_LPC_H_
  107493. /* simple linear scale LPC code */
  107494. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  107495. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  107496. float *data,long n);
  107497. #endif
  107498. /*** End of inlined file: lpc.h ***/
  107499. /* pcm accumulator examples (not exhaustive):
  107500. <-------------- lW ---------------->
  107501. <--------------- W ---------------->
  107502. : .....|..... _______________ |
  107503. : .''' | '''_--- | |\ |
  107504. :.....''' |_____--- '''......| | \_______|
  107505. :.................|__________________|_______|__|______|
  107506. |<------ Sl ------>| > Sr < |endW
  107507. |beginSl |endSl | |endSr
  107508. |beginW |endlW |beginSr
  107509. |< lW >|
  107510. <--------------- W ---------------->
  107511. | | .. ______________ |
  107512. | | ' `/ | ---_ |
  107513. |___.'___/`. | ---_____|
  107514. |_______|__|_______|_________________|
  107515. | >|Sl|< |<------ Sr ----->|endW
  107516. | | |endSl |beginSr |endSr
  107517. |beginW | |endlW
  107518. mult[0] |beginSl mult[n]
  107519. <-------------- lW ----------------->
  107520. |<--W-->|
  107521. : .............. ___ | |
  107522. : .''' |`/ \ | |
  107523. :.....''' |/`....\|...|
  107524. :.........................|___|___|___|
  107525. |Sl |Sr |endW
  107526. | | |endSr
  107527. | |beginSr
  107528. | |endSl
  107529. |beginSl
  107530. |beginW
  107531. */
  107532. /* block abstraction setup *********************************************/
  107533. #ifndef WORD_ALIGN
  107534. #define WORD_ALIGN 8
  107535. #endif
  107536. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  107537. int i;
  107538. memset(vb,0,sizeof(*vb));
  107539. vb->vd=v;
  107540. vb->localalloc=0;
  107541. vb->localstore=NULL;
  107542. if(v->analysisp){
  107543. vorbis_block_internal *vbi=(vorbis_block_internal*)
  107544. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  107545. vbi->ampmax=-9999;
  107546. for(i=0;i<PACKETBLOBS;i++){
  107547. if(i==PACKETBLOBS/2){
  107548. vbi->packetblob[i]=&vb->opb;
  107549. }else{
  107550. vbi->packetblob[i]=
  107551. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  107552. }
  107553. oggpack_writeinit(vbi->packetblob[i]);
  107554. }
  107555. }
  107556. return(0);
  107557. }
  107558. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  107559. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  107560. if(bytes+vb->localtop>vb->localalloc){
  107561. /* can't just _ogg_realloc... there are outstanding pointers */
  107562. if(vb->localstore){
  107563. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  107564. vb->totaluse+=vb->localtop;
  107565. link->next=vb->reap;
  107566. link->ptr=vb->localstore;
  107567. vb->reap=link;
  107568. }
  107569. /* highly conservative */
  107570. vb->localalloc=bytes;
  107571. vb->localstore=_ogg_malloc(vb->localalloc);
  107572. vb->localtop=0;
  107573. }
  107574. {
  107575. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  107576. vb->localtop+=bytes;
  107577. return ret;
  107578. }
  107579. }
  107580. /* reap the chain, pull the ripcord */
  107581. void _vorbis_block_ripcord(vorbis_block *vb){
  107582. /* reap the chain */
  107583. struct alloc_chain *reap=vb->reap;
  107584. while(reap){
  107585. struct alloc_chain *next=reap->next;
  107586. _ogg_free(reap->ptr);
  107587. memset(reap,0,sizeof(*reap));
  107588. _ogg_free(reap);
  107589. reap=next;
  107590. }
  107591. /* consolidate storage */
  107592. if(vb->totaluse){
  107593. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  107594. vb->localalloc+=vb->totaluse;
  107595. vb->totaluse=0;
  107596. }
  107597. /* pull the ripcord */
  107598. vb->localtop=0;
  107599. vb->reap=NULL;
  107600. }
  107601. int vorbis_block_clear(vorbis_block *vb){
  107602. int i;
  107603. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107604. _vorbis_block_ripcord(vb);
  107605. if(vb->localstore)_ogg_free(vb->localstore);
  107606. if(vbi){
  107607. for(i=0;i<PACKETBLOBS;i++){
  107608. oggpack_writeclear(vbi->packetblob[i]);
  107609. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  107610. }
  107611. _ogg_free(vbi);
  107612. }
  107613. memset(vb,0,sizeof(*vb));
  107614. return(0);
  107615. }
  107616. /* Analysis side code, but directly related to blocking. Thus it's
  107617. here and not in analysis.c (which is for analysis transforms only).
  107618. The init is here because some of it is shared */
  107619. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  107620. int i;
  107621. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107622. private_state *b=NULL;
  107623. int hs;
  107624. if(ci==NULL) return 1;
  107625. hs=ci->halfrate_flag;
  107626. memset(v,0,sizeof(*v));
  107627. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  107628. v->vi=vi;
  107629. b->modebits=ilog2(ci->modes);
  107630. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  107631. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  107632. /* MDCT is tranform 0 */
  107633. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  107634. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  107635. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  107636. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  107637. /* Vorbis I uses only window type 0 */
  107638. b->window[0]=ilog2(ci->blocksizes[0])-6;
  107639. b->window[1]=ilog2(ci->blocksizes[1])-6;
  107640. if(encp){ /* encode/decode differ here */
  107641. /* analysis always needs an fft */
  107642. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  107643. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  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_encode(ci->fullbooks+i,ci->book_param[i]);
  107649. }
  107650. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  107651. for(i=0;i<ci->psys;i++){
  107652. _vp_psy_init(b->psy+i,
  107653. ci->psy_param[i],
  107654. &ci->psy_g_param,
  107655. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  107656. vi->rate);
  107657. }
  107658. v->analysisp=1;
  107659. }else{
  107660. /* finish the codebooks */
  107661. if(!ci->fullbooks){
  107662. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  107663. for(i=0;i<ci->books;i++){
  107664. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  107665. /* decode codebooks are now standalone after init */
  107666. vorbis_staticbook_destroy(ci->book_param[i]);
  107667. ci->book_param[i]=NULL;
  107668. }
  107669. }
  107670. }
  107671. /* initialize the storage vectors. blocksize[1] is small for encode,
  107672. but the correct size for decode */
  107673. v->pcm_storage=ci->blocksizes[1];
  107674. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  107675. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  107676. {
  107677. int i;
  107678. for(i=0;i<vi->channels;i++)
  107679. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  107680. }
  107681. /* all 1 (large block) or 0 (small block) */
  107682. /* explicitly set for the sake of clarity */
  107683. v->lW=0; /* previous window size */
  107684. v->W=0; /* current window size */
  107685. /* all vector indexes */
  107686. v->centerW=ci->blocksizes[1]/2;
  107687. v->pcm_current=v->centerW;
  107688. /* initialize all the backend lookups */
  107689. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  107690. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  107691. for(i=0;i<ci->floors;i++)
  107692. b->flr[i]=_floor_P[ci->floor_type[i]]->
  107693. look(v,ci->floor_param[i]);
  107694. for(i=0;i<ci->residues;i++)
  107695. b->residue[i]=_residue_P[ci->residue_type[i]]->
  107696. look(v,ci->residue_param[i]);
  107697. return 0;
  107698. }
  107699. /* arbitrary settings and spec-mandated numbers get filled in here */
  107700. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  107701. private_state *b=NULL;
  107702. if(_vds_shared_init(v,vi,1))return 1;
  107703. b=(private_state*)v->backend_state;
  107704. b->psy_g_look=_vp_global_look(vi);
  107705. /* Initialize the envelope state storage */
  107706. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  107707. _ve_envelope_init(b->ve,vi);
  107708. vorbis_bitrate_init(vi,&b->bms);
  107709. /* compressed audio packets start after the headers
  107710. with sequence number 3 */
  107711. v->sequence=3;
  107712. return(0);
  107713. }
  107714. void vorbis_dsp_clear(vorbis_dsp_state *v){
  107715. int i;
  107716. if(v){
  107717. vorbis_info *vi=v->vi;
  107718. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  107719. private_state *b=(private_state*)v->backend_state;
  107720. if(b){
  107721. if(b->ve){
  107722. _ve_envelope_clear(b->ve);
  107723. _ogg_free(b->ve);
  107724. }
  107725. if(b->transform[0]){
  107726. mdct_clear((mdct_lookup*) b->transform[0][0]);
  107727. _ogg_free(b->transform[0][0]);
  107728. _ogg_free(b->transform[0]);
  107729. }
  107730. if(b->transform[1]){
  107731. mdct_clear((mdct_lookup*) b->transform[1][0]);
  107732. _ogg_free(b->transform[1][0]);
  107733. _ogg_free(b->transform[1]);
  107734. }
  107735. if(b->flr){
  107736. for(i=0;i<ci->floors;i++)
  107737. _floor_P[ci->floor_type[i]]->
  107738. free_look(b->flr[i]);
  107739. _ogg_free(b->flr);
  107740. }
  107741. if(b->residue){
  107742. for(i=0;i<ci->residues;i++)
  107743. _residue_P[ci->residue_type[i]]->
  107744. free_look(b->residue[i]);
  107745. _ogg_free(b->residue);
  107746. }
  107747. if(b->psy){
  107748. for(i=0;i<ci->psys;i++)
  107749. _vp_psy_clear(b->psy+i);
  107750. _ogg_free(b->psy);
  107751. }
  107752. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  107753. vorbis_bitrate_clear(&b->bms);
  107754. drft_clear(&b->fft_look[0]);
  107755. drft_clear(&b->fft_look[1]);
  107756. }
  107757. if(v->pcm){
  107758. for(i=0;i<vi->channels;i++)
  107759. if(v->pcm[i])_ogg_free(v->pcm[i]);
  107760. _ogg_free(v->pcm);
  107761. if(v->pcmret)_ogg_free(v->pcmret);
  107762. }
  107763. if(b){
  107764. /* free header, header1, header2 */
  107765. if(b->header)_ogg_free(b->header);
  107766. if(b->header1)_ogg_free(b->header1);
  107767. if(b->header2)_ogg_free(b->header2);
  107768. _ogg_free(b);
  107769. }
  107770. memset(v,0,sizeof(*v));
  107771. }
  107772. }
  107773. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  107774. int i;
  107775. vorbis_info *vi=v->vi;
  107776. private_state *b=(private_state*)v->backend_state;
  107777. /* free header, header1, header2 */
  107778. if(b->header)_ogg_free(b->header);b->header=NULL;
  107779. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  107780. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  107781. /* Do we have enough storage space for the requested buffer? If not,
  107782. expand the PCM (and envelope) storage */
  107783. if(v->pcm_current+vals>=v->pcm_storage){
  107784. v->pcm_storage=v->pcm_current+vals*2;
  107785. for(i=0;i<vi->channels;i++){
  107786. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  107787. }
  107788. }
  107789. for(i=0;i<vi->channels;i++)
  107790. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  107791. return(v->pcmret);
  107792. }
  107793. static void _preextrapolate_helper(vorbis_dsp_state *v){
  107794. int i;
  107795. int order=32;
  107796. float *lpc=(float*)alloca(order*sizeof(*lpc));
  107797. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  107798. long j;
  107799. v->preextrapolate=1;
  107800. if(v->pcm_current-v->centerW>order*2){ /* safety */
  107801. for(i=0;i<v->vi->channels;i++){
  107802. /* need to run the extrapolation in reverse! */
  107803. for(j=0;j<v->pcm_current;j++)
  107804. work[j]=v->pcm[i][v->pcm_current-j-1];
  107805. /* prime as above */
  107806. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  107807. /* run the predictor filter */
  107808. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  107809. order,
  107810. work+v->pcm_current-v->centerW,
  107811. v->centerW);
  107812. for(j=0;j<v->pcm_current;j++)
  107813. v->pcm[i][v->pcm_current-j-1]=work[j];
  107814. }
  107815. }
  107816. }
  107817. /* call with val<=0 to set eof */
  107818. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  107819. vorbis_info *vi=v->vi;
  107820. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107821. if(vals<=0){
  107822. int order=32;
  107823. int i;
  107824. float *lpc=(float*) alloca(order*sizeof(*lpc));
  107825. /* if it wasn't done earlier (very short sample) */
  107826. if(!v->preextrapolate)
  107827. _preextrapolate_helper(v);
  107828. /* We're encoding the end of the stream. Just make sure we have
  107829. [at least] a few full blocks of zeroes at the end. */
  107830. /* actually, we don't want zeroes; that could drop a large
  107831. amplitude off a cliff, creating spread spectrum noise that will
  107832. suck to encode. Extrapolate for the sake of cleanliness. */
  107833. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  107834. v->eofflag=v->pcm_current;
  107835. v->pcm_current+=ci->blocksizes[1]*3;
  107836. for(i=0;i<vi->channels;i++){
  107837. if(v->eofflag>order*2){
  107838. /* extrapolate with LPC to fill in */
  107839. long n;
  107840. /* make a predictor filter */
  107841. n=v->eofflag;
  107842. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  107843. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  107844. /* run the predictor filter */
  107845. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  107846. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  107847. }else{
  107848. /* not enough data to extrapolate (unlikely to happen due to
  107849. guarding the overlap, but bulletproof in case that
  107850. assumtion goes away). zeroes will do. */
  107851. memset(v->pcm[i]+v->eofflag,0,
  107852. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  107853. }
  107854. }
  107855. }else{
  107856. if(v->pcm_current+vals>v->pcm_storage)
  107857. return(OV_EINVAL);
  107858. v->pcm_current+=vals;
  107859. /* we may want to reverse extrapolate the beginning of a stream
  107860. too... in case we're beginning on a cliff! */
  107861. /* clumsy, but simple. It only runs once, so simple is good. */
  107862. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  107863. _preextrapolate_helper(v);
  107864. }
  107865. return(0);
  107866. }
  107867. /* do the deltas, envelope shaping, pre-echo and determine the size of
  107868. the next block on which to continue analysis */
  107869. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  107870. int i;
  107871. vorbis_info *vi=v->vi;
  107872. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107873. private_state *b=(private_state*)v->backend_state;
  107874. vorbis_look_psy_global *g=b->psy_g_look;
  107875. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  107876. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107877. /* check to see if we're started... */
  107878. if(!v->preextrapolate)return(0);
  107879. /* check to see if we're done... */
  107880. if(v->eofflag==-1)return(0);
  107881. /* By our invariant, we have lW, W and centerW set. Search for
  107882. the next boundary so we can determine nW (the next window size)
  107883. which lets us compute the shape of the current block's window */
  107884. /* we do an envelope search even on a single blocksize; we may still
  107885. be throwing more bits at impulses, and envelope search handles
  107886. marking impulses too. */
  107887. {
  107888. long bp=_ve_envelope_search(v);
  107889. if(bp==-1){
  107890. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  107891. full long block */
  107892. v->nW=0;
  107893. }else{
  107894. if(ci->blocksizes[0]==ci->blocksizes[1])
  107895. v->nW=0;
  107896. else
  107897. v->nW=bp;
  107898. }
  107899. }
  107900. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  107901. {
  107902. /* center of next block + next block maximum right side. */
  107903. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  107904. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  107905. although this check is
  107906. less strict that the
  107907. _ve_envelope_search,
  107908. the search is not run
  107909. if we only use one
  107910. block size */
  107911. }
  107912. /* fill in the block. Note that for a short window, lW and nW are *short*
  107913. regardless of actual settings in the stream */
  107914. _vorbis_block_ripcord(vb);
  107915. vb->lW=v->lW;
  107916. vb->W=v->W;
  107917. vb->nW=v->nW;
  107918. if(v->W){
  107919. if(!v->lW || !v->nW){
  107920. vbi->blocktype=BLOCKTYPE_TRANSITION;
  107921. /*fprintf(stderr,"-");*/
  107922. }else{
  107923. vbi->blocktype=BLOCKTYPE_LONG;
  107924. /*fprintf(stderr,"_");*/
  107925. }
  107926. }else{
  107927. if(_ve_envelope_mark(v)){
  107928. vbi->blocktype=BLOCKTYPE_IMPULSE;
  107929. /*fprintf(stderr,"|");*/
  107930. }else{
  107931. vbi->blocktype=BLOCKTYPE_PADDING;
  107932. /*fprintf(stderr,".");*/
  107933. }
  107934. }
  107935. vb->vd=v;
  107936. vb->sequence=v->sequence++;
  107937. vb->granulepos=v->granulepos;
  107938. vb->pcmend=ci->blocksizes[v->W];
  107939. /* copy the vectors; this uses the local storage in vb */
  107940. /* this tracks 'strongest peak' for later psychoacoustics */
  107941. /* moved to the global psy state; clean this mess up */
  107942. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  107943. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  107944. vbi->ampmax=g->ampmax;
  107945. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  107946. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  107947. for(i=0;i<vi->channels;i++){
  107948. vbi->pcmdelay[i]=
  107949. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107950. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107951. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  107952. /* before we added the delay
  107953. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  107954. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  107955. */
  107956. }
  107957. /* handle eof detection: eof==0 means that we've not yet received EOF
  107958. eof>0 marks the last 'real' sample in pcm[]
  107959. eof<0 'no more to do'; doesn't get here */
  107960. if(v->eofflag){
  107961. if(v->centerW>=v->eofflag){
  107962. v->eofflag=-1;
  107963. vb->eofflag=1;
  107964. return(1);
  107965. }
  107966. }
  107967. /* advance storage vectors and clean up */
  107968. {
  107969. int new_centerNext=ci->blocksizes[1]/2;
  107970. int movementW=centerNext-new_centerNext;
  107971. if(movementW>0){
  107972. _ve_envelope_shift(b->ve,movementW);
  107973. v->pcm_current-=movementW;
  107974. for(i=0;i<vi->channels;i++)
  107975. memmove(v->pcm[i],v->pcm[i]+movementW,
  107976. v->pcm_current*sizeof(*v->pcm[i]));
  107977. v->lW=v->W;
  107978. v->W=v->nW;
  107979. v->centerW=new_centerNext;
  107980. if(v->eofflag){
  107981. v->eofflag-=movementW;
  107982. if(v->eofflag<=0)v->eofflag=-1;
  107983. /* do not add padding to end of stream! */
  107984. if(v->centerW>=v->eofflag){
  107985. v->granulepos+=movementW-(v->centerW-v->eofflag);
  107986. }else{
  107987. v->granulepos+=movementW;
  107988. }
  107989. }else{
  107990. v->granulepos+=movementW;
  107991. }
  107992. }
  107993. }
  107994. /* done */
  107995. return(1);
  107996. }
  107997. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  107998. vorbis_info *vi=v->vi;
  107999. codec_setup_info *ci;
  108000. int hs;
  108001. if(!v->backend_state)return -1;
  108002. if(!vi)return -1;
  108003. ci=(codec_setup_info*) vi->codec_setup;
  108004. if(!ci)return -1;
  108005. hs=ci->halfrate_flag;
  108006. v->centerW=ci->blocksizes[1]>>(hs+1);
  108007. v->pcm_current=v->centerW>>hs;
  108008. v->pcm_returned=-1;
  108009. v->granulepos=-1;
  108010. v->sequence=-1;
  108011. v->eofflag=0;
  108012. ((private_state *)(v->backend_state))->sample_count=-1;
  108013. return(0);
  108014. }
  108015. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  108016. if(_vds_shared_init(v,vi,0)) return 1;
  108017. vorbis_synthesis_restart(v);
  108018. return 0;
  108019. }
  108020. /* Unlike in analysis, the window is only partially applied for each
  108021. block. The time domain envelope is not yet handled at the point of
  108022. calling (as it relies on the previous block). */
  108023. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  108024. vorbis_info *vi=v->vi;
  108025. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108026. private_state *b=(private_state*)v->backend_state;
  108027. int hs=ci->halfrate_flag;
  108028. int i,j;
  108029. if(!vb)return(OV_EINVAL);
  108030. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  108031. v->lW=v->W;
  108032. v->W=vb->W;
  108033. v->nW=-1;
  108034. if((v->sequence==-1)||
  108035. (v->sequence+1 != vb->sequence)){
  108036. v->granulepos=-1; /* out of sequence; lose count */
  108037. b->sample_count=-1;
  108038. }
  108039. v->sequence=vb->sequence;
  108040. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  108041. was called on block */
  108042. int n=ci->blocksizes[v->W]>>(hs+1);
  108043. int n0=ci->blocksizes[0]>>(hs+1);
  108044. int n1=ci->blocksizes[1]>>(hs+1);
  108045. int thisCenter;
  108046. int prevCenter;
  108047. v->glue_bits+=vb->glue_bits;
  108048. v->time_bits+=vb->time_bits;
  108049. v->floor_bits+=vb->floor_bits;
  108050. v->res_bits+=vb->res_bits;
  108051. if(v->centerW){
  108052. thisCenter=n1;
  108053. prevCenter=0;
  108054. }else{
  108055. thisCenter=0;
  108056. prevCenter=n1;
  108057. }
  108058. /* v->pcm is now used like a two-stage double buffer. We don't want
  108059. to have to constantly shift *or* adjust memory usage. Don't
  108060. accept a new block until the old is shifted out */
  108061. for(j=0;j<vi->channels;j++){
  108062. /* the overlap/add section */
  108063. if(v->lW){
  108064. if(v->W){
  108065. /* large/large */
  108066. float *w=_vorbis_window_get(b->window[1]-hs);
  108067. float *pcm=v->pcm[j]+prevCenter;
  108068. float *p=vb->pcm[j];
  108069. for(i=0;i<n1;i++)
  108070. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  108071. }else{
  108072. /* large/small */
  108073. float *w=_vorbis_window_get(b->window[0]-hs);
  108074. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  108075. float *p=vb->pcm[j];
  108076. for(i=0;i<n0;i++)
  108077. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108078. }
  108079. }else{
  108080. if(v->W){
  108081. /* small/large */
  108082. float *w=_vorbis_window_get(b->window[0]-hs);
  108083. float *pcm=v->pcm[j]+prevCenter;
  108084. float *p=vb->pcm[j]+n1/2-n0/2;
  108085. for(i=0;i<n0;i++)
  108086. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108087. for(;i<n1/2+n0/2;i++)
  108088. pcm[i]=p[i];
  108089. }else{
  108090. /* small/small */
  108091. float *w=_vorbis_window_get(b->window[0]-hs);
  108092. float *pcm=v->pcm[j]+prevCenter;
  108093. float *p=vb->pcm[j];
  108094. for(i=0;i<n0;i++)
  108095. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108096. }
  108097. }
  108098. /* the copy section */
  108099. {
  108100. float *pcm=v->pcm[j]+thisCenter;
  108101. float *p=vb->pcm[j]+n;
  108102. for(i=0;i<n;i++)
  108103. pcm[i]=p[i];
  108104. }
  108105. }
  108106. if(v->centerW)
  108107. v->centerW=0;
  108108. else
  108109. v->centerW=n1;
  108110. /* deal with initial packet state; we do this using the explicit
  108111. pcm_returned==-1 flag otherwise we're sensitive to first block
  108112. being short or long */
  108113. if(v->pcm_returned==-1){
  108114. v->pcm_returned=thisCenter;
  108115. v->pcm_current=thisCenter;
  108116. }else{
  108117. v->pcm_returned=prevCenter;
  108118. v->pcm_current=prevCenter+
  108119. ((ci->blocksizes[v->lW]/4+
  108120. ci->blocksizes[v->W]/4)>>hs);
  108121. }
  108122. }
  108123. /* track the frame number... This is for convenience, but also
  108124. making sure our last packet doesn't end with added padding. If
  108125. the last packet is partial, the number of samples we'll have to
  108126. return will be past the vb->granulepos.
  108127. This is not foolproof! It will be confused if we begin
  108128. decoding at the last page after a seek or hole. In that case,
  108129. we don't have a starting point to judge where the last frame
  108130. is. For this reason, vorbisfile will always try to make sure
  108131. it reads the last two marked pages in proper sequence */
  108132. if(b->sample_count==-1){
  108133. b->sample_count=0;
  108134. }else{
  108135. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108136. }
  108137. if(v->granulepos==-1){
  108138. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  108139. v->granulepos=vb->granulepos;
  108140. /* is this a short page? */
  108141. if(b->sample_count>v->granulepos){
  108142. /* corner case; if this is both the first and last audio page,
  108143. then spec says the end is cut, not beginning */
  108144. if(vb->eofflag){
  108145. /* trim the end */
  108146. /* no preceeding granulepos; assume we started at zero (we'd
  108147. have to in a short single-page stream) */
  108148. /* granulepos could be -1 due to a seek, but that would result
  108149. in a long count, not short count */
  108150. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  108151. }else{
  108152. /* trim the beginning */
  108153. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  108154. if(v->pcm_returned>v->pcm_current)
  108155. v->pcm_returned=v->pcm_current;
  108156. }
  108157. }
  108158. }
  108159. }else{
  108160. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108161. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  108162. if(v->granulepos>vb->granulepos){
  108163. long extra=v->granulepos-vb->granulepos;
  108164. if(extra)
  108165. if(vb->eofflag){
  108166. /* partial last frame. Strip the extra samples off */
  108167. v->pcm_current-=extra>>hs;
  108168. } /* else {Shouldn't happen *unless* the bitstream is out of
  108169. spec. Either way, believe the bitstream } */
  108170. } /* else {Shouldn't happen *unless* the bitstream is out of
  108171. spec. Either way, believe the bitstream } */
  108172. v->granulepos=vb->granulepos;
  108173. }
  108174. }
  108175. /* Update, cleanup */
  108176. if(vb->eofflag)v->eofflag=1;
  108177. return(0);
  108178. }
  108179. /* pcm==NULL indicates we just want the pending samples, no more */
  108180. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  108181. vorbis_info *vi=v->vi;
  108182. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  108183. if(pcm){
  108184. int i;
  108185. for(i=0;i<vi->channels;i++)
  108186. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108187. *pcm=v->pcmret;
  108188. }
  108189. return(v->pcm_current-v->pcm_returned);
  108190. }
  108191. return(0);
  108192. }
  108193. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  108194. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  108195. v->pcm_returned+=n;
  108196. return(0);
  108197. }
  108198. /* intended for use with a specific vorbisfile feature; we want access
  108199. to the [usually synthetic/postextrapolated] buffer and lapping at
  108200. the end of a decode cycle, specifically, a half-short-block worth.
  108201. This funtion works like pcmout above, except it will also expose
  108202. this implicit buffer data not normally decoded. */
  108203. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  108204. vorbis_info *vi=v->vi;
  108205. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108206. int hs=ci->halfrate_flag;
  108207. int n=ci->blocksizes[v->W]>>(hs+1);
  108208. int n0=ci->blocksizes[0]>>(hs+1);
  108209. int n1=ci->blocksizes[1]>>(hs+1);
  108210. int i,j;
  108211. if(v->pcm_returned<0)return 0;
  108212. /* our returned data ends at pcm_returned; because the synthesis pcm
  108213. buffer is a two-fragment ring, that means our data block may be
  108214. fragmented by buffering, wrapping or a short block not filling
  108215. out a buffer. To simplify things, we unfragment if it's at all
  108216. possibly needed. Otherwise, we'd need to call lapout more than
  108217. once as well as hold additional dsp state. Opt for
  108218. simplicity. */
  108219. /* centerW was advanced by blockin; it would be the center of the
  108220. *next* block */
  108221. if(v->centerW==n1){
  108222. /* the data buffer wraps; swap the halves */
  108223. /* slow, sure, small */
  108224. for(j=0;j<vi->channels;j++){
  108225. float *p=v->pcm[j];
  108226. for(i=0;i<n1;i++){
  108227. float temp=p[i];
  108228. p[i]=p[i+n1];
  108229. p[i+n1]=temp;
  108230. }
  108231. }
  108232. v->pcm_current-=n1;
  108233. v->pcm_returned-=n1;
  108234. v->centerW=0;
  108235. }
  108236. /* solidify buffer into contiguous space */
  108237. if((v->lW^v->W)==1){
  108238. /* long/short or short/long */
  108239. for(j=0;j<vi->channels;j++){
  108240. float *s=v->pcm[j];
  108241. float *d=v->pcm[j]+(n1-n0)/2;
  108242. for(i=(n1+n0)/2-1;i>=0;--i)
  108243. d[i]=s[i];
  108244. }
  108245. v->pcm_returned+=(n1-n0)/2;
  108246. v->pcm_current+=(n1-n0)/2;
  108247. }else{
  108248. if(v->lW==0){
  108249. /* short/short */
  108250. for(j=0;j<vi->channels;j++){
  108251. float *s=v->pcm[j];
  108252. float *d=v->pcm[j]+n1-n0;
  108253. for(i=n0-1;i>=0;--i)
  108254. d[i]=s[i];
  108255. }
  108256. v->pcm_returned+=n1-n0;
  108257. v->pcm_current+=n1-n0;
  108258. }
  108259. }
  108260. if(pcm){
  108261. int i;
  108262. for(i=0;i<vi->channels;i++)
  108263. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108264. *pcm=v->pcmret;
  108265. }
  108266. return(n1+n-v->pcm_returned);
  108267. }
  108268. float *vorbis_window(vorbis_dsp_state *v,int W){
  108269. vorbis_info *vi=v->vi;
  108270. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  108271. int hs=ci->halfrate_flag;
  108272. private_state *b=(private_state*)v->backend_state;
  108273. if(b->window[W]-1<0)return NULL;
  108274. return _vorbis_window_get(b->window[W]-hs);
  108275. }
  108276. #endif
  108277. /*** End of inlined file: block.c ***/
  108278. /*** Start of inlined file: codebook.c ***/
  108279. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108280. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108281. // tasks..
  108282. #if JUCE_MSVC
  108283. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108284. #endif
  108285. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108286. #if JUCE_USE_OGGVORBIS
  108287. #include <stdlib.h>
  108288. #include <string.h>
  108289. #include <math.h>
  108290. /* packs the given codebook into the bitstream **************************/
  108291. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  108292. long i,j;
  108293. int ordered=0;
  108294. /* first the basic parameters */
  108295. oggpack_write(opb,0x564342,24);
  108296. oggpack_write(opb,c->dim,16);
  108297. oggpack_write(opb,c->entries,24);
  108298. /* pack the codewords. There are two packings; length ordered and
  108299. length random. Decide between the two now. */
  108300. for(i=1;i<c->entries;i++)
  108301. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  108302. if(i==c->entries)ordered=1;
  108303. if(ordered){
  108304. /* length ordered. We only need to say how many codewords of
  108305. each length. The actual codewords are generated
  108306. deterministically */
  108307. long count=0;
  108308. oggpack_write(opb,1,1); /* ordered */
  108309. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  108310. for(i=1;i<c->entries;i++){
  108311. long thisx=c->lengthlist[i];
  108312. long last=c->lengthlist[i-1];
  108313. if(thisx>last){
  108314. for(j=last;j<thisx;j++){
  108315. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108316. count=i;
  108317. }
  108318. }
  108319. }
  108320. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108321. }else{
  108322. /* length random. Again, we don't code the codeword itself, just
  108323. the length. This time, though, we have to encode each length */
  108324. oggpack_write(opb,0,1); /* unordered */
  108325. /* algortihmic mapping has use for 'unused entries', which we tag
  108326. here. The algorithmic mapping happens as usual, but the unused
  108327. entry has no codeword. */
  108328. for(i=0;i<c->entries;i++)
  108329. if(c->lengthlist[i]==0)break;
  108330. if(i==c->entries){
  108331. oggpack_write(opb,0,1); /* no unused entries */
  108332. for(i=0;i<c->entries;i++)
  108333. oggpack_write(opb,c->lengthlist[i]-1,5);
  108334. }else{
  108335. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  108336. for(i=0;i<c->entries;i++){
  108337. if(c->lengthlist[i]==0){
  108338. oggpack_write(opb,0,1);
  108339. }else{
  108340. oggpack_write(opb,1,1);
  108341. oggpack_write(opb,c->lengthlist[i]-1,5);
  108342. }
  108343. }
  108344. }
  108345. }
  108346. /* is the entry number the desired return value, or do we have a
  108347. mapping? If we have a mapping, what type? */
  108348. oggpack_write(opb,c->maptype,4);
  108349. switch(c->maptype){
  108350. case 0:
  108351. /* no mapping */
  108352. break;
  108353. case 1:case 2:
  108354. /* implicitly populated value mapping */
  108355. /* explicitly populated value mapping */
  108356. if(!c->quantlist){
  108357. /* no quantlist? error */
  108358. return(-1);
  108359. }
  108360. /* values that define the dequantization */
  108361. oggpack_write(opb,c->q_min,32);
  108362. oggpack_write(opb,c->q_delta,32);
  108363. oggpack_write(opb,c->q_quant-1,4);
  108364. oggpack_write(opb,c->q_sequencep,1);
  108365. {
  108366. int quantvals;
  108367. switch(c->maptype){
  108368. case 1:
  108369. /* a single column of (c->entries/c->dim) quantized values for
  108370. building a full value list algorithmically (square lattice) */
  108371. quantvals=_book_maptype1_quantvals(c);
  108372. break;
  108373. case 2:
  108374. /* every value (c->entries*c->dim total) specified explicitly */
  108375. quantvals=c->entries*c->dim;
  108376. break;
  108377. default: /* NOT_REACHABLE */
  108378. quantvals=-1;
  108379. }
  108380. /* quantized values */
  108381. for(i=0;i<quantvals;i++)
  108382. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  108383. }
  108384. break;
  108385. default:
  108386. /* error case; we don't have any other map types now */
  108387. return(-1);
  108388. }
  108389. return(0);
  108390. }
  108391. /* unpacks a codebook from the packet buffer into the codebook struct,
  108392. readies the codebook auxiliary structures for decode *************/
  108393. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  108394. long i,j;
  108395. memset(s,0,sizeof(*s));
  108396. s->allocedp=1;
  108397. /* make sure alignment is correct */
  108398. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  108399. /* first the basic parameters */
  108400. s->dim=oggpack_read(opb,16);
  108401. s->entries=oggpack_read(opb,24);
  108402. if(s->entries==-1)goto _eofout;
  108403. /* codeword ordering.... length ordered or unordered? */
  108404. switch((int)oggpack_read(opb,1)){
  108405. case 0:
  108406. /* unordered */
  108407. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  108408. /* allocated but unused entries? */
  108409. if(oggpack_read(opb,1)){
  108410. /* yes, unused entries */
  108411. for(i=0;i<s->entries;i++){
  108412. if(oggpack_read(opb,1)){
  108413. long num=oggpack_read(opb,5);
  108414. if(num==-1)goto _eofout;
  108415. s->lengthlist[i]=num+1;
  108416. }else
  108417. s->lengthlist[i]=0;
  108418. }
  108419. }else{
  108420. /* all entries used; no tagging */
  108421. for(i=0;i<s->entries;i++){
  108422. long num=oggpack_read(opb,5);
  108423. if(num==-1)goto _eofout;
  108424. s->lengthlist[i]=num+1;
  108425. }
  108426. }
  108427. break;
  108428. case 1:
  108429. /* ordered */
  108430. {
  108431. long length=oggpack_read(opb,5)+1;
  108432. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  108433. for(i=0;i<s->entries;){
  108434. long num=oggpack_read(opb,_ilog(s->entries-i));
  108435. if(num==-1)goto _eofout;
  108436. for(j=0;j<num && i<s->entries;j++,i++)
  108437. s->lengthlist[i]=length;
  108438. length++;
  108439. }
  108440. }
  108441. break;
  108442. default:
  108443. /* EOF */
  108444. return(-1);
  108445. }
  108446. /* Do we have a mapping to unpack? */
  108447. switch((s->maptype=oggpack_read(opb,4))){
  108448. case 0:
  108449. /* no mapping */
  108450. break;
  108451. case 1: case 2:
  108452. /* implicitly populated value mapping */
  108453. /* explicitly populated value mapping */
  108454. s->q_min=oggpack_read(opb,32);
  108455. s->q_delta=oggpack_read(opb,32);
  108456. s->q_quant=oggpack_read(opb,4)+1;
  108457. s->q_sequencep=oggpack_read(opb,1);
  108458. {
  108459. int quantvals=0;
  108460. switch(s->maptype){
  108461. case 1:
  108462. quantvals=_book_maptype1_quantvals(s);
  108463. break;
  108464. case 2:
  108465. quantvals=s->entries*s->dim;
  108466. break;
  108467. }
  108468. /* quantized values */
  108469. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  108470. for(i=0;i<quantvals;i++)
  108471. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  108472. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  108473. }
  108474. break;
  108475. default:
  108476. goto _errout;
  108477. }
  108478. /* all set */
  108479. return(0);
  108480. _errout:
  108481. _eofout:
  108482. vorbis_staticbook_clear(s);
  108483. return(-1);
  108484. }
  108485. /* returns the number of bits ************************************************/
  108486. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  108487. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  108488. return(book->c->lengthlist[a]);
  108489. }
  108490. /* One the encode side, our vector writers are each designed for a
  108491. specific purpose, and the encoder is not flexible without modification:
  108492. The LSP vector coder uses a single stage nearest-match with no
  108493. interleave, so no step and no error return. This is specced by floor0
  108494. and doesn't change.
  108495. Residue0 encoding interleaves, uses multiple stages, and each stage
  108496. peels of a specific amount of resolution from a lattice (thus we want
  108497. to match by threshold, not nearest match). Residue doesn't *have* to
  108498. be encoded that way, but to change it, one will need to add more
  108499. infrastructure on the encode side (decode side is specced and simpler) */
  108500. /* floor0 LSP (single stage, non interleaved, nearest match) */
  108501. /* returns entry number and *modifies a* to the quantization value *****/
  108502. int vorbis_book_errorv(codebook *book,float *a){
  108503. int dim=book->dim,k;
  108504. int best=_best(book,a,1);
  108505. for(k=0;k<dim;k++)
  108506. a[k]=(book->valuelist+best*dim)[k];
  108507. return(best);
  108508. }
  108509. /* returns the number of bits and *modifies a* to the quantization value *****/
  108510. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  108511. int k,dim=book->dim;
  108512. for(k=0;k<dim;k++)
  108513. a[k]=(book->valuelist+best*dim)[k];
  108514. return(vorbis_book_encode(book,best,b));
  108515. }
  108516. /* the 'eliminate the decode tree' optimization actually requires the
  108517. codewords to be MSb first, not LSb. This is an annoying inelegancy
  108518. (and one of the first places where carefully thought out design
  108519. turned out to be wrong; Vorbis II and future Ogg codecs should go
  108520. to an MSb bitpacker), but not actually the huge hit it appears to
  108521. be. The first-stage decode table catches most words so that
  108522. bitreverse is not in the main execution path. */
  108523. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  108524. int read=book->dec_maxlength;
  108525. long lo,hi;
  108526. long lok = oggpack_look(b,book->dec_firsttablen);
  108527. if (lok >= 0) {
  108528. long entry = book->dec_firsttable[lok];
  108529. if(entry&0x80000000UL){
  108530. lo=(entry>>15)&0x7fff;
  108531. hi=book->used_entries-(entry&0x7fff);
  108532. }else{
  108533. oggpack_adv(b, book->dec_codelengths[entry-1]);
  108534. return(entry-1);
  108535. }
  108536. }else{
  108537. lo=0;
  108538. hi=book->used_entries;
  108539. }
  108540. lok = oggpack_look(b, read);
  108541. while(lok<0 && read>1)
  108542. lok = oggpack_look(b, --read);
  108543. if(lok<0)return -1;
  108544. /* bisect search for the codeword in the ordered list */
  108545. {
  108546. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  108547. while(hi-lo>1){
  108548. long p=(hi-lo)>>1;
  108549. long test=book->codelist[lo+p]>testword;
  108550. lo+=p&(test-1);
  108551. hi-=p&(-test);
  108552. }
  108553. if(book->dec_codelengths[lo]<=read){
  108554. oggpack_adv(b, book->dec_codelengths[lo]);
  108555. return(lo);
  108556. }
  108557. }
  108558. oggpack_adv(b, read);
  108559. return(-1);
  108560. }
  108561. /* Decode side is specced and easier, because we don't need to find
  108562. matches using different criteria; we simply read and map. There are
  108563. two things we need to do 'depending':
  108564. We may need to support interleave. We don't really, but it's
  108565. convenient to do it here rather than rebuild the vector later.
  108566. Cascades may be additive or multiplicitive; this is not inherent in
  108567. the codebook, but set in the code using the codebook. Like
  108568. interleaving, it's easiest to do it here.
  108569. addmul==0 -> declarative (set the value)
  108570. addmul==1 -> additive
  108571. addmul==2 -> multiplicitive */
  108572. /* returns the [original, not compacted] entry number or -1 on eof *********/
  108573. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  108574. long packed_entry=decode_packed_entry_number(book,b);
  108575. if(packed_entry>=0)
  108576. return(book->dec_index[packed_entry]);
  108577. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  108578. return(packed_entry);
  108579. }
  108580. /* returns 0 on OK or -1 on eof *************************************/
  108581. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  108582. int step=n/book->dim;
  108583. long *entry = (long*)alloca(sizeof(*entry)*step);
  108584. float **t = (float**)alloca(sizeof(*t)*step);
  108585. int i,j,o;
  108586. for (i = 0; i < step; i++) {
  108587. entry[i]=decode_packed_entry_number(book,b);
  108588. if(entry[i]==-1)return(-1);
  108589. t[i] = book->valuelist+entry[i]*book->dim;
  108590. }
  108591. for(i=0,o=0;i<book->dim;i++,o+=step)
  108592. for (j=0;j<step;j++)
  108593. a[o+j]+=t[j][i];
  108594. return(0);
  108595. }
  108596. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  108597. int i,j,entry;
  108598. float *t;
  108599. if(book->dim>8){
  108600. for(i=0;i<n;){
  108601. entry = decode_packed_entry_number(book,b);
  108602. if(entry==-1)return(-1);
  108603. t = book->valuelist+entry*book->dim;
  108604. for (j=0;j<book->dim;)
  108605. a[i++]+=t[j++];
  108606. }
  108607. }else{
  108608. for(i=0;i<n;){
  108609. entry = decode_packed_entry_number(book,b);
  108610. if(entry==-1)return(-1);
  108611. t = book->valuelist+entry*book->dim;
  108612. j=0;
  108613. switch((int)book->dim){
  108614. case 8:
  108615. a[i++]+=t[j++];
  108616. case 7:
  108617. a[i++]+=t[j++];
  108618. case 6:
  108619. a[i++]+=t[j++];
  108620. case 5:
  108621. a[i++]+=t[j++];
  108622. case 4:
  108623. a[i++]+=t[j++];
  108624. case 3:
  108625. a[i++]+=t[j++];
  108626. case 2:
  108627. a[i++]+=t[j++];
  108628. case 1:
  108629. a[i++]+=t[j++];
  108630. case 0:
  108631. break;
  108632. }
  108633. }
  108634. }
  108635. return(0);
  108636. }
  108637. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  108638. int i,j,entry;
  108639. float *t;
  108640. for(i=0;i<n;){
  108641. entry = decode_packed_entry_number(book,b);
  108642. if(entry==-1)return(-1);
  108643. t = book->valuelist+entry*book->dim;
  108644. for (j=0;j<book->dim;)
  108645. a[i++]=t[j++];
  108646. }
  108647. return(0);
  108648. }
  108649. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  108650. oggpack_buffer *b,int n){
  108651. long i,j,entry;
  108652. int chptr=0;
  108653. for(i=offset/ch;i<(offset+n)/ch;){
  108654. entry = decode_packed_entry_number(book,b);
  108655. if(entry==-1)return(-1);
  108656. {
  108657. const float *t = book->valuelist+entry*book->dim;
  108658. for (j=0;j<book->dim;j++){
  108659. a[chptr++][i]+=t[j];
  108660. if(chptr==ch){
  108661. chptr=0;
  108662. i++;
  108663. }
  108664. }
  108665. }
  108666. }
  108667. return(0);
  108668. }
  108669. #ifdef _V_SELFTEST
  108670. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  108671. number of vectors through (keeping track of the quantized values),
  108672. and decode using the unpacked book. quantized version of in should
  108673. exactly equal out */
  108674. #include <stdio.h>
  108675. #include "vorbis/book/lsp20_0.vqh"
  108676. #include "vorbis/book/res0a_13.vqh"
  108677. #define TESTSIZE 40
  108678. float test1[TESTSIZE]={
  108679. 0.105939f,
  108680. 0.215373f,
  108681. 0.429117f,
  108682. 0.587974f,
  108683. 0.181173f,
  108684. 0.296583f,
  108685. 0.515707f,
  108686. 0.715261f,
  108687. 0.162327f,
  108688. 0.263834f,
  108689. 0.342876f,
  108690. 0.406025f,
  108691. 0.103571f,
  108692. 0.223561f,
  108693. 0.368513f,
  108694. 0.540313f,
  108695. 0.136672f,
  108696. 0.395882f,
  108697. 0.587183f,
  108698. 0.652476f,
  108699. 0.114338f,
  108700. 0.417300f,
  108701. 0.525486f,
  108702. 0.698679f,
  108703. 0.147492f,
  108704. 0.324481f,
  108705. 0.643089f,
  108706. 0.757582f,
  108707. 0.139556f,
  108708. 0.215795f,
  108709. 0.324559f,
  108710. 0.399387f,
  108711. 0.120236f,
  108712. 0.267420f,
  108713. 0.446940f,
  108714. 0.608760f,
  108715. 0.115587f,
  108716. 0.287234f,
  108717. 0.571081f,
  108718. 0.708603f,
  108719. };
  108720. float test3[TESTSIZE]={
  108721. 0,1,-2,3,4,-5,6,7,8,9,
  108722. 8,-2,7,-1,4,6,8,3,1,-9,
  108723. 10,11,12,13,14,15,26,17,18,19,
  108724. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  108725. static_codebook *testlist[]={&_vq_book_lsp20_0,
  108726. &_vq_book_res0a_13,NULL};
  108727. float *testvec[]={test1,test3};
  108728. int main(){
  108729. oggpack_buffer write;
  108730. oggpack_buffer read;
  108731. long ptr=0,i;
  108732. oggpack_writeinit(&write);
  108733. fprintf(stderr,"Testing codebook abstraction...:\n");
  108734. while(testlist[ptr]){
  108735. codebook c;
  108736. static_codebook s;
  108737. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  108738. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  108739. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  108740. memset(iv,0,sizeof(*iv)*TESTSIZE);
  108741. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  108742. /* pack the codebook, write the testvector */
  108743. oggpack_reset(&write);
  108744. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  108745. we can write */
  108746. vorbis_staticbook_pack(testlist[ptr],&write);
  108747. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  108748. for(i=0;i<TESTSIZE;i+=c.dim){
  108749. int best=_best(&c,qv+i,1);
  108750. vorbis_book_encodev(&c,best,qv+i,&write);
  108751. }
  108752. vorbis_book_clear(&c);
  108753. fprintf(stderr,"OK.\n");
  108754. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  108755. /* transfer the write data to a read buffer and unpack/read */
  108756. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  108757. if(vorbis_staticbook_unpack(&read,&s)){
  108758. fprintf(stderr,"Error unpacking codebook.\n");
  108759. exit(1);
  108760. }
  108761. if(vorbis_book_init_decode(&c,&s)){
  108762. fprintf(stderr,"Error initializing codebook.\n");
  108763. exit(1);
  108764. }
  108765. for(i=0;i<TESTSIZE;i+=c.dim)
  108766. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  108767. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  108768. exit(1);
  108769. }
  108770. for(i=0;i<TESTSIZE;i++)
  108771. if(fabs(qv[i]-iv[i])>.000001){
  108772. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  108773. iv[i],qv[i],i);
  108774. exit(1);
  108775. }
  108776. fprintf(stderr,"OK\n");
  108777. ptr++;
  108778. }
  108779. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  108780. exit(0);
  108781. }
  108782. #endif
  108783. #endif
  108784. /*** End of inlined file: codebook.c ***/
  108785. /*** Start of inlined file: envelope.c ***/
  108786. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108787. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108788. // tasks..
  108789. #if JUCE_MSVC
  108790. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108791. #endif
  108792. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108793. #if JUCE_USE_OGGVORBIS
  108794. #include <stdlib.h>
  108795. #include <string.h>
  108796. #include <stdio.h>
  108797. #include <math.h>
  108798. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  108799. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108800. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108801. int ch=vi->channels;
  108802. int i,j;
  108803. int n=e->winlength=128;
  108804. e->searchstep=64; /* not random */
  108805. e->minenergy=gi->preecho_minenergy;
  108806. e->ch=ch;
  108807. e->storage=128;
  108808. e->cursor=ci->blocksizes[1]/2;
  108809. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  108810. mdct_init(&e->mdct,n);
  108811. for(i=0;i<n;i++){
  108812. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  108813. e->mdct_win[i]*=e->mdct_win[i];
  108814. }
  108815. /* magic follows */
  108816. e->band[0].begin=2; e->band[0].end=4;
  108817. e->band[1].begin=4; e->band[1].end=5;
  108818. e->band[2].begin=6; e->band[2].end=6;
  108819. e->band[3].begin=9; e->band[3].end=8;
  108820. e->band[4].begin=13; e->band[4].end=8;
  108821. e->band[5].begin=17; e->band[5].end=8;
  108822. e->band[6].begin=22; e->band[6].end=8;
  108823. for(j=0;j<VE_BANDS;j++){
  108824. n=e->band[j].end;
  108825. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  108826. for(i=0;i<n;i++){
  108827. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  108828. e->band[j].total+=e->band[j].window[i];
  108829. }
  108830. e->band[j].total=1./e->band[j].total;
  108831. }
  108832. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  108833. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  108834. }
  108835. void _ve_envelope_clear(envelope_lookup *e){
  108836. int i;
  108837. mdct_clear(&e->mdct);
  108838. for(i=0;i<VE_BANDS;i++)
  108839. _ogg_free(e->band[i].window);
  108840. _ogg_free(e->mdct_win);
  108841. _ogg_free(e->filter);
  108842. _ogg_free(e->mark);
  108843. memset(e,0,sizeof(*e));
  108844. }
  108845. /* fairly straight threshhold-by-band based until we find something
  108846. that works better and isn't patented. */
  108847. static int _ve_amp(envelope_lookup *ve,
  108848. vorbis_info_psy_global *gi,
  108849. float *data,
  108850. envelope_band *bands,
  108851. envelope_filter_state *filters,
  108852. long pos){
  108853. long n=ve->winlength;
  108854. int ret=0;
  108855. long i,j;
  108856. float decay;
  108857. /* we want to have a 'minimum bar' for energy, else we're just
  108858. basing blocks on quantization noise that outweighs the signal
  108859. itself (for low power signals) */
  108860. float minV=ve->minenergy;
  108861. float *vec=(float*) alloca(n*sizeof(*vec));
  108862. /* stretch is used to gradually lengthen the number of windows
  108863. considered prevoius-to-potential-trigger */
  108864. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  108865. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  108866. if(penalty<0.f)penalty=0.f;
  108867. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  108868. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  108869. totalshift+pos*ve->searchstep);*/
  108870. /* window and transform */
  108871. for(i=0;i<n;i++)
  108872. vec[i]=data[i]*ve->mdct_win[i];
  108873. mdct_forward(&ve->mdct,vec,vec);
  108874. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  108875. /* near-DC spreading function; this has nothing to do with
  108876. psychoacoustics, just sidelobe leakage and window size */
  108877. {
  108878. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  108879. int ptr=filters->nearptr;
  108880. /* the accumulation is regularly refreshed from scratch to avoid
  108881. floating point creep */
  108882. if(ptr==0){
  108883. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  108884. filters->nearDC_partialacc=temp;
  108885. }else{
  108886. decay=filters->nearDC_acc+=temp;
  108887. filters->nearDC_partialacc+=temp;
  108888. }
  108889. filters->nearDC_acc-=filters->nearDC[ptr];
  108890. filters->nearDC[ptr]=temp;
  108891. decay*=(1./(VE_NEARDC+1));
  108892. filters->nearptr++;
  108893. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  108894. decay=todB(&decay)*.5-15.f;
  108895. }
  108896. /* perform spreading and limiting, also smooth the spectrum. yes,
  108897. the MDCT results in all real coefficients, but it still *behaves*
  108898. like real/imaginary pairs */
  108899. for(i=0;i<n/2;i+=2){
  108900. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  108901. val=todB(&val)*.5f;
  108902. if(val<decay)val=decay;
  108903. if(val<minV)val=minV;
  108904. vec[i>>1]=val;
  108905. decay-=8.;
  108906. }
  108907. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  108908. /* perform preecho/postecho triggering by band */
  108909. for(j=0;j<VE_BANDS;j++){
  108910. float acc=0.;
  108911. float valmax,valmin;
  108912. /* accumulate amplitude */
  108913. for(i=0;i<bands[j].end;i++)
  108914. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  108915. acc*=bands[j].total;
  108916. /* convert amplitude to delta */
  108917. {
  108918. int p,thisx=filters[j].ampptr;
  108919. float postmax,postmin,premax=-99999.f,premin=99999.f;
  108920. p=thisx;
  108921. p--;
  108922. if(p<0)p+=VE_AMP;
  108923. postmax=max(acc,filters[j].ampbuf[p]);
  108924. postmin=min(acc,filters[j].ampbuf[p]);
  108925. for(i=0;i<stretch;i++){
  108926. p--;
  108927. if(p<0)p+=VE_AMP;
  108928. premax=max(premax,filters[j].ampbuf[p]);
  108929. premin=min(premin,filters[j].ampbuf[p]);
  108930. }
  108931. valmin=postmin-premin;
  108932. valmax=postmax-premax;
  108933. /*filters[j].markers[pos]=valmax;*/
  108934. filters[j].ampbuf[thisx]=acc;
  108935. filters[j].ampptr++;
  108936. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  108937. }
  108938. /* look at min/max, decide trigger */
  108939. if(valmax>gi->preecho_thresh[j]+penalty){
  108940. ret|=1;
  108941. ret|=4;
  108942. }
  108943. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  108944. }
  108945. return(ret);
  108946. }
  108947. #if 0
  108948. static int seq=0;
  108949. static ogg_int64_t totalshift=-1024;
  108950. #endif
  108951. long _ve_envelope_search(vorbis_dsp_state *v){
  108952. vorbis_info *vi=v->vi;
  108953. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108954. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108955. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108956. long i,j;
  108957. int first=ve->current/ve->searchstep;
  108958. int last=v->pcm_current/ve->searchstep-VE_WIN;
  108959. if(first<0)first=0;
  108960. /* make sure we have enough storage to match the PCM */
  108961. if(last+VE_WIN+VE_POST>ve->storage){
  108962. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  108963. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  108964. }
  108965. for(j=first;j<last;j++){
  108966. int ret=0;
  108967. ve->stretch++;
  108968. if(ve->stretch>VE_MAXSTRETCH*2)
  108969. ve->stretch=VE_MAXSTRETCH*2;
  108970. for(i=0;i<ve->ch;i++){
  108971. float *pcm=v->pcm[i]+ve->searchstep*(j);
  108972. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  108973. }
  108974. ve->mark[j+VE_POST]=0;
  108975. if(ret&1){
  108976. ve->mark[j]=1;
  108977. ve->mark[j+1]=1;
  108978. }
  108979. if(ret&2){
  108980. ve->mark[j]=1;
  108981. if(j>0)ve->mark[j-1]=1;
  108982. }
  108983. if(ret&4)ve->stretch=-1;
  108984. }
  108985. ve->current=last*ve->searchstep;
  108986. {
  108987. long centerW=v->centerW;
  108988. long testW=
  108989. centerW+
  108990. ci->blocksizes[v->W]/4+
  108991. ci->blocksizes[1]/2+
  108992. ci->blocksizes[0]/4;
  108993. j=ve->cursor;
  108994. while(j<ve->current-(ve->searchstep)){/* account for postecho
  108995. working back one window */
  108996. if(j>=testW)return(1);
  108997. ve->cursor=j;
  108998. if(ve->mark[j/ve->searchstep]){
  108999. if(j>centerW){
  109000. #if 0
  109001. if(j>ve->curmark){
  109002. float *marker=alloca(v->pcm_current*sizeof(*marker));
  109003. int l,m;
  109004. memset(marker,0,sizeof(*marker)*v->pcm_current);
  109005. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  109006. seq,
  109007. (totalshift+ve->cursor)/44100.,
  109008. (totalshift+j)/44100.);
  109009. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  109010. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  109011. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  109012. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  109013. for(m=0;m<VE_BANDS;m++){
  109014. char buf[80];
  109015. sprintf(buf,"delL%d",m);
  109016. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  109017. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109018. }
  109019. for(m=0;m<VE_BANDS;m++){
  109020. char buf[80];
  109021. sprintf(buf,"delR%d",m);
  109022. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  109023. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109024. }
  109025. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  109026. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  109027. seq++;
  109028. }
  109029. #endif
  109030. ve->curmark=j;
  109031. if(j>=testW)return(1);
  109032. return(0);
  109033. }
  109034. }
  109035. j+=ve->searchstep;
  109036. }
  109037. }
  109038. return(-1);
  109039. }
  109040. int _ve_envelope_mark(vorbis_dsp_state *v){
  109041. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  109042. vorbis_info *vi=v->vi;
  109043. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109044. long centerW=v->centerW;
  109045. long beginW=centerW-ci->blocksizes[v->W]/4;
  109046. long endW=centerW+ci->blocksizes[v->W]/4;
  109047. if(v->W){
  109048. beginW-=ci->blocksizes[v->lW]/4;
  109049. endW+=ci->blocksizes[v->nW]/4;
  109050. }else{
  109051. beginW-=ci->blocksizes[0]/4;
  109052. endW+=ci->blocksizes[0]/4;
  109053. }
  109054. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  109055. {
  109056. long first=beginW/ve->searchstep;
  109057. long last=endW/ve->searchstep;
  109058. long i;
  109059. for(i=first;i<last;i++)
  109060. if(ve->mark[i])return(1);
  109061. }
  109062. return(0);
  109063. }
  109064. void _ve_envelope_shift(envelope_lookup *e,long shift){
  109065. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  109066. ahead of ve->current */
  109067. int smallshift=shift/e->searchstep;
  109068. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  109069. #if 0
  109070. for(i=0;i<VE_BANDS*e->ch;i++)
  109071. memmove(e->filter[i].markers,
  109072. e->filter[i].markers+smallshift,
  109073. (1024-smallshift)*sizeof(*(*e->filter).markers));
  109074. totalshift+=shift;
  109075. #endif
  109076. e->current-=shift;
  109077. if(e->curmark>=0)
  109078. e->curmark-=shift;
  109079. e->cursor-=shift;
  109080. }
  109081. #endif
  109082. /*** End of inlined file: envelope.c ***/
  109083. /*** Start of inlined file: floor0.c ***/
  109084. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109085. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109086. // tasks..
  109087. #if JUCE_MSVC
  109088. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109089. #endif
  109090. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109091. #if JUCE_USE_OGGVORBIS
  109092. #include <stdlib.h>
  109093. #include <string.h>
  109094. #include <math.h>
  109095. /*** Start of inlined file: lsp.h ***/
  109096. #ifndef _V_LSP_H_
  109097. #define _V_LSP_H_
  109098. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  109099. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  109100. float *lsp,int m,
  109101. float amp,float ampoffset);
  109102. #endif
  109103. /*** End of inlined file: lsp.h ***/
  109104. #include <stdio.h>
  109105. typedef struct {
  109106. int ln;
  109107. int m;
  109108. int **linearmap;
  109109. int n[2];
  109110. vorbis_info_floor0 *vi;
  109111. long bits;
  109112. long frames;
  109113. } vorbis_look_floor0;
  109114. /***********************************************/
  109115. static void floor0_free_info(vorbis_info_floor *i){
  109116. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  109117. if(info){
  109118. memset(info,0,sizeof(*info));
  109119. _ogg_free(info);
  109120. }
  109121. }
  109122. static void floor0_free_look(vorbis_look_floor *i){
  109123. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109124. if(look){
  109125. if(look->linearmap){
  109126. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  109127. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  109128. _ogg_free(look->linearmap);
  109129. }
  109130. memset(look,0,sizeof(*look));
  109131. _ogg_free(look);
  109132. }
  109133. }
  109134. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109135. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109136. int j;
  109137. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  109138. info->order=oggpack_read(opb,8);
  109139. info->rate=oggpack_read(opb,16);
  109140. info->barkmap=oggpack_read(opb,16);
  109141. info->ampbits=oggpack_read(opb,6);
  109142. info->ampdB=oggpack_read(opb,8);
  109143. info->numbooks=oggpack_read(opb,4)+1;
  109144. if(info->order<1)goto err_out;
  109145. if(info->rate<1)goto err_out;
  109146. if(info->barkmap<1)goto err_out;
  109147. if(info->numbooks<1)goto err_out;
  109148. for(j=0;j<info->numbooks;j++){
  109149. info->books[j]=oggpack_read(opb,8);
  109150. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  109151. }
  109152. return(info);
  109153. err_out:
  109154. floor0_free_info(info);
  109155. return(NULL);
  109156. }
  109157. /* initialize Bark scale and normalization lookups. We could do this
  109158. with static tables, but Vorbis allows a number of possible
  109159. combinations, so it's best to do it computationally.
  109160. The below is authoritative in terms of defining scale mapping.
  109161. Note that the scale depends on the sampling rate as well as the
  109162. linear block and mapping sizes */
  109163. static void floor0_map_lazy_init(vorbis_block *vb,
  109164. vorbis_info_floor *infoX,
  109165. vorbis_look_floor0 *look){
  109166. if(!look->linearmap[vb->W]){
  109167. vorbis_dsp_state *vd=vb->vd;
  109168. vorbis_info *vi=vd->vi;
  109169. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109170. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  109171. int W=vb->W;
  109172. int n=ci->blocksizes[W]/2,j;
  109173. /* we choose a scaling constant so that:
  109174. floor(bark(rate/2-1)*C)=mapped-1
  109175. floor(bark(rate/2)*C)=mapped */
  109176. float scale=look->ln/toBARK(info->rate/2.f);
  109177. /* the mapping from a linear scale to a smaller bark scale is
  109178. straightforward. We do *not* make sure that the linear mapping
  109179. does not skip bark-scale bins; the decoder simply skips them and
  109180. the encoder may do what it wishes in filling them. They're
  109181. necessary in some mapping combinations to keep the scale spacing
  109182. accurate */
  109183. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  109184. for(j=0;j<n;j++){
  109185. int val=floor( toBARK((info->rate/2.f)/n*j)
  109186. *scale); /* bark numbers represent band edges */
  109187. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  109188. look->linearmap[W][j]=val;
  109189. }
  109190. look->linearmap[W][j]=-1;
  109191. look->n[W]=n;
  109192. }
  109193. }
  109194. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  109195. vorbis_info_floor *i){
  109196. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  109197. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  109198. look->m=info->order;
  109199. look->ln=info->barkmap;
  109200. look->vi=info;
  109201. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  109202. return look;
  109203. }
  109204. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  109205. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109206. vorbis_info_floor0 *info=look->vi;
  109207. int j,k;
  109208. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  109209. if(ampraw>0){ /* also handles the -1 out of data case */
  109210. long maxval=(1<<info->ampbits)-1;
  109211. float amp=(float)ampraw/maxval*info->ampdB;
  109212. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  109213. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  109214. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  109215. codebook *b=ci->fullbooks+info->books[booknum];
  109216. float last=0.f;
  109217. /* the additional b->dim is a guard against any possible stack
  109218. smash; b->dim is provably more than we can overflow the
  109219. vector */
  109220. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  109221. for(j=0;j<look->m;j+=b->dim)
  109222. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  109223. for(j=0;j<look->m;){
  109224. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  109225. last=lsp[j-1];
  109226. }
  109227. lsp[look->m]=amp;
  109228. return(lsp);
  109229. }
  109230. }
  109231. eop:
  109232. return(NULL);
  109233. }
  109234. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  109235. void *memo,float *out){
  109236. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109237. vorbis_info_floor0 *info=look->vi;
  109238. floor0_map_lazy_init(vb,info,look);
  109239. if(memo){
  109240. float *lsp=(float *)memo;
  109241. float amp=lsp[look->m];
  109242. /* take the coefficients back to a spectral envelope curve */
  109243. vorbis_lsp_to_curve(out,
  109244. look->linearmap[vb->W],
  109245. look->n[vb->W],
  109246. look->ln,
  109247. lsp,look->m,amp,(float)info->ampdB);
  109248. return(1);
  109249. }
  109250. memset(out,0,sizeof(*out)*look->n[vb->W]);
  109251. return(0);
  109252. }
  109253. /* export hooks */
  109254. vorbis_func_floor floor0_exportbundle={
  109255. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  109256. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  109257. };
  109258. #endif
  109259. /*** End of inlined file: floor0.c ***/
  109260. /*** Start of inlined file: floor1.c ***/
  109261. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109262. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109263. // tasks..
  109264. #if JUCE_MSVC
  109265. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109266. #endif
  109267. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109268. #if JUCE_USE_OGGVORBIS
  109269. #include <stdlib.h>
  109270. #include <string.h>
  109271. #include <math.h>
  109272. #include <stdio.h>
  109273. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  109274. typedef struct {
  109275. int sorted_index[VIF_POSIT+2];
  109276. int forward_index[VIF_POSIT+2];
  109277. int reverse_index[VIF_POSIT+2];
  109278. int hineighbor[VIF_POSIT];
  109279. int loneighbor[VIF_POSIT];
  109280. int posts;
  109281. int n;
  109282. int quant_q;
  109283. vorbis_info_floor1 *vi;
  109284. long phrasebits;
  109285. long postbits;
  109286. long frames;
  109287. } vorbis_look_floor1;
  109288. typedef struct lsfit_acc{
  109289. long x0;
  109290. long x1;
  109291. long xa;
  109292. long ya;
  109293. long x2a;
  109294. long y2a;
  109295. long xya;
  109296. long an;
  109297. } lsfit_acc;
  109298. /***********************************************/
  109299. static void floor1_free_info(vorbis_info_floor *i){
  109300. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109301. if(info){
  109302. memset(info,0,sizeof(*info));
  109303. _ogg_free(info);
  109304. }
  109305. }
  109306. static void floor1_free_look(vorbis_look_floor *i){
  109307. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  109308. if(look){
  109309. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  109310. (float)look->phrasebits/look->frames,
  109311. (float)look->postbits/look->frames,
  109312. (float)(look->postbits+look->phrasebits)/look->frames);*/
  109313. memset(look,0,sizeof(*look));
  109314. _ogg_free(look);
  109315. }
  109316. }
  109317. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  109318. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109319. int j,k;
  109320. int count=0;
  109321. int rangebits;
  109322. int maxposit=info->postlist[1];
  109323. int maxclass=-1;
  109324. /* save out partitions */
  109325. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  109326. for(j=0;j<info->partitions;j++){
  109327. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  109328. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109329. }
  109330. /* save out partition classes */
  109331. for(j=0;j<maxclass+1;j++){
  109332. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  109333. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  109334. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  109335. for(k=0;k<(1<<info->class_subs[j]);k++)
  109336. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  109337. }
  109338. /* save out the post list */
  109339. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  109340. oggpack_write(opb,ilog2(maxposit),4);
  109341. rangebits=ilog2(maxposit);
  109342. for(j=0,k=0;j<info->partitions;j++){
  109343. count+=info->class_dim[info->partitionclass[j]];
  109344. for(;k<count;k++)
  109345. oggpack_write(opb,info->postlist[k+2],rangebits);
  109346. }
  109347. }
  109348. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109349. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109350. int j,k,count=0,maxclass=-1,rangebits;
  109351. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  109352. /* read partitions */
  109353. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  109354. for(j=0;j<info->partitions;j++){
  109355. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  109356. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109357. }
  109358. /* read partition classes */
  109359. for(j=0;j<maxclass+1;j++){
  109360. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  109361. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  109362. if(info->class_subs[j]<0)
  109363. goto err_out;
  109364. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  109365. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  109366. goto err_out;
  109367. for(k=0;k<(1<<info->class_subs[j]);k++){
  109368. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  109369. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  109370. goto err_out;
  109371. }
  109372. }
  109373. /* read the post list */
  109374. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  109375. rangebits=oggpack_read(opb,4);
  109376. for(j=0,k=0;j<info->partitions;j++){
  109377. count+=info->class_dim[info->partitionclass[j]];
  109378. for(;k<count;k++){
  109379. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  109380. if(t<0 || t>=(1<<rangebits))
  109381. goto err_out;
  109382. }
  109383. }
  109384. info->postlist[0]=0;
  109385. info->postlist[1]=1<<rangebits;
  109386. return(info);
  109387. err_out:
  109388. floor1_free_info(info);
  109389. return(NULL);
  109390. }
  109391. static int icomp(const void *a,const void *b){
  109392. return(**(int **)a-**(int **)b);
  109393. }
  109394. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  109395. vorbis_info_floor *in){
  109396. int *sortpointer[VIF_POSIT+2];
  109397. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  109398. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  109399. int i,j,n=0;
  109400. look->vi=info;
  109401. look->n=info->postlist[1];
  109402. /* we drop each position value in-between already decoded values,
  109403. and use linear interpolation to predict each new value past the
  109404. edges. The positions are read in the order of the position
  109405. list... we precompute the bounding positions in the lookup. Of
  109406. course, the neighbors can change (if a position is declined), but
  109407. this is an initial mapping */
  109408. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  109409. n+=2;
  109410. look->posts=n;
  109411. /* also store a sorted position index */
  109412. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  109413. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  109414. /* points from sort order back to range number */
  109415. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  109416. /* points from range order to sorted position */
  109417. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  109418. /* we actually need the post values too */
  109419. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  109420. /* quantize values to multiplier spec */
  109421. switch(info->mult){
  109422. case 1: /* 1024 -> 256 */
  109423. look->quant_q=256;
  109424. break;
  109425. case 2: /* 1024 -> 128 */
  109426. look->quant_q=128;
  109427. break;
  109428. case 3: /* 1024 -> 86 */
  109429. look->quant_q=86;
  109430. break;
  109431. case 4: /* 1024 -> 64 */
  109432. look->quant_q=64;
  109433. break;
  109434. }
  109435. /* discover our neighbors for decode where we don't use fit flags
  109436. (that would push the neighbors outward) */
  109437. for(i=0;i<n-2;i++){
  109438. int lo=0;
  109439. int hi=1;
  109440. int lx=0;
  109441. int hx=look->n;
  109442. int currentx=info->postlist[i+2];
  109443. for(j=0;j<i+2;j++){
  109444. int x=info->postlist[j];
  109445. if(x>lx && x<currentx){
  109446. lo=j;
  109447. lx=x;
  109448. }
  109449. if(x<hx && x>currentx){
  109450. hi=j;
  109451. hx=x;
  109452. }
  109453. }
  109454. look->loneighbor[i]=lo;
  109455. look->hineighbor[i]=hi;
  109456. }
  109457. return(look);
  109458. }
  109459. static int render_point(int x0,int x1,int y0,int y1,int x){
  109460. y0&=0x7fff; /* mask off flag */
  109461. y1&=0x7fff;
  109462. {
  109463. int dy=y1-y0;
  109464. int adx=x1-x0;
  109465. int ady=abs(dy);
  109466. int err=ady*(x-x0);
  109467. int off=err/adx;
  109468. if(dy<0)return(y0-off);
  109469. return(y0+off);
  109470. }
  109471. }
  109472. static int vorbis_dBquant(const float *x){
  109473. int i= *x*7.3142857f+1023.5f;
  109474. if(i>1023)return(1023);
  109475. if(i<0)return(0);
  109476. return i;
  109477. }
  109478. static float FLOOR1_fromdB_LOOKUP[256]={
  109479. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  109480. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  109481. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  109482. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  109483. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  109484. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  109485. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  109486. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  109487. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  109488. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  109489. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  109490. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  109491. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  109492. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  109493. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  109494. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  109495. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  109496. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  109497. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  109498. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  109499. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  109500. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  109501. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  109502. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  109503. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  109504. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  109505. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  109506. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  109507. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  109508. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  109509. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  109510. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  109511. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  109512. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  109513. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  109514. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  109515. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  109516. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  109517. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  109518. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  109519. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  109520. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  109521. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  109522. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  109523. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  109524. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  109525. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  109526. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  109527. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  109528. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  109529. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  109530. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  109531. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  109532. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  109533. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  109534. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  109535. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  109536. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  109537. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  109538. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  109539. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  109540. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  109541. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  109542. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  109543. };
  109544. static void render_line(int x0,int x1,int y0,int y1,float *d){
  109545. int dy=y1-y0;
  109546. int adx=x1-x0;
  109547. int ady=abs(dy);
  109548. int base=dy/adx;
  109549. int sy=(dy<0?base-1:base+1);
  109550. int x=x0;
  109551. int y=y0;
  109552. int err=0;
  109553. ady-=abs(base*adx);
  109554. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  109555. while(++x<x1){
  109556. err=err+ady;
  109557. if(err>=adx){
  109558. err-=adx;
  109559. y+=sy;
  109560. }else{
  109561. y+=base;
  109562. }
  109563. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  109564. }
  109565. }
  109566. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  109567. int dy=y1-y0;
  109568. int adx=x1-x0;
  109569. int ady=abs(dy);
  109570. int base=dy/adx;
  109571. int sy=(dy<0?base-1:base+1);
  109572. int x=x0;
  109573. int y=y0;
  109574. int err=0;
  109575. ady-=abs(base*adx);
  109576. d[x]=y;
  109577. while(++x<x1){
  109578. err=err+ady;
  109579. if(err>=adx){
  109580. err-=adx;
  109581. y+=sy;
  109582. }else{
  109583. y+=base;
  109584. }
  109585. d[x]=y;
  109586. }
  109587. }
  109588. /* the floor has already been filtered to only include relevant sections */
  109589. static int accumulate_fit(const float *flr,const float *mdct,
  109590. int x0, int x1,lsfit_acc *a,
  109591. int n,vorbis_info_floor1 *info){
  109592. long i;
  109593. 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;
  109594. memset(a,0,sizeof(*a));
  109595. a->x0=x0;
  109596. a->x1=x1;
  109597. if(x1>=n)x1=n-1;
  109598. for(i=x0;i<=x1;i++){
  109599. int quantized=vorbis_dBquant(flr+i);
  109600. if(quantized){
  109601. if(mdct[i]+info->twofitatten>=flr[i]){
  109602. xa += i;
  109603. ya += quantized;
  109604. x2a += i*i;
  109605. y2a += quantized*quantized;
  109606. xya += i*quantized;
  109607. na++;
  109608. }else{
  109609. xb += i;
  109610. yb += quantized;
  109611. x2b += i*i;
  109612. y2b += quantized*quantized;
  109613. xyb += i*quantized;
  109614. nb++;
  109615. }
  109616. }
  109617. }
  109618. xb+=xa;
  109619. yb+=ya;
  109620. x2b+=x2a;
  109621. y2b+=y2a;
  109622. xyb+=xya;
  109623. nb+=na;
  109624. /* weight toward the actually used frequencies if we meet the threshhold */
  109625. {
  109626. int weight=nb*info->twofitweight/(na+1);
  109627. a->xa=xa*weight+xb;
  109628. a->ya=ya*weight+yb;
  109629. a->x2a=x2a*weight+x2b;
  109630. a->y2a=y2a*weight+y2b;
  109631. a->xya=xya*weight+xyb;
  109632. a->an=na*weight+nb;
  109633. }
  109634. return(na);
  109635. }
  109636. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  109637. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  109638. long x0=a[0].x0;
  109639. long x1=a[fits-1].x1;
  109640. for(i=0;i<fits;i++){
  109641. x+=a[i].xa;
  109642. y+=a[i].ya;
  109643. x2+=a[i].x2a;
  109644. y2+=a[i].y2a;
  109645. xy+=a[i].xya;
  109646. an+=a[i].an;
  109647. }
  109648. if(*y0>=0){
  109649. x+= x0;
  109650. y+= *y0;
  109651. x2+= x0 * x0;
  109652. y2+= *y0 * *y0;
  109653. xy+= *y0 * x0;
  109654. an++;
  109655. }
  109656. if(*y1>=0){
  109657. x+= x1;
  109658. y+= *y1;
  109659. x2+= x1 * x1;
  109660. y2+= *y1 * *y1;
  109661. xy+= *y1 * x1;
  109662. an++;
  109663. }
  109664. if(an){
  109665. /* need 64 bit multiplies, which C doesn't give portably as int */
  109666. double fx=x;
  109667. double fy=y;
  109668. double fx2=x2;
  109669. double fxy=xy;
  109670. double denom=1./(an*fx2-fx*fx);
  109671. double a=(fy*fx2-fxy*fx)*denom;
  109672. double b=(an*fxy-fx*fy)*denom;
  109673. *y0=rint(a+b*x0);
  109674. *y1=rint(a+b*x1);
  109675. /* limit to our range! */
  109676. if(*y0>1023)*y0=1023;
  109677. if(*y1>1023)*y1=1023;
  109678. if(*y0<0)*y0=0;
  109679. if(*y1<0)*y1=0;
  109680. }else{
  109681. *y0=0;
  109682. *y1=0;
  109683. }
  109684. }
  109685. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  109686. long y=0;
  109687. int i;
  109688. for(i=0;i<fits && y==0;i++)
  109689. y+=a[i].ya;
  109690. *y0=*y1=y;
  109691. }*/
  109692. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  109693. const float *mdct,
  109694. vorbis_info_floor1 *info){
  109695. int dy=y1-y0;
  109696. int adx=x1-x0;
  109697. int ady=abs(dy);
  109698. int base=dy/adx;
  109699. int sy=(dy<0?base-1:base+1);
  109700. int x=x0;
  109701. int y=y0;
  109702. int err=0;
  109703. int val=vorbis_dBquant(mask+x);
  109704. int mse=0;
  109705. int n=0;
  109706. ady-=abs(base*adx);
  109707. mse=(y-val);
  109708. mse*=mse;
  109709. n++;
  109710. if(mdct[x]+info->twofitatten>=mask[x]){
  109711. if(y+info->maxover<val)return(1);
  109712. if(y-info->maxunder>val)return(1);
  109713. }
  109714. while(++x<x1){
  109715. err=err+ady;
  109716. if(err>=adx){
  109717. err-=adx;
  109718. y+=sy;
  109719. }else{
  109720. y+=base;
  109721. }
  109722. val=vorbis_dBquant(mask+x);
  109723. mse+=((y-val)*(y-val));
  109724. n++;
  109725. if(mdct[x]+info->twofitatten>=mask[x]){
  109726. if(val){
  109727. if(y+info->maxover<val)return(1);
  109728. if(y-info->maxunder>val)return(1);
  109729. }
  109730. }
  109731. }
  109732. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  109733. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  109734. if(mse/n>info->maxerr)return(1);
  109735. return(0);
  109736. }
  109737. static int post_Y(int *A,int *B,int pos){
  109738. if(A[pos]<0)
  109739. return B[pos];
  109740. if(B[pos]<0)
  109741. return A[pos];
  109742. return (A[pos]+B[pos])>>1;
  109743. }
  109744. int *floor1_fit(vorbis_block *vb,void *look_,
  109745. const float *logmdct, /* in */
  109746. const float *logmask){
  109747. long i,j;
  109748. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  109749. vorbis_info_floor1 *info=look->vi;
  109750. long n=look->n;
  109751. long posts=look->posts;
  109752. long nonzero=0;
  109753. lsfit_acc fits[VIF_POSIT+1];
  109754. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  109755. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  109756. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  109757. int hineighbor[VIF_POSIT+2];
  109758. int *output=NULL;
  109759. int memo[VIF_POSIT+2];
  109760. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  109761. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  109762. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  109763. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  109764. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  109765. /* quantize the relevant floor points and collect them into line fit
  109766. structures (one per minimal division) at the same time */
  109767. if(posts==0){
  109768. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  109769. }else{
  109770. for(i=0;i<posts-1;i++)
  109771. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  109772. look->sorted_index[i+1],fits+i,
  109773. n,info);
  109774. }
  109775. if(nonzero){
  109776. /* start by fitting the implicit base case.... */
  109777. int y0=-200;
  109778. int y1=-200;
  109779. fit_line(fits,posts-1,&y0,&y1);
  109780. fit_valueA[0]=y0;
  109781. fit_valueB[0]=y0;
  109782. fit_valueB[1]=y1;
  109783. fit_valueA[1]=y1;
  109784. /* Non degenerate case */
  109785. /* start progressive splitting. This is a greedy, non-optimal
  109786. algorithm, but simple and close enough to the best
  109787. answer. */
  109788. for(i=2;i<posts;i++){
  109789. int sortpos=look->reverse_index[i];
  109790. int ln=loneighbor[sortpos];
  109791. int hn=hineighbor[sortpos];
  109792. /* eliminate repeat searches of a particular range with a memo */
  109793. if(memo[ln]!=hn){
  109794. /* haven't performed this error search yet */
  109795. int lsortpos=look->reverse_index[ln];
  109796. int hsortpos=look->reverse_index[hn];
  109797. memo[ln]=hn;
  109798. {
  109799. /* A note: we want to bound/minimize *local*, not global, error */
  109800. int lx=info->postlist[ln];
  109801. int hx=info->postlist[hn];
  109802. int ly=post_Y(fit_valueA,fit_valueB,ln);
  109803. int hy=post_Y(fit_valueA,fit_valueB,hn);
  109804. if(ly==-1 || hy==-1){
  109805. exit(1);
  109806. }
  109807. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  109808. /* outside error bounds/begin search area. Split it. */
  109809. int ly0=-200;
  109810. int ly1=-200;
  109811. int hy0=-200;
  109812. int hy1=-200;
  109813. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  109814. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  109815. /* store new edge values */
  109816. fit_valueB[ln]=ly0;
  109817. if(ln==0)fit_valueA[ln]=ly0;
  109818. fit_valueA[i]=ly1;
  109819. fit_valueB[i]=hy0;
  109820. fit_valueA[hn]=hy1;
  109821. if(hn==1)fit_valueB[hn]=hy1;
  109822. if(ly1>=0 || hy0>=0){
  109823. /* store new neighbor values */
  109824. for(j=sortpos-1;j>=0;j--)
  109825. if(hineighbor[j]==hn)
  109826. hineighbor[j]=i;
  109827. else
  109828. break;
  109829. for(j=sortpos+1;j<posts;j++)
  109830. if(loneighbor[j]==ln)
  109831. loneighbor[j]=i;
  109832. else
  109833. break;
  109834. }
  109835. }else{
  109836. fit_valueA[i]=-200;
  109837. fit_valueB[i]=-200;
  109838. }
  109839. }
  109840. }
  109841. }
  109842. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109843. output[0]=post_Y(fit_valueA,fit_valueB,0);
  109844. output[1]=post_Y(fit_valueA,fit_valueB,1);
  109845. /* fill in posts marked as not using a fit; we will zero
  109846. back out to 'unused' when encoding them so long as curve
  109847. interpolation doesn't force them into use */
  109848. for(i=2;i<posts;i++){
  109849. int ln=look->loneighbor[i-2];
  109850. int hn=look->hineighbor[i-2];
  109851. int x0=info->postlist[ln];
  109852. int x1=info->postlist[hn];
  109853. int y0=output[ln];
  109854. int y1=output[hn];
  109855. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109856. int vx=post_Y(fit_valueA,fit_valueB,i);
  109857. if(vx>=0 && predicted!=vx){
  109858. output[i]=vx;
  109859. }else{
  109860. output[i]= predicted|0x8000;
  109861. }
  109862. }
  109863. }
  109864. return(output);
  109865. }
  109866. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  109867. int *A,int *B,
  109868. int del){
  109869. long i;
  109870. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  109871. long posts=look->posts;
  109872. int *output=NULL;
  109873. if(A && B){
  109874. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109875. for(i=0;i<posts;i++){
  109876. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  109877. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  109878. }
  109879. }
  109880. return(output);
  109881. }
  109882. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109883. void*look_,
  109884. int *post,int *ilogmask){
  109885. long i,j;
  109886. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  109887. vorbis_info_floor1 *info=look->vi;
  109888. long posts=look->posts;
  109889. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109890. int out[VIF_POSIT+2];
  109891. static_codebook **sbooks=ci->book_param;
  109892. codebook *books=ci->fullbooks;
  109893. static long seq=0;
  109894. /* quantize values to multiplier spec */
  109895. if(post){
  109896. for(i=0;i<posts;i++){
  109897. int val=post[i]&0x7fff;
  109898. switch(info->mult){
  109899. case 1: /* 1024 -> 256 */
  109900. val>>=2;
  109901. break;
  109902. case 2: /* 1024 -> 128 */
  109903. val>>=3;
  109904. break;
  109905. case 3: /* 1024 -> 86 */
  109906. val/=12;
  109907. break;
  109908. case 4: /* 1024 -> 64 */
  109909. val>>=4;
  109910. break;
  109911. }
  109912. post[i]=val | (post[i]&0x8000);
  109913. }
  109914. out[0]=post[0];
  109915. out[1]=post[1];
  109916. /* find prediction values for each post and subtract them */
  109917. for(i=2;i<posts;i++){
  109918. int ln=look->loneighbor[i-2];
  109919. int hn=look->hineighbor[i-2];
  109920. int x0=info->postlist[ln];
  109921. int x1=info->postlist[hn];
  109922. int y0=post[ln];
  109923. int y1=post[hn];
  109924. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109925. if((post[i]&0x8000) || (predicted==post[i])){
  109926. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  109927. in interpolation */
  109928. out[i]=0;
  109929. }else{
  109930. int headroom=(look->quant_q-predicted<predicted?
  109931. look->quant_q-predicted:predicted);
  109932. int val=post[i]-predicted;
  109933. /* at this point the 'deviation' value is in the range +/- max
  109934. range, but the real, unique range can always be mapped to
  109935. only [0-maxrange). So we want to wrap the deviation into
  109936. this limited range, but do it in the way that least screws
  109937. an essentially gaussian probability distribution. */
  109938. if(val<0)
  109939. if(val<-headroom)
  109940. val=headroom-val-1;
  109941. else
  109942. val=-1-(val<<1);
  109943. else
  109944. if(val>=headroom)
  109945. val= val+headroom;
  109946. else
  109947. val<<=1;
  109948. out[i]=val;
  109949. post[ln]&=0x7fff;
  109950. post[hn]&=0x7fff;
  109951. }
  109952. }
  109953. /* we have everything we need. pack it out */
  109954. /* mark nontrivial floor */
  109955. oggpack_write(opb,1,1);
  109956. /* beginning/end post */
  109957. look->frames++;
  109958. look->postbits+=ilog(look->quant_q-1)*2;
  109959. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  109960. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  109961. /* partition by partition */
  109962. for(i=0,j=2;i<info->partitions;i++){
  109963. int classx=info->partitionclass[i];
  109964. int cdim=info->class_dim[classx];
  109965. int csubbits=info->class_subs[classx];
  109966. int csub=1<<csubbits;
  109967. int bookas[8]={0,0,0,0,0,0,0,0};
  109968. int cval=0;
  109969. int cshift=0;
  109970. int k,l;
  109971. /* generate the partition's first stage cascade value */
  109972. if(csubbits){
  109973. int maxval[8];
  109974. for(k=0;k<csub;k++){
  109975. int booknum=info->class_subbook[classx][k];
  109976. if(booknum<0){
  109977. maxval[k]=1;
  109978. }else{
  109979. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  109980. }
  109981. }
  109982. for(k=0;k<cdim;k++){
  109983. for(l=0;l<csub;l++){
  109984. int val=out[j+k];
  109985. if(val<maxval[l]){
  109986. bookas[k]=l;
  109987. break;
  109988. }
  109989. }
  109990. cval|= bookas[k]<<cshift;
  109991. cshift+=csubbits;
  109992. }
  109993. /* write it */
  109994. look->phrasebits+=
  109995. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  109996. #ifdef TRAIN_FLOOR1
  109997. {
  109998. FILE *of;
  109999. char buffer[80];
  110000. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  110001. vb->pcmend/2,posts-2,class);
  110002. of=fopen(buffer,"a");
  110003. fprintf(of,"%d\n",cval);
  110004. fclose(of);
  110005. }
  110006. #endif
  110007. }
  110008. /* write post values */
  110009. for(k=0;k<cdim;k++){
  110010. int book=info->class_subbook[classx][bookas[k]];
  110011. if(book>=0){
  110012. /* hack to allow training with 'bad' books */
  110013. if(out[j+k]<(books+book)->entries)
  110014. look->postbits+=vorbis_book_encode(books+book,
  110015. out[j+k],opb);
  110016. /*else
  110017. fprintf(stderr,"+!");*/
  110018. #ifdef TRAIN_FLOOR1
  110019. {
  110020. FILE *of;
  110021. char buffer[80];
  110022. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  110023. vb->pcmend/2,posts-2,class,bookas[k]);
  110024. of=fopen(buffer,"a");
  110025. fprintf(of,"%d\n",out[j+k]);
  110026. fclose(of);
  110027. }
  110028. #endif
  110029. }
  110030. }
  110031. j+=cdim;
  110032. }
  110033. {
  110034. /* generate quantized floor equivalent to what we'd unpack in decode */
  110035. /* render the lines */
  110036. int hx=0;
  110037. int lx=0;
  110038. int ly=post[0]*info->mult;
  110039. for(j=1;j<look->posts;j++){
  110040. int current=look->forward_index[j];
  110041. int hy=post[current]&0x7fff;
  110042. if(hy==post[current]){
  110043. hy*=info->mult;
  110044. hx=info->postlist[current];
  110045. render_line0(lx,hx,ly,hy,ilogmask);
  110046. lx=hx;
  110047. ly=hy;
  110048. }
  110049. }
  110050. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  110051. seq++;
  110052. return(1);
  110053. }
  110054. }else{
  110055. oggpack_write(opb,0,1);
  110056. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  110057. seq++;
  110058. return(0);
  110059. }
  110060. }
  110061. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  110062. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110063. vorbis_info_floor1 *info=look->vi;
  110064. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110065. int i,j,k;
  110066. codebook *books=ci->fullbooks;
  110067. /* unpack wrapped/predicted values from stream */
  110068. if(oggpack_read(&vb->opb,1)==1){
  110069. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  110070. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110071. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110072. /* partition by partition */
  110073. for(i=0,j=2;i<info->partitions;i++){
  110074. int classx=info->partitionclass[i];
  110075. int cdim=info->class_dim[classx];
  110076. int csubbits=info->class_subs[classx];
  110077. int csub=1<<csubbits;
  110078. int cval=0;
  110079. /* decode the partition's first stage cascade value */
  110080. if(csubbits){
  110081. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  110082. if(cval==-1)goto eop;
  110083. }
  110084. for(k=0;k<cdim;k++){
  110085. int book=info->class_subbook[classx][cval&(csub-1)];
  110086. cval>>=csubbits;
  110087. if(book>=0){
  110088. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  110089. goto eop;
  110090. }else{
  110091. fit_value[j+k]=0;
  110092. }
  110093. }
  110094. j+=cdim;
  110095. }
  110096. /* unwrap positive values and reconsitute via linear interpolation */
  110097. for(i=2;i<look->posts;i++){
  110098. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  110099. info->postlist[look->hineighbor[i-2]],
  110100. fit_value[look->loneighbor[i-2]],
  110101. fit_value[look->hineighbor[i-2]],
  110102. info->postlist[i]);
  110103. int hiroom=look->quant_q-predicted;
  110104. int loroom=predicted;
  110105. int room=(hiroom<loroom?hiroom:loroom)<<1;
  110106. int val=fit_value[i];
  110107. if(val){
  110108. if(val>=room){
  110109. if(hiroom>loroom){
  110110. val = val-loroom;
  110111. }else{
  110112. val = -1-(val-hiroom);
  110113. }
  110114. }else{
  110115. if(val&1){
  110116. val= -((val+1)>>1);
  110117. }else{
  110118. val>>=1;
  110119. }
  110120. }
  110121. fit_value[i]=val+predicted;
  110122. fit_value[look->loneighbor[i-2]]&=0x7fff;
  110123. fit_value[look->hineighbor[i-2]]&=0x7fff;
  110124. }else{
  110125. fit_value[i]=predicted|0x8000;
  110126. }
  110127. }
  110128. return(fit_value);
  110129. }
  110130. eop:
  110131. return(NULL);
  110132. }
  110133. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  110134. float *out){
  110135. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110136. vorbis_info_floor1 *info=look->vi;
  110137. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110138. int n=ci->blocksizes[vb->W]/2;
  110139. int j;
  110140. if(memo){
  110141. /* render the lines */
  110142. int *fit_value=(int *)memo;
  110143. int hx=0;
  110144. int lx=0;
  110145. int ly=fit_value[0]*info->mult;
  110146. for(j=1;j<look->posts;j++){
  110147. int current=look->forward_index[j];
  110148. int hy=fit_value[current]&0x7fff;
  110149. if(hy==fit_value[current]){
  110150. hy*=info->mult;
  110151. hx=info->postlist[current];
  110152. render_line(lx,hx,ly,hy,out);
  110153. lx=hx;
  110154. ly=hy;
  110155. }
  110156. }
  110157. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  110158. return(1);
  110159. }
  110160. memset(out,0,sizeof(*out)*n);
  110161. return(0);
  110162. }
  110163. /* export hooks */
  110164. vorbis_func_floor floor1_exportbundle={
  110165. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  110166. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  110167. };
  110168. #endif
  110169. /*** End of inlined file: floor1.c ***/
  110170. /*** Start of inlined file: info.c ***/
  110171. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110172. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110173. // tasks..
  110174. #if JUCE_MSVC
  110175. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110176. #endif
  110177. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110178. #if JUCE_USE_OGGVORBIS
  110179. /* general handling of the header and the vorbis_info structure (and
  110180. substructures) */
  110181. #include <stdlib.h>
  110182. #include <string.h>
  110183. #include <ctype.h>
  110184. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  110185. while(bytes--){
  110186. oggpack_write(o,*s++,8);
  110187. }
  110188. }
  110189. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  110190. while(bytes--){
  110191. *buf++=oggpack_read(o,8);
  110192. }
  110193. }
  110194. void vorbis_comment_init(vorbis_comment *vc){
  110195. memset(vc,0,sizeof(*vc));
  110196. }
  110197. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  110198. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  110199. (vc->comments+2)*sizeof(*vc->user_comments));
  110200. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  110201. (vc->comments+2)*sizeof(*vc->comment_lengths));
  110202. vc->comment_lengths[vc->comments]=strlen(comment);
  110203. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  110204. strcpy(vc->user_comments[vc->comments], comment);
  110205. vc->comments++;
  110206. vc->user_comments[vc->comments]=NULL;
  110207. }
  110208. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  110209. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  110210. strcpy(comment, tag);
  110211. strcat(comment, "=");
  110212. strcat(comment, contents);
  110213. vorbis_comment_add(vc, comment);
  110214. }
  110215. /* This is more or less the same as strncasecmp - but that doesn't exist
  110216. * everywhere, and this is a fairly trivial function, so we include it */
  110217. static int tagcompare(const char *s1, const char *s2, int n){
  110218. int c=0;
  110219. while(c < n){
  110220. if(toupper(s1[c]) != toupper(s2[c]))
  110221. return !0;
  110222. c++;
  110223. }
  110224. return 0;
  110225. }
  110226. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  110227. long i;
  110228. int found = 0;
  110229. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110230. char *fulltag = (char*)alloca(taglen+ 1);
  110231. strcpy(fulltag, tag);
  110232. strcat(fulltag, "=");
  110233. for(i=0;i<vc->comments;i++){
  110234. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  110235. if(count == found)
  110236. /* We return a pointer to the data, not a copy */
  110237. return vc->user_comments[i] + taglen;
  110238. else
  110239. found++;
  110240. }
  110241. }
  110242. return NULL; /* didn't find anything */
  110243. }
  110244. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  110245. int i,count=0;
  110246. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110247. char *fulltag = (char*)alloca(taglen+1);
  110248. strcpy(fulltag,tag);
  110249. strcat(fulltag, "=");
  110250. for(i=0;i<vc->comments;i++){
  110251. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  110252. count++;
  110253. }
  110254. return count;
  110255. }
  110256. void vorbis_comment_clear(vorbis_comment *vc){
  110257. if(vc){
  110258. long i;
  110259. for(i=0;i<vc->comments;i++)
  110260. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  110261. if(vc->user_comments)_ogg_free(vc->user_comments);
  110262. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  110263. if(vc->vendor)_ogg_free(vc->vendor);
  110264. }
  110265. memset(vc,0,sizeof(*vc));
  110266. }
  110267. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  110268. They may be equal, but short will never ge greater than long */
  110269. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  110270. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  110271. return ci ? ci->blocksizes[zo] : -1;
  110272. }
  110273. /* used by synthesis, which has a full, alloced vi */
  110274. void vorbis_info_init(vorbis_info *vi){
  110275. memset(vi,0,sizeof(*vi));
  110276. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  110277. }
  110278. void vorbis_info_clear(vorbis_info *vi){
  110279. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110280. int i;
  110281. if(ci){
  110282. for(i=0;i<ci->modes;i++)
  110283. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  110284. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  110285. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  110286. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  110287. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  110288. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  110289. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  110290. for(i=0;i<ci->books;i++){
  110291. if(ci->book_param[i]){
  110292. /* knows if the book was not alloced */
  110293. vorbis_staticbook_destroy(ci->book_param[i]);
  110294. }
  110295. if(ci->fullbooks)
  110296. vorbis_book_clear(ci->fullbooks+i);
  110297. }
  110298. if(ci->fullbooks)
  110299. _ogg_free(ci->fullbooks);
  110300. for(i=0;i<ci->psys;i++)
  110301. _vi_psy_free(ci->psy_param[i]);
  110302. _ogg_free(ci);
  110303. }
  110304. memset(vi,0,sizeof(*vi));
  110305. }
  110306. /* Header packing/unpacking ********************************************/
  110307. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  110308. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110309. if(!ci)return(OV_EFAULT);
  110310. vi->version=oggpack_read(opb,32);
  110311. if(vi->version!=0)return(OV_EVERSION);
  110312. vi->channels=oggpack_read(opb,8);
  110313. vi->rate=oggpack_read(opb,32);
  110314. vi->bitrate_upper=oggpack_read(opb,32);
  110315. vi->bitrate_nominal=oggpack_read(opb,32);
  110316. vi->bitrate_lower=oggpack_read(opb,32);
  110317. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  110318. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  110319. if(vi->rate<1)goto err_out;
  110320. if(vi->channels<1)goto err_out;
  110321. if(ci->blocksizes[0]<8)goto err_out;
  110322. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  110323. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110324. return(0);
  110325. err_out:
  110326. vorbis_info_clear(vi);
  110327. return(OV_EBADHEADER);
  110328. }
  110329. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  110330. int i;
  110331. int vendorlen=oggpack_read(opb,32);
  110332. if(vendorlen<0)goto err_out;
  110333. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  110334. _v_readstring(opb,vc->vendor,vendorlen);
  110335. vc->comments=oggpack_read(opb,32);
  110336. if(vc->comments<0)goto err_out;
  110337. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  110338. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  110339. for(i=0;i<vc->comments;i++){
  110340. int len=oggpack_read(opb,32);
  110341. if(len<0)goto err_out;
  110342. vc->comment_lengths[i]=len;
  110343. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  110344. _v_readstring(opb,vc->user_comments[i],len);
  110345. }
  110346. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110347. return(0);
  110348. err_out:
  110349. vorbis_comment_clear(vc);
  110350. return(OV_EBADHEADER);
  110351. }
  110352. /* all of the real encoding details are here. The modes, books,
  110353. everything */
  110354. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  110355. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110356. int i;
  110357. if(!ci)return(OV_EFAULT);
  110358. /* codebooks */
  110359. ci->books=oggpack_read(opb,8)+1;
  110360. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  110361. for(i=0;i<ci->books;i++){
  110362. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  110363. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  110364. }
  110365. /* time backend settings; hooks are unused */
  110366. {
  110367. int times=oggpack_read(opb,6)+1;
  110368. for(i=0;i<times;i++){
  110369. int test=oggpack_read(opb,16);
  110370. if(test<0 || test>=VI_TIMEB)goto err_out;
  110371. }
  110372. }
  110373. /* floor backend settings */
  110374. ci->floors=oggpack_read(opb,6)+1;
  110375. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  110376. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  110377. for(i=0;i<ci->floors;i++){
  110378. ci->floor_type[i]=oggpack_read(opb,16);
  110379. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  110380. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  110381. if(!ci->floor_param[i])goto err_out;
  110382. }
  110383. /* residue backend settings */
  110384. ci->residues=oggpack_read(opb,6)+1;
  110385. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  110386. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  110387. for(i=0;i<ci->residues;i++){
  110388. ci->residue_type[i]=oggpack_read(opb,16);
  110389. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  110390. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  110391. if(!ci->residue_param[i])goto err_out;
  110392. }
  110393. /* map backend settings */
  110394. ci->maps=oggpack_read(opb,6)+1;
  110395. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  110396. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  110397. for(i=0;i<ci->maps;i++){
  110398. ci->map_type[i]=oggpack_read(opb,16);
  110399. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  110400. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  110401. if(!ci->map_param[i])goto err_out;
  110402. }
  110403. /* mode settings */
  110404. ci->modes=oggpack_read(opb,6)+1;
  110405. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  110406. for(i=0;i<ci->modes;i++){
  110407. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  110408. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  110409. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  110410. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  110411. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  110412. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  110413. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  110414. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  110415. }
  110416. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  110417. return(0);
  110418. err_out:
  110419. vorbis_info_clear(vi);
  110420. return(OV_EBADHEADER);
  110421. }
  110422. /* The Vorbis header is in three packets; the initial small packet in
  110423. the first page that identifies basic parameters, a second packet
  110424. with bitstream comments and a third packet that holds the
  110425. codebook. */
  110426. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  110427. oggpack_buffer opb;
  110428. if(op){
  110429. oggpack_readinit(&opb,op->packet,op->bytes);
  110430. /* Which of the three types of header is this? */
  110431. /* Also verify header-ness, vorbis */
  110432. {
  110433. char buffer[6];
  110434. int packtype=oggpack_read(&opb,8);
  110435. memset(buffer,0,6);
  110436. _v_readstring(&opb,buffer,6);
  110437. if(memcmp(buffer,"vorbis",6)){
  110438. /* not a vorbis header */
  110439. return(OV_ENOTVORBIS);
  110440. }
  110441. switch(packtype){
  110442. case 0x01: /* least significant *bit* is read first */
  110443. if(!op->b_o_s){
  110444. /* Not the initial packet */
  110445. return(OV_EBADHEADER);
  110446. }
  110447. if(vi->rate!=0){
  110448. /* previously initialized info header */
  110449. return(OV_EBADHEADER);
  110450. }
  110451. return(_vorbis_unpack_info(vi,&opb));
  110452. case 0x03: /* least significant *bit* is read first */
  110453. if(vi->rate==0){
  110454. /* um... we didn't get the initial header */
  110455. return(OV_EBADHEADER);
  110456. }
  110457. return(_vorbis_unpack_comment(vc,&opb));
  110458. case 0x05: /* least significant *bit* is read first */
  110459. if(vi->rate==0 || vc->vendor==NULL){
  110460. /* um... we didn;t get the initial header or comments yet */
  110461. return(OV_EBADHEADER);
  110462. }
  110463. return(_vorbis_unpack_books(vi,&opb));
  110464. default:
  110465. /* Not a valid vorbis header type */
  110466. return(OV_EBADHEADER);
  110467. break;
  110468. }
  110469. }
  110470. }
  110471. return(OV_EBADHEADER);
  110472. }
  110473. /* pack side **********************************************************/
  110474. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  110475. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110476. if(!ci)return(OV_EFAULT);
  110477. /* preamble */
  110478. oggpack_write(opb,0x01,8);
  110479. _v_writestring(opb,"vorbis", 6);
  110480. /* basic information about the stream */
  110481. oggpack_write(opb,0x00,32);
  110482. oggpack_write(opb,vi->channels,8);
  110483. oggpack_write(opb,vi->rate,32);
  110484. oggpack_write(opb,vi->bitrate_upper,32);
  110485. oggpack_write(opb,vi->bitrate_nominal,32);
  110486. oggpack_write(opb,vi->bitrate_lower,32);
  110487. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  110488. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  110489. oggpack_write(opb,1,1);
  110490. return(0);
  110491. }
  110492. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  110493. char temp[]="Xiph.Org libVorbis I 20050304";
  110494. int bytes = strlen(temp);
  110495. /* preamble */
  110496. oggpack_write(opb,0x03,8);
  110497. _v_writestring(opb,"vorbis", 6);
  110498. /* vendor */
  110499. oggpack_write(opb,bytes,32);
  110500. _v_writestring(opb,temp, bytes);
  110501. /* comments */
  110502. oggpack_write(opb,vc->comments,32);
  110503. if(vc->comments){
  110504. int i;
  110505. for(i=0;i<vc->comments;i++){
  110506. if(vc->user_comments[i]){
  110507. oggpack_write(opb,vc->comment_lengths[i],32);
  110508. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  110509. }else{
  110510. oggpack_write(opb,0,32);
  110511. }
  110512. }
  110513. }
  110514. oggpack_write(opb,1,1);
  110515. return(0);
  110516. }
  110517. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  110518. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110519. int i;
  110520. if(!ci)return(OV_EFAULT);
  110521. oggpack_write(opb,0x05,8);
  110522. _v_writestring(opb,"vorbis", 6);
  110523. /* books */
  110524. oggpack_write(opb,ci->books-1,8);
  110525. for(i=0;i<ci->books;i++)
  110526. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  110527. /* times; hook placeholders */
  110528. oggpack_write(opb,0,6);
  110529. oggpack_write(opb,0,16);
  110530. /* floors */
  110531. oggpack_write(opb,ci->floors-1,6);
  110532. for(i=0;i<ci->floors;i++){
  110533. oggpack_write(opb,ci->floor_type[i],16);
  110534. if(_floor_P[ci->floor_type[i]]->pack)
  110535. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  110536. else
  110537. goto err_out;
  110538. }
  110539. /* residues */
  110540. oggpack_write(opb,ci->residues-1,6);
  110541. for(i=0;i<ci->residues;i++){
  110542. oggpack_write(opb,ci->residue_type[i],16);
  110543. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  110544. }
  110545. /* maps */
  110546. oggpack_write(opb,ci->maps-1,6);
  110547. for(i=0;i<ci->maps;i++){
  110548. oggpack_write(opb,ci->map_type[i],16);
  110549. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  110550. }
  110551. /* modes */
  110552. oggpack_write(opb,ci->modes-1,6);
  110553. for(i=0;i<ci->modes;i++){
  110554. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  110555. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  110556. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  110557. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  110558. }
  110559. oggpack_write(opb,1,1);
  110560. return(0);
  110561. err_out:
  110562. return(-1);
  110563. }
  110564. int vorbis_commentheader_out(vorbis_comment *vc,
  110565. ogg_packet *op){
  110566. oggpack_buffer opb;
  110567. oggpack_writeinit(&opb);
  110568. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  110569. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110570. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  110571. op->bytes=oggpack_bytes(&opb);
  110572. op->b_o_s=0;
  110573. op->e_o_s=0;
  110574. op->granulepos=0;
  110575. op->packetno=1;
  110576. return 0;
  110577. }
  110578. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  110579. vorbis_comment *vc,
  110580. ogg_packet *op,
  110581. ogg_packet *op_comm,
  110582. ogg_packet *op_code){
  110583. int ret=OV_EIMPL;
  110584. vorbis_info *vi=v->vi;
  110585. oggpack_buffer opb;
  110586. private_state *b=(private_state*)v->backend_state;
  110587. if(!b){
  110588. ret=OV_EFAULT;
  110589. goto err_out;
  110590. }
  110591. /* first header packet **********************************************/
  110592. oggpack_writeinit(&opb);
  110593. if(_vorbis_pack_info(&opb,vi))goto err_out;
  110594. /* build the packet */
  110595. if(b->header)_ogg_free(b->header);
  110596. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110597. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  110598. op->packet=b->header;
  110599. op->bytes=oggpack_bytes(&opb);
  110600. op->b_o_s=1;
  110601. op->e_o_s=0;
  110602. op->granulepos=0;
  110603. op->packetno=0;
  110604. /* second header packet (comments) **********************************/
  110605. oggpack_reset(&opb);
  110606. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  110607. if(b->header1)_ogg_free(b->header1);
  110608. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110609. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  110610. op_comm->packet=b->header1;
  110611. op_comm->bytes=oggpack_bytes(&opb);
  110612. op_comm->b_o_s=0;
  110613. op_comm->e_o_s=0;
  110614. op_comm->granulepos=0;
  110615. op_comm->packetno=1;
  110616. /* third header packet (modes/codebooks) ****************************/
  110617. oggpack_reset(&opb);
  110618. if(_vorbis_pack_books(&opb,vi))goto err_out;
  110619. if(b->header2)_ogg_free(b->header2);
  110620. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110621. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  110622. op_code->packet=b->header2;
  110623. op_code->bytes=oggpack_bytes(&opb);
  110624. op_code->b_o_s=0;
  110625. op_code->e_o_s=0;
  110626. op_code->granulepos=0;
  110627. op_code->packetno=2;
  110628. oggpack_writeclear(&opb);
  110629. return(0);
  110630. err_out:
  110631. oggpack_writeclear(&opb);
  110632. memset(op,0,sizeof(*op));
  110633. memset(op_comm,0,sizeof(*op_comm));
  110634. memset(op_code,0,sizeof(*op_code));
  110635. if(b->header)_ogg_free(b->header);
  110636. if(b->header1)_ogg_free(b->header1);
  110637. if(b->header2)_ogg_free(b->header2);
  110638. b->header=NULL;
  110639. b->header1=NULL;
  110640. b->header2=NULL;
  110641. return(ret);
  110642. }
  110643. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  110644. if(granulepos>=0)
  110645. return((double)granulepos/v->vi->rate);
  110646. return(-1);
  110647. }
  110648. #endif
  110649. /*** End of inlined file: info.c ***/
  110650. /*** Start of inlined file: lpc.c ***/
  110651. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  110652. are derived from code written by Jutta Degener and Carsten Bormann;
  110653. thus we include their copyright below. The entirety of this file
  110654. is freely redistributable on the condition that both of these
  110655. copyright notices are preserved without modification. */
  110656. /* Preserved Copyright: *********************************************/
  110657. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  110658. Technische Universita"t Berlin
  110659. Any use of this software is permitted provided that this notice is not
  110660. removed and that neither the authors nor the Technische Universita"t
  110661. Berlin are deemed to have made any representations as to the
  110662. suitability of this software for any purpose nor are held responsible
  110663. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  110664. THIS SOFTWARE.
  110665. As a matter of courtesy, the authors request to be informed about uses
  110666. this software has found, about bugs in this software, and about any
  110667. improvements that may be of general interest.
  110668. Berlin, 28.11.1994
  110669. Jutta Degener
  110670. Carsten Bormann
  110671. *********************************************************************/
  110672. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110673. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110674. // tasks..
  110675. #if JUCE_MSVC
  110676. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110677. #endif
  110678. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110679. #if JUCE_USE_OGGVORBIS
  110680. #include <stdlib.h>
  110681. #include <string.h>
  110682. #include <math.h>
  110683. /* Autocorrelation LPC coeff generation algorithm invented by
  110684. N. Levinson in 1947, modified by J. Durbin in 1959. */
  110685. /* Input : n elements of time doamin data
  110686. Output: m lpc coefficients, excitation energy */
  110687. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  110688. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  110689. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  110690. double error;
  110691. int i,j;
  110692. /* autocorrelation, p+1 lag coefficients */
  110693. j=m+1;
  110694. while(j--){
  110695. double d=0; /* double needed for accumulator depth */
  110696. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  110697. aut[j]=d;
  110698. }
  110699. /* Generate lpc coefficients from autocorr values */
  110700. error=aut[0];
  110701. for(i=0;i<m;i++){
  110702. double r= -aut[i+1];
  110703. if(error==0){
  110704. memset(lpci,0,m*sizeof(*lpci));
  110705. return 0;
  110706. }
  110707. /* Sum up this iteration's reflection coefficient; note that in
  110708. Vorbis we don't save it. If anyone wants to recycle this code
  110709. and needs reflection coefficients, save the results of 'r' from
  110710. each iteration. */
  110711. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  110712. r/=error;
  110713. /* Update LPC coefficients and total error */
  110714. lpc[i]=r;
  110715. for(j=0;j<i/2;j++){
  110716. double tmp=lpc[j];
  110717. lpc[j]+=r*lpc[i-1-j];
  110718. lpc[i-1-j]+=r*tmp;
  110719. }
  110720. if(i%2)lpc[j]+=lpc[j]*r;
  110721. error*=1.f-r*r;
  110722. }
  110723. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  110724. /* we need the error value to know how big an impulse to hit the
  110725. filter with later */
  110726. return error;
  110727. }
  110728. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110729. float *data,long n){
  110730. /* in: coeff[0...m-1] LPC coefficients
  110731. prime[0...m-1] initial values (allocated size of n+m-1)
  110732. out: data[0...n-1] data samples */
  110733. long i,j,o,p;
  110734. float y;
  110735. float *work=(float*)alloca(sizeof(*work)*(m+n));
  110736. if(!prime)
  110737. for(i=0;i<m;i++)
  110738. work[i]=0.f;
  110739. else
  110740. for(i=0;i<m;i++)
  110741. work[i]=prime[i];
  110742. for(i=0;i<n;i++){
  110743. y=0;
  110744. o=i;
  110745. p=m;
  110746. for(j=0;j<m;j++)
  110747. y-=work[o++]*coeff[--p];
  110748. data[i]=work[o]=y;
  110749. }
  110750. }
  110751. #endif
  110752. /*** End of inlined file: lpc.c ***/
  110753. /*** Start of inlined file: lsp.c ***/
  110754. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  110755. an iterative root polisher (CACM algorithm 283). It *is* possible
  110756. to confuse this algorithm into not converging; that should only
  110757. happen with absurdly closely spaced roots (very sharp peaks in the
  110758. LPC f response) which in turn should be impossible in our use of
  110759. the code. If this *does* happen anyway, it's a bug in the floor
  110760. finder; find the cause of the confusion (probably a single bin
  110761. spike or accidental near-float-limit resolution problems) and
  110762. correct it. */
  110763. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110764. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110765. // tasks..
  110766. #if JUCE_MSVC
  110767. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110768. #endif
  110769. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110770. #if JUCE_USE_OGGVORBIS
  110771. #include <math.h>
  110772. #include <string.h>
  110773. #include <stdlib.h>
  110774. /*** Start of inlined file: lookup.h ***/
  110775. #ifndef _V_LOOKUP_H_
  110776. #ifdef FLOAT_LOOKUP
  110777. extern float vorbis_coslook(float a);
  110778. extern float vorbis_invsqlook(float a);
  110779. extern float vorbis_invsq2explook(int a);
  110780. extern float vorbis_fromdBlook(float a);
  110781. #endif
  110782. #ifdef INT_LOOKUP
  110783. extern long vorbis_invsqlook_i(long a,long e);
  110784. extern long vorbis_coslook_i(long a);
  110785. extern float vorbis_fromdBlook_i(long a);
  110786. #endif
  110787. #endif
  110788. /*** End of inlined file: lookup.h ***/
  110789. /* three possible LSP to f curve functions; the exact computation
  110790. (float), a lookup based float implementation, and an integer
  110791. implementation. The float lookup is likely the optimal choice on
  110792. any machine with an FPU. The integer implementation is *not* fixed
  110793. point (due to the need for a large dynamic range and thus a
  110794. seperately tracked exponent) and thus much more complex than the
  110795. relatively simple float implementations. It's mostly for future
  110796. work on a fully fixed point implementation for processors like the
  110797. ARM family. */
  110798. /* undefine both for the 'old' but more precise implementation */
  110799. #define FLOAT_LOOKUP
  110800. #undef INT_LOOKUP
  110801. #ifdef FLOAT_LOOKUP
  110802. /*** Start of inlined file: lookup.c ***/
  110803. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110804. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110805. // tasks..
  110806. #if JUCE_MSVC
  110807. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110808. #endif
  110809. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110810. #if JUCE_USE_OGGVORBIS
  110811. #include <math.h>
  110812. /*** Start of inlined file: lookup.h ***/
  110813. #ifndef _V_LOOKUP_H_
  110814. #ifdef FLOAT_LOOKUP
  110815. extern float vorbis_coslook(float a);
  110816. extern float vorbis_invsqlook(float a);
  110817. extern float vorbis_invsq2explook(int a);
  110818. extern float vorbis_fromdBlook(float a);
  110819. #endif
  110820. #ifdef INT_LOOKUP
  110821. extern long vorbis_invsqlook_i(long a,long e);
  110822. extern long vorbis_coslook_i(long a);
  110823. extern float vorbis_fromdBlook_i(long a);
  110824. #endif
  110825. #endif
  110826. /*** End of inlined file: lookup.h ***/
  110827. /*** Start of inlined file: lookup_data.h ***/
  110828. #ifndef _V_LOOKUP_DATA_H_
  110829. #ifdef FLOAT_LOOKUP
  110830. #define COS_LOOKUP_SZ 128
  110831. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110832. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110833. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110834. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110835. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110836. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110837. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110838. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110839. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110840. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110841. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110842. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110843. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110844. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110845. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110846. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110847. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110848. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110849. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110850. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110851. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110852. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110853. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110854. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110855. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110856. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110857. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110858. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110859. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110860. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110861. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110862. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110863. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110864. -1.0000000000000f,
  110865. };
  110866. #define INVSQ_LOOKUP_SZ 32
  110867. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110868. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110869. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110870. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110871. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110872. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110873. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110874. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110875. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110876. 1.000000000000f,
  110877. };
  110878. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110879. #define INVSQ2EXP_LOOKUP_MAX 32
  110880. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110881. INVSQ2EXP_LOOKUP_MIN+1]={
  110882. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110883. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110884. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110885. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110886. 256.f, 181.019336f, 128.f, 90.50966799f,
  110887. 64.f, 45.254834f, 32.f, 22.627417f,
  110888. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110889. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110890. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110891. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110892. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110893. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110894. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110895. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110896. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110897. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110898. 1.525878906e-05f,
  110899. };
  110900. #endif
  110901. #define FROMdB_LOOKUP_SZ 35
  110902. #define FROMdB2_LOOKUP_SZ 32
  110903. #define FROMdB_SHIFT 5
  110904. #define FROMdB2_SHIFT 3
  110905. #define FROMdB2_MASK 31
  110906. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110907. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110908. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110909. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110910. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110911. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110912. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110913. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110914. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110915. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110916. };
  110917. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110918. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110919. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110920. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110921. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110922. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110923. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110924. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110925. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110926. };
  110927. #ifdef INT_LOOKUP
  110928. #define INVSQ_LOOKUP_I_SHIFT 10
  110929. #define INVSQ_LOOKUP_I_MASK 1023
  110930. static long INVSQ_LOOKUP_I[64+1]={
  110931. 92682l, 91966l, 91267l, 90583l,
  110932. 89915l, 89261l, 88621l, 87995l,
  110933. 87381l, 86781l, 86192l, 85616l,
  110934. 85051l, 84497l, 83953l, 83420l,
  110935. 82897l, 82384l, 81880l, 81385l,
  110936. 80899l, 80422l, 79953l, 79492l,
  110937. 79039l, 78594l, 78156l, 77726l,
  110938. 77302l, 76885l, 76475l, 76072l,
  110939. 75674l, 75283l, 74898l, 74519l,
  110940. 74146l, 73778l, 73415l, 73058l,
  110941. 72706l, 72359l, 72016l, 71679l,
  110942. 71347l, 71019l, 70695l, 70376l,
  110943. 70061l, 69750l, 69444l, 69141l,
  110944. 68842l, 68548l, 68256l, 67969l,
  110945. 67685l, 67405l, 67128l, 66855l,
  110946. 66585l, 66318l, 66054l, 65794l,
  110947. 65536l,
  110948. };
  110949. #define COS_LOOKUP_I_SHIFT 9
  110950. #define COS_LOOKUP_I_MASK 511
  110951. #define COS_LOOKUP_I_SZ 128
  110952. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110953. 16384l, 16379l, 16364l, 16340l,
  110954. 16305l, 16261l, 16207l, 16143l,
  110955. 16069l, 15986l, 15893l, 15791l,
  110956. 15679l, 15557l, 15426l, 15286l,
  110957. 15137l, 14978l, 14811l, 14635l,
  110958. 14449l, 14256l, 14053l, 13842l,
  110959. 13623l, 13395l, 13160l, 12916l,
  110960. 12665l, 12406l, 12140l, 11866l,
  110961. 11585l, 11297l, 11003l, 10702l,
  110962. 10394l, 10080l, 9760l, 9434l,
  110963. 9102l, 8765l, 8423l, 8076l,
  110964. 7723l, 7366l, 7005l, 6639l,
  110965. 6270l, 5897l, 5520l, 5139l,
  110966. 4756l, 4370l, 3981l, 3590l,
  110967. 3196l, 2801l, 2404l, 2006l,
  110968. 1606l, 1205l, 804l, 402l,
  110969. 0l, -401l, -803l, -1204l,
  110970. -1605l, -2005l, -2403l, -2800l,
  110971. -3195l, -3589l, -3980l, -4369l,
  110972. -4755l, -5138l, -5519l, -5896l,
  110973. -6269l, -6638l, -7004l, -7365l,
  110974. -7722l, -8075l, -8422l, -8764l,
  110975. -9101l, -9433l, -9759l, -10079l,
  110976. -10393l, -10701l, -11002l, -11296l,
  110977. -11584l, -11865l, -12139l, -12405l,
  110978. -12664l, -12915l, -13159l, -13394l,
  110979. -13622l, -13841l, -14052l, -14255l,
  110980. -14448l, -14634l, -14810l, -14977l,
  110981. -15136l, -15285l, -15425l, -15556l,
  110982. -15678l, -15790l, -15892l, -15985l,
  110983. -16068l, -16142l, -16206l, -16260l,
  110984. -16304l, -16339l, -16363l, -16378l,
  110985. -16383l,
  110986. };
  110987. #endif
  110988. #endif
  110989. /*** End of inlined file: lookup_data.h ***/
  110990. #ifdef FLOAT_LOOKUP
  110991. /* interpolated lookup based cos function, domain 0 to PI only */
  110992. float vorbis_coslook(float a){
  110993. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110994. int i=vorbis_ftoi(d-.5);
  110995. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110996. }
  110997. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110998. float vorbis_invsqlook(float a){
  110999. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111000. int i=vorbis_ftoi(d-.5f);
  111001. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111002. }
  111003. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111004. float vorbis_invsq2explook(int a){
  111005. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111006. }
  111007. #include <stdio.h>
  111008. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111009. float vorbis_fromdBlook(float a){
  111010. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111011. return (i<0)?1.f:
  111012. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111013. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111014. }
  111015. #endif
  111016. #ifdef INT_LOOKUP
  111017. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111018. 16.16 format
  111019. returns in m.8 format */
  111020. long vorbis_invsqlook_i(long a,long e){
  111021. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111022. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111023. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111024. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111025. d)>>16); /* result 1.16 */
  111026. e+=32;
  111027. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111028. e=(e>>1)-8;
  111029. return(val>>e);
  111030. }
  111031. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111032. /* a is in n.12 format */
  111033. float vorbis_fromdBlook_i(long a){
  111034. int i=(-a)>>(12-FROMdB2_SHIFT);
  111035. return (i<0)?1.f:
  111036. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111037. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111038. }
  111039. /* interpolated lookup based cos function, domain 0 to PI only */
  111040. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111041. long vorbis_coslook_i(long a){
  111042. int i=a>>COS_LOOKUP_I_SHIFT;
  111043. int d=a&COS_LOOKUP_I_MASK;
  111044. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111045. COS_LOOKUP_I_SHIFT);
  111046. }
  111047. #endif
  111048. #endif
  111049. /*** End of inlined file: lookup.c ***/
  111050. /* catch this in the build system; we #include for
  111051. compilers (like gcc) that can't inline across
  111052. modules */
  111053. /* side effect: changes *lsp to cosines of lsp */
  111054. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111055. float amp,float ampoffset){
  111056. int i;
  111057. float wdel=M_PI/ln;
  111058. vorbis_fpu_control fpu;
  111059. (void) fpu; // to avoid an unused variable warning
  111060. vorbis_fpu_setround(&fpu);
  111061. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  111062. i=0;
  111063. while(i<n){
  111064. int k=map[i];
  111065. int qexp;
  111066. float p=.7071067812f;
  111067. float q=.7071067812f;
  111068. float w=vorbis_coslook(wdel*k);
  111069. float *ftmp=lsp;
  111070. int c=m>>1;
  111071. do{
  111072. q*=ftmp[0]-w;
  111073. p*=ftmp[1]-w;
  111074. ftmp+=2;
  111075. }while(--c);
  111076. if(m&1){
  111077. /* odd order filter; slightly assymetric */
  111078. /* the last coefficient */
  111079. q*=ftmp[0]-w;
  111080. q*=q;
  111081. p*=p*(1.f-w*w);
  111082. }else{
  111083. /* even order filter; still symmetric */
  111084. q*=q*(1.f+w);
  111085. p*=p*(1.f-w);
  111086. }
  111087. q=frexp(p+q,&qexp);
  111088. q=vorbis_fromdBlook(amp*
  111089. vorbis_invsqlook(q)*
  111090. vorbis_invsq2explook(qexp+m)-
  111091. ampoffset);
  111092. do{
  111093. curve[i++]*=q;
  111094. }while(map[i]==k);
  111095. }
  111096. vorbis_fpu_restore(fpu);
  111097. }
  111098. #else
  111099. #ifdef INT_LOOKUP
  111100. /*** Start of inlined file: lookup.c ***/
  111101. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111102. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111103. // tasks..
  111104. #if JUCE_MSVC
  111105. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111106. #endif
  111107. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111108. #if JUCE_USE_OGGVORBIS
  111109. #include <math.h>
  111110. /*** Start of inlined file: lookup.h ***/
  111111. #ifndef _V_LOOKUP_H_
  111112. #ifdef FLOAT_LOOKUP
  111113. extern float vorbis_coslook(float a);
  111114. extern float vorbis_invsqlook(float a);
  111115. extern float vorbis_invsq2explook(int a);
  111116. extern float vorbis_fromdBlook(float a);
  111117. #endif
  111118. #ifdef INT_LOOKUP
  111119. extern long vorbis_invsqlook_i(long a,long e);
  111120. extern long vorbis_coslook_i(long a);
  111121. extern float vorbis_fromdBlook_i(long a);
  111122. #endif
  111123. #endif
  111124. /*** End of inlined file: lookup.h ***/
  111125. /*** Start of inlined file: lookup_data.h ***/
  111126. #ifndef _V_LOOKUP_DATA_H_
  111127. #ifdef FLOAT_LOOKUP
  111128. #define COS_LOOKUP_SZ 128
  111129. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  111130. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  111131. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  111132. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  111133. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  111134. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  111135. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  111136. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  111137. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  111138. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  111139. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  111140. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  111141. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  111142. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  111143. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  111144. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  111145. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  111146. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  111147. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  111148. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  111149. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  111150. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  111151. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  111152. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  111153. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  111154. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  111155. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  111156. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  111157. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  111158. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  111159. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  111160. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  111161. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  111162. -1.0000000000000f,
  111163. };
  111164. #define INVSQ_LOOKUP_SZ 32
  111165. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  111166. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  111167. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  111168. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  111169. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  111170. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  111171. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  111172. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  111173. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  111174. 1.000000000000f,
  111175. };
  111176. #define INVSQ2EXP_LOOKUP_MIN (-32)
  111177. #define INVSQ2EXP_LOOKUP_MAX 32
  111178. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  111179. INVSQ2EXP_LOOKUP_MIN+1]={
  111180. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  111181. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  111182. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  111183. 1024.f, 724.0773439f, 512.f, 362.038672f,
  111184. 256.f, 181.019336f, 128.f, 90.50966799f,
  111185. 64.f, 45.254834f, 32.f, 22.627417f,
  111186. 16.f, 11.3137085f, 8.f, 5.656854249f,
  111187. 4.f, 2.828427125f, 2.f, 1.414213562f,
  111188. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  111189. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  111190. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  111191. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  111192. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  111193. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  111194. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  111195. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  111196. 1.525878906e-05f,
  111197. };
  111198. #endif
  111199. #define FROMdB_LOOKUP_SZ 35
  111200. #define FROMdB2_LOOKUP_SZ 32
  111201. #define FROMdB_SHIFT 5
  111202. #define FROMdB2_SHIFT 3
  111203. #define FROMdB2_MASK 31
  111204. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  111205. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  111206. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  111207. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  111208. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  111209. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  111210. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  111211. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  111212. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  111213. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  111214. };
  111215. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  111216. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  111217. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  111218. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  111219. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  111220. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  111221. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  111222. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  111223. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  111224. };
  111225. #ifdef INT_LOOKUP
  111226. #define INVSQ_LOOKUP_I_SHIFT 10
  111227. #define INVSQ_LOOKUP_I_MASK 1023
  111228. static long INVSQ_LOOKUP_I[64+1]={
  111229. 92682l, 91966l, 91267l, 90583l,
  111230. 89915l, 89261l, 88621l, 87995l,
  111231. 87381l, 86781l, 86192l, 85616l,
  111232. 85051l, 84497l, 83953l, 83420l,
  111233. 82897l, 82384l, 81880l, 81385l,
  111234. 80899l, 80422l, 79953l, 79492l,
  111235. 79039l, 78594l, 78156l, 77726l,
  111236. 77302l, 76885l, 76475l, 76072l,
  111237. 75674l, 75283l, 74898l, 74519l,
  111238. 74146l, 73778l, 73415l, 73058l,
  111239. 72706l, 72359l, 72016l, 71679l,
  111240. 71347l, 71019l, 70695l, 70376l,
  111241. 70061l, 69750l, 69444l, 69141l,
  111242. 68842l, 68548l, 68256l, 67969l,
  111243. 67685l, 67405l, 67128l, 66855l,
  111244. 66585l, 66318l, 66054l, 65794l,
  111245. 65536l,
  111246. };
  111247. #define COS_LOOKUP_I_SHIFT 9
  111248. #define COS_LOOKUP_I_MASK 511
  111249. #define COS_LOOKUP_I_SZ 128
  111250. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  111251. 16384l, 16379l, 16364l, 16340l,
  111252. 16305l, 16261l, 16207l, 16143l,
  111253. 16069l, 15986l, 15893l, 15791l,
  111254. 15679l, 15557l, 15426l, 15286l,
  111255. 15137l, 14978l, 14811l, 14635l,
  111256. 14449l, 14256l, 14053l, 13842l,
  111257. 13623l, 13395l, 13160l, 12916l,
  111258. 12665l, 12406l, 12140l, 11866l,
  111259. 11585l, 11297l, 11003l, 10702l,
  111260. 10394l, 10080l, 9760l, 9434l,
  111261. 9102l, 8765l, 8423l, 8076l,
  111262. 7723l, 7366l, 7005l, 6639l,
  111263. 6270l, 5897l, 5520l, 5139l,
  111264. 4756l, 4370l, 3981l, 3590l,
  111265. 3196l, 2801l, 2404l, 2006l,
  111266. 1606l, 1205l, 804l, 402l,
  111267. 0l, -401l, -803l, -1204l,
  111268. -1605l, -2005l, -2403l, -2800l,
  111269. -3195l, -3589l, -3980l, -4369l,
  111270. -4755l, -5138l, -5519l, -5896l,
  111271. -6269l, -6638l, -7004l, -7365l,
  111272. -7722l, -8075l, -8422l, -8764l,
  111273. -9101l, -9433l, -9759l, -10079l,
  111274. -10393l, -10701l, -11002l, -11296l,
  111275. -11584l, -11865l, -12139l, -12405l,
  111276. -12664l, -12915l, -13159l, -13394l,
  111277. -13622l, -13841l, -14052l, -14255l,
  111278. -14448l, -14634l, -14810l, -14977l,
  111279. -15136l, -15285l, -15425l, -15556l,
  111280. -15678l, -15790l, -15892l, -15985l,
  111281. -16068l, -16142l, -16206l, -16260l,
  111282. -16304l, -16339l, -16363l, -16378l,
  111283. -16383l,
  111284. };
  111285. #endif
  111286. #endif
  111287. /*** End of inlined file: lookup_data.h ***/
  111288. #ifdef FLOAT_LOOKUP
  111289. /* interpolated lookup based cos function, domain 0 to PI only */
  111290. float vorbis_coslook(float a){
  111291. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  111292. int i=vorbis_ftoi(d-.5);
  111293. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  111294. }
  111295. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111296. float vorbis_invsqlook(float a){
  111297. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111298. int i=vorbis_ftoi(d-.5f);
  111299. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111300. }
  111301. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111302. float vorbis_invsq2explook(int a){
  111303. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111304. }
  111305. #include <stdio.h>
  111306. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111307. float vorbis_fromdBlook(float a){
  111308. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111309. return (i<0)?1.f:
  111310. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111311. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111312. }
  111313. #endif
  111314. #ifdef INT_LOOKUP
  111315. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111316. 16.16 format
  111317. returns in m.8 format */
  111318. long vorbis_invsqlook_i(long a,long e){
  111319. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111320. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111321. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111322. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111323. d)>>16); /* result 1.16 */
  111324. e+=32;
  111325. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111326. e=(e>>1)-8;
  111327. return(val>>e);
  111328. }
  111329. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111330. /* a is in n.12 format */
  111331. float vorbis_fromdBlook_i(long a){
  111332. int i=(-a)>>(12-FROMdB2_SHIFT);
  111333. return (i<0)?1.f:
  111334. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111335. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111336. }
  111337. /* interpolated lookup based cos function, domain 0 to PI only */
  111338. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111339. long vorbis_coslook_i(long a){
  111340. int i=a>>COS_LOOKUP_I_SHIFT;
  111341. int d=a&COS_LOOKUP_I_MASK;
  111342. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111343. COS_LOOKUP_I_SHIFT);
  111344. }
  111345. #endif
  111346. #endif
  111347. /*** End of inlined file: lookup.c ***/
  111348. /* catch this in the build system; we #include for
  111349. compilers (like gcc) that can't inline across
  111350. modules */
  111351. static int MLOOP_1[64]={
  111352. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  111353. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  111354. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111355. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111356. };
  111357. static int MLOOP_2[64]={
  111358. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  111359. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  111360. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  111361. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  111362. };
  111363. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  111364. /* side effect: changes *lsp to cosines of lsp */
  111365. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111366. float amp,float ampoffset){
  111367. /* 0 <= m < 256 */
  111368. /* set up for using all int later */
  111369. int i;
  111370. int ampoffseti=rint(ampoffset*4096.f);
  111371. int ampi=rint(amp*16.f);
  111372. long *ilsp=alloca(m*sizeof(*ilsp));
  111373. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  111374. i=0;
  111375. while(i<n){
  111376. int j,k=map[i];
  111377. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  111378. unsigned long qi=46341;
  111379. int qexp=0,shift;
  111380. long wi=vorbis_coslook_i(k*65536/ln);
  111381. qi*=labs(ilsp[0]-wi);
  111382. pi*=labs(ilsp[1]-wi);
  111383. for(j=3;j<m;j+=2){
  111384. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111385. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111386. shift=MLOOP_3[(pi|qi)>>16];
  111387. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  111388. pi=(pi>>shift)*labs(ilsp[j]-wi);
  111389. qexp+=shift;
  111390. }
  111391. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111392. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111393. shift=MLOOP_3[(pi|qi)>>16];
  111394. /* pi,qi normalized collectively, both tracked using qexp */
  111395. if(m&1){
  111396. /* odd order filter; slightly assymetric */
  111397. /* the last coefficient */
  111398. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  111399. pi=(pi>>shift)<<14;
  111400. qexp+=shift;
  111401. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111402. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111403. shift=MLOOP_3[(pi|qi)>>16];
  111404. pi>>=shift;
  111405. qi>>=shift;
  111406. qexp+=shift-14*((m+1)>>1);
  111407. pi=((pi*pi)>>16);
  111408. qi=((qi*qi)>>16);
  111409. qexp=qexp*2+m;
  111410. pi*=(1<<14)-((wi*wi)>>14);
  111411. qi+=pi>>14;
  111412. }else{
  111413. /* even order filter; still symmetric */
  111414. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  111415. worth tracking step by step */
  111416. pi>>=shift;
  111417. qi>>=shift;
  111418. qexp+=shift-7*m;
  111419. pi=((pi*pi)>>16);
  111420. qi=((qi*qi)>>16);
  111421. qexp=qexp*2+m;
  111422. pi*=(1<<14)-wi;
  111423. qi*=(1<<14)+wi;
  111424. qi=(qi+pi)>>14;
  111425. }
  111426. /* we've let the normalization drift because it wasn't important;
  111427. however, for the lookup, things must be normalized again. We
  111428. need at most one right shift or a number of left shifts */
  111429. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  111430. qi>>=1; qexp++;
  111431. }else
  111432. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  111433. qi<<=1; qexp--;
  111434. }
  111435. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  111436. vorbis_invsqlook_i(qi,qexp)-
  111437. /* m.8, m+n<=8 */
  111438. ampoffseti); /* 8.12[0] */
  111439. curve[i]*=amp;
  111440. while(map[++i]==k)curve[i]*=amp;
  111441. }
  111442. }
  111443. #else
  111444. /* old, nonoptimized but simple version for any poor sap who needs to
  111445. figure out what the hell this code does, or wants the other
  111446. fraction of a dB precision */
  111447. /* side effect: changes *lsp to cosines of lsp */
  111448. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111449. float amp,float ampoffset){
  111450. int i;
  111451. float wdel=M_PI/ln;
  111452. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  111453. i=0;
  111454. while(i<n){
  111455. int j,k=map[i];
  111456. float p=.5f;
  111457. float q=.5f;
  111458. float w=2.f*cos(wdel*k);
  111459. for(j=1;j<m;j+=2){
  111460. q *= w-lsp[j-1];
  111461. p *= w-lsp[j];
  111462. }
  111463. if(j==m){
  111464. /* odd order filter; slightly assymetric */
  111465. /* the last coefficient */
  111466. q*=w-lsp[j-1];
  111467. p*=p*(4.f-w*w);
  111468. q*=q;
  111469. }else{
  111470. /* even order filter; still symmetric */
  111471. p*=p*(2.f-w);
  111472. q*=q*(2.f+w);
  111473. }
  111474. q=fromdB(amp/sqrt(p+q)-ampoffset);
  111475. curve[i]*=q;
  111476. while(map[++i]==k)curve[i]*=q;
  111477. }
  111478. }
  111479. #endif
  111480. #endif
  111481. static void cheby(float *g, int ord) {
  111482. int i, j;
  111483. g[0] *= .5f;
  111484. for(i=2; i<= ord; i++) {
  111485. for(j=ord; j >= i; j--) {
  111486. g[j-2] -= g[j];
  111487. g[j] += g[j];
  111488. }
  111489. }
  111490. }
  111491. static int comp(const void *a,const void *b){
  111492. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  111493. }
  111494. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  111495. but there are root sets for which it gets into limit cycles
  111496. (exacerbated by zero suppression) and fails. We can't afford to
  111497. fail, even if the failure is 1 in 100,000,000, so we now use
  111498. Laguerre and later polish with Newton-Raphson (which can then
  111499. afford to fail) */
  111500. #define EPSILON 10e-7
  111501. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  111502. int i,m;
  111503. double lastdelta=0.f;
  111504. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  111505. for(i=0;i<=ord;i++)defl[i]=a[i];
  111506. for(m=ord;m>0;m--){
  111507. double newx=0.f,delta;
  111508. /* iterate a root */
  111509. while(1){
  111510. double p=defl[m],pp=0.f,ppp=0.f,denom;
  111511. /* eval the polynomial and its first two derivatives */
  111512. for(i=m;i>0;i--){
  111513. ppp = newx*ppp + pp;
  111514. pp = newx*pp + p;
  111515. p = newx*p + defl[i-1];
  111516. }
  111517. /* Laguerre's method */
  111518. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  111519. if(denom<0)
  111520. return(-1); /* complex root! The LPC generator handed us a bad filter */
  111521. if(pp>0){
  111522. denom = pp + sqrt(denom);
  111523. if(denom<EPSILON)denom=EPSILON;
  111524. }else{
  111525. denom = pp - sqrt(denom);
  111526. if(denom>-(EPSILON))denom=-(EPSILON);
  111527. }
  111528. delta = m*p/denom;
  111529. newx -= delta;
  111530. if(delta<0.f)delta*=-1;
  111531. if(fabs(delta/newx)<10e-12)break;
  111532. lastdelta=delta;
  111533. }
  111534. r[m-1]=newx;
  111535. /* forward deflation */
  111536. for(i=m;i>0;i--)
  111537. defl[i-1]+=newx*defl[i];
  111538. defl++;
  111539. }
  111540. return(0);
  111541. }
  111542. /* for spit-and-polish only */
  111543. static int Newton_Raphson(float *a,int ord,float *r){
  111544. int i, k, count=0;
  111545. double error=1.f;
  111546. double *root=(double*)alloca(ord*sizeof(*root));
  111547. for(i=0; i<ord;i++) root[i] = r[i];
  111548. while(error>1e-20){
  111549. error=0;
  111550. for(i=0; i<ord; i++) { /* Update each point. */
  111551. double pp=0.,delta;
  111552. double rooti=root[i];
  111553. double p=a[ord];
  111554. for(k=ord-1; k>= 0; k--) {
  111555. pp= pp* rooti + p;
  111556. p = p * rooti + a[k];
  111557. }
  111558. delta = p/pp;
  111559. root[i] -= delta;
  111560. error+= delta*delta;
  111561. }
  111562. if(count>40)return(-1);
  111563. count++;
  111564. }
  111565. /* Replaced the original bubble sort with a real sort. With your
  111566. help, we can eliminate the bubble sort in our lifetime. --Monty */
  111567. for(i=0; i<ord;i++) r[i] = root[i];
  111568. return(0);
  111569. }
  111570. /* Convert lpc coefficients to lsp coefficients */
  111571. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  111572. int order2=(m+1)>>1;
  111573. int g1_order,g2_order;
  111574. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  111575. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  111576. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  111577. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  111578. int i;
  111579. /* even and odd are slightly different base cases */
  111580. g1_order=(m+1)>>1;
  111581. g2_order=(m) >>1;
  111582. /* Compute the lengths of the x polynomials. */
  111583. /* Compute the first half of K & R F1 & F2 polynomials. */
  111584. /* Compute half of the symmetric and antisymmetric polynomials. */
  111585. /* Remove the roots at +1 and -1. */
  111586. g1[g1_order] = 1.f;
  111587. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  111588. g2[g2_order] = 1.f;
  111589. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  111590. if(g1_order>g2_order){
  111591. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  111592. }else{
  111593. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  111594. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  111595. }
  111596. /* Convert into polynomials in cos(alpha) */
  111597. cheby(g1,g1_order);
  111598. cheby(g2,g2_order);
  111599. /* Find the roots of the 2 even polynomials.*/
  111600. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  111601. Laguerre_With_Deflation(g2,g2_order,g2r))
  111602. return(-1);
  111603. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  111604. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  111605. qsort(g1r,g1_order,sizeof(*g1r),comp);
  111606. qsort(g2r,g2_order,sizeof(*g2r),comp);
  111607. for(i=0;i<g1_order;i++)
  111608. lsp[i*2] = acos(g1r[i]);
  111609. for(i=0;i<g2_order;i++)
  111610. lsp[i*2+1] = acos(g2r[i]);
  111611. return(0);
  111612. }
  111613. #endif
  111614. /*** End of inlined file: lsp.c ***/
  111615. /*** Start of inlined file: mapping0.c ***/
  111616. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111617. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111618. // tasks..
  111619. #if JUCE_MSVC
  111620. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111621. #endif
  111622. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111623. #if JUCE_USE_OGGVORBIS
  111624. #include <stdlib.h>
  111625. #include <stdio.h>
  111626. #include <string.h>
  111627. #include <math.h>
  111628. /* simplistic, wasteful way of doing this (unique lookup for each
  111629. mode/submapping); there should be a central repository for
  111630. identical lookups. That will require minor work, so I'm putting it
  111631. off as low priority.
  111632. Why a lookup for each backend in a given mode? Because the
  111633. blocksize is set by the mode, and low backend lookups may require
  111634. parameters from other areas of the mode/mapping */
  111635. static void mapping0_free_info(vorbis_info_mapping *i){
  111636. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  111637. if(info){
  111638. memset(info,0,sizeof(*info));
  111639. _ogg_free(info);
  111640. }
  111641. }
  111642. static int ilog3(unsigned int v){
  111643. int ret=0;
  111644. if(v)--v;
  111645. while(v){
  111646. ret++;
  111647. v>>=1;
  111648. }
  111649. return(ret);
  111650. }
  111651. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  111652. oggpack_buffer *opb){
  111653. int i;
  111654. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  111655. /* another 'we meant to do it this way' hack... up to beta 4, we
  111656. packed 4 binary zeros here to signify one submapping in use. We
  111657. now redefine that to mean four bitflags that indicate use of
  111658. deeper features; bit0:submappings, bit1:coupling,
  111659. bit2,3:reserved. This is backward compatable with all actual uses
  111660. of the beta code. */
  111661. if(info->submaps>1){
  111662. oggpack_write(opb,1,1);
  111663. oggpack_write(opb,info->submaps-1,4);
  111664. }else
  111665. oggpack_write(opb,0,1);
  111666. if(info->coupling_steps>0){
  111667. oggpack_write(opb,1,1);
  111668. oggpack_write(opb,info->coupling_steps-1,8);
  111669. for(i=0;i<info->coupling_steps;i++){
  111670. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  111671. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  111672. }
  111673. }else
  111674. oggpack_write(opb,0,1);
  111675. oggpack_write(opb,0,2); /* 2,3:reserved */
  111676. /* we don't write the channel submappings if we only have one... */
  111677. if(info->submaps>1){
  111678. for(i=0;i<vi->channels;i++)
  111679. oggpack_write(opb,info->chmuxlist[i],4);
  111680. }
  111681. for(i=0;i<info->submaps;i++){
  111682. oggpack_write(opb,0,8); /* time submap unused */
  111683. oggpack_write(opb,info->floorsubmap[i],8);
  111684. oggpack_write(opb,info->residuesubmap[i],8);
  111685. }
  111686. }
  111687. /* also responsible for range checking */
  111688. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  111689. int i;
  111690. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  111691. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111692. memset(info,0,sizeof(*info));
  111693. if(oggpack_read(opb,1))
  111694. info->submaps=oggpack_read(opb,4)+1;
  111695. else
  111696. info->submaps=1;
  111697. if(oggpack_read(opb,1)){
  111698. info->coupling_steps=oggpack_read(opb,8)+1;
  111699. for(i=0;i<info->coupling_steps;i++){
  111700. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  111701. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  111702. if(testM<0 ||
  111703. testA<0 ||
  111704. testM==testA ||
  111705. testM>=vi->channels ||
  111706. testA>=vi->channels) goto err_out;
  111707. }
  111708. }
  111709. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  111710. if(info->submaps>1){
  111711. for(i=0;i<vi->channels;i++){
  111712. info->chmuxlist[i]=oggpack_read(opb,4);
  111713. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  111714. }
  111715. }
  111716. for(i=0;i<info->submaps;i++){
  111717. oggpack_read(opb,8); /* time submap unused */
  111718. info->floorsubmap[i]=oggpack_read(opb,8);
  111719. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  111720. info->residuesubmap[i]=oggpack_read(opb,8);
  111721. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  111722. }
  111723. return info;
  111724. err_out:
  111725. mapping0_free_info(info);
  111726. return(NULL);
  111727. }
  111728. #if 0
  111729. static long seq=0;
  111730. static ogg_int64_t total=0;
  111731. static float FLOOR1_fromdB_LOOKUP[256]={
  111732. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  111733. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  111734. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  111735. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  111736. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  111737. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  111738. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  111739. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  111740. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  111741. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  111742. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  111743. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  111744. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  111745. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  111746. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  111747. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  111748. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  111749. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  111750. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  111751. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  111752. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  111753. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  111754. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  111755. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  111756. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  111757. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  111758. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  111759. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  111760. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  111761. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  111762. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  111763. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  111764. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  111765. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  111766. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  111767. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  111768. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  111769. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111770. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111771. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  111772. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  111773. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  111774. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  111775. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  111776. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  111777. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  111778. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  111779. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  111780. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  111781. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  111782. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  111783. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  111784. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  111785. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  111786. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  111787. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  111788. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  111789. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  111790. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  111791. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  111792. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  111793. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  111794. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  111795. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  111796. };
  111797. #endif
  111798. extern int *floor1_fit(vorbis_block *vb,void *look,
  111799. const float *logmdct, /* in */
  111800. const float *logmask);
  111801. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  111802. int *A,int *B,
  111803. int del);
  111804. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  111805. void*look,
  111806. int *post,int *ilogmask);
  111807. static int mapping0_forward(vorbis_block *vb){
  111808. vorbis_dsp_state *vd=vb->vd;
  111809. vorbis_info *vi=vd->vi;
  111810. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111811. private_state *b=(private_state*)vb->vd->backend_state;
  111812. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111813. int n=vb->pcmend;
  111814. int i,j,k;
  111815. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  111816. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  111817. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  111818. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  111819. float global_ampmax=vbi->ampmax;
  111820. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  111821. int blocktype=vbi->blocktype;
  111822. int modenumber=vb->W;
  111823. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  111824. vorbis_look_psy *psy_look=
  111825. b->psy+blocktype+(vb->W?2:0);
  111826. vb->mode=modenumber;
  111827. for(i=0;i<vi->channels;i++){
  111828. float scale=4.f/n;
  111829. float scale_dB;
  111830. float *pcm =vb->pcm[i];
  111831. float *logfft =pcm;
  111832. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111833. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  111834. todB estimation used on IEEE 754
  111835. compliant machines had a bug that
  111836. returned dB values about a third
  111837. of a decibel too high. The bug
  111838. was harmless because tunings
  111839. implicitly took that into
  111840. account. However, fixing the bug
  111841. in the estimator requires
  111842. changing all the tunings as well.
  111843. For now, it's easier to sync
  111844. things back up here, and
  111845. recalibrate the tunings in the
  111846. next major model upgrade. */
  111847. #if 0
  111848. if(vi->channels==2)
  111849. if(i==0)
  111850. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  111851. else
  111852. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  111853. #endif
  111854. /* window the PCM data */
  111855. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  111856. #if 0
  111857. if(vi->channels==2)
  111858. if(i==0)
  111859. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  111860. else
  111861. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  111862. #endif
  111863. /* transform the PCM data */
  111864. /* only MDCT right now.... */
  111865. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  111866. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  111867. drft_forward(&b->fft_look[vb->W],pcm);
  111868. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  111869. original todB estimation used on
  111870. IEEE 754 compliant machines had a
  111871. bug that returned dB values about
  111872. a third of a decibel too high.
  111873. The bug was harmless because
  111874. tunings implicitly took that into
  111875. account. However, fixing the bug
  111876. in the estimator requires
  111877. changing all the tunings as well.
  111878. For now, it's easier to sync
  111879. things back up here, and
  111880. recalibrate the tunings in the
  111881. next major model upgrade. */
  111882. local_ampmax[i]=logfft[0];
  111883. for(j=1;j<n-1;j+=2){
  111884. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  111885. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  111886. .345 is a hack; the original todB
  111887. estimation used on IEEE 754
  111888. compliant machines had a bug that
  111889. returned dB values about a third
  111890. of a decibel too high. The bug
  111891. was harmless because tunings
  111892. implicitly took that into
  111893. account. However, fixing the bug
  111894. in the estimator requires
  111895. changing all the tunings as well.
  111896. For now, it's easier to sync
  111897. things back up here, and
  111898. recalibrate the tunings in the
  111899. next major model upgrade. */
  111900. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  111901. }
  111902. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  111903. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  111904. #if 0
  111905. if(vi->channels==2){
  111906. if(i==0){
  111907. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  111908. }else{
  111909. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  111910. }
  111911. }
  111912. #endif
  111913. }
  111914. {
  111915. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  111916. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  111917. for(i=0;i<vi->channels;i++){
  111918. /* the encoder setup assumes that all the modes used by any
  111919. specific bitrate tweaking use the same floor */
  111920. int submap=info->chmuxlist[i];
  111921. /* the following makes things clearer to *me* anyway */
  111922. float *mdct =gmdct[i];
  111923. float *logfft =vb->pcm[i];
  111924. float *logmdct =logfft+n/2;
  111925. float *logmask =logfft;
  111926. vb->mode=modenumber;
  111927. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  111928. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  111929. for(j=0;j<n/2;j++)
  111930. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  111931. todB estimation used on IEEE 754
  111932. compliant machines had a bug that
  111933. returned dB values about a third
  111934. of a decibel too high. The bug
  111935. was harmless because tunings
  111936. implicitly took that into
  111937. account. However, fixing the bug
  111938. in the estimator requires
  111939. changing all the tunings as well.
  111940. For now, it's easier to sync
  111941. things back up here, and
  111942. recalibrate the tunings in the
  111943. next major model upgrade. */
  111944. #if 0
  111945. if(vi->channels==2){
  111946. if(i==0)
  111947. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  111948. else
  111949. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  111950. }else{
  111951. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  111952. }
  111953. #endif
  111954. /* first step; noise masking. Not only does 'noise masking'
  111955. give us curves from which we can decide how much resolution
  111956. to give noise parts of the spectrum, it also implicitly hands
  111957. us a tonality estimate (the larger the value in the
  111958. 'noise_depth' vector, the more tonal that area is) */
  111959. _vp_noisemask(psy_look,
  111960. logmdct,
  111961. noise); /* noise does not have by-frequency offset
  111962. bias applied yet */
  111963. #if 0
  111964. if(vi->channels==2){
  111965. if(i==0)
  111966. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  111967. else
  111968. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  111969. }
  111970. #endif
  111971. /* second step: 'all the other crap'; all the stuff that isn't
  111972. computed/fit for bitrate management goes in the second psy
  111973. vector. This includes tone masking, peak limiting and ATH */
  111974. _vp_tonemask(psy_look,
  111975. logfft,
  111976. tone,
  111977. global_ampmax,
  111978. local_ampmax[i]);
  111979. #if 0
  111980. if(vi->channels==2){
  111981. if(i==0)
  111982. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  111983. else
  111984. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  111985. }
  111986. #endif
  111987. /* third step; we offset the noise vectors, overlay tone
  111988. masking. We then do a floor1-specific line fit. If we're
  111989. performing bitrate management, the line fit is performed
  111990. multiple times for up/down tweakage on demand. */
  111991. #if 0
  111992. {
  111993. float aotuv[psy_look->n];
  111994. #endif
  111995. _vp_offset_and_mix(psy_look,
  111996. noise,
  111997. tone,
  111998. 1,
  111999. logmask,
  112000. mdct,
  112001. logmdct);
  112002. #if 0
  112003. if(vi->channels==2){
  112004. if(i==0)
  112005. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  112006. else
  112007. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  112008. }
  112009. }
  112010. #endif
  112011. #if 0
  112012. if(vi->channels==2){
  112013. if(i==0)
  112014. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  112015. else
  112016. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  112017. }
  112018. #endif
  112019. /* this algorithm is hardwired to floor 1 for now; abort out if
  112020. we're *not* floor1. This won't happen unless someone has
  112021. broken the encode setup lib. Guard it anyway. */
  112022. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  112023. floor_posts[i][PACKETBLOBS/2]=
  112024. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112025. logmdct,
  112026. logmask);
  112027. /* are we managing bitrate? If so, perform two more fits for
  112028. later rate tweaking (fits represent hi/lo) */
  112029. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  112030. /* higher rate by way of lower noise curve */
  112031. _vp_offset_and_mix(psy_look,
  112032. noise,
  112033. tone,
  112034. 2,
  112035. logmask,
  112036. mdct,
  112037. logmdct);
  112038. #if 0
  112039. if(vi->channels==2){
  112040. if(i==0)
  112041. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  112042. else
  112043. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  112044. }
  112045. #endif
  112046. floor_posts[i][PACKETBLOBS-1]=
  112047. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112048. logmdct,
  112049. logmask);
  112050. /* lower rate by way of higher noise curve */
  112051. _vp_offset_and_mix(psy_look,
  112052. noise,
  112053. tone,
  112054. 0,
  112055. logmask,
  112056. mdct,
  112057. logmdct);
  112058. #if 0
  112059. if(vi->channels==2)
  112060. if(i==0)
  112061. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  112062. else
  112063. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  112064. #endif
  112065. floor_posts[i][0]=
  112066. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112067. logmdct,
  112068. logmask);
  112069. /* we also interpolate a range of intermediate curves for
  112070. intermediate rates */
  112071. for(k=1;k<PACKETBLOBS/2;k++)
  112072. floor_posts[i][k]=
  112073. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112074. floor_posts[i][0],
  112075. floor_posts[i][PACKETBLOBS/2],
  112076. k*65536/(PACKETBLOBS/2));
  112077. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  112078. floor_posts[i][k]=
  112079. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112080. floor_posts[i][PACKETBLOBS/2],
  112081. floor_posts[i][PACKETBLOBS-1],
  112082. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  112083. }
  112084. }
  112085. }
  112086. vbi->ampmax=global_ampmax;
  112087. /*
  112088. the next phases are performed once for vbr-only and PACKETBLOB
  112089. times for bitrate managed modes.
  112090. 1) encode actual mode being used
  112091. 2) encode the floor for each channel, compute coded mask curve/res
  112092. 3) normalize and couple.
  112093. 4) encode residue
  112094. 5) save packet bytes to the packetblob vector
  112095. */
  112096. /* iterate over the many masking curve fits we've created */
  112097. {
  112098. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  112099. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  112100. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112101. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  112102. float **mag_memo;
  112103. int **mag_sort;
  112104. if(info->coupling_steps){
  112105. mag_memo=_vp_quantize_couple_memo(vb,
  112106. &ci->psy_g_param,
  112107. psy_look,
  112108. info,
  112109. gmdct);
  112110. mag_sort=_vp_quantize_couple_sort(vb,
  112111. psy_look,
  112112. info,
  112113. mag_memo);
  112114. hf_reduction(&ci->psy_g_param,
  112115. psy_look,
  112116. info,
  112117. mag_memo);
  112118. }
  112119. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  112120. if(psy_look->vi->normal_channel_p){
  112121. for(i=0;i<vi->channels;i++){
  112122. float *mdct =gmdct[i];
  112123. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  112124. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  112125. }
  112126. }
  112127. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  112128. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  112129. k++){
  112130. oggpack_buffer *opb=vbi->packetblob[k];
  112131. /* start out our new packet blob with packet type and mode */
  112132. /* Encode the packet type */
  112133. oggpack_write(opb,0,1);
  112134. /* Encode the modenumber */
  112135. /* Encode frame mode, pre,post windowsize, then dispatch */
  112136. oggpack_write(opb,modenumber,b->modebits);
  112137. if(vb->W){
  112138. oggpack_write(opb,vb->lW,1);
  112139. oggpack_write(opb,vb->nW,1);
  112140. }
  112141. /* encode floor, compute masking curve, sep out residue */
  112142. for(i=0;i<vi->channels;i++){
  112143. int submap=info->chmuxlist[i];
  112144. float *mdct =gmdct[i];
  112145. float *res =vb->pcm[i];
  112146. int *ilogmask=ilogmaskch[i]=
  112147. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  112148. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  112149. floor_posts[i][k],
  112150. ilogmask);
  112151. #if 0
  112152. {
  112153. char buf[80];
  112154. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  112155. float work[n/2];
  112156. for(j=0;j<n/2;j++)
  112157. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  112158. _analysis_output(buf,seq,work,n/2,1,1,0);
  112159. }
  112160. #endif
  112161. _vp_remove_floor(psy_look,
  112162. mdct,
  112163. ilogmask,
  112164. res,
  112165. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112166. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  112167. #if 0
  112168. {
  112169. char buf[80];
  112170. float work[n/2];
  112171. for(j=0;j<n/2;j++)
  112172. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  112173. sprintf(buf,"resI%c%d",i?'R':'L',k);
  112174. _analysis_output(buf,seq,work,n/2,1,1,0);
  112175. }
  112176. #endif
  112177. }
  112178. /* our iteration is now based on masking curve, not prequant and
  112179. coupling. Only one prequant/coupling step */
  112180. /* quantize/couple */
  112181. /* incomplete implementation that assumes the tree is all depth
  112182. one, or no tree at all */
  112183. if(info->coupling_steps){
  112184. _vp_couple(k,
  112185. &ci->psy_g_param,
  112186. psy_look,
  112187. info,
  112188. vb->pcm,
  112189. mag_memo,
  112190. mag_sort,
  112191. ilogmaskch,
  112192. nonzero,
  112193. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112194. }
  112195. /* classify and encode by submap */
  112196. for(i=0;i<info->submaps;i++){
  112197. int ch_in_bundle=0;
  112198. long **classifications;
  112199. int resnum=info->residuesubmap[i];
  112200. for(j=0;j<vi->channels;j++){
  112201. if(info->chmuxlist[j]==i){
  112202. zerobundle[ch_in_bundle]=0;
  112203. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  112204. res_bundle[ch_in_bundle]=vb->pcm[j];
  112205. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  112206. }
  112207. }
  112208. classifications=_residue_P[ci->residue_type[resnum]]->
  112209. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  112210. _residue_P[ci->residue_type[resnum]]->
  112211. forward(opb,vb,b->residue[resnum],
  112212. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  112213. }
  112214. /* ok, done encoding. Next protopacket. */
  112215. }
  112216. }
  112217. #if 0
  112218. seq++;
  112219. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  112220. #endif
  112221. return(0);
  112222. }
  112223. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  112224. vorbis_dsp_state *vd=vb->vd;
  112225. vorbis_info *vi=vd->vi;
  112226. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112227. private_state *b=(private_state*)vd->backend_state;
  112228. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  112229. int i,j;
  112230. long n=vb->pcmend=ci->blocksizes[vb->W];
  112231. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  112232. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112233. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  112234. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  112235. /* recover the spectral envelope; store it in the PCM vector for now */
  112236. for(i=0;i<vi->channels;i++){
  112237. int submap=info->chmuxlist[i];
  112238. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112239. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  112240. if(floormemo[i])
  112241. nonzero[i]=1;
  112242. else
  112243. nonzero[i]=0;
  112244. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  112245. }
  112246. /* channel coupling can 'dirty' the nonzero listing */
  112247. for(i=0;i<info->coupling_steps;i++){
  112248. if(nonzero[info->coupling_mag[i]] ||
  112249. nonzero[info->coupling_ang[i]]){
  112250. nonzero[info->coupling_mag[i]]=1;
  112251. nonzero[info->coupling_ang[i]]=1;
  112252. }
  112253. }
  112254. /* recover the residue into our working vectors */
  112255. for(i=0;i<info->submaps;i++){
  112256. int ch_in_bundle=0;
  112257. for(j=0;j<vi->channels;j++){
  112258. if(info->chmuxlist[j]==i){
  112259. if(nonzero[j])
  112260. zerobundle[ch_in_bundle]=1;
  112261. else
  112262. zerobundle[ch_in_bundle]=0;
  112263. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  112264. }
  112265. }
  112266. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  112267. inverse(vb,b->residue[info->residuesubmap[i]],
  112268. pcmbundle,zerobundle,ch_in_bundle);
  112269. }
  112270. /* channel coupling */
  112271. for(i=info->coupling_steps-1;i>=0;i--){
  112272. float *pcmM=vb->pcm[info->coupling_mag[i]];
  112273. float *pcmA=vb->pcm[info->coupling_ang[i]];
  112274. for(j=0;j<n/2;j++){
  112275. float mag=pcmM[j];
  112276. float ang=pcmA[j];
  112277. if(mag>0)
  112278. if(ang>0){
  112279. pcmM[j]=mag;
  112280. pcmA[j]=mag-ang;
  112281. }else{
  112282. pcmA[j]=mag;
  112283. pcmM[j]=mag+ang;
  112284. }
  112285. else
  112286. if(ang>0){
  112287. pcmM[j]=mag;
  112288. pcmA[j]=mag+ang;
  112289. }else{
  112290. pcmA[j]=mag;
  112291. pcmM[j]=mag-ang;
  112292. }
  112293. }
  112294. }
  112295. /* compute and apply spectral envelope */
  112296. for(i=0;i<vi->channels;i++){
  112297. float *pcm=vb->pcm[i];
  112298. int submap=info->chmuxlist[i];
  112299. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112300. inverse2(vb,b->flr[info->floorsubmap[submap]],
  112301. floormemo[i],pcm);
  112302. }
  112303. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  112304. /* only MDCT right now.... */
  112305. for(i=0;i<vi->channels;i++){
  112306. float *pcm=vb->pcm[i];
  112307. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  112308. }
  112309. /* all done! */
  112310. return(0);
  112311. }
  112312. /* export hooks */
  112313. vorbis_func_mapping mapping0_exportbundle={
  112314. &mapping0_pack,
  112315. &mapping0_unpack,
  112316. &mapping0_free_info,
  112317. &mapping0_forward,
  112318. &mapping0_inverse
  112319. };
  112320. #endif
  112321. /*** End of inlined file: mapping0.c ***/
  112322. /*** Start of inlined file: mdct.c ***/
  112323. /* this can also be run as an integer transform by uncommenting a
  112324. define in mdct.h; the integerization is a first pass and although
  112325. it's likely stable for Vorbis, the dynamic range is constrained and
  112326. roundoff isn't done (so it's noisy). Consider it functional, but
  112327. only a starting point. There's no point on a machine with an FPU */
  112328. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112329. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112330. // tasks..
  112331. #if JUCE_MSVC
  112332. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112333. #endif
  112334. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112335. #if JUCE_USE_OGGVORBIS
  112336. #include <stdio.h>
  112337. #include <stdlib.h>
  112338. #include <string.h>
  112339. #include <math.h>
  112340. /* build lookups for trig functions; also pre-figure scaling and
  112341. some window function algebra. */
  112342. void mdct_init(mdct_lookup *lookup,int n){
  112343. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  112344. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  112345. int i;
  112346. int n2=n>>1;
  112347. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  112348. lookup->n=n;
  112349. lookup->trig=T;
  112350. lookup->bitrev=bitrev;
  112351. /* trig lookups... */
  112352. for(i=0;i<n/4;i++){
  112353. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  112354. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  112355. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  112356. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  112357. }
  112358. for(i=0;i<n/8;i++){
  112359. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  112360. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  112361. }
  112362. /* bitreverse lookup... */
  112363. {
  112364. int mask=(1<<(log2n-1))-1,i,j;
  112365. int msb=1<<(log2n-2);
  112366. for(i=0;i<n/8;i++){
  112367. int acc=0;
  112368. for(j=0;msb>>j;j++)
  112369. if((msb>>j)&i)acc|=1<<j;
  112370. bitrev[i*2]=((~acc)&mask)-1;
  112371. bitrev[i*2+1]=acc;
  112372. }
  112373. }
  112374. lookup->scale=FLOAT_CONV(4.f/n);
  112375. }
  112376. /* 8 point butterfly (in place, 4 register) */
  112377. STIN void mdct_butterfly_8(DATA_TYPE *x){
  112378. REG_TYPE r0 = x[6] + x[2];
  112379. REG_TYPE r1 = x[6] - x[2];
  112380. REG_TYPE r2 = x[4] + x[0];
  112381. REG_TYPE r3 = x[4] - x[0];
  112382. x[6] = r0 + r2;
  112383. x[4] = r0 - r2;
  112384. r0 = x[5] - x[1];
  112385. r2 = x[7] - x[3];
  112386. x[0] = r1 + r0;
  112387. x[2] = r1 - r0;
  112388. r0 = x[5] + x[1];
  112389. r1 = x[7] + x[3];
  112390. x[3] = r2 + r3;
  112391. x[1] = r2 - r3;
  112392. x[7] = r1 + r0;
  112393. x[5] = r1 - r0;
  112394. }
  112395. /* 16 point butterfly (in place, 4 register) */
  112396. STIN void mdct_butterfly_16(DATA_TYPE *x){
  112397. REG_TYPE r0 = x[1] - x[9];
  112398. REG_TYPE r1 = x[0] - x[8];
  112399. x[8] += x[0];
  112400. x[9] += x[1];
  112401. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  112402. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  112403. r0 = x[3] - x[11];
  112404. r1 = x[10] - x[2];
  112405. x[10] += x[2];
  112406. x[11] += x[3];
  112407. x[2] = r0;
  112408. x[3] = r1;
  112409. r0 = x[12] - x[4];
  112410. r1 = x[13] - x[5];
  112411. x[12] += x[4];
  112412. x[13] += x[5];
  112413. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  112414. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  112415. r0 = x[14] - x[6];
  112416. r1 = x[15] - x[7];
  112417. x[14] += x[6];
  112418. x[15] += x[7];
  112419. x[6] = r0;
  112420. x[7] = r1;
  112421. mdct_butterfly_8(x);
  112422. mdct_butterfly_8(x+8);
  112423. }
  112424. /* 32 point butterfly (in place, 4 register) */
  112425. STIN void mdct_butterfly_32(DATA_TYPE *x){
  112426. REG_TYPE r0 = x[30] - x[14];
  112427. REG_TYPE r1 = x[31] - x[15];
  112428. x[30] += x[14];
  112429. x[31] += x[15];
  112430. x[14] = r0;
  112431. x[15] = r1;
  112432. r0 = x[28] - x[12];
  112433. r1 = x[29] - x[13];
  112434. x[28] += x[12];
  112435. x[29] += x[13];
  112436. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  112437. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  112438. r0 = x[26] - x[10];
  112439. r1 = x[27] - x[11];
  112440. x[26] += x[10];
  112441. x[27] += x[11];
  112442. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  112443. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  112444. r0 = x[24] - x[8];
  112445. r1 = x[25] - x[9];
  112446. x[24] += x[8];
  112447. x[25] += x[9];
  112448. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  112449. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  112450. r0 = x[22] - x[6];
  112451. r1 = x[7] - x[23];
  112452. x[22] += x[6];
  112453. x[23] += x[7];
  112454. x[6] = r1;
  112455. x[7] = r0;
  112456. r0 = x[4] - x[20];
  112457. r1 = x[5] - x[21];
  112458. x[20] += x[4];
  112459. x[21] += x[5];
  112460. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  112461. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  112462. r0 = x[2] - x[18];
  112463. r1 = x[3] - x[19];
  112464. x[18] += x[2];
  112465. x[19] += x[3];
  112466. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  112467. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  112468. r0 = x[0] - x[16];
  112469. r1 = x[1] - x[17];
  112470. x[16] += x[0];
  112471. x[17] += x[1];
  112472. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  112473. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  112474. mdct_butterfly_16(x);
  112475. mdct_butterfly_16(x+16);
  112476. }
  112477. /* N point first stage butterfly (in place, 2 register) */
  112478. STIN void mdct_butterfly_first(DATA_TYPE *T,
  112479. DATA_TYPE *x,
  112480. int points){
  112481. DATA_TYPE *x1 = x + points - 8;
  112482. DATA_TYPE *x2 = x + (points>>1) - 8;
  112483. REG_TYPE r0;
  112484. REG_TYPE r1;
  112485. do{
  112486. r0 = x1[6] - x2[6];
  112487. r1 = x1[7] - x2[7];
  112488. x1[6] += x2[6];
  112489. x1[7] += x2[7];
  112490. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112491. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112492. r0 = x1[4] - x2[4];
  112493. r1 = x1[5] - x2[5];
  112494. x1[4] += x2[4];
  112495. x1[5] += x2[5];
  112496. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  112497. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  112498. r0 = x1[2] - x2[2];
  112499. r1 = x1[3] - x2[3];
  112500. x1[2] += x2[2];
  112501. x1[3] += x2[3];
  112502. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  112503. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  112504. r0 = x1[0] - x2[0];
  112505. r1 = x1[1] - x2[1];
  112506. x1[0] += x2[0];
  112507. x1[1] += x2[1];
  112508. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  112509. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  112510. x1-=8;
  112511. x2-=8;
  112512. T+=16;
  112513. }while(x2>=x);
  112514. }
  112515. /* N/stage point generic N stage butterfly (in place, 2 register) */
  112516. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  112517. DATA_TYPE *x,
  112518. int points,
  112519. int trigint){
  112520. DATA_TYPE *x1 = x + points - 8;
  112521. DATA_TYPE *x2 = x + (points>>1) - 8;
  112522. REG_TYPE r0;
  112523. REG_TYPE r1;
  112524. do{
  112525. r0 = x1[6] - x2[6];
  112526. r1 = x1[7] - x2[7];
  112527. x1[6] += x2[6];
  112528. x1[7] += x2[7];
  112529. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112530. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112531. T+=trigint;
  112532. r0 = x1[4] - x2[4];
  112533. r1 = x1[5] - x2[5];
  112534. x1[4] += x2[4];
  112535. x1[5] += x2[5];
  112536. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112537. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112538. T+=trigint;
  112539. r0 = x1[2] - x2[2];
  112540. r1 = x1[3] - x2[3];
  112541. x1[2] += x2[2];
  112542. x1[3] += x2[3];
  112543. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112544. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112545. T+=trigint;
  112546. r0 = x1[0] - x2[0];
  112547. r1 = x1[1] - x2[1];
  112548. x1[0] += x2[0];
  112549. x1[1] += x2[1];
  112550. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112551. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112552. T+=trigint;
  112553. x1-=8;
  112554. x2-=8;
  112555. }while(x2>=x);
  112556. }
  112557. STIN void mdct_butterflies(mdct_lookup *init,
  112558. DATA_TYPE *x,
  112559. int points){
  112560. DATA_TYPE *T=init->trig;
  112561. int stages=init->log2n-5;
  112562. int i,j;
  112563. if(--stages>0){
  112564. mdct_butterfly_first(T,x,points);
  112565. }
  112566. for(i=1;--stages>0;i++){
  112567. for(j=0;j<(1<<i);j++)
  112568. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  112569. }
  112570. for(j=0;j<points;j+=32)
  112571. mdct_butterfly_32(x+j);
  112572. }
  112573. void mdct_clear(mdct_lookup *l){
  112574. if(l){
  112575. if(l->trig)_ogg_free(l->trig);
  112576. if(l->bitrev)_ogg_free(l->bitrev);
  112577. memset(l,0,sizeof(*l));
  112578. }
  112579. }
  112580. STIN void mdct_bitreverse(mdct_lookup *init,
  112581. DATA_TYPE *x){
  112582. int n = init->n;
  112583. int *bit = init->bitrev;
  112584. DATA_TYPE *w0 = x;
  112585. DATA_TYPE *w1 = x = w0+(n>>1);
  112586. DATA_TYPE *T = init->trig+n;
  112587. do{
  112588. DATA_TYPE *x0 = x+bit[0];
  112589. DATA_TYPE *x1 = x+bit[1];
  112590. REG_TYPE r0 = x0[1] - x1[1];
  112591. REG_TYPE r1 = x0[0] + x1[0];
  112592. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  112593. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  112594. w1 -= 4;
  112595. r0 = HALVE(x0[1] + x1[1]);
  112596. r1 = HALVE(x0[0] - x1[0]);
  112597. w0[0] = r0 + r2;
  112598. w1[2] = r0 - r2;
  112599. w0[1] = r1 + r3;
  112600. w1[3] = r3 - r1;
  112601. x0 = x+bit[2];
  112602. x1 = x+bit[3];
  112603. r0 = x0[1] - x1[1];
  112604. r1 = x0[0] + x1[0];
  112605. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  112606. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  112607. r0 = HALVE(x0[1] + x1[1]);
  112608. r1 = HALVE(x0[0] - x1[0]);
  112609. w0[2] = r0 + r2;
  112610. w1[0] = r0 - r2;
  112611. w0[3] = r1 + r3;
  112612. w1[1] = r3 - r1;
  112613. T += 4;
  112614. bit += 4;
  112615. w0 += 4;
  112616. }while(w0<w1);
  112617. }
  112618. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  112619. int n=init->n;
  112620. int n2=n>>1;
  112621. int n4=n>>2;
  112622. /* rotate */
  112623. DATA_TYPE *iX = in+n2-7;
  112624. DATA_TYPE *oX = out+n2+n4;
  112625. DATA_TYPE *T = init->trig+n4;
  112626. do{
  112627. oX -= 4;
  112628. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  112629. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  112630. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  112631. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  112632. iX -= 8;
  112633. T += 4;
  112634. }while(iX>=in);
  112635. iX = in+n2-8;
  112636. oX = out+n2+n4;
  112637. T = init->trig+n4;
  112638. do{
  112639. T -= 4;
  112640. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  112641. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  112642. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  112643. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  112644. iX -= 8;
  112645. oX += 4;
  112646. }while(iX>=in);
  112647. mdct_butterflies(init,out+n2,n2);
  112648. mdct_bitreverse(init,out);
  112649. /* roatate + window */
  112650. {
  112651. DATA_TYPE *oX1=out+n2+n4;
  112652. DATA_TYPE *oX2=out+n2+n4;
  112653. DATA_TYPE *iX =out;
  112654. T =init->trig+n2;
  112655. do{
  112656. oX1-=4;
  112657. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  112658. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  112659. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  112660. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  112661. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  112662. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  112663. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  112664. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  112665. oX2+=4;
  112666. iX += 8;
  112667. T += 8;
  112668. }while(iX<oX1);
  112669. iX=out+n2+n4;
  112670. oX1=out+n4;
  112671. oX2=oX1;
  112672. do{
  112673. oX1-=4;
  112674. iX-=4;
  112675. oX2[0] = -(oX1[3] = iX[3]);
  112676. oX2[1] = -(oX1[2] = iX[2]);
  112677. oX2[2] = -(oX1[1] = iX[1]);
  112678. oX2[3] = -(oX1[0] = iX[0]);
  112679. oX2+=4;
  112680. }while(oX2<iX);
  112681. iX=out+n2+n4;
  112682. oX1=out+n2+n4;
  112683. oX2=out+n2;
  112684. do{
  112685. oX1-=4;
  112686. oX1[0]= iX[3];
  112687. oX1[1]= iX[2];
  112688. oX1[2]= iX[1];
  112689. oX1[3]= iX[0];
  112690. iX+=4;
  112691. }while(oX1>oX2);
  112692. }
  112693. }
  112694. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  112695. int n=init->n;
  112696. int n2=n>>1;
  112697. int n4=n>>2;
  112698. int n8=n>>3;
  112699. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  112700. DATA_TYPE *w2=w+n2;
  112701. /* rotate */
  112702. /* window + rotate + step 1 */
  112703. REG_TYPE r0;
  112704. REG_TYPE r1;
  112705. DATA_TYPE *x0=in+n2+n4;
  112706. DATA_TYPE *x1=x0+1;
  112707. DATA_TYPE *T=init->trig+n2;
  112708. int i=0;
  112709. for(i=0;i<n8;i+=2){
  112710. x0 -=4;
  112711. T-=2;
  112712. r0= x0[2] + x1[0];
  112713. r1= x0[0] + x1[2];
  112714. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112715. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112716. x1 +=4;
  112717. }
  112718. x1=in+1;
  112719. for(;i<n2-n8;i+=2){
  112720. T-=2;
  112721. x0 -=4;
  112722. r0= x0[2] - x1[0];
  112723. r1= x0[0] - x1[2];
  112724. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112725. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112726. x1 +=4;
  112727. }
  112728. x0=in+n;
  112729. for(;i<n2;i+=2){
  112730. T-=2;
  112731. x0 -=4;
  112732. r0= -x0[2] - x1[0];
  112733. r1= -x0[0] - x1[2];
  112734. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112735. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112736. x1 +=4;
  112737. }
  112738. mdct_butterflies(init,w+n2,n2);
  112739. mdct_bitreverse(init,w);
  112740. /* roatate + window */
  112741. T=init->trig+n2;
  112742. x0=out+n2;
  112743. for(i=0;i<n4;i++){
  112744. x0--;
  112745. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  112746. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  112747. w+=2;
  112748. T+=2;
  112749. }
  112750. }
  112751. #endif
  112752. /*** End of inlined file: mdct.c ***/
  112753. /*** Start of inlined file: psy.c ***/
  112754. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112755. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112756. // tasks..
  112757. #if JUCE_MSVC
  112758. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112759. #endif
  112760. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112761. #if JUCE_USE_OGGVORBIS
  112762. #include <stdlib.h>
  112763. #include <math.h>
  112764. #include <string.h>
  112765. /*** Start of inlined file: masking.h ***/
  112766. #ifndef _V_MASKING_H_
  112767. #define _V_MASKING_H_
  112768. /* more detailed ATH; the bass if flat to save stressing the floor
  112769. overly for only a bin or two of savings. */
  112770. #define MAX_ATH 88
  112771. static float ATH[]={
  112772. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  112773. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  112774. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  112775. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  112776. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  112777. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  112778. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  112779. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  112780. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  112781. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  112782. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  112783. };
  112784. /* The tone masking curves from Ehmer's and Fielder's papers have been
  112785. replaced by an empirically collected data set. The previously
  112786. published values were, far too often, simply on crack. */
  112787. #define EHMER_OFFSET 16
  112788. #define EHMER_MAX 56
  112789. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  112790. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  112791. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  112792. for collection of these curves) */
  112793. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  112794. /* 62.5 Hz */
  112795. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  112796. -60, -60, -60, -60, -62, -62, -65, -73,
  112797. -69, -68, -68, -67, -70, -70, -72, -74,
  112798. -75, -79, -79, -80, -83, -88, -93, -100,
  112799. -110, -999, -999, -999, -999, -999, -999, -999,
  112800. -999, -999, -999, -999, -999, -999, -999, -999,
  112801. -999, -999, -999, -999, -999, -999, -999, -999},
  112802. { -48, -48, -48, -48, -48, -48, -48, -48,
  112803. -48, -48, -48, -48, -48, -53, -61, -66,
  112804. -66, -68, -67, -70, -76, -76, -72, -73,
  112805. -75, -76, -78, -79, -83, -88, -93, -100,
  112806. -110, -999, -999, -999, -999, -999, -999, -999,
  112807. -999, -999, -999, -999, -999, -999, -999, -999,
  112808. -999, -999, -999, -999, -999, -999, -999, -999},
  112809. { -37, -37, -37, -37, -37, -37, -37, -37,
  112810. -38, -40, -42, -46, -48, -53, -55, -62,
  112811. -65, -58, -56, -56, -61, -60, -65, -67,
  112812. -69, -71, -77, -77, -78, -80, -82, -84,
  112813. -88, -93, -98, -106, -112, -999, -999, -999,
  112814. -999, -999, -999, -999, -999, -999, -999, -999,
  112815. -999, -999, -999, -999, -999, -999, -999, -999},
  112816. { -25, -25, -25, -25, -25, -25, -25, -25,
  112817. -25, -26, -27, -29, -32, -38, -48, -52,
  112818. -52, -50, -48, -48, -51, -52, -54, -60,
  112819. -67, -67, -66, -68, -69, -73, -73, -76,
  112820. -80, -81, -81, -85, -85, -86, -88, -93,
  112821. -100, -110, -999, -999, -999, -999, -999, -999,
  112822. -999, -999, -999, -999, -999, -999, -999, -999},
  112823. { -16, -16, -16, -16, -16, -16, -16, -16,
  112824. -17, -19, -20, -22, -26, -28, -31, -40,
  112825. -47, -39, -39, -40, -42, -43, -47, -51,
  112826. -57, -52, -55, -55, -60, -58, -62, -63,
  112827. -70, -67, -69, -72, -73, -77, -80, -82,
  112828. -83, -87, -90, -94, -98, -104, -115, -999,
  112829. -999, -999, -999, -999, -999, -999, -999, -999},
  112830. { -8, -8, -8, -8, -8, -8, -8, -8,
  112831. -8, -8, -10, -11, -15, -19, -25, -30,
  112832. -34, -31, -30, -31, -29, -32, -35, -42,
  112833. -48, -42, -44, -46, -50, -50, -51, -52,
  112834. -59, -54, -55, -55, -58, -62, -63, -66,
  112835. -72, -73, -76, -75, -78, -80, -80, -81,
  112836. -84, -88, -90, -94, -98, -101, -106, -110}},
  112837. /* 88Hz */
  112838. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  112839. -66, -66, -66, -66, -66, -67, -67, -67,
  112840. -76, -72, -71, -74, -76, -76, -75, -78,
  112841. -79, -79, -81, -83, -86, -89, -93, -97,
  112842. -100, -105, -110, -999, -999, -999, -999, -999,
  112843. -999, -999, -999, -999, -999, -999, -999, -999,
  112844. -999, -999, -999, -999, -999, -999, -999, -999},
  112845. { -47, -47, -47, -47, -47, -47, -47, -47,
  112846. -47, -47, -47, -48, -51, -55, -59, -66,
  112847. -66, -66, -67, -66, -68, -69, -70, -74,
  112848. -79, -77, -77, -78, -80, -81, -82, -84,
  112849. -86, -88, -91, -95, -100, -108, -116, -999,
  112850. -999, -999, -999, -999, -999, -999, -999, -999,
  112851. -999, -999, -999, -999, -999, -999, -999, -999},
  112852. { -36, -36, -36, -36, -36, -36, -36, -36,
  112853. -36, -37, -37, -41, -44, -48, -51, -58,
  112854. -62, -60, -57, -59, -59, -60, -63, -65,
  112855. -72, -71, -70, -72, -74, -77, -76, -78,
  112856. -81, -81, -80, -83, -86, -91, -96, -100,
  112857. -105, -110, -999, -999, -999, -999, -999, -999,
  112858. -999, -999, -999, -999, -999, -999, -999, -999},
  112859. { -28, -28, -28, -28, -28, -28, -28, -28,
  112860. -28, -30, -32, -32, -33, -35, -41, -49,
  112861. -50, -49, -47, -48, -48, -52, -51, -57,
  112862. -65, -61, -59, -61, -64, -69, -70, -74,
  112863. -77, -77, -78, -81, -84, -85, -87, -90,
  112864. -92, -96, -100, -107, -112, -999, -999, -999,
  112865. -999, -999, -999, -999, -999, -999, -999, -999},
  112866. { -19, -19, -19, -19, -19, -19, -19, -19,
  112867. -20, -21, -23, -27, -30, -35, -36, -41,
  112868. -46, -44, -42, -40, -41, -41, -43, -48,
  112869. -55, -53, -52, -53, -56, -59, -58, -60,
  112870. -67, -66, -69, -71, -72, -75, -79, -81,
  112871. -84, -87, -90, -93, -97, -101, -107, -114,
  112872. -999, -999, -999, -999, -999, -999, -999, -999},
  112873. { -9, -9, -9, -9, -9, -9, -9, -9,
  112874. -11, -12, -12, -15, -16, -20, -23, -30,
  112875. -37, -34, -33, -34, -31, -32, -32, -38,
  112876. -47, -44, -41, -40, -47, -49, -46, -46,
  112877. -58, -50, -50, -54, -58, -62, -64, -67,
  112878. -67, -70, -72, -76, -79, -83, -87, -91,
  112879. -96, -100, -104, -110, -999, -999, -999, -999}},
  112880. /* 125 Hz */
  112881. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  112882. -62, -62, -63, -64, -66, -67, -66, -68,
  112883. -75, -72, -76, -75, -76, -78, -79, -82,
  112884. -84, -85, -90, -94, -101, -110, -999, -999,
  112885. -999, -999, -999, -999, -999, -999, -999, -999,
  112886. -999, -999, -999, -999, -999, -999, -999, -999,
  112887. -999, -999, -999, -999, -999, -999, -999, -999},
  112888. { -59, -59, -59, -59, -59, -59, -59, -59,
  112889. -59, -59, -59, -60, -60, -61, -63, -66,
  112890. -71, -68, -70, -70, -71, -72, -72, -75,
  112891. -81, -78, -79, -82, -83, -86, -90, -97,
  112892. -103, -113, -999, -999, -999, -999, -999, -999,
  112893. -999, -999, -999, -999, -999, -999, -999, -999,
  112894. -999, -999, -999, -999, -999, -999, -999, -999},
  112895. { -53, -53, -53, -53, -53, -53, -53, -53,
  112896. -53, -54, -55, -57, -56, -57, -55, -61,
  112897. -65, -60, -60, -62, -63, -63, -66, -68,
  112898. -74, -73, -75, -75, -78, -80, -80, -82,
  112899. -85, -90, -96, -101, -108, -999, -999, -999,
  112900. -999, -999, -999, -999, -999, -999, -999, -999,
  112901. -999, -999, -999, -999, -999, -999, -999, -999},
  112902. { -46, -46, -46, -46, -46, -46, -46, -46,
  112903. -46, -46, -47, -47, -47, -47, -48, -51,
  112904. -57, -51, -49, -50, -51, -53, -54, -59,
  112905. -66, -60, -62, -67, -67, -70, -72, -75,
  112906. -76, -78, -81, -85, -88, -94, -97, -104,
  112907. -112, -999, -999, -999, -999, -999, -999, -999,
  112908. -999, -999, -999, -999, -999, -999, -999, -999},
  112909. { -36, -36, -36, -36, -36, -36, -36, -36,
  112910. -39, -41, -42, -42, -39, -38, -41, -43,
  112911. -52, -44, -40, -39, -37, -37, -40, -47,
  112912. -54, -50, -48, -50, -55, -61, -59, -62,
  112913. -66, -66, -66, -69, -69, -73, -74, -74,
  112914. -75, -77, -79, -82, -87, -91, -95, -100,
  112915. -108, -115, -999, -999, -999, -999, -999, -999},
  112916. { -28, -26, -24, -22, -20, -20, -23, -29,
  112917. -30, -31, -28, -27, -28, -28, -28, -35,
  112918. -40, -33, -32, -29, -30, -30, -30, -37,
  112919. -45, -41, -37, -38, -45, -47, -47, -48,
  112920. -53, -49, -48, -50, -49, -49, -51, -52,
  112921. -58, -56, -57, -56, -60, -61, -62, -70,
  112922. -72, -74, -78, -83, -88, -93, -100, -106}},
  112923. /* 177 Hz */
  112924. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112925. -999, -110, -105, -100, -95, -91, -87, -83,
  112926. -80, -78, -76, -78, -78, -81, -83, -85,
  112927. -86, -85, -86, -87, -90, -97, -107, -999,
  112928. -999, -999, -999, -999, -999, -999, -999, -999,
  112929. -999, -999, -999, -999, -999, -999, -999, -999,
  112930. -999, -999, -999, -999, -999, -999, -999, -999},
  112931. {-999, -999, -999, -110, -105, -100, -95, -90,
  112932. -85, -81, -77, -73, -70, -67, -67, -68,
  112933. -75, -73, -70, -69, -70, -72, -75, -79,
  112934. -84, -83, -84, -86, -88, -89, -89, -93,
  112935. -98, -105, -112, -999, -999, -999, -999, -999,
  112936. -999, -999, -999, -999, -999, -999, -999, -999,
  112937. -999, -999, -999, -999, -999, -999, -999, -999},
  112938. {-105, -100, -95, -90, -85, -80, -76, -71,
  112939. -68, -68, -65, -63, -63, -62, -62, -64,
  112940. -65, -64, -61, -62, -63, -64, -66, -68,
  112941. -73, -73, -74, -75, -76, -81, -83, -85,
  112942. -88, -89, -92, -95, -100, -108, -999, -999,
  112943. -999, -999, -999, -999, -999, -999, -999, -999,
  112944. -999, -999, -999, -999, -999, -999, -999, -999},
  112945. { -80, -75, -71, -68, -65, -63, -62, -61,
  112946. -61, -61, -61, -59, -56, -57, -53, -50,
  112947. -58, -52, -50, -50, -52, -53, -54, -58,
  112948. -67, -63, -67, -68, -72, -75, -78, -80,
  112949. -81, -81, -82, -85, -89, -90, -93, -97,
  112950. -101, -107, -114, -999, -999, -999, -999, -999,
  112951. -999, -999, -999, -999, -999, -999, -999, -999},
  112952. { -65, -61, -59, -57, -56, -55, -55, -56,
  112953. -56, -57, -55, -53, -52, -47, -44, -44,
  112954. -50, -44, -41, -39, -39, -42, -40, -46,
  112955. -51, -49, -50, -53, -54, -63, -60, -61,
  112956. -62, -66, -66, -66, -70, -73, -74, -75,
  112957. -76, -75, -79, -85, -89, -91, -96, -102,
  112958. -110, -999, -999, -999, -999, -999, -999, -999},
  112959. { -52, -50, -49, -49, -48, -48, -48, -49,
  112960. -50, -50, -49, -46, -43, -39, -35, -33,
  112961. -38, -36, -32, -29, -32, -32, -32, -35,
  112962. -44, -39, -38, -38, -46, -50, -45, -46,
  112963. -53, -50, -50, -50, -54, -54, -53, -53,
  112964. -56, -57, -59, -66, -70, -72, -74, -79,
  112965. -83, -85, -90, -97, -114, -999, -999, -999}},
  112966. /* 250 Hz */
  112967. {{-999, -999, -999, -999, -999, -999, -110, -105,
  112968. -100, -95, -90, -86, -80, -75, -75, -79,
  112969. -80, -79, -80, -81, -82, -88, -95, -103,
  112970. -110, -999, -999, -999, -999, -999, -999, -999,
  112971. -999, -999, -999, -999, -999, -999, -999, -999,
  112972. -999, -999, -999, -999, -999, -999, -999, -999,
  112973. -999, -999, -999, -999, -999, -999, -999, -999},
  112974. {-999, -999, -999, -999, -108, -103, -98, -93,
  112975. -88, -83, -79, -78, -75, -71, -67, -68,
  112976. -73, -73, -72, -73, -75, -77, -80, -82,
  112977. -88, -93, -100, -107, -114, -999, -999, -999,
  112978. -999, -999, -999, -999, -999, -999, -999, -999,
  112979. -999, -999, -999, -999, -999, -999, -999, -999,
  112980. -999, -999, -999, -999, -999, -999, -999, -999},
  112981. {-999, -999, -999, -110, -105, -101, -96, -90,
  112982. -86, -81, -77, -73, -69, -66, -61, -62,
  112983. -66, -64, -62, -65, -66, -70, -72, -76,
  112984. -81, -80, -84, -90, -95, -102, -110, -999,
  112985. -999, -999, -999, -999, -999, -999, -999, -999,
  112986. -999, -999, -999, -999, -999, -999, -999, -999,
  112987. -999, -999, -999, -999, -999, -999, -999, -999},
  112988. {-999, -999, -999, -107, -103, -97, -92, -88,
  112989. -83, -79, -74, -70, -66, -59, -53, -58,
  112990. -62, -55, -54, -54, -54, -58, -61, -62,
  112991. -72, -70, -72, -75, -78, -80, -81, -80,
  112992. -83, -83, -88, -93, -100, -107, -115, -999,
  112993. -999, -999, -999, -999, -999, -999, -999, -999,
  112994. -999, -999, -999, -999, -999, -999, -999, -999},
  112995. {-999, -999, -999, -105, -100, -95, -90, -85,
  112996. -80, -75, -70, -66, -62, -56, -48, -44,
  112997. -48, -46, -46, -43, -46, -48, -48, -51,
  112998. -58, -58, -59, -60, -62, -62, -61, -61,
  112999. -65, -64, -65, -68, -70, -74, -75, -78,
  113000. -81, -86, -95, -110, -999, -999, -999, -999,
  113001. -999, -999, -999, -999, -999, -999, -999, -999},
  113002. {-999, -999, -105, -100, -95, -90, -85, -80,
  113003. -75, -70, -65, -61, -55, -49, -39, -33,
  113004. -40, -35, -32, -38, -40, -33, -35, -37,
  113005. -46, -41, -45, -44, -46, -42, -45, -46,
  113006. -52, -50, -50, -50, -54, -54, -55, -57,
  113007. -62, -64, -66, -68, -70, -76, -81, -90,
  113008. -100, -110, -999, -999, -999, -999, -999, -999}},
  113009. /* 354 hz */
  113010. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113011. -105, -98, -90, -85, -82, -83, -80, -78,
  113012. -84, -79, -80, -83, -87, -89, -91, -93,
  113013. -99, -106, -117, -999, -999, -999, -999, -999,
  113014. -999, -999, -999, -999, -999, -999, -999, -999,
  113015. -999, -999, -999, -999, -999, -999, -999, -999,
  113016. -999, -999, -999, -999, -999, -999, -999, -999},
  113017. {-999, -999, -999, -999, -999, -999, -999, -999,
  113018. -105, -98, -90, -85, -80, -75, -70, -68,
  113019. -74, -72, -74, -77, -80, -82, -85, -87,
  113020. -92, -89, -91, -95, -100, -106, -112, -999,
  113021. -999, -999, -999, -999, -999, -999, -999, -999,
  113022. -999, -999, -999, -999, -999, -999, -999, -999,
  113023. -999, -999, -999, -999, -999, -999, -999, -999},
  113024. {-999, -999, -999, -999, -999, -999, -999, -999,
  113025. -105, -98, -90, -83, -75, -71, -63, -64,
  113026. -67, -62, -64, -67, -70, -73, -77, -81,
  113027. -84, -83, -85, -89, -90, -93, -98, -104,
  113028. -109, -114, -999, -999, -999, -999, -999, -999,
  113029. -999, -999, -999, -999, -999, -999, -999, -999,
  113030. -999, -999, -999, -999, -999, -999, -999, -999},
  113031. {-999, -999, -999, -999, -999, -999, -999, -999,
  113032. -103, -96, -88, -81, -75, -68, -58, -54,
  113033. -56, -54, -56, -56, -58, -60, -63, -66,
  113034. -74, -69, -72, -72, -75, -74, -77, -81,
  113035. -81, -82, -84, -87, -93, -96, -99, -104,
  113036. -110, -999, -999, -999, -999, -999, -999, -999,
  113037. -999, -999, -999, -999, -999, -999, -999, -999},
  113038. {-999, -999, -999, -999, -999, -108, -102, -96,
  113039. -91, -85, -80, -74, -68, -60, -51, -46,
  113040. -48, -46, -43, -45, -47, -47, -49, -48,
  113041. -56, -53, -55, -58, -57, -63, -58, -60,
  113042. -66, -64, -67, -70, -70, -74, -77, -84,
  113043. -86, -89, -91, -93, -94, -101, -109, -118,
  113044. -999, -999, -999, -999, -999, -999, -999, -999},
  113045. {-999, -999, -999, -108, -103, -98, -93, -88,
  113046. -83, -78, -73, -68, -60, -53, -44, -35,
  113047. -38, -38, -34, -34, -36, -40, -41, -44,
  113048. -51, -45, -46, -47, -46, -54, -50, -49,
  113049. -50, -50, -50, -51, -54, -57, -58, -60,
  113050. -66, -66, -66, -64, -65, -68, -77, -82,
  113051. -87, -95, -110, -999, -999, -999, -999, -999}},
  113052. /* 500 Hz */
  113053. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113054. -107, -102, -97, -92, -87, -83, -78, -75,
  113055. -82, -79, -83, -85, -89, -92, -95, -98,
  113056. -101, -105, -109, -113, -999, -999, -999, -999,
  113057. -999, -999, -999, -999, -999, -999, -999, -999,
  113058. -999, -999, -999, -999, -999, -999, -999, -999,
  113059. -999, -999, -999, -999, -999, -999, -999, -999},
  113060. {-999, -999, -999, -999, -999, -999, -999, -106,
  113061. -100, -95, -90, -86, -81, -78, -74, -69,
  113062. -74, -74, -76, -79, -83, -84, -86, -89,
  113063. -92, -97, -93, -100, -103, -107, -110, -999,
  113064. -999, -999, -999, -999, -999, -999, -999, -999,
  113065. -999, -999, -999, -999, -999, -999, -999, -999,
  113066. -999, -999, -999, -999, -999, -999, -999, -999},
  113067. {-999, -999, -999, -999, -999, -999, -106, -100,
  113068. -95, -90, -87, -83, -80, -75, -69, -60,
  113069. -66, -66, -68, -70, -74, -78, -79, -81,
  113070. -81, -83, -84, -87, -93, -96, -99, -103,
  113071. -107, -110, -999, -999, -999, -999, -999, -999,
  113072. -999, -999, -999, -999, -999, -999, -999, -999,
  113073. -999, -999, -999, -999, -999, -999, -999, -999},
  113074. {-999, -999, -999, -999, -999, -108, -103, -98,
  113075. -93, -89, -85, -82, -78, -71, -62, -55,
  113076. -58, -58, -54, -54, -55, -59, -61, -62,
  113077. -70, -66, -66, -67, -70, -72, -75, -78,
  113078. -84, -84, -84, -88, -91, -90, -95, -98,
  113079. -102, -103, -106, -110, -999, -999, -999, -999,
  113080. -999, -999, -999, -999, -999, -999, -999, -999},
  113081. {-999, -999, -999, -999, -108, -103, -98, -94,
  113082. -90, -87, -82, -79, -73, -67, -58, -47,
  113083. -50, -45, -41, -45, -48, -44, -44, -49,
  113084. -54, -51, -48, -47, -49, -50, -51, -57,
  113085. -58, -60, -63, -69, -70, -69, -71, -74,
  113086. -78, -82, -90, -95, -101, -105, -110, -999,
  113087. -999, -999, -999, -999, -999, -999, -999, -999},
  113088. {-999, -999, -999, -105, -101, -97, -93, -90,
  113089. -85, -80, -77, -72, -65, -56, -48, -37,
  113090. -40, -36, -34, -40, -50, -47, -38, -41,
  113091. -47, -38, -35, -39, -38, -43, -40, -45,
  113092. -50, -45, -44, -47, -50, -55, -48, -48,
  113093. -52, -66, -70, -76, -82, -90, -97, -105,
  113094. -110, -999, -999, -999, -999, -999, -999, -999}},
  113095. /* 707 Hz */
  113096. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113097. -999, -108, -103, -98, -93, -86, -79, -76,
  113098. -83, -81, -85, -87, -89, -93, -98, -102,
  113099. -107, -112, -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. -999, -999, -999, -999, -999, -999, -999, -999},
  113103. {-999, -999, -999, -999, -999, -999, -999, -999,
  113104. -999, -108, -103, -98, -93, -86, -79, -71,
  113105. -77, -74, -77, -79, -81, -84, -85, -90,
  113106. -92, -93, -92, -98, -101, -108, -112, -999,
  113107. -999, -999, -999, -999, -999, -999, -999, -999,
  113108. -999, -999, -999, -999, -999, -999, -999, -999,
  113109. -999, -999, -999, -999, -999, -999, -999, -999},
  113110. {-999, -999, -999, -999, -999, -999, -999, -999,
  113111. -108, -103, -98, -93, -87, -78, -68, -65,
  113112. -66, -62, -65, -67, -70, -73, -75, -78,
  113113. -82, -82, -83, -84, -91, -93, -98, -102,
  113114. -106, -110, -999, -999, -999, -999, -999, -999,
  113115. -999, -999, -999, -999, -999, -999, -999, -999,
  113116. -999, -999, -999, -999, -999, -999, -999, -999},
  113117. {-999, -999, -999, -999, -999, -999, -999, -999,
  113118. -105, -100, -95, -90, -82, -74, -62, -57,
  113119. -58, -56, -51, -52, -52, -54, -54, -58,
  113120. -66, -59, -60, -63, -66, -69, -73, -79,
  113121. -83, -84, -80, -81, -81, -82, -88, -92,
  113122. -98, -105, -113, -999, -999, -999, -999, -999,
  113123. -999, -999, -999, -999, -999, -999, -999, -999},
  113124. {-999, -999, -999, -999, -999, -999, -999, -107,
  113125. -102, -97, -92, -84, -79, -69, -57, -47,
  113126. -52, -47, -44, -45, -50, -52, -42, -42,
  113127. -53, -43, -43, -48, -51, -56, -55, -52,
  113128. -57, -59, -61, -62, -67, -71, -78, -83,
  113129. -86, -94, -98, -103, -110, -999, -999, -999,
  113130. -999, -999, -999, -999, -999, -999, -999, -999},
  113131. {-999, -999, -999, -999, -999, -999, -105, -100,
  113132. -95, -90, -84, -78, -70, -61, -51, -41,
  113133. -40, -38, -40, -46, -52, -51, -41, -40,
  113134. -46, -40, -38, -38, -41, -46, -41, -46,
  113135. -47, -43, -43, -45, -41, -45, -56, -67,
  113136. -68, -83, -87, -90, -95, -102, -107, -113,
  113137. -999, -999, -999, -999, -999, -999, -999, -999}},
  113138. /* 1000 Hz */
  113139. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113140. -999, -109, -105, -101, -96, -91, -84, -77,
  113141. -82, -82, -85, -89, -94, -100, -106, -110,
  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, -999,
  113145. -999, -999, -999, -999, -999, -999, -999, -999},
  113146. {-999, -999, -999, -999, -999, -999, -999, -999,
  113147. -999, -106, -103, -98, -92, -85, -80, -71,
  113148. -75, -72, -76, -80, -84, -86, -89, -93,
  113149. -100, -107, -113, -999, -999, -999, -999, -999,
  113150. -999, -999, -999, -999, -999, -999, -999, -999,
  113151. -999, -999, -999, -999, -999, -999, -999, -999,
  113152. -999, -999, -999, -999, -999, -999, -999, -999},
  113153. {-999, -999, -999, -999, -999, -999, -999, -107,
  113154. -104, -101, -97, -92, -88, -84, -80, -64,
  113155. -66, -63, -64, -66, -69, -73, -77, -83,
  113156. -83, -86, -91, -98, -104, -111, -999, -999,
  113157. -999, -999, -999, -999, -999, -999, -999, -999,
  113158. -999, -999, -999, -999, -999, -999, -999, -999,
  113159. -999, -999, -999, -999, -999, -999, -999, -999},
  113160. {-999, -999, -999, -999, -999, -999, -999, -107,
  113161. -104, -101, -97, -92, -90, -84, -74, -57,
  113162. -58, -52, -55, -54, -50, -52, -50, -52,
  113163. -63, -62, -69, -76, -77, -78, -78, -79,
  113164. -82, -88, -94, -100, -106, -111, -999, -999,
  113165. -999, -999, -999, -999, -999, -999, -999, -999,
  113166. -999, -999, -999, -999, -999, -999, -999, -999},
  113167. {-999, -999, -999, -999, -999, -999, -106, -102,
  113168. -98, -95, -90, -85, -83, -78, -70, -50,
  113169. -50, -41, -44, -49, -47, -50, -50, -44,
  113170. -55, -46, -47, -48, -48, -54, -49, -49,
  113171. -58, -62, -71, -81, -87, -92, -97, -102,
  113172. -108, -114, -999, -999, -999, -999, -999, -999,
  113173. -999, -999, -999, -999, -999, -999, -999, -999},
  113174. {-999, -999, -999, -999, -999, -999, -106, -102,
  113175. -98, -95, -90, -85, -83, -78, -70, -45,
  113176. -43, -41, -47, -50, -51, -50, -49, -45,
  113177. -47, -41, -44, -41, -39, -43, -38, -37,
  113178. -40, -41, -44, -50, -58, -65, -73, -79,
  113179. -85, -92, -97, -101, -105, -109, -113, -999,
  113180. -999, -999, -999, -999, -999, -999, -999, -999}},
  113181. /* 1414 Hz */
  113182. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113183. -999, -999, -999, -107, -100, -95, -87, -81,
  113184. -85, -83, -88, -93, -100, -107, -114, -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, -999, -999, -999, -999, -999, -999},
  113189. {-999, -999, -999, -999, -999, -999, -999, -999,
  113190. -999, -999, -107, -101, -95, -88, -83, -76,
  113191. -73, -72, -79, -84, -90, -95, -100, -105,
  113192. -110, -115, -999, -999, -999, -999, -999, -999,
  113193. -999, -999, -999, -999, -999, -999, -999, -999,
  113194. -999, -999, -999, -999, -999, -999, -999, -999,
  113195. -999, -999, -999, -999, -999, -999, -999, -999},
  113196. {-999, -999, -999, -999, -999, -999, -999, -999,
  113197. -999, -999, -104, -98, -92, -87, -81, -70,
  113198. -65, -62, -67, -71, -74, -80, -85, -91,
  113199. -95, -99, -103, -108, -111, -114, -999, -999,
  113200. -999, -999, -999, -999, -999, -999, -999, -999,
  113201. -999, -999, -999, -999, -999, -999, -999, -999,
  113202. -999, -999, -999, -999, -999, -999, -999, -999},
  113203. {-999, -999, -999, -999, -999, -999, -999, -999,
  113204. -999, -999, -103, -97, -90, -85, -76, -60,
  113205. -56, -54, -60, -62, -61, -56, -63, -65,
  113206. -73, -74, -77, -75, -78, -81, -86, -87,
  113207. -88, -91, -94, -98, -103, -110, -999, -999,
  113208. -999, -999, -999, -999, -999, -999, -999, -999,
  113209. -999, -999, -999, -999, -999, -999, -999, -999},
  113210. {-999, -999, -999, -999, -999, -999, -999, -105,
  113211. -100, -97, -92, -86, -81, -79, -70, -57,
  113212. -51, -47, -51, -58, -60, -56, -53, -50,
  113213. -58, -52, -50, -50, -53, -55, -64, -69,
  113214. -71, -85, -82, -78, -81, -85, -95, -102,
  113215. -112, -999, -999, -999, -999, -999, -999, -999,
  113216. -999, -999, -999, -999, -999, -999, -999, -999},
  113217. {-999, -999, -999, -999, -999, -999, -999, -105,
  113218. -100, -97, -92, -85, -83, -79, -72, -49,
  113219. -40, -43, -43, -54, -56, -51, -50, -40,
  113220. -43, -38, -36, -35, -37, -38, -37, -44,
  113221. -54, -60, -57, -60, -70, -75, -84, -92,
  113222. -103, -112, -999, -999, -999, -999, -999, -999,
  113223. -999, -999, -999, -999, -999, -999, -999, -999}},
  113224. /* 2000 Hz */
  113225. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113226. -999, -999, -999, -110, -102, -95, -89, -82,
  113227. -83, -84, -90, -92, -99, -107, -113, -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, -999, -999, -999, -999, -999, -999, -999},
  113232. {-999, -999, -999, -999, -999, -999, -999, -999,
  113233. -999, -999, -107, -101, -95, -89, -83, -72,
  113234. -74, -78, -85, -88, -88, -90, -92, -98,
  113235. -105, -111, -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, -999, -999, -999, -999, -999, -999, -999},
  113239. {-999, -999, -999, -999, -999, -999, -999, -999,
  113240. -999, -109, -103, -97, -93, -87, -81, -70,
  113241. -70, -67, -75, -73, -76, -79, -81, -83,
  113242. -88, -89, -97, -103, -110, -999, -999, -999,
  113243. -999, -999, -999, -999, -999, -999, -999, -999,
  113244. -999, -999, -999, -999, -999, -999, -999, -999,
  113245. -999, -999, -999, -999, -999, -999, -999, -999},
  113246. {-999, -999, -999, -999, -999, -999, -999, -999,
  113247. -999, -107, -100, -94, -88, -83, -75, -63,
  113248. -59, -59, -63, -66, -60, -62, -67, -67,
  113249. -77, -76, -81, -88, -86, -92, -96, -102,
  113250. -109, -116, -999, -999, -999, -999, -999, -999,
  113251. -999, -999, -999, -999, -999, -999, -999, -999,
  113252. -999, -999, -999, -999, -999, -999, -999, -999},
  113253. {-999, -999, -999, -999, -999, -999, -999, -999,
  113254. -999, -105, -98, -92, -86, -81, -73, -56,
  113255. -52, -47, -55, -60, -58, -52, -51, -45,
  113256. -49, -50, -53, -54, -61, -71, -70, -69,
  113257. -78, -79, -87, -90, -96, -104, -112, -999,
  113258. -999, -999, -999, -999, -999, -999, -999, -999,
  113259. -999, -999, -999, -999, -999, -999, -999, -999},
  113260. {-999, -999, -999, -999, -999, -999, -999, -999,
  113261. -999, -103, -96, -90, -86, -78, -70, -51,
  113262. -42, -47, -48, -55, -54, -54, -53, -42,
  113263. -35, -28, -33, -38, -37, -44, -47, -49,
  113264. -54, -63, -68, -78, -82, -89, -94, -99,
  113265. -104, -109, -114, -999, -999, -999, -999, -999,
  113266. -999, -999, -999, -999, -999, -999, -999, -999}},
  113267. /* 2828 Hz */
  113268. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113269. -999, -999, -999, -999, -110, -100, -90, -79,
  113270. -85, -81, -82, -82, -89, -94, -99, -103,
  113271. -109, -115, -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, -999, -999, -999, -999, -999},
  113275. {-999, -999, -999, -999, -999, -999, -999, -999,
  113276. -999, -999, -999, -999, -105, -97, -85, -72,
  113277. -74, -70, -70, -70, -76, -85, -91, -93,
  113278. -97, -103, -109, -115, -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, -999, -999, -999, -999, -999},
  113282. {-999, -999, -999, -999, -999, -999, -999, -999,
  113283. -999, -999, -999, -999, -112, -93, -81, -68,
  113284. -62, -60, -60, -57, -63, -70, -77, -82,
  113285. -90, -93, -98, -104, -109, -113, -999, -999,
  113286. -999, -999, -999, -999, -999, -999, -999, -999,
  113287. -999, -999, -999, -999, -999, -999, -999, -999,
  113288. -999, -999, -999, -999, -999, -999, -999, -999},
  113289. {-999, -999, -999, -999, -999, -999, -999, -999,
  113290. -999, -999, -999, -113, -100, -93, -84, -63,
  113291. -58, -48, -53, -54, -52, -52, -57, -64,
  113292. -66, -76, -83, -81, -85, -85, -90, -95,
  113293. -98, -101, -103, -106, -108, -111, -999, -999,
  113294. -999, -999, -999, -999, -999, -999, -999, -999,
  113295. -999, -999, -999, -999, -999, -999, -999, -999},
  113296. {-999, -999, -999, -999, -999, -999, -999, -999,
  113297. -999, -999, -999, -105, -95, -86, -74, -53,
  113298. -50, -38, -43, -49, -43, -42, -39, -39,
  113299. -46, -52, -57, -56, -72, -69, -74, -81,
  113300. -87, -92, -94, -97, -99, -102, -105, -108,
  113301. -999, -999, -999, -999, -999, -999, -999, -999,
  113302. -999, -999, -999, -999, -999, -999, -999, -999},
  113303. {-999, -999, -999, -999, -999, -999, -999, -999,
  113304. -999, -999, -108, -99, -90, -76, -66, -45,
  113305. -43, -41, -44, -47, -43, -47, -40, -30,
  113306. -31, -31, -39, -33, -40, -41, -43, -53,
  113307. -59, -70, -73, -77, -79, -82, -84, -87,
  113308. -999, -999, -999, -999, -999, -999, -999, -999,
  113309. -999, -999, -999, -999, -999, -999, -999, -999}},
  113310. /* 4000 Hz */
  113311. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113312. -999, -999, -999, -999, -999, -110, -91, -76,
  113313. -75, -85, -93, -98, -104, -110, -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, -999, -999, -999, -999},
  113318. {-999, -999, -999, -999, -999, -999, -999, -999,
  113319. -999, -999, -999, -999, -999, -110, -91, -70,
  113320. -70, -75, -86, -89, -94, -98, -101, -106,
  113321. -110, -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, -999, -999, -999, -999},
  113325. {-999, -999, -999, -999, -999, -999, -999, -999,
  113326. -999, -999, -999, -999, -110, -95, -80, -60,
  113327. -65, -64, -74, -83, -88, -91, -95, -99,
  113328. -103, -107, -110, -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, -999, -999, -999, -999, -999},
  113332. {-999, -999, -999, -999, -999, -999, -999, -999,
  113333. -999, -999, -999, -999, -110, -95, -80, -58,
  113334. -55, -49, -66, -68, -71, -78, -78, -80,
  113335. -88, -85, -89, -97, -100, -105, -110, -999,
  113336. -999, -999, -999, -999, -999, -999, -999, -999,
  113337. -999, -999, -999, -999, -999, -999, -999, -999,
  113338. -999, -999, -999, -999, -999, -999, -999, -999},
  113339. {-999, -999, -999, -999, -999, -999, -999, -999,
  113340. -999, -999, -999, -999, -110, -95, -80, -53,
  113341. -52, -41, -59, -59, -49, -58, -56, -63,
  113342. -86, -79, -90, -93, -98, -103, -107, -112,
  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, -999, -999, -999, -999, -999, -999,
  113347. -999, -999, -999, -110, -97, -91, -73, -45,
  113348. -40, -33, -53, -61, -49, -54, -50, -50,
  113349. -60, -52, -67, -74, -81, -92, -96, -100,
  113350. -105, -110, -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. /* 5657 Hz */
  113354. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113355. -999, -999, -999, -113, -106, -99, -92, -77,
  113356. -80, -88, -97, -106, -115, -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, -999, -999, -999, -999, -999, -999},
  113361. {-999, -999, -999, -999, -999, -999, -999, -999,
  113362. -999, -999, -116, -109, -102, -95, -89, -74,
  113363. -72, -88, -87, -95, -102, -109, -116, -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, -999, -999, -999, -999, -999, -999},
  113368. {-999, -999, -999, -999, -999, -999, -999, -999,
  113369. -999, -999, -116, -109, -102, -95, -89, -75,
  113370. -66, -74, -77, -78, -86, -87, -90, -96,
  113371. -105, -115, -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, -999, -999, -999, -999, -999, -999, -999},
  113375. {-999, -999, -999, -999, -999, -999, -999, -999,
  113376. -999, -999, -115, -108, -101, -94, -88, -66,
  113377. -56, -61, -70, -65, -78, -72, -83, -84,
  113378. -93, -98, -105, -110, -999, -999, -999, -999,
  113379. -999, -999, -999, -999, -999, -999, -999, -999,
  113380. -999, -999, -999, -999, -999, -999, -999, -999,
  113381. -999, -999, -999, -999, -999, -999, -999, -999},
  113382. {-999, -999, -999, -999, -999, -999, -999, -999,
  113383. -999, -999, -110, -105, -95, -89, -82, -57,
  113384. -52, -52, -59, -56, -59, -58, -69, -67,
  113385. -88, -82, -82, -89, -94, -100, -108, -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, -999, -999, -999, -999,
  113390. -999, -110, -101, -96, -90, -83, -77, -54,
  113391. -43, -38, -50, -48, -52, -48, -42, -42,
  113392. -51, -52, -53, -59, -65, -71, -78, -85,
  113393. -95, -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. /* 8000 Hz */
  113397. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113398. -999, -999, -999, -999, -120, -105, -86, -68,
  113399. -78, -79, -90, -100, -110, -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, -999, -999, -999, -999, -999},
  113404. {-999, -999, -999, -999, -999, -999, -999, -999,
  113405. -999, -999, -999, -999, -120, -105, -86, -66,
  113406. -73, -77, -88, -96, -105, -115, -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, -999, -999, -999, -999, -999},
  113411. {-999, -999, -999, -999, -999, -999, -999, -999,
  113412. -999, -999, -999, -120, -105, -92, -80, -61,
  113413. -64, -68, -80, -87, -92, -100, -110, -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, -999, -999, -999, -999, -999},
  113418. {-999, -999, -999, -999, -999, -999, -999, -999,
  113419. -999, -999, -999, -120, -104, -91, -79, -52,
  113420. -60, -54, -64, -69, -77, -80, -82, -84,
  113421. -85, -87, -88, -90, -999, -999, -999, -999,
  113422. -999, -999, -999, -999, -999, -999, -999, -999,
  113423. -999, -999, -999, -999, -999, -999, -999, -999,
  113424. -999, -999, -999, -999, -999, -999, -999, -999},
  113425. {-999, -999, -999, -999, -999, -999, -999, -999,
  113426. -999, -999, -999, -118, -100, -87, -77, -49,
  113427. -50, -44, -58, -61, -61, -67, -65, -62,
  113428. -62, -62, -65, -68, -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, -999, -999, -999,
  113433. -999, -999, -999, -115, -98, -84, -62, -49,
  113434. -44, -38, -46, -49, -49, -46, -39, -37,
  113435. -39, -40, -42, -43, -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. /* 11314 Hz */
  113440. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113441. -999, -999, -999, -999, -999, -110, -88, -74,
  113442. -77, -82, -82, -85, -90, -94, -99, -104,
  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, -999, -999, -999},
  113447. {-999, -999, -999, -999, -999, -999, -999, -999,
  113448. -999, -999, -999, -999, -999, -110, -88, -66,
  113449. -70, -81, -80, -81, -84, -88, -91, -93,
  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, -999, -999, -999, -999},
  113454. {-999, -999, -999, -999, -999, -999, -999, -999,
  113455. -999, -999, -999, -999, -999, -110, -88, -61,
  113456. -63, -70, -71, -74, -77, -80, -83, -85,
  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, -999, -999, -999, -999},
  113461. {-999, -999, -999, -999, -999, -999, -999, -999,
  113462. -999, -999, -999, -999, -999, -110, -86, -62,
  113463. -63, -62, -62, -58, -52, -50, -50, -52,
  113464. -54, -999, -999, -999, -999, -999, -999, -999,
  113465. -999, -999, -999, -999, -999, -999, -999, -999,
  113466. -999, -999, -999, -999, -999, -999, -999, -999,
  113467. -999, -999, -999, -999, -999, -999, -999, -999},
  113468. {-999, -999, -999, -999, -999, -999, -999, -999,
  113469. -999, -999, -999, -999, -118, -108, -84, -53,
  113470. -50, -50, -50, -55, -47, -45, -40, -40,
  113471. -40, -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, -999, -999, -999, -999, -999,
  113476. -999, -999, -999, -999, -118, -100, -73, -43,
  113477. -37, -42, -43, -53, -38, -37, -35, -35,
  113478. -38, -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. /* 16000 Hz */
  113483. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113484. -999, -999, -999, -110, -100, -91, -84, -74,
  113485. -80, -80, -80, -80, -80, -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, -999, -999, -999, -999, -999},
  113490. {-999, -999, -999, -999, -999, -999, -999, -999,
  113491. -999, -999, -999, -110, -100, -91, -84, -74,
  113492. -68, -68, -68, -68, -68, -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, -999, -999, -999, -999, -999},
  113497. {-999, -999, -999, -999, -999, -999, -999, -999,
  113498. -999, -999, -999, -110, -100, -86, -78, -70,
  113499. -60, -45, -30, -21, -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, -999, -999, -999, -999, -999},
  113504. {-999, -999, -999, -999, -999, -999, -999, -999,
  113505. -999, -999, -999, -110, -100, -87, -78, -67,
  113506. -48, -38, -29, -21, -999, -999, -999, -999,
  113507. -999, -999, -999, -999, -999, -999, -999, -999,
  113508. -999, -999, -999, -999, -999, -999, -999, -999,
  113509. -999, -999, -999, -999, -999, -999, -999, -999,
  113510. -999, -999, -999, -999, -999, -999, -999, -999},
  113511. {-999, -999, -999, -999, -999, -999, -999, -999,
  113512. -999, -999, -999, -110, -100, -86, -69, -56,
  113513. -45, -35, -33, -29, -999, -999, -999, -999,
  113514. -999, -999, -999, -999, -999, -999, -999, -999,
  113515. -999, -999, -999, -999, -999, -999, -999, -999,
  113516. -999, -999, -999, -999, -999, -999, -999, -999,
  113517. -999, -999, -999, -999, -999, -999, -999, -999},
  113518. {-999, -999, -999, -999, -999, -999, -999, -999,
  113519. -999, -999, -999, -110, -100, -83, -71, -48,
  113520. -27, -38, -37, -34, -999, -999, -999, -999,
  113521. -999, -999, -999, -999, -999, -999, -999, -999,
  113522. -999, -999, -999, -999, -999, -999, -999, -999,
  113523. -999, -999, -999, -999, -999, -999, -999, -999,
  113524. -999, -999, -999, -999, -999, -999, -999, -999}}
  113525. };
  113526. #endif
  113527. /*** End of inlined file: masking.h ***/
  113528. #define NEGINF -9999.f
  113529. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  113530. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  113531. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  113532. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113533. vorbis_info_psy_global *gi=&ci->psy_g_param;
  113534. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  113535. look->channels=vi->channels;
  113536. look->ampmax=-9999.;
  113537. look->gi=gi;
  113538. return(look);
  113539. }
  113540. void _vp_global_free(vorbis_look_psy_global *look){
  113541. if(look){
  113542. memset(look,0,sizeof(*look));
  113543. _ogg_free(look);
  113544. }
  113545. }
  113546. void _vi_gpsy_free(vorbis_info_psy_global *i){
  113547. if(i){
  113548. memset(i,0,sizeof(*i));
  113549. _ogg_free(i);
  113550. }
  113551. }
  113552. void _vi_psy_free(vorbis_info_psy *i){
  113553. if(i){
  113554. memset(i,0,sizeof(*i));
  113555. _ogg_free(i);
  113556. }
  113557. }
  113558. static void min_curve(float *c,
  113559. float *c2){
  113560. int i;
  113561. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  113562. }
  113563. static void max_curve(float *c,
  113564. float *c2){
  113565. int i;
  113566. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  113567. }
  113568. static void attenuate_curve(float *c,float att){
  113569. int i;
  113570. for(i=0;i<EHMER_MAX;i++)
  113571. c[i]+=att;
  113572. }
  113573. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  113574. float center_boost, float center_decay_rate){
  113575. int i,j,k,m;
  113576. float ath[EHMER_MAX];
  113577. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  113578. float athc[P_LEVELS][EHMER_MAX];
  113579. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  113580. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  113581. memset(workc,0,sizeof(workc));
  113582. for(i=0;i<P_BANDS;i++){
  113583. /* we add back in the ATH to avoid low level curves falling off to
  113584. -infinity and unnecessarily cutting off high level curves in the
  113585. curve limiting (last step). */
  113586. /* A half-band's settings must be valid over the whole band, and
  113587. it's better to mask too little than too much */
  113588. int ath_offset=i*4;
  113589. for(j=0;j<EHMER_MAX;j++){
  113590. float min=999.;
  113591. for(k=0;k<4;k++)
  113592. if(j+k+ath_offset<MAX_ATH){
  113593. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  113594. }else{
  113595. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  113596. }
  113597. ath[j]=min;
  113598. }
  113599. /* copy curves into working space, replicate the 50dB curve to 30
  113600. and 40, replicate the 100dB curve to 110 */
  113601. for(j=0;j<6;j++)
  113602. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  113603. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  113604. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  113605. /* apply centered curve boost/decay */
  113606. for(j=0;j<P_LEVELS;j++){
  113607. for(k=0;k<EHMER_MAX;k++){
  113608. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  113609. if(adj<0. && center_boost>0)adj=0.;
  113610. if(adj>0. && center_boost<0)adj=0.;
  113611. workc[i][j][k]+=adj;
  113612. }
  113613. }
  113614. /* normalize curves so the driving amplitude is 0dB */
  113615. /* make temp curves with the ATH overlayed */
  113616. for(j=0;j<P_LEVELS;j++){
  113617. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  113618. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  113619. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  113620. max_curve(athc[j],workc[i][j]);
  113621. }
  113622. /* Now limit the louder curves.
  113623. the idea is this: We don't know what the playback attenuation
  113624. will be; 0dB SL moves every time the user twiddles the volume
  113625. knob. So that means we have to use a single 'most pessimal' curve
  113626. for all masking amplitudes, right? Wrong. The *loudest* sound
  113627. can be in (we assume) a range of ...+100dB] SL. However, sounds
  113628. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  113629. etc... */
  113630. for(j=1;j<P_LEVELS;j++){
  113631. min_curve(athc[j],athc[j-1]);
  113632. min_curve(workc[i][j],athc[j]);
  113633. }
  113634. }
  113635. for(i=0;i<P_BANDS;i++){
  113636. int hi_curve,lo_curve,bin;
  113637. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  113638. /* low frequency curves are measured with greater resolution than
  113639. the MDCT/FFT will actually give us; we want the curve applied
  113640. to the tone data to be pessimistic and thus apply the minimum
  113641. masking possible for a given bin. That means that a single bin
  113642. could span more than one octave and that the curve will be a
  113643. composite of multiple octaves. It also may mean that a single
  113644. bin may span > an eighth of an octave and that the eighth
  113645. octave values may also be composited. */
  113646. /* which octave curves will we be compositing? */
  113647. bin=floor(fromOC(i*.5)/binHz);
  113648. lo_curve= ceil(toOC(bin*binHz+1)*2);
  113649. hi_curve= floor(toOC((bin+1)*binHz)*2);
  113650. if(lo_curve>i)lo_curve=i;
  113651. if(lo_curve<0)lo_curve=0;
  113652. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  113653. for(m=0;m<P_LEVELS;m++){
  113654. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  113655. for(j=0;j<n;j++)brute_buffer[j]=999.;
  113656. /* render the curve into bins, then pull values back into curve.
  113657. The point is that any inherent subsampling aliasing results in
  113658. a safe minimum */
  113659. for(k=lo_curve;k<=hi_curve;k++){
  113660. int l=0;
  113661. for(j=0;j<EHMER_MAX;j++){
  113662. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  113663. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  113664. if(lo_bin<0)lo_bin=0;
  113665. if(lo_bin>n)lo_bin=n;
  113666. if(lo_bin<l)l=lo_bin;
  113667. if(hi_bin<0)hi_bin=0;
  113668. if(hi_bin>n)hi_bin=n;
  113669. for(;l<hi_bin && l<n;l++)
  113670. if(brute_buffer[l]>workc[k][m][j])
  113671. brute_buffer[l]=workc[k][m][j];
  113672. }
  113673. for(;l<n;l++)
  113674. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  113675. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  113676. }
  113677. /* be equally paranoid about being valid up to next half ocatve */
  113678. if(i+1<P_BANDS){
  113679. int l=0;
  113680. k=i+1;
  113681. for(j=0;j<EHMER_MAX;j++){
  113682. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  113683. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  113684. if(lo_bin<0)lo_bin=0;
  113685. if(lo_bin>n)lo_bin=n;
  113686. if(lo_bin<l)l=lo_bin;
  113687. if(hi_bin<0)hi_bin=0;
  113688. if(hi_bin>n)hi_bin=n;
  113689. for(;l<hi_bin && l<n;l++)
  113690. if(brute_buffer[l]>workc[k][m][j])
  113691. brute_buffer[l]=workc[k][m][j];
  113692. }
  113693. for(;l<n;l++)
  113694. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  113695. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  113696. }
  113697. for(j=0;j<EHMER_MAX;j++){
  113698. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  113699. if(bin<0){
  113700. ret[i][m][j+2]=-999.;
  113701. }else{
  113702. if(bin>=n){
  113703. ret[i][m][j+2]=-999.;
  113704. }else{
  113705. ret[i][m][j+2]=brute_buffer[bin];
  113706. }
  113707. }
  113708. }
  113709. /* add fenceposts */
  113710. for(j=0;j<EHMER_OFFSET;j++)
  113711. if(ret[i][m][j+2]>-200.f)break;
  113712. ret[i][m][0]=j;
  113713. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  113714. if(ret[i][m][j+2]>-200.f)
  113715. break;
  113716. ret[i][m][1]=j;
  113717. }
  113718. }
  113719. return(ret);
  113720. }
  113721. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  113722. vorbis_info_psy_global *gi,int n,long rate){
  113723. long i,j,lo=-99,hi=1;
  113724. long maxoc;
  113725. memset(p,0,sizeof(*p));
  113726. p->eighth_octave_lines=gi->eighth_octave_lines;
  113727. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  113728. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  113729. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  113730. p->total_octave_lines=maxoc-p->firstoc+1;
  113731. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  113732. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  113733. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  113734. p->vi=vi;
  113735. p->n=n;
  113736. p->rate=rate;
  113737. /* AoTuV HF weighting */
  113738. p->m_val = 1.;
  113739. if(rate < 26000) p->m_val = 0;
  113740. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  113741. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  113742. /* set up the lookups for a given blocksize and sample rate */
  113743. for(i=0,j=0;i<MAX_ATH-1;i++){
  113744. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  113745. float base=ATH[i];
  113746. if(j<endpos){
  113747. float delta=(ATH[i+1]-base)/(endpos-j);
  113748. for(;j<endpos && j<n;j++){
  113749. p->ath[j]=base+100.;
  113750. base+=delta;
  113751. }
  113752. }
  113753. }
  113754. for(i=0;i<n;i++){
  113755. float bark=toBARK(rate/(2*n)*i);
  113756. for(;lo+vi->noisewindowlomin<i &&
  113757. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  113758. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  113759. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  113760. p->bark[i]=((lo-1)<<16)+(hi-1);
  113761. }
  113762. for(i=0;i<n;i++)
  113763. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  113764. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  113765. vi->tone_centerboost,vi->tone_decay);
  113766. /* set up rolling noise median */
  113767. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  113768. for(i=0;i<P_NOISECURVES;i++)
  113769. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  113770. for(i=0;i<n;i++){
  113771. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  113772. int inthalfoc;
  113773. float del;
  113774. if(halfoc<0)halfoc=0;
  113775. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  113776. inthalfoc=(int)halfoc;
  113777. del=halfoc-inthalfoc;
  113778. for(j=0;j<P_NOISECURVES;j++)
  113779. p->noiseoffset[j][i]=
  113780. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  113781. p->vi->noiseoff[j][inthalfoc+1]*del;
  113782. }
  113783. #if 0
  113784. {
  113785. static int ls=0;
  113786. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  113787. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  113788. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  113789. }
  113790. #endif
  113791. }
  113792. void _vp_psy_clear(vorbis_look_psy *p){
  113793. int i,j;
  113794. if(p){
  113795. if(p->ath)_ogg_free(p->ath);
  113796. if(p->octave)_ogg_free(p->octave);
  113797. if(p->bark)_ogg_free(p->bark);
  113798. if(p->tonecurves){
  113799. for(i=0;i<P_BANDS;i++){
  113800. for(j=0;j<P_LEVELS;j++){
  113801. _ogg_free(p->tonecurves[i][j]);
  113802. }
  113803. _ogg_free(p->tonecurves[i]);
  113804. }
  113805. _ogg_free(p->tonecurves);
  113806. }
  113807. if(p->noiseoffset){
  113808. for(i=0;i<P_NOISECURVES;i++){
  113809. _ogg_free(p->noiseoffset[i]);
  113810. }
  113811. _ogg_free(p->noiseoffset);
  113812. }
  113813. memset(p,0,sizeof(*p));
  113814. }
  113815. }
  113816. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  113817. static void seed_curve(float *seed,
  113818. const float **curves,
  113819. float amp,
  113820. int oc, int n,
  113821. int linesper,float dBoffset){
  113822. int i,post1;
  113823. int seedptr;
  113824. const float *posts,*curve;
  113825. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  113826. choice=max(choice,0);
  113827. choice=min(choice,P_LEVELS-1);
  113828. posts=curves[choice];
  113829. curve=posts+2;
  113830. post1=(int)posts[1];
  113831. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  113832. for(i=posts[0];i<post1;i++){
  113833. if(seedptr>0){
  113834. float lin=amp+curve[i];
  113835. if(seed[seedptr]<lin)seed[seedptr]=lin;
  113836. }
  113837. seedptr+=linesper;
  113838. if(seedptr>=n)break;
  113839. }
  113840. }
  113841. static void seed_loop(vorbis_look_psy *p,
  113842. const float ***curves,
  113843. const float *f,
  113844. const float *flr,
  113845. float *seed,
  113846. float specmax){
  113847. vorbis_info_psy *vi=p->vi;
  113848. long n=p->n,i;
  113849. float dBoffset=vi->max_curve_dB-specmax;
  113850. /* prime the working vector with peak values */
  113851. for(i=0;i<n;i++){
  113852. float max=f[i];
  113853. long oc=p->octave[i];
  113854. while(i+1<n && p->octave[i+1]==oc){
  113855. i++;
  113856. if(f[i]>max)max=f[i];
  113857. }
  113858. if(max+6.f>flr[i]){
  113859. oc=oc>>p->shiftoc;
  113860. if(oc>=P_BANDS)oc=P_BANDS-1;
  113861. if(oc<0)oc=0;
  113862. seed_curve(seed,
  113863. curves[oc],
  113864. max,
  113865. p->octave[i]-p->firstoc,
  113866. p->total_octave_lines,
  113867. p->eighth_octave_lines,
  113868. dBoffset);
  113869. }
  113870. }
  113871. }
  113872. static void seed_chase(float *seeds, int linesper, long n){
  113873. long *posstack=(long*)alloca(n*sizeof(*posstack));
  113874. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  113875. long stack=0;
  113876. long pos=0;
  113877. long i;
  113878. for(i=0;i<n;i++){
  113879. if(stack<2){
  113880. posstack[stack]=i;
  113881. ampstack[stack++]=seeds[i];
  113882. }else{
  113883. while(1){
  113884. if(seeds[i]<ampstack[stack-1]){
  113885. posstack[stack]=i;
  113886. ampstack[stack++]=seeds[i];
  113887. break;
  113888. }else{
  113889. if(i<posstack[stack-1]+linesper){
  113890. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  113891. i<posstack[stack-2]+linesper){
  113892. /* we completely overlap, making stack-1 irrelevant. pop it */
  113893. stack--;
  113894. continue;
  113895. }
  113896. }
  113897. posstack[stack]=i;
  113898. ampstack[stack++]=seeds[i];
  113899. break;
  113900. }
  113901. }
  113902. }
  113903. }
  113904. /* the stack now contains only the positions that are relevant. Scan
  113905. 'em straight through */
  113906. for(i=0;i<stack;i++){
  113907. long endpos;
  113908. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  113909. endpos=posstack[i+1];
  113910. }else{
  113911. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  113912. discarded in short frames */
  113913. }
  113914. if(endpos>n)endpos=n;
  113915. for(;pos<endpos;pos++)
  113916. seeds[pos]=ampstack[i];
  113917. }
  113918. /* there. Linear time. I now remember this was on a problem set I
  113919. had in Grad Skool... I didn't solve it at the time ;-) */
  113920. }
  113921. /* bleaugh, this is more complicated than it needs to be */
  113922. #include<stdio.h>
  113923. static void max_seeds(vorbis_look_psy *p,
  113924. float *seed,
  113925. float *flr){
  113926. long n=p->total_octave_lines;
  113927. int linesper=p->eighth_octave_lines;
  113928. long linpos=0;
  113929. long pos;
  113930. seed_chase(seed,linesper,n); /* for masking */
  113931. pos=p->octave[0]-p->firstoc-(linesper>>1);
  113932. while(linpos+1<p->n){
  113933. float minV=seed[pos];
  113934. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  113935. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  113936. while(pos+1<=end){
  113937. pos++;
  113938. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  113939. minV=seed[pos];
  113940. }
  113941. end=pos+p->firstoc;
  113942. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  113943. if(flr[linpos]<minV)flr[linpos]=minV;
  113944. }
  113945. {
  113946. float minV=seed[p->total_octave_lines-1];
  113947. for(;linpos<p->n;linpos++)
  113948. if(flr[linpos]<minV)flr[linpos]=minV;
  113949. }
  113950. }
  113951. static void bark_noise_hybridmp(int n,const long *b,
  113952. const float *f,
  113953. float *noise,
  113954. const float offset,
  113955. const int fixed){
  113956. float *N=(float*) alloca(n*sizeof(*N));
  113957. float *X=(float*) alloca(n*sizeof(*N));
  113958. float *XX=(float*) alloca(n*sizeof(*N));
  113959. float *Y=(float*) alloca(n*sizeof(*N));
  113960. float *XY=(float*) alloca(n*sizeof(*N));
  113961. float tN, tX, tXX, tY, tXY;
  113962. int i;
  113963. int lo, hi;
  113964. float R, A, B, D;
  113965. float w, x, y;
  113966. tN = tX = tXX = tY = tXY = 0.f;
  113967. y = f[0] + offset;
  113968. if (y < 1.f) y = 1.f;
  113969. w = y * y * .5;
  113970. tN += w;
  113971. tX += w;
  113972. tY += w * y;
  113973. N[0] = tN;
  113974. X[0] = tX;
  113975. XX[0] = tXX;
  113976. Y[0] = tY;
  113977. XY[0] = tXY;
  113978. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  113979. y = f[i] + offset;
  113980. if (y < 1.f) y = 1.f;
  113981. w = y * y;
  113982. tN += w;
  113983. tX += w * x;
  113984. tXX += w * x * x;
  113985. tY += w * y;
  113986. tXY += w * x * y;
  113987. N[i] = tN;
  113988. X[i] = tX;
  113989. XX[i] = tXX;
  113990. Y[i] = tY;
  113991. XY[i] = tXY;
  113992. }
  113993. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113994. lo = b[i] >> 16;
  113995. if( lo>=0 ) break;
  113996. hi = b[i] & 0xffff;
  113997. tN = N[hi] + N[-lo];
  113998. tX = X[hi] - X[-lo];
  113999. tXX = XX[hi] + XX[-lo];
  114000. tY = Y[hi] + Y[-lo];
  114001. tXY = XY[hi] - XY[-lo];
  114002. A = tY * tXX - tX * tXY;
  114003. B = tN * tXY - tX * tY;
  114004. D = tN * tXX - tX * tX;
  114005. R = (A + x * B) / D;
  114006. if (R < 0.f)
  114007. R = 0.f;
  114008. noise[i] = R - offset;
  114009. }
  114010. for ( ;; i++, x += 1.f) {
  114011. lo = b[i] >> 16;
  114012. hi = b[i] & 0xffff;
  114013. if(hi>=n)break;
  114014. tN = N[hi] - N[lo];
  114015. tX = X[hi] - X[lo];
  114016. tXX = XX[hi] - XX[lo];
  114017. tY = Y[hi] - Y[lo];
  114018. tXY = XY[hi] - XY[lo];
  114019. A = tY * tXX - tX * tXY;
  114020. B = tN * tXY - tX * tY;
  114021. D = tN * tXX - tX * tX;
  114022. R = (A + x * B) / D;
  114023. if (R < 0.f) R = 0.f;
  114024. noise[i] = R - offset;
  114025. }
  114026. for ( ; i < n; i++, x += 1.f) {
  114027. R = (A + x * B) / D;
  114028. if (R < 0.f) R = 0.f;
  114029. noise[i] = R - offset;
  114030. }
  114031. if (fixed <= 0) return;
  114032. for (i = 0, x = 0.f;; i++, x += 1.f) {
  114033. hi = i + fixed / 2;
  114034. lo = hi - fixed;
  114035. if(lo>=0)break;
  114036. tN = N[hi] + N[-lo];
  114037. tX = X[hi] - X[-lo];
  114038. tXX = XX[hi] + XX[-lo];
  114039. tY = Y[hi] + Y[-lo];
  114040. tXY = XY[hi] - XY[-lo];
  114041. A = tY * tXX - tX * tXY;
  114042. B = tN * tXY - tX * tY;
  114043. D = tN * tXX - tX * tX;
  114044. R = (A + x * B) / D;
  114045. if (R - offset < noise[i]) noise[i] = R - offset;
  114046. }
  114047. for ( ;; i++, x += 1.f) {
  114048. hi = i + fixed / 2;
  114049. lo = hi - fixed;
  114050. if(hi>=n)break;
  114051. tN = N[hi] - N[lo];
  114052. tX = X[hi] - X[lo];
  114053. tXX = XX[hi] - XX[lo];
  114054. tY = Y[hi] - Y[lo];
  114055. tXY = XY[hi] - XY[lo];
  114056. A = tY * tXX - tX * tXY;
  114057. B = tN * tXY - tX * tY;
  114058. D = tN * tXX - tX * tX;
  114059. R = (A + x * B) / D;
  114060. if (R - offset < noise[i]) noise[i] = R - offset;
  114061. }
  114062. for ( ; i < n; i++, x += 1.f) {
  114063. R = (A + x * B) / D;
  114064. if (R - offset < noise[i]) noise[i] = R - offset;
  114065. }
  114066. }
  114067. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  114068. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  114069. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  114070. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  114071. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  114072. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  114073. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  114074. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  114075. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  114076. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  114077. 973377.F, 913981.F, 858210.F, 805842.F,
  114078. 756669.F, 710497.F, 667142.F, 626433.F,
  114079. 588208.F, 552316.F, 518613.F, 486967.F,
  114080. 457252.F, 429351.F, 403152.F, 378551.F,
  114081. 355452.F, 333762.F, 313396.F, 294273.F,
  114082. 276316.F, 259455.F, 243623.F, 228757.F,
  114083. 214798.F, 201691.F, 189384.F, 177828.F,
  114084. 166977.F, 156788.F, 147221.F, 138237.F,
  114085. 129802.F, 121881.F, 114444.F, 107461.F,
  114086. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  114087. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  114088. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  114089. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  114090. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  114091. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  114092. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  114093. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  114094. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  114095. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  114096. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  114097. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  114098. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  114099. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  114100. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  114101. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  114102. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  114103. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  114104. 1084.32F, 1018.15F, 956.024F, 897.687F,
  114105. 842.910F, 791.475F, 743.179F, 697.830F,
  114106. 655.249F, 615.265F, 577.722F, 542.469F,
  114107. 509.367F, 478.286F, 449.101F, 421.696F,
  114108. 395.964F, 371.803F, 349.115F, 327.812F,
  114109. 307.809F, 289.026F, 271.390F, 254.830F,
  114110. 239.280F, 224.679F, 210.969F, 198.096F,
  114111. 186.008F, 174.658F, 164.000F, 153.993F,
  114112. 144.596F, 135.773F, 127.488F, 119.708F,
  114113. 112.404F, 105.545F, 99.1046F, 93.0572F,
  114114. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  114115. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  114116. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  114117. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  114118. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  114119. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  114120. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  114121. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  114122. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  114123. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  114124. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  114125. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  114126. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  114127. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  114128. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  114129. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  114130. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  114131. 1.20790F, 1.13419F, 1.06499F, 1.F
  114132. };
  114133. void _vp_remove_floor(vorbis_look_psy *p,
  114134. float *mdct,
  114135. int *codedflr,
  114136. float *residue,
  114137. int sliding_lowpass){
  114138. int i,n=p->n;
  114139. if(sliding_lowpass>n)sliding_lowpass=n;
  114140. for(i=0;i<sliding_lowpass;i++){
  114141. residue[i]=
  114142. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  114143. }
  114144. for(;i<n;i++)
  114145. residue[i]=0.;
  114146. }
  114147. void _vp_noisemask(vorbis_look_psy *p,
  114148. float *logmdct,
  114149. float *logmask){
  114150. int i,n=p->n;
  114151. float *work=(float*) alloca(n*sizeof(*work));
  114152. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  114153. 140.,-1);
  114154. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  114155. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  114156. p->vi->noisewindowfixed);
  114157. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  114158. #if 0
  114159. {
  114160. static int seq=0;
  114161. float work2[n];
  114162. for(i=0;i<n;i++){
  114163. work2[i]=logmask[i]+work[i];
  114164. }
  114165. if(seq&1)
  114166. _analysis_output("median2R",seq/2,work,n,1,0,0);
  114167. else
  114168. _analysis_output("median2L",seq/2,work,n,1,0,0);
  114169. if(seq&1)
  114170. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  114171. else
  114172. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  114173. seq++;
  114174. }
  114175. #endif
  114176. for(i=0;i<n;i++){
  114177. int dB=logmask[i]+.5;
  114178. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  114179. if(dB<0)dB=0;
  114180. logmask[i]= work[i]+p->vi->noisecompand[dB];
  114181. }
  114182. }
  114183. void _vp_tonemask(vorbis_look_psy *p,
  114184. float *logfft,
  114185. float *logmask,
  114186. float global_specmax,
  114187. float local_specmax){
  114188. int i,n=p->n;
  114189. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  114190. float att=local_specmax+p->vi->ath_adjatt;
  114191. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  114192. /* set the ATH (floating below localmax, not global max by a
  114193. specified att) */
  114194. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  114195. for(i=0;i<n;i++)
  114196. logmask[i]=p->ath[i]+att;
  114197. /* tone masking */
  114198. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  114199. max_seeds(p,seed,logmask);
  114200. }
  114201. void _vp_offset_and_mix(vorbis_look_psy *p,
  114202. float *noise,
  114203. float *tone,
  114204. int offset_select,
  114205. float *logmask,
  114206. float *mdct,
  114207. float *logmdct){
  114208. int i,n=p->n;
  114209. float de, coeffi, cx;/* AoTuV */
  114210. float toneatt=p->vi->tone_masteratt[offset_select];
  114211. cx = p->m_val;
  114212. for(i=0;i<n;i++){
  114213. float val= noise[i]+p->noiseoffset[offset_select][i];
  114214. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  114215. logmask[i]=max(val,tone[i]+toneatt);
  114216. /* AoTuV */
  114217. /** @ M1 **
  114218. The following codes improve a noise problem.
  114219. A fundamental idea uses the value of masking and carries out
  114220. the relative compensation of the MDCT.
  114221. However, this code is not perfect and all noise problems cannot be solved.
  114222. by Aoyumi @ 2004/04/18
  114223. */
  114224. if(offset_select == 1) {
  114225. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  114226. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  114227. if(val > coeffi){
  114228. /* mdct value is > -17.2 dB below floor */
  114229. de = 1.0-((val-coeffi)*0.005*cx);
  114230. /* pro-rated attenuation:
  114231. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  114232. -0.77 dB boost if mdct value is 0dB (relative to floor)
  114233. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  114234. etc... */
  114235. if(de < 0) de = 0.0001;
  114236. }else
  114237. /* mdct value is <= -17.2 dB below floor */
  114238. de = 1.0-((val-coeffi)*0.0003*cx);
  114239. /* pro-rated attenuation:
  114240. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  114241. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  114242. etc... */
  114243. mdct[i] *= de;
  114244. }
  114245. }
  114246. }
  114247. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  114248. vorbis_info *vi=vd->vi;
  114249. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114250. vorbis_info_psy_global *gi=&ci->psy_g_param;
  114251. int n=ci->blocksizes[vd->W]/2;
  114252. float secs=(float)n/vi->rate;
  114253. amp+=secs*gi->ampmax_att_per_sec;
  114254. if(amp<-9999)amp=-9999;
  114255. return(amp);
  114256. }
  114257. static void couple_lossless(float A, float B,
  114258. float *qA, float *qB){
  114259. int test1=fabs(*qA)>fabs(*qB);
  114260. test1-= fabs(*qA)<fabs(*qB);
  114261. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  114262. if(test1==1){
  114263. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  114264. }else{
  114265. float temp=*qB;
  114266. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  114267. *qA=temp;
  114268. }
  114269. if(*qB>fabs(*qA)*1.9999f){
  114270. *qB= -fabs(*qA)*2.f;
  114271. *qA= -*qA;
  114272. }
  114273. }
  114274. static float hypot_lookup[32]={
  114275. -0.009935, -0.011245, -0.012726, -0.014397,
  114276. -0.016282, -0.018407, -0.020800, -0.023494,
  114277. -0.026522, -0.029923, -0.033737, -0.038010,
  114278. -0.042787, -0.048121, -0.054064, -0.060671,
  114279. -0.068000, -0.076109, -0.085054, -0.094892,
  114280. -0.105675, -0.117451, -0.130260, -0.144134,
  114281. -0.159093, -0.175146, -0.192286, -0.210490,
  114282. -0.229718, -0.249913, -0.271001, -0.292893};
  114283. static void precomputed_couple_point(float premag,
  114284. int floorA,int floorB,
  114285. float *mag, float *ang){
  114286. int test=(floorA>floorB)-1;
  114287. int offset=31-abs(floorA-floorB);
  114288. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  114289. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  114290. *mag=premag*floormag;
  114291. *ang=0.f;
  114292. }
  114293. /* just like below, this is currently set up to only do
  114294. single-step-depth coupling. Otherwise, we'd have to do more
  114295. copying (which will be inevitable later) */
  114296. /* doing the real circular magnitude calculation is audibly superior
  114297. to (A+B)/sqrt(2) */
  114298. static float dipole_hypot(float a, float b){
  114299. if(a>0.){
  114300. if(b>0.)return sqrt(a*a+b*b);
  114301. if(a>-b)return sqrt(a*a-b*b);
  114302. return -sqrt(b*b-a*a);
  114303. }
  114304. if(b<0.)return -sqrt(a*a+b*b);
  114305. if(-a>b)return -sqrt(a*a-b*b);
  114306. return sqrt(b*b-a*a);
  114307. }
  114308. static float round_hypot(float a, float b){
  114309. if(a>0.){
  114310. if(b>0.)return sqrt(a*a+b*b);
  114311. if(a>-b)return sqrt(a*a+b*b);
  114312. return -sqrt(b*b+a*a);
  114313. }
  114314. if(b<0.)return -sqrt(a*a+b*b);
  114315. if(-a>b)return -sqrt(a*a+b*b);
  114316. return sqrt(b*b+a*a);
  114317. }
  114318. /* revert to round hypot for now */
  114319. float **_vp_quantize_couple_memo(vorbis_block *vb,
  114320. vorbis_info_psy_global *g,
  114321. vorbis_look_psy *p,
  114322. vorbis_info_mapping0 *vi,
  114323. float **mdct){
  114324. int i,j,n=p->n;
  114325. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114326. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  114327. for(i=0;i<vi->coupling_steps;i++){
  114328. float *mdctM=mdct[vi->coupling_mag[i]];
  114329. float *mdctA=mdct[vi->coupling_ang[i]];
  114330. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114331. for(j=0;j<limit;j++)
  114332. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  114333. for(;j<n;j++)
  114334. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  114335. }
  114336. return(ret);
  114337. }
  114338. /* this is for per-channel noise normalization */
  114339. static int apsort(const void *a, const void *b){
  114340. float f1=fabs(**(float**)a);
  114341. float f2=fabs(**(float**)b);
  114342. return (f1<f2)-(f1>f2);
  114343. }
  114344. int **_vp_quantize_couple_sort(vorbis_block *vb,
  114345. vorbis_look_psy *p,
  114346. vorbis_info_mapping0 *vi,
  114347. float **mags){
  114348. if(p->vi->normal_point_p){
  114349. int i,j,k,n=p->n;
  114350. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114351. int partition=p->vi->normal_partition;
  114352. float **work=(float**) alloca(sizeof(*work)*partition);
  114353. for(i=0;i<vi->coupling_steps;i++){
  114354. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114355. for(j=0;j<n;j+=partition){
  114356. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  114357. qsort(work,partition,sizeof(*work),apsort);
  114358. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  114359. }
  114360. }
  114361. return(ret);
  114362. }
  114363. return(NULL);
  114364. }
  114365. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  114366. float *magnitudes,int *sortedindex){
  114367. int i,j,n=p->n;
  114368. vorbis_info_psy *vi=p->vi;
  114369. int partition=vi->normal_partition;
  114370. float **work=(float**) alloca(sizeof(*work)*partition);
  114371. int start=vi->normal_start;
  114372. for(j=start;j<n;j+=partition){
  114373. if(j+partition>n)partition=n-j;
  114374. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  114375. qsort(work,partition,sizeof(*work),apsort);
  114376. for(i=0;i<partition;i++){
  114377. sortedindex[i+j-start]=work[i]-magnitudes;
  114378. }
  114379. }
  114380. }
  114381. void _vp_noise_normalize(vorbis_look_psy *p,
  114382. float *in,float *out,int *sortedindex){
  114383. int flag=0,i,j=0,n=p->n;
  114384. vorbis_info_psy *vi=p->vi;
  114385. int partition=vi->normal_partition;
  114386. int start=vi->normal_start;
  114387. if(start>n)start=n;
  114388. if(vi->normal_channel_p){
  114389. for(;j<start;j++)
  114390. out[j]=rint(in[j]);
  114391. for(;j+partition<=n;j+=partition){
  114392. float acc=0.;
  114393. int k;
  114394. for(i=j;i<j+partition;i++)
  114395. acc+=in[i]*in[i];
  114396. for(i=0;i<partition;i++){
  114397. k=sortedindex[i+j-start];
  114398. if(in[k]*in[k]>=.25f){
  114399. out[k]=rint(in[k]);
  114400. acc-=in[k]*in[k];
  114401. flag=1;
  114402. }else{
  114403. if(acc<vi->normal_thresh)break;
  114404. out[k]=unitnorm(in[k]);
  114405. acc-=1.;
  114406. }
  114407. }
  114408. for(;i<partition;i++){
  114409. k=sortedindex[i+j-start];
  114410. out[k]=0.;
  114411. }
  114412. }
  114413. }
  114414. for(;j<n;j++)
  114415. out[j]=rint(in[j]);
  114416. }
  114417. void _vp_couple(int blobno,
  114418. vorbis_info_psy_global *g,
  114419. vorbis_look_psy *p,
  114420. vorbis_info_mapping0 *vi,
  114421. float **res,
  114422. float **mag_memo,
  114423. int **mag_sort,
  114424. int **ifloor,
  114425. int *nonzero,
  114426. int sliding_lowpass){
  114427. int i,j,k,n=p->n;
  114428. /* perform any requested channel coupling */
  114429. /* point stereo can only be used in a first stage (in this encoder)
  114430. because of the dependency on floor lookups */
  114431. for(i=0;i<vi->coupling_steps;i++){
  114432. /* once we're doing multistage coupling in which a channel goes
  114433. through more than one coupling step, the floor vector
  114434. magnitudes will also have to be recalculated an propogated
  114435. along with PCM. Right now, we're not (that will wait until 5.1
  114436. most likely), so the code isn't here yet. The memory management
  114437. here is all assuming single depth couplings anyway. */
  114438. /* make sure coupling a zero and a nonzero channel results in two
  114439. nonzero channels. */
  114440. if(nonzero[vi->coupling_mag[i]] ||
  114441. nonzero[vi->coupling_ang[i]]){
  114442. float *rM=res[vi->coupling_mag[i]];
  114443. float *rA=res[vi->coupling_ang[i]];
  114444. float *qM=rM+n;
  114445. float *qA=rA+n;
  114446. int *floorM=ifloor[vi->coupling_mag[i]];
  114447. int *floorA=ifloor[vi->coupling_ang[i]];
  114448. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  114449. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  114450. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  114451. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  114452. int pointlimit=limit;
  114453. nonzero[vi->coupling_mag[i]]=1;
  114454. nonzero[vi->coupling_ang[i]]=1;
  114455. /* The threshold of a stereo is changed with the size of n */
  114456. if(n > 1000)
  114457. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  114458. for(j=0;j<p->n;j+=partition){
  114459. float acc=0.f;
  114460. for(k=0;k<partition;k++){
  114461. int l=k+j;
  114462. if(l<sliding_lowpass){
  114463. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  114464. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  114465. precomputed_couple_point(mag_memo[i][l],
  114466. floorM[l],floorA[l],
  114467. qM+l,qA+l);
  114468. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  114469. }else{
  114470. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  114471. }
  114472. }else{
  114473. qM[l]=0.;
  114474. qA[l]=0.;
  114475. }
  114476. }
  114477. if(p->vi->normal_point_p){
  114478. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  114479. int l=mag_sort[i][j+k];
  114480. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  114481. qM[l]=unitnorm(qM[l]);
  114482. acc-=1.f;
  114483. }
  114484. }
  114485. }
  114486. }
  114487. }
  114488. }
  114489. }
  114490. /* AoTuV */
  114491. /** @ M2 **
  114492. The boost problem by the combination of noise normalization and point stereo is eased.
  114493. However, this is a temporary patch.
  114494. by Aoyumi @ 2004/04/18
  114495. */
  114496. void hf_reduction(vorbis_info_psy_global *g,
  114497. vorbis_look_psy *p,
  114498. vorbis_info_mapping0 *vi,
  114499. float **mdct){
  114500. int i,j,n=p->n, de=0.3*p->m_val;
  114501. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  114502. for(i=0; i<vi->coupling_steps; i++){
  114503. /* for(j=start; j<limit; j++){} // ???*/
  114504. for(j=limit; j<n; j++)
  114505. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  114506. }
  114507. }
  114508. #endif
  114509. /*** End of inlined file: psy.c ***/
  114510. /*** Start of inlined file: registry.c ***/
  114511. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114512. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114513. // tasks..
  114514. #if JUCE_MSVC
  114515. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114516. #endif
  114517. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114518. #if JUCE_USE_OGGVORBIS
  114519. /* seems like major overkill now; the backend numbers will grow into
  114520. the infrastructure soon enough */
  114521. extern vorbis_func_floor floor0_exportbundle;
  114522. extern vorbis_func_floor floor1_exportbundle;
  114523. extern vorbis_func_residue residue0_exportbundle;
  114524. extern vorbis_func_residue residue1_exportbundle;
  114525. extern vorbis_func_residue residue2_exportbundle;
  114526. extern vorbis_func_mapping mapping0_exportbundle;
  114527. vorbis_func_floor *_floor_P[]={
  114528. &floor0_exportbundle,
  114529. &floor1_exportbundle,
  114530. };
  114531. vorbis_func_residue *_residue_P[]={
  114532. &residue0_exportbundle,
  114533. &residue1_exportbundle,
  114534. &residue2_exportbundle,
  114535. };
  114536. vorbis_func_mapping *_mapping_P[]={
  114537. &mapping0_exportbundle,
  114538. };
  114539. #endif
  114540. /*** End of inlined file: registry.c ***/
  114541. /*** Start of inlined file: res0.c ***/
  114542. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  114543. encode/decode loops are coded for clarity and performance is not
  114544. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  114545. it's slow. */
  114546. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114547. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114548. // tasks..
  114549. #if JUCE_MSVC
  114550. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114551. #endif
  114552. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114553. #if JUCE_USE_OGGVORBIS
  114554. #include <stdlib.h>
  114555. #include <string.h>
  114556. #include <math.h>
  114557. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114558. #include <stdio.h>
  114559. #endif
  114560. typedef struct {
  114561. vorbis_info_residue0 *info;
  114562. int parts;
  114563. int stages;
  114564. codebook *fullbooks;
  114565. codebook *phrasebook;
  114566. codebook ***partbooks;
  114567. int partvals;
  114568. int **decodemap;
  114569. long postbits;
  114570. long phrasebits;
  114571. long frames;
  114572. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  114573. int train_seq;
  114574. long *training_data[8][64];
  114575. float training_max[8][64];
  114576. float training_min[8][64];
  114577. float tmin;
  114578. float tmax;
  114579. #endif
  114580. } vorbis_look_residue0;
  114581. void res0_free_info(vorbis_info_residue *i){
  114582. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  114583. if(info){
  114584. memset(info,0,sizeof(*info));
  114585. _ogg_free(info);
  114586. }
  114587. }
  114588. void res0_free_look(vorbis_look_residue *i){
  114589. int j;
  114590. if(i){
  114591. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  114592. #ifdef TRAIN_RES
  114593. {
  114594. int j,k,l;
  114595. for(j=0;j<look->parts;j++){
  114596. /*fprintf(stderr,"partition %d: ",j);*/
  114597. for(k=0;k<8;k++)
  114598. if(look->training_data[k][j]){
  114599. char buffer[80];
  114600. FILE *of;
  114601. codebook *statebook=look->partbooks[j][k];
  114602. /* long and short into the same bucket by current convention */
  114603. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  114604. of=fopen(buffer,"a");
  114605. for(l=0;l<statebook->entries;l++)
  114606. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  114607. fclose(of);
  114608. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  114609. look->training_min[k][j],look->training_max[k][j]);*/
  114610. _ogg_free(look->training_data[k][j]);
  114611. look->training_data[k][j]=NULL;
  114612. }
  114613. /*fprintf(stderr,"\n");*/
  114614. }
  114615. }
  114616. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  114617. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  114618. (float)look->phrasebits/look->frames,
  114619. (float)look->postbits/look->frames,
  114620. (float)(look->postbits+look->phrasebits)/look->frames);*/
  114621. #endif
  114622. /*vorbis_info_residue0 *info=look->info;
  114623. fprintf(stderr,
  114624. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  114625. "(%g/frame) \n",look->frames,look->phrasebits,
  114626. look->resbitsflat,
  114627. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  114628. for(j=0;j<look->parts;j++){
  114629. long acc=0;
  114630. fprintf(stderr,"\t[%d] == ",j);
  114631. for(k=0;k<look->stages;k++)
  114632. if((info->secondstages[j]>>k)&1){
  114633. fprintf(stderr,"%ld,",look->resbits[j][k]);
  114634. acc+=look->resbits[j][k];
  114635. }
  114636. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  114637. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  114638. }
  114639. fprintf(stderr,"\n");*/
  114640. for(j=0;j<look->parts;j++)
  114641. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  114642. _ogg_free(look->partbooks);
  114643. for(j=0;j<look->partvals;j++)
  114644. _ogg_free(look->decodemap[j]);
  114645. _ogg_free(look->decodemap);
  114646. memset(look,0,sizeof(*look));
  114647. _ogg_free(look);
  114648. }
  114649. }
  114650. static int icount(unsigned int v){
  114651. int ret=0;
  114652. while(v){
  114653. ret+=v&1;
  114654. v>>=1;
  114655. }
  114656. return(ret);
  114657. }
  114658. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  114659. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  114660. int j,acc=0;
  114661. oggpack_write(opb,info->begin,24);
  114662. oggpack_write(opb,info->end,24);
  114663. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  114664. code with a partitioned book */
  114665. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  114666. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  114667. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  114668. bitmask of one indicates this partition class has bits to write
  114669. this pass */
  114670. for(j=0;j<info->partitions;j++){
  114671. if(ilog(info->secondstages[j])>3){
  114672. /* yes, this is a minor hack due to not thinking ahead */
  114673. oggpack_write(opb,info->secondstages[j],3);
  114674. oggpack_write(opb,1,1);
  114675. oggpack_write(opb,info->secondstages[j]>>3,5);
  114676. }else
  114677. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  114678. acc+=icount(info->secondstages[j]);
  114679. }
  114680. for(j=0;j<acc;j++)
  114681. oggpack_write(opb,info->booklist[j],8);
  114682. }
  114683. /* vorbis_info is for range checking */
  114684. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114685. int j,acc=0;
  114686. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  114687. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114688. info->begin=oggpack_read(opb,24);
  114689. info->end=oggpack_read(opb,24);
  114690. info->grouping=oggpack_read(opb,24)+1;
  114691. info->partitions=oggpack_read(opb,6)+1;
  114692. info->groupbook=oggpack_read(opb,8);
  114693. for(j=0;j<info->partitions;j++){
  114694. int cascade=oggpack_read(opb,3);
  114695. if(oggpack_read(opb,1))
  114696. cascade|=(oggpack_read(opb,5)<<3);
  114697. info->secondstages[j]=cascade;
  114698. acc+=icount(cascade);
  114699. }
  114700. for(j=0;j<acc;j++)
  114701. info->booklist[j]=oggpack_read(opb,8);
  114702. if(info->groupbook>=ci->books)goto errout;
  114703. for(j=0;j<acc;j++)
  114704. if(info->booklist[j]>=ci->books)goto errout;
  114705. return(info);
  114706. errout:
  114707. res0_free_info(info);
  114708. return(NULL);
  114709. }
  114710. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  114711. vorbis_info_residue *vr){
  114712. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  114713. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  114714. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  114715. int j,k,acc=0;
  114716. int dim;
  114717. int maxstage=0;
  114718. look->info=info;
  114719. look->parts=info->partitions;
  114720. look->fullbooks=ci->fullbooks;
  114721. look->phrasebook=ci->fullbooks+info->groupbook;
  114722. dim=look->phrasebook->dim;
  114723. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  114724. for(j=0;j<look->parts;j++){
  114725. int stages=ilog(info->secondstages[j]);
  114726. if(stages){
  114727. if(stages>maxstage)maxstage=stages;
  114728. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  114729. for(k=0;k<stages;k++)
  114730. if(info->secondstages[j]&(1<<k)){
  114731. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  114732. #ifdef TRAIN_RES
  114733. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  114734. sizeof(***look->training_data));
  114735. #endif
  114736. }
  114737. }
  114738. }
  114739. look->partvals=rint(pow((float)look->parts,(float)dim));
  114740. look->stages=maxstage;
  114741. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  114742. for(j=0;j<look->partvals;j++){
  114743. long val=j;
  114744. long mult=look->partvals/look->parts;
  114745. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  114746. for(k=0;k<dim;k++){
  114747. long deco=val/mult;
  114748. val-=deco*mult;
  114749. mult/=look->parts;
  114750. look->decodemap[j][k]=deco;
  114751. }
  114752. }
  114753. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114754. {
  114755. static int train_seq=0;
  114756. look->train_seq=train_seq++;
  114757. }
  114758. #endif
  114759. return(look);
  114760. }
  114761. /* break an abstraction and copy some code for performance purposes */
  114762. static int local_book_besterror(codebook *book,float *a){
  114763. int dim=book->dim,i,k,o;
  114764. int best=0;
  114765. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114766. /* find the quant val of each scalar */
  114767. for(k=0,o=dim;k<dim;++k){
  114768. float val=a[--o];
  114769. i=tt->threshvals>>1;
  114770. if(val<tt->quantthresh[i]){
  114771. if(val<tt->quantthresh[i-1]){
  114772. for(--i;i>0;--i)
  114773. if(val>=tt->quantthresh[i-1])
  114774. break;
  114775. }
  114776. }else{
  114777. for(++i;i<tt->threshvals-1;++i)
  114778. if(val<tt->quantthresh[i])break;
  114779. }
  114780. best=(best*tt->quantvals)+tt->quantmap[i];
  114781. }
  114782. /* regular lattices are easy :-) */
  114783. if(book->c->lengthlist[best]<=0){
  114784. const static_codebook *c=book->c;
  114785. int i,j;
  114786. float bestf=0.f;
  114787. float *e=book->valuelist;
  114788. best=-1;
  114789. for(i=0;i<book->entries;i++){
  114790. if(c->lengthlist[i]>0){
  114791. float thisx=0.f;
  114792. for(j=0;j<dim;j++){
  114793. float val=(e[j]-a[j]);
  114794. thisx+=val*val;
  114795. }
  114796. if(best==-1 || thisx<bestf){
  114797. bestf=thisx;
  114798. best=i;
  114799. }
  114800. }
  114801. e+=dim;
  114802. }
  114803. }
  114804. {
  114805. float *ptr=book->valuelist+best*dim;
  114806. for(i=0;i<dim;i++)
  114807. *a++ -= *ptr++;
  114808. }
  114809. return(best);
  114810. }
  114811. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  114812. codebook *book,long *acc){
  114813. int i,bits=0;
  114814. int dim=book->dim;
  114815. int step=n/dim;
  114816. for(i=0;i<step;i++){
  114817. int entry=local_book_besterror(book,vec+i*dim);
  114818. #ifdef TRAIN_RES
  114819. acc[entry]++;
  114820. #endif
  114821. bits+=vorbis_book_encode(book,entry,opb);
  114822. }
  114823. return(bits);
  114824. }
  114825. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  114826. float **in,int ch){
  114827. long i,j,k;
  114828. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114829. vorbis_info_residue0 *info=look->info;
  114830. /* move all this setup out later */
  114831. int samples_per_partition=info->grouping;
  114832. int possible_partitions=info->partitions;
  114833. int n=info->end-info->begin;
  114834. int partvals=n/samples_per_partition;
  114835. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  114836. float scale=100./samples_per_partition;
  114837. /* we find the partition type for each partition of each
  114838. channel. We'll go back and do the interleaved encoding in a
  114839. bit. For now, clarity */
  114840. for(i=0;i<ch;i++){
  114841. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  114842. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  114843. }
  114844. for(i=0;i<partvals;i++){
  114845. int offset=i*samples_per_partition+info->begin;
  114846. for(j=0;j<ch;j++){
  114847. float max=0.;
  114848. float ent=0.;
  114849. for(k=0;k<samples_per_partition;k++){
  114850. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  114851. ent+=fabs(rint(in[j][offset+k]));
  114852. }
  114853. ent*=scale;
  114854. for(k=0;k<possible_partitions-1;k++)
  114855. if(max<=info->classmetric1[k] &&
  114856. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  114857. break;
  114858. partword[j][i]=k;
  114859. }
  114860. }
  114861. #ifdef TRAIN_RESAUX
  114862. {
  114863. FILE *of;
  114864. char buffer[80];
  114865. for(i=0;i<ch;i++){
  114866. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114867. of=fopen(buffer,"a");
  114868. for(j=0;j<partvals;j++)
  114869. fprintf(of,"%ld, ",partword[i][j]);
  114870. fprintf(of,"\n");
  114871. fclose(of);
  114872. }
  114873. }
  114874. #endif
  114875. look->frames++;
  114876. return(partword);
  114877. }
  114878. /* designed for stereo or other modes where the partition size is an
  114879. integer multiple of the number of channels encoded in the current
  114880. submap */
  114881. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  114882. int ch){
  114883. long i,j,k,l;
  114884. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114885. vorbis_info_residue0 *info=look->info;
  114886. /* move all this setup out later */
  114887. int samples_per_partition=info->grouping;
  114888. int possible_partitions=info->partitions;
  114889. int n=info->end-info->begin;
  114890. int partvals=n/samples_per_partition;
  114891. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  114892. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114893. FILE *of;
  114894. char buffer[80];
  114895. #endif
  114896. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  114897. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  114898. for(i=0,l=info->begin/ch;i<partvals;i++){
  114899. float magmax=0.f;
  114900. float angmax=0.f;
  114901. for(j=0;j<samples_per_partition;j+=ch){
  114902. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  114903. for(k=1;k<ch;k++)
  114904. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  114905. l++;
  114906. }
  114907. for(j=0;j<possible_partitions-1;j++)
  114908. if(magmax<=info->classmetric1[j] &&
  114909. angmax<=info->classmetric2[j])
  114910. break;
  114911. partword[0][i]=j;
  114912. }
  114913. #ifdef TRAIN_RESAUX
  114914. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114915. of=fopen(buffer,"a");
  114916. for(i=0;i<partvals;i++)
  114917. fprintf(of,"%ld, ",partword[0][i]);
  114918. fprintf(of,"\n");
  114919. fclose(of);
  114920. #endif
  114921. look->frames++;
  114922. return(partword);
  114923. }
  114924. static int _01forward(oggpack_buffer *opb,
  114925. vorbis_block *vb,vorbis_look_residue *vl,
  114926. float **in,int ch,
  114927. long **partword,
  114928. int (*encode)(oggpack_buffer *,float *,int,
  114929. codebook *,long *)){
  114930. long i,j,k,s;
  114931. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114932. vorbis_info_residue0 *info=look->info;
  114933. /* move all this setup out later */
  114934. int samples_per_partition=info->grouping;
  114935. int possible_partitions=info->partitions;
  114936. int partitions_per_word=look->phrasebook->dim;
  114937. int n=info->end-info->begin;
  114938. int partvals=n/samples_per_partition;
  114939. long resbits[128];
  114940. long resvals[128];
  114941. #ifdef TRAIN_RES
  114942. for(i=0;i<ch;i++)
  114943. for(j=info->begin;j<info->end;j++){
  114944. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  114945. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  114946. }
  114947. #endif
  114948. memset(resbits,0,sizeof(resbits));
  114949. memset(resvals,0,sizeof(resvals));
  114950. /* we code the partition words for each channel, then the residual
  114951. words for a partition per channel until we've written all the
  114952. residual words for that partition word. Then write the next
  114953. partition channel words... */
  114954. for(s=0;s<look->stages;s++){
  114955. for(i=0;i<partvals;){
  114956. /* first we encode a partition codeword for each channel */
  114957. if(s==0){
  114958. for(j=0;j<ch;j++){
  114959. long val=partword[j][i];
  114960. for(k=1;k<partitions_per_word;k++){
  114961. val*=possible_partitions;
  114962. if(i+k<partvals)
  114963. val+=partword[j][i+k];
  114964. }
  114965. /* training hack */
  114966. if(val<look->phrasebook->entries)
  114967. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  114968. #if 0 /*def TRAIN_RES*/
  114969. else
  114970. fprintf(stderr,"!");
  114971. #endif
  114972. }
  114973. }
  114974. /* now we encode interleaved residual values for the partitions */
  114975. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  114976. long offset=i*samples_per_partition+info->begin;
  114977. for(j=0;j<ch;j++){
  114978. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  114979. if(info->secondstages[partword[j][i]]&(1<<s)){
  114980. codebook *statebook=look->partbooks[partword[j][i]][s];
  114981. if(statebook){
  114982. int ret;
  114983. long *accumulator=NULL;
  114984. #ifdef TRAIN_RES
  114985. accumulator=look->training_data[s][partword[j][i]];
  114986. {
  114987. int l;
  114988. float *samples=in[j]+offset;
  114989. for(l=0;l<samples_per_partition;l++){
  114990. if(samples[l]<look->training_min[s][partword[j][i]])
  114991. look->training_min[s][partword[j][i]]=samples[l];
  114992. if(samples[l]>look->training_max[s][partword[j][i]])
  114993. look->training_max[s][partword[j][i]]=samples[l];
  114994. }
  114995. }
  114996. #endif
  114997. ret=encode(opb,in[j]+offset,samples_per_partition,
  114998. statebook,accumulator);
  114999. look->postbits+=ret;
  115000. resbits[partword[j][i]]+=ret;
  115001. }
  115002. }
  115003. }
  115004. }
  115005. }
  115006. }
  115007. /*{
  115008. long total=0;
  115009. long totalbits=0;
  115010. fprintf(stderr,"%d :: ",vb->mode);
  115011. for(k=0;k<possible_partitions;k++){
  115012. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  115013. total+=resvals[k];
  115014. totalbits+=resbits[k];
  115015. }
  115016. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  115017. }*/
  115018. return(0);
  115019. }
  115020. /* a truncated packet here just means 'stop working'; it's not an error */
  115021. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115022. float **in,int ch,
  115023. long (*decodepart)(codebook *, float *,
  115024. oggpack_buffer *,int)){
  115025. long i,j,k,l,s;
  115026. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115027. vorbis_info_residue0 *info=look->info;
  115028. /* move all this setup out later */
  115029. int samples_per_partition=info->grouping;
  115030. int partitions_per_word=look->phrasebook->dim;
  115031. int n=info->end-info->begin;
  115032. int partvals=n/samples_per_partition;
  115033. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115034. int ***partword=(int***)alloca(ch*sizeof(*partword));
  115035. for(j=0;j<ch;j++)
  115036. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  115037. for(s=0;s<look->stages;s++){
  115038. /* each loop decodes on partition codeword containing
  115039. partitions_pre_word partitions */
  115040. for(i=0,l=0;i<partvals;l++){
  115041. if(s==0){
  115042. /* fetch the partition word for each channel */
  115043. for(j=0;j<ch;j++){
  115044. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115045. if(temp==-1)goto eopbreak;
  115046. partword[j][l]=look->decodemap[temp];
  115047. if(partword[j][l]==NULL)goto errout;
  115048. }
  115049. }
  115050. /* now we decode residual values for the partitions */
  115051. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115052. for(j=0;j<ch;j++){
  115053. long offset=info->begin+i*samples_per_partition;
  115054. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  115055. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  115056. if(stagebook){
  115057. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  115058. samples_per_partition)==-1)goto eopbreak;
  115059. }
  115060. }
  115061. }
  115062. }
  115063. }
  115064. errout:
  115065. eopbreak:
  115066. return(0);
  115067. }
  115068. #if 0
  115069. /* residue 0 and 1 are just slight variants of one another. 0 is
  115070. interleaved, 1 is not */
  115071. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  115072. float **in,int *nonzero,int ch){
  115073. /* we encode only the nonzero parts of a bundle */
  115074. int i,used=0;
  115075. for(i=0;i<ch;i++)
  115076. if(nonzero[i])
  115077. in[used++]=in[i];
  115078. if(used)
  115079. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  115080. return(_01class(vb,vl,in,used));
  115081. else
  115082. return(0);
  115083. }
  115084. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  115085. float **in,float **out,int *nonzero,int ch,
  115086. long **partword){
  115087. /* we encode only the nonzero parts of a bundle */
  115088. int i,j,used=0,n=vb->pcmend/2;
  115089. for(i=0;i<ch;i++)
  115090. if(nonzero[i]){
  115091. if(out)
  115092. for(j=0;j<n;j++)
  115093. out[i][j]+=in[i][j];
  115094. in[used++]=in[i];
  115095. }
  115096. if(used){
  115097. int ret=_01forward(vb,vl,in,used,partword,
  115098. _interleaved_encodepart);
  115099. if(out){
  115100. used=0;
  115101. for(i=0;i<ch;i++)
  115102. if(nonzero[i]){
  115103. for(j=0;j<n;j++)
  115104. out[i][j]-=in[used][j];
  115105. used++;
  115106. }
  115107. }
  115108. return(ret);
  115109. }else{
  115110. return(0);
  115111. }
  115112. }
  115113. #endif
  115114. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115115. float **in,int *nonzero,int ch){
  115116. int i,used=0;
  115117. for(i=0;i<ch;i++)
  115118. if(nonzero[i])
  115119. in[used++]=in[i];
  115120. if(used)
  115121. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  115122. else
  115123. return(0);
  115124. }
  115125. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  115126. float **in,float **out,int *nonzero,int ch,
  115127. long **partword){
  115128. int i,j,used=0,n=vb->pcmend/2;
  115129. for(i=0;i<ch;i++)
  115130. if(nonzero[i]){
  115131. if(out)
  115132. for(j=0;j<n;j++)
  115133. out[i][j]+=in[i][j];
  115134. in[used++]=in[i];
  115135. }
  115136. if(used){
  115137. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  115138. if(out){
  115139. used=0;
  115140. for(i=0;i<ch;i++)
  115141. if(nonzero[i]){
  115142. for(j=0;j<n;j++)
  115143. out[i][j]-=in[used][j];
  115144. used++;
  115145. }
  115146. }
  115147. return(ret);
  115148. }else{
  115149. return(0);
  115150. }
  115151. }
  115152. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  115153. float **in,int *nonzero,int ch){
  115154. int i,used=0;
  115155. for(i=0;i<ch;i++)
  115156. if(nonzero[i])
  115157. in[used++]=in[i];
  115158. if(used)
  115159. return(_01class(vb,vl,in,used));
  115160. else
  115161. return(0);
  115162. }
  115163. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115164. float **in,int *nonzero,int ch){
  115165. int i,used=0;
  115166. for(i=0;i<ch;i++)
  115167. if(nonzero[i])
  115168. in[used++]=in[i];
  115169. if(used)
  115170. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  115171. else
  115172. return(0);
  115173. }
  115174. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  115175. float **in,int *nonzero,int ch){
  115176. int i,used=0;
  115177. for(i=0;i<ch;i++)
  115178. if(nonzero[i])used++;
  115179. if(used)
  115180. return(_2class(vb,vl,in,ch));
  115181. else
  115182. return(0);
  115183. }
  115184. /* res2 is slightly more different; all the channels are interleaved
  115185. into a single vector and encoded. */
  115186. int res2_forward(oggpack_buffer *opb,
  115187. vorbis_block *vb,vorbis_look_residue *vl,
  115188. float **in,float **out,int *nonzero,int ch,
  115189. long **partword){
  115190. long i,j,k,n=vb->pcmend/2,used=0;
  115191. /* don't duplicate the code; use a working vector hack for now and
  115192. reshape ourselves into a single channel res1 */
  115193. /* ugly; reallocs for each coupling pass :-( */
  115194. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  115195. for(i=0;i<ch;i++){
  115196. float *pcm=in[i];
  115197. if(nonzero[i])used++;
  115198. for(j=0,k=i;j<n;j++,k+=ch)
  115199. work[k]=pcm[j];
  115200. }
  115201. if(used){
  115202. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  115203. /* update the sofar vector */
  115204. if(out){
  115205. for(i=0;i<ch;i++){
  115206. float *pcm=in[i];
  115207. float *sofar=out[i];
  115208. for(j=0,k=i;j<n;j++,k+=ch)
  115209. sofar[j]+=pcm[j]-work[k];
  115210. }
  115211. }
  115212. return(ret);
  115213. }else{
  115214. return(0);
  115215. }
  115216. }
  115217. /* duplicate code here as speed is somewhat more important */
  115218. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115219. float **in,int *nonzero,int ch){
  115220. long i,k,l,s;
  115221. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115222. vorbis_info_residue0 *info=look->info;
  115223. /* move all this setup out later */
  115224. int samples_per_partition=info->grouping;
  115225. int partitions_per_word=look->phrasebook->dim;
  115226. int n=info->end-info->begin;
  115227. int partvals=n/samples_per_partition;
  115228. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115229. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  115230. for(i=0;i<ch;i++)if(nonzero[i])break;
  115231. if(i==ch)return(0); /* no nonzero vectors */
  115232. for(s=0;s<look->stages;s++){
  115233. for(i=0,l=0;i<partvals;l++){
  115234. if(s==0){
  115235. /* fetch the partition word */
  115236. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115237. if(temp==-1)goto eopbreak;
  115238. partword[l]=look->decodemap[temp];
  115239. if(partword[l]==NULL)goto errout;
  115240. }
  115241. /* now we decode residual values for the partitions */
  115242. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115243. if(info->secondstages[partword[l][k]]&(1<<s)){
  115244. codebook *stagebook=look->partbooks[partword[l][k]][s];
  115245. if(stagebook){
  115246. if(vorbis_book_decodevv_add(stagebook,in,
  115247. i*samples_per_partition+info->begin,ch,
  115248. &vb->opb,samples_per_partition)==-1)
  115249. goto eopbreak;
  115250. }
  115251. }
  115252. }
  115253. }
  115254. errout:
  115255. eopbreak:
  115256. return(0);
  115257. }
  115258. vorbis_func_residue residue0_exportbundle={
  115259. NULL,
  115260. &res0_unpack,
  115261. &res0_look,
  115262. &res0_free_info,
  115263. &res0_free_look,
  115264. NULL,
  115265. NULL,
  115266. &res0_inverse
  115267. };
  115268. vorbis_func_residue residue1_exportbundle={
  115269. &res0_pack,
  115270. &res0_unpack,
  115271. &res0_look,
  115272. &res0_free_info,
  115273. &res0_free_look,
  115274. &res1_class,
  115275. &res1_forward,
  115276. &res1_inverse
  115277. };
  115278. vorbis_func_residue residue2_exportbundle={
  115279. &res0_pack,
  115280. &res0_unpack,
  115281. &res0_look,
  115282. &res0_free_info,
  115283. &res0_free_look,
  115284. &res2_class,
  115285. &res2_forward,
  115286. &res2_inverse
  115287. };
  115288. #endif
  115289. /*** End of inlined file: res0.c ***/
  115290. /*** Start of inlined file: sharedbook.c ***/
  115291. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115292. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115293. // tasks..
  115294. #if JUCE_MSVC
  115295. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115296. #endif
  115297. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115298. #if JUCE_USE_OGGVORBIS
  115299. #include <stdlib.h>
  115300. #include <math.h>
  115301. #include <string.h>
  115302. /**** pack/unpack helpers ******************************************/
  115303. int _ilog(unsigned int v){
  115304. int ret=0;
  115305. while(v){
  115306. ret++;
  115307. v>>=1;
  115308. }
  115309. return(ret);
  115310. }
  115311. /* 32 bit float (not IEEE; nonnormalized mantissa +
  115312. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  115313. Why not IEEE? It's just not that important here. */
  115314. #define VQ_FEXP 10
  115315. #define VQ_FMAN 21
  115316. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  115317. /* doesn't currently guard under/overflow */
  115318. long _float32_pack(float val){
  115319. int sign=0;
  115320. long exp;
  115321. long mant;
  115322. if(val<0){
  115323. sign=0x80000000;
  115324. val= -val;
  115325. }
  115326. exp= floor(log(val)/log(2.f));
  115327. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  115328. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  115329. return(sign|exp|mant);
  115330. }
  115331. float _float32_unpack(long val){
  115332. double mant=val&0x1fffff;
  115333. int sign=val&0x80000000;
  115334. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  115335. if(sign)mant= -mant;
  115336. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  115337. }
  115338. /* given a list of word lengths, generate a list of codewords. Works
  115339. for length ordered or unordered, always assigns the lowest valued
  115340. codewords first. Extended to handle unused entries (length 0) */
  115341. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  115342. long i,j,count=0;
  115343. ogg_uint32_t marker[33];
  115344. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  115345. memset(marker,0,sizeof(marker));
  115346. for(i=0;i<n;i++){
  115347. long length=l[i];
  115348. if(length>0){
  115349. ogg_uint32_t entry=marker[length];
  115350. /* when we claim a node for an entry, we also claim the nodes
  115351. below it (pruning off the imagined tree that may have dangled
  115352. from it) as well as blocking the use of any nodes directly
  115353. above for leaves */
  115354. /* update ourself */
  115355. if(length<32 && (entry>>length)){
  115356. /* error condition; the lengths must specify an overpopulated tree */
  115357. _ogg_free(r);
  115358. return(NULL);
  115359. }
  115360. r[count++]=entry;
  115361. /* Look to see if the next shorter marker points to the node
  115362. above. if so, update it and repeat. */
  115363. {
  115364. for(j=length;j>0;j--){
  115365. if(marker[j]&1){
  115366. /* have to jump branches */
  115367. if(j==1)
  115368. marker[1]++;
  115369. else
  115370. marker[j]=marker[j-1]<<1;
  115371. break; /* invariant says next upper marker would already
  115372. have been moved if it was on the same path */
  115373. }
  115374. marker[j]++;
  115375. }
  115376. }
  115377. /* prune the tree; the implicit invariant says all the longer
  115378. markers were dangling from our just-taken node. Dangle them
  115379. from our *new* node. */
  115380. for(j=length+1;j<33;j++)
  115381. if((marker[j]>>1) == entry){
  115382. entry=marker[j];
  115383. marker[j]=marker[j-1]<<1;
  115384. }else
  115385. break;
  115386. }else
  115387. if(sparsecount==0)count++;
  115388. }
  115389. /* bitreverse the words because our bitwise packer/unpacker is LSb
  115390. endian */
  115391. for(i=0,count=0;i<n;i++){
  115392. ogg_uint32_t temp=0;
  115393. for(j=0;j<l[i];j++){
  115394. temp<<=1;
  115395. temp|=(r[count]>>j)&1;
  115396. }
  115397. if(sparsecount){
  115398. if(l[i])
  115399. r[count++]=temp;
  115400. }else
  115401. r[count++]=temp;
  115402. }
  115403. return(r);
  115404. }
  115405. /* there might be a straightforward one-line way to do the below
  115406. that's portable and totally safe against roundoff, but I haven't
  115407. thought of it. Therefore, we opt on the side of caution */
  115408. long _book_maptype1_quantvals(const static_codebook *b){
  115409. long vals=floor(pow((float)b->entries,1.f/b->dim));
  115410. /* the above *should* be reliable, but we'll not assume that FP is
  115411. ever reliable when bitstream sync is at stake; verify via integer
  115412. means that vals really is the greatest value of dim for which
  115413. vals^b->bim <= b->entries */
  115414. /* treat the above as an initial guess */
  115415. while(1){
  115416. long acc=1;
  115417. long acc1=1;
  115418. int i;
  115419. for(i=0;i<b->dim;i++){
  115420. acc*=vals;
  115421. acc1*=vals+1;
  115422. }
  115423. if(acc<=b->entries && acc1>b->entries){
  115424. return(vals);
  115425. }else{
  115426. if(acc>b->entries){
  115427. vals--;
  115428. }else{
  115429. vals++;
  115430. }
  115431. }
  115432. }
  115433. }
  115434. /* unpack the quantized list of values for encode/decode ***********/
  115435. /* we need to deal with two map types: in map type 1, the values are
  115436. generated algorithmically (each column of the vector counts through
  115437. the values in the quant vector). in map type 2, all the values came
  115438. in in an explicit list. Both value lists must be unpacked */
  115439. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  115440. long j,k,count=0;
  115441. if(b->maptype==1 || b->maptype==2){
  115442. int quantvals;
  115443. float mindel=_float32_unpack(b->q_min);
  115444. float delta=_float32_unpack(b->q_delta);
  115445. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  115446. /* maptype 1 and 2 both use a quantized value vector, but
  115447. different sizes */
  115448. switch(b->maptype){
  115449. case 1:
  115450. /* most of the time, entries%dimensions == 0, but we need to be
  115451. well defined. We define that the possible vales at each
  115452. scalar is values == entries/dim. If entries%dim != 0, we'll
  115453. have 'too few' values (values*dim<entries), which means that
  115454. we'll have 'left over' entries; left over entries use zeroed
  115455. values (and are wasted). So don't generate codebooks like
  115456. that */
  115457. quantvals=_book_maptype1_quantvals(b);
  115458. for(j=0;j<b->entries;j++){
  115459. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  115460. float last=0.f;
  115461. int indexdiv=1;
  115462. for(k=0;k<b->dim;k++){
  115463. int index= (j/indexdiv)%quantvals;
  115464. float val=b->quantlist[index];
  115465. val=fabs(val)*delta+mindel+last;
  115466. if(b->q_sequencep)last=val;
  115467. if(sparsemap)
  115468. r[sparsemap[count]*b->dim+k]=val;
  115469. else
  115470. r[count*b->dim+k]=val;
  115471. indexdiv*=quantvals;
  115472. }
  115473. count++;
  115474. }
  115475. }
  115476. break;
  115477. case 2:
  115478. for(j=0;j<b->entries;j++){
  115479. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  115480. float last=0.f;
  115481. for(k=0;k<b->dim;k++){
  115482. float val=b->quantlist[j*b->dim+k];
  115483. val=fabs(val)*delta+mindel+last;
  115484. if(b->q_sequencep)last=val;
  115485. if(sparsemap)
  115486. r[sparsemap[count]*b->dim+k]=val;
  115487. else
  115488. r[count*b->dim+k]=val;
  115489. }
  115490. count++;
  115491. }
  115492. }
  115493. break;
  115494. }
  115495. return(r);
  115496. }
  115497. return(NULL);
  115498. }
  115499. void vorbis_staticbook_clear(static_codebook *b){
  115500. if(b->allocedp){
  115501. if(b->quantlist)_ogg_free(b->quantlist);
  115502. if(b->lengthlist)_ogg_free(b->lengthlist);
  115503. if(b->nearest_tree){
  115504. _ogg_free(b->nearest_tree->ptr0);
  115505. _ogg_free(b->nearest_tree->ptr1);
  115506. _ogg_free(b->nearest_tree->p);
  115507. _ogg_free(b->nearest_tree->q);
  115508. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  115509. _ogg_free(b->nearest_tree);
  115510. }
  115511. if(b->thresh_tree){
  115512. _ogg_free(b->thresh_tree->quantthresh);
  115513. _ogg_free(b->thresh_tree->quantmap);
  115514. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  115515. _ogg_free(b->thresh_tree);
  115516. }
  115517. memset(b,0,sizeof(*b));
  115518. }
  115519. }
  115520. void vorbis_staticbook_destroy(static_codebook *b){
  115521. if(b->allocedp){
  115522. vorbis_staticbook_clear(b);
  115523. _ogg_free(b);
  115524. }
  115525. }
  115526. void vorbis_book_clear(codebook *b){
  115527. /* static book is not cleared; we're likely called on the lookup and
  115528. the static codebook belongs to the info struct */
  115529. if(b->valuelist)_ogg_free(b->valuelist);
  115530. if(b->codelist)_ogg_free(b->codelist);
  115531. if(b->dec_index)_ogg_free(b->dec_index);
  115532. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  115533. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  115534. memset(b,0,sizeof(*b));
  115535. }
  115536. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  115537. memset(c,0,sizeof(*c));
  115538. c->c=s;
  115539. c->entries=s->entries;
  115540. c->used_entries=s->entries;
  115541. c->dim=s->dim;
  115542. c->codelist=_make_words(s->lengthlist,s->entries,0);
  115543. c->valuelist=_book_unquantize(s,s->entries,NULL);
  115544. return(0);
  115545. }
  115546. static int sort32a(const void *a,const void *b){
  115547. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  115548. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  115549. }
  115550. /* decode codebook arrangement is more heavily optimized than encode */
  115551. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  115552. int i,j,n=0,tabn;
  115553. int *sortindex;
  115554. memset(c,0,sizeof(*c));
  115555. /* count actually used entries */
  115556. for(i=0;i<s->entries;i++)
  115557. if(s->lengthlist[i]>0)
  115558. n++;
  115559. c->entries=s->entries;
  115560. c->used_entries=n;
  115561. c->dim=s->dim;
  115562. /* two different remappings go on here.
  115563. First, we collapse the likely sparse codebook down only to
  115564. actually represented values/words. This collapsing needs to be
  115565. indexed as map-valueless books are used to encode original entry
  115566. positions as integers.
  115567. Second, we reorder all vectors, including the entry index above,
  115568. by sorted bitreversed codeword to allow treeless decode. */
  115569. {
  115570. /* perform sort */
  115571. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  115572. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  115573. if(codes==NULL)goto err_out;
  115574. for(i=0;i<n;i++){
  115575. codes[i]=ogg_bitreverse(codes[i]);
  115576. codep[i]=codes+i;
  115577. }
  115578. qsort(codep,n,sizeof(*codep),sort32a);
  115579. sortindex=(int*)alloca(n*sizeof(*sortindex));
  115580. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  115581. /* the index is a reverse index */
  115582. for(i=0;i<n;i++){
  115583. int position=codep[i]-codes;
  115584. sortindex[position]=i;
  115585. }
  115586. for(i=0;i<n;i++)
  115587. c->codelist[sortindex[i]]=codes[i];
  115588. _ogg_free(codes);
  115589. }
  115590. c->valuelist=_book_unquantize(s,n,sortindex);
  115591. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  115592. for(n=0,i=0;i<s->entries;i++)
  115593. if(s->lengthlist[i]>0)
  115594. c->dec_index[sortindex[n++]]=i;
  115595. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  115596. for(n=0,i=0;i<s->entries;i++)
  115597. if(s->lengthlist[i]>0)
  115598. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  115599. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  115600. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  115601. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  115602. tabn=1<<c->dec_firsttablen;
  115603. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  115604. c->dec_maxlength=0;
  115605. for(i=0;i<n;i++){
  115606. if(c->dec_maxlength<c->dec_codelengths[i])
  115607. c->dec_maxlength=c->dec_codelengths[i];
  115608. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  115609. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  115610. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  115611. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  115612. }
  115613. }
  115614. /* now fill in 'unused' entries in the firsttable with hi/lo search
  115615. hints for the non-direct-hits */
  115616. {
  115617. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  115618. long lo=0,hi=0;
  115619. for(i=0;i<tabn;i++){
  115620. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  115621. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  115622. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  115623. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  115624. /* we only actually have 15 bits per hint to play with here.
  115625. In order to overflow gracefully (nothing breaks, efficiency
  115626. just drops), encode as the difference from the extremes. */
  115627. {
  115628. unsigned long loval=lo;
  115629. unsigned long hival=n-hi;
  115630. if(loval>0x7fff)loval=0x7fff;
  115631. if(hival>0x7fff)hival=0x7fff;
  115632. c->dec_firsttable[ogg_bitreverse(word)]=
  115633. 0x80000000UL | (loval<<15) | hival;
  115634. }
  115635. }
  115636. }
  115637. }
  115638. return(0);
  115639. err_out:
  115640. vorbis_book_clear(c);
  115641. return(-1);
  115642. }
  115643. static float _dist(int el,float *ref, float *b,int step){
  115644. int i;
  115645. float acc=0.f;
  115646. for(i=0;i<el;i++){
  115647. float val=(ref[i]-b[i*step]);
  115648. acc+=val*val;
  115649. }
  115650. return(acc);
  115651. }
  115652. int _best(codebook *book, float *a, int step){
  115653. encode_aux_threshmatch *tt=book->c->thresh_tree;
  115654. #if 0
  115655. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  115656. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  115657. #endif
  115658. int dim=book->dim;
  115659. int k,o;
  115660. /*int savebest=-1;
  115661. float saverr;*/
  115662. /* do we have a threshhold encode hint? */
  115663. if(tt){
  115664. int index=0,i;
  115665. /* find the quant val of each scalar */
  115666. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  115667. i=tt->threshvals>>1;
  115668. if(a[o]<tt->quantthresh[i]){
  115669. for(;i>0;i--)
  115670. if(a[o]>=tt->quantthresh[i-1])
  115671. break;
  115672. }else{
  115673. for(i++;i<tt->threshvals-1;i++)
  115674. if(a[o]<tt->quantthresh[i])break;
  115675. }
  115676. index=(index*tt->quantvals)+tt->quantmap[i];
  115677. }
  115678. /* regular lattices are easy :-) */
  115679. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  115680. use a decision tree after all
  115681. and fall through*/
  115682. return(index);
  115683. }
  115684. #if 0
  115685. /* do we have a pigeonhole encode hint? */
  115686. if(pt){
  115687. const static_codebook *c=book->c;
  115688. int i,besti=-1;
  115689. float best=0.f;
  115690. int entry=0;
  115691. /* dealing with sequentialness is a pain in the ass */
  115692. if(c->q_sequencep){
  115693. int pv;
  115694. long mul=1;
  115695. float qlast=0;
  115696. for(k=0,o=0;k<dim;k++,o+=step){
  115697. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  115698. if(pv<0 || pv>=pt->mapentries)break;
  115699. entry+=pt->pigeonmap[pv]*mul;
  115700. mul*=pt->quantvals;
  115701. qlast+=pv*pt->del+pt->min;
  115702. }
  115703. }else{
  115704. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  115705. int pv=(int)((a[o]-pt->min)/pt->del);
  115706. if(pv<0 || pv>=pt->mapentries)break;
  115707. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  115708. }
  115709. }
  115710. /* must be within the pigeonholable range; if we quant outside (or
  115711. in an entry that we define no list for), brute force it */
  115712. if(k==dim && pt->fitlength[entry]){
  115713. /* search the abbreviated list */
  115714. long *list=pt->fitlist+pt->fitmap[entry];
  115715. for(i=0;i<pt->fitlength[entry];i++){
  115716. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  115717. if(besti==-1 || this<best){
  115718. best=this;
  115719. besti=list[i];
  115720. }
  115721. }
  115722. return(besti);
  115723. }
  115724. }
  115725. if(nt){
  115726. /* optimized using the decision tree */
  115727. while(1){
  115728. float c=0.f;
  115729. float *p=book->valuelist+nt->p[ptr];
  115730. float *q=book->valuelist+nt->q[ptr];
  115731. for(k=0,o=0;k<dim;k++,o+=step)
  115732. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  115733. if(c>0.f) /* in A */
  115734. ptr= -nt->ptr0[ptr];
  115735. else /* in B */
  115736. ptr= -nt->ptr1[ptr];
  115737. if(ptr<=0)break;
  115738. }
  115739. return(-ptr);
  115740. }
  115741. #endif
  115742. /* brute force it! */
  115743. {
  115744. const static_codebook *c=book->c;
  115745. int i,besti=-1;
  115746. float best=0.f;
  115747. float *e=book->valuelist;
  115748. for(i=0;i<book->entries;i++){
  115749. if(c->lengthlist[i]>0){
  115750. float thisx=_dist(dim,e,a,step);
  115751. if(besti==-1 || thisx<best){
  115752. best=thisx;
  115753. besti=i;
  115754. }
  115755. }
  115756. e+=dim;
  115757. }
  115758. /*if(savebest!=-1 && savebest!=besti){
  115759. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  115760. "original:");
  115761. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  115762. fprintf(stderr,"\n"
  115763. "pigeonhole (entry %d, err %g):",savebest,saverr);
  115764. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  115765. (book->valuelist+savebest*dim)[i]);
  115766. fprintf(stderr,"\n"
  115767. "bruteforce (entry %d, err %g):",besti,best);
  115768. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  115769. (book->valuelist+besti*dim)[i]);
  115770. fprintf(stderr,"\n");
  115771. }*/
  115772. return(besti);
  115773. }
  115774. }
  115775. long vorbis_book_codeword(codebook *book,int entry){
  115776. if(book->c) /* only use with encode; decode optimizations are
  115777. allowed to break this */
  115778. return book->codelist[entry];
  115779. return -1;
  115780. }
  115781. long vorbis_book_codelen(codebook *book,int entry){
  115782. if(book->c) /* only use with encode; decode optimizations are
  115783. allowed to break this */
  115784. return book->c->lengthlist[entry];
  115785. return -1;
  115786. }
  115787. #ifdef _V_SELFTEST
  115788. /* Unit tests of the dequantizer; this stuff will be OK
  115789. cross-platform, I simply want to be sure that special mapping cases
  115790. actually work properly; a bug could go unnoticed for a while */
  115791. #include <stdio.h>
  115792. /* cases:
  115793. no mapping
  115794. full, explicit mapping
  115795. algorithmic mapping
  115796. nonsequential
  115797. sequential
  115798. */
  115799. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  115800. static long partial_quantlist1[]={0,7,2};
  115801. /* no mapping */
  115802. static_codebook test1={
  115803. 4,16,
  115804. NULL,
  115805. 0,
  115806. 0,0,0,0,
  115807. NULL,
  115808. NULL,NULL
  115809. };
  115810. static float *test1_result=NULL;
  115811. /* linear, full mapping, nonsequential */
  115812. static_codebook test2={
  115813. 4,3,
  115814. NULL,
  115815. 2,
  115816. -533200896,1611661312,4,0,
  115817. full_quantlist1,
  115818. NULL,NULL
  115819. };
  115820. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  115821. /* linear, full mapping, sequential */
  115822. static_codebook test3={
  115823. 4,3,
  115824. NULL,
  115825. 2,
  115826. -533200896,1611661312,4,1,
  115827. full_quantlist1,
  115828. NULL,NULL
  115829. };
  115830. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  115831. /* linear, algorithmic mapping, nonsequential */
  115832. static_codebook test4={
  115833. 3,27,
  115834. NULL,
  115835. 1,
  115836. -533200896,1611661312,4,0,
  115837. partial_quantlist1,
  115838. NULL,NULL
  115839. };
  115840. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  115841. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  115842. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  115843. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  115844. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  115845. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  115846. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  115847. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  115848. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  115849. /* linear, algorithmic mapping, sequential */
  115850. static_codebook test5={
  115851. 3,27,
  115852. NULL,
  115853. 1,
  115854. -533200896,1611661312,4,1,
  115855. partial_quantlist1,
  115856. NULL,NULL
  115857. };
  115858. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  115859. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  115860. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  115861. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  115862. -3, 1, 5, 4, 8,12, -1, 3, 7,
  115863. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  115864. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  115865. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  115866. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  115867. void run_test(static_codebook *b,float *comp){
  115868. float *out=_book_unquantize(b,b->entries,NULL);
  115869. int i;
  115870. if(comp){
  115871. if(!out){
  115872. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  115873. exit(1);
  115874. }
  115875. for(i=0;i<b->entries*b->dim;i++)
  115876. if(fabs(out[i]-comp[i])>.0001){
  115877. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  115878. "position %d, %g != %g\n",i,out[i],comp[i]);
  115879. exit(1);
  115880. }
  115881. }else{
  115882. if(out){
  115883. fprintf(stderr,"_book_unquantize returned a value array: \n"
  115884. " correct result should have been NULL\n");
  115885. exit(1);
  115886. }
  115887. }
  115888. }
  115889. int main(){
  115890. /* run the nine dequant tests, and compare to the hand-rolled results */
  115891. fprintf(stderr,"Dequant test 1... ");
  115892. run_test(&test1,test1_result);
  115893. fprintf(stderr,"OK\nDequant test 2... ");
  115894. run_test(&test2,test2_result);
  115895. fprintf(stderr,"OK\nDequant test 3... ");
  115896. run_test(&test3,test3_result);
  115897. fprintf(stderr,"OK\nDequant test 4... ");
  115898. run_test(&test4,test4_result);
  115899. fprintf(stderr,"OK\nDequant test 5... ");
  115900. run_test(&test5,test5_result);
  115901. fprintf(stderr,"OK\n\n");
  115902. return(0);
  115903. }
  115904. #endif
  115905. #endif
  115906. /*** End of inlined file: sharedbook.c ***/
  115907. /*** Start of inlined file: smallft.c ***/
  115908. /* FFT implementation from OggSquish, minus cosine transforms,
  115909. * minus all but radix 2/4 case. In Vorbis we only need this
  115910. * cut-down version.
  115911. *
  115912. * To do more than just power-of-two sized vectors, see the full
  115913. * version I wrote for NetLib.
  115914. *
  115915. * Note that the packing is a little strange; rather than the FFT r/i
  115916. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  115917. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  115918. * FORTRAN version
  115919. */
  115920. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115921. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115922. // tasks..
  115923. #if JUCE_MSVC
  115924. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115925. #endif
  115926. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115927. #if JUCE_USE_OGGVORBIS
  115928. #include <stdlib.h>
  115929. #include <string.h>
  115930. #include <math.h>
  115931. static void drfti1(int n, float *wa, int *ifac){
  115932. static int ntryh[4] = { 4,2,3,5 };
  115933. static float tpi = 6.28318530717958648f;
  115934. float arg,argh,argld,fi;
  115935. int ntry=0,i,j=-1;
  115936. int k1, l1, l2, ib;
  115937. int ld, ii, ip, is, nq, nr;
  115938. int ido, ipm, nfm1;
  115939. int nl=n;
  115940. int nf=0;
  115941. L101:
  115942. j++;
  115943. if (j < 4)
  115944. ntry=ntryh[j];
  115945. else
  115946. ntry+=2;
  115947. L104:
  115948. nq=nl/ntry;
  115949. nr=nl-ntry*nq;
  115950. if (nr!=0) goto L101;
  115951. nf++;
  115952. ifac[nf+1]=ntry;
  115953. nl=nq;
  115954. if(ntry!=2)goto L107;
  115955. if(nf==1)goto L107;
  115956. for (i=1;i<nf;i++){
  115957. ib=nf-i+1;
  115958. ifac[ib+1]=ifac[ib];
  115959. }
  115960. ifac[2] = 2;
  115961. L107:
  115962. if(nl!=1)goto L104;
  115963. ifac[0]=n;
  115964. ifac[1]=nf;
  115965. argh=tpi/n;
  115966. is=0;
  115967. nfm1=nf-1;
  115968. l1=1;
  115969. if(nfm1==0)return;
  115970. for (k1=0;k1<nfm1;k1++){
  115971. ip=ifac[k1+2];
  115972. ld=0;
  115973. l2=l1*ip;
  115974. ido=n/l2;
  115975. ipm=ip-1;
  115976. for (j=0;j<ipm;j++){
  115977. ld+=l1;
  115978. i=is;
  115979. argld=(float)ld*argh;
  115980. fi=0.f;
  115981. for (ii=2;ii<ido;ii+=2){
  115982. fi+=1.f;
  115983. arg=fi*argld;
  115984. wa[i++]=cos(arg);
  115985. wa[i++]=sin(arg);
  115986. }
  115987. is+=ido;
  115988. }
  115989. l1=l2;
  115990. }
  115991. }
  115992. static void fdrffti(int n, float *wsave, int *ifac){
  115993. if (n == 1) return;
  115994. drfti1(n, wsave+n, ifac);
  115995. }
  115996. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  115997. int i,k;
  115998. float ti2,tr2;
  115999. int t0,t1,t2,t3,t4,t5,t6;
  116000. t1=0;
  116001. t0=(t2=l1*ido);
  116002. t3=ido<<1;
  116003. for(k=0;k<l1;k++){
  116004. ch[t1<<1]=cc[t1]+cc[t2];
  116005. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  116006. t1+=ido;
  116007. t2+=ido;
  116008. }
  116009. if(ido<2)return;
  116010. if(ido==2)goto L105;
  116011. t1=0;
  116012. t2=t0;
  116013. for(k=0;k<l1;k++){
  116014. t3=t2;
  116015. t4=(t1<<1)+(ido<<1);
  116016. t5=t1;
  116017. t6=t1+t1;
  116018. for(i=2;i<ido;i+=2){
  116019. t3+=2;
  116020. t4-=2;
  116021. t5+=2;
  116022. t6+=2;
  116023. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116024. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116025. ch[t6]=cc[t5]+ti2;
  116026. ch[t4]=ti2-cc[t5];
  116027. ch[t6-1]=cc[t5-1]+tr2;
  116028. ch[t4-1]=cc[t5-1]-tr2;
  116029. }
  116030. t1+=ido;
  116031. t2+=ido;
  116032. }
  116033. if(ido%2==1)return;
  116034. L105:
  116035. t3=(t2=(t1=ido)-1);
  116036. t2+=t0;
  116037. for(k=0;k<l1;k++){
  116038. ch[t1]=-cc[t2];
  116039. ch[t1-1]=cc[t3];
  116040. t1+=ido<<1;
  116041. t2+=ido;
  116042. t3+=ido;
  116043. }
  116044. }
  116045. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  116046. float *wa2,float *wa3){
  116047. static float hsqt2 = .70710678118654752f;
  116048. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116049. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  116050. t0=l1*ido;
  116051. t1=t0;
  116052. t4=t1<<1;
  116053. t2=t1+(t1<<1);
  116054. t3=0;
  116055. for(k=0;k<l1;k++){
  116056. tr1=cc[t1]+cc[t2];
  116057. tr2=cc[t3]+cc[t4];
  116058. ch[t5=t3<<2]=tr1+tr2;
  116059. ch[(ido<<2)+t5-1]=tr2-tr1;
  116060. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  116061. ch[t5]=cc[t2]-cc[t1];
  116062. t1+=ido;
  116063. t2+=ido;
  116064. t3+=ido;
  116065. t4+=ido;
  116066. }
  116067. if(ido<2)return;
  116068. if(ido==2)goto L105;
  116069. t1=0;
  116070. for(k=0;k<l1;k++){
  116071. t2=t1;
  116072. t4=t1<<2;
  116073. t5=(t6=ido<<1)+t4;
  116074. for(i=2;i<ido;i+=2){
  116075. t3=(t2+=2);
  116076. t4+=2;
  116077. t5-=2;
  116078. t3+=t0;
  116079. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116080. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116081. t3+=t0;
  116082. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  116083. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  116084. t3+=t0;
  116085. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  116086. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  116087. tr1=cr2+cr4;
  116088. tr4=cr4-cr2;
  116089. ti1=ci2+ci4;
  116090. ti4=ci2-ci4;
  116091. ti2=cc[t2]+ci3;
  116092. ti3=cc[t2]-ci3;
  116093. tr2=cc[t2-1]+cr3;
  116094. tr3=cc[t2-1]-cr3;
  116095. ch[t4-1]=tr1+tr2;
  116096. ch[t4]=ti1+ti2;
  116097. ch[t5-1]=tr3-ti4;
  116098. ch[t5]=tr4-ti3;
  116099. ch[t4+t6-1]=ti4+tr3;
  116100. ch[t4+t6]=tr4+ti3;
  116101. ch[t5+t6-1]=tr2-tr1;
  116102. ch[t5+t6]=ti1-ti2;
  116103. }
  116104. t1+=ido;
  116105. }
  116106. if(ido&1)return;
  116107. L105:
  116108. t2=(t1=t0+ido-1)+(t0<<1);
  116109. t3=ido<<2;
  116110. t4=ido;
  116111. t5=ido<<1;
  116112. t6=ido;
  116113. for(k=0;k<l1;k++){
  116114. ti1=-hsqt2*(cc[t1]+cc[t2]);
  116115. tr1=hsqt2*(cc[t1]-cc[t2]);
  116116. ch[t4-1]=tr1+cc[t6-1];
  116117. ch[t4+t5-1]=cc[t6-1]-tr1;
  116118. ch[t4]=ti1-cc[t1+t0];
  116119. ch[t4+t5]=ti1+cc[t1+t0];
  116120. t1+=ido;
  116121. t2+=ido;
  116122. t4+=t3;
  116123. t6+=ido;
  116124. }
  116125. }
  116126. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  116127. float *c2,float *ch,float *ch2,float *wa){
  116128. static float tpi=6.283185307179586f;
  116129. int idij,ipph,i,j,k,l,ic,ik,is;
  116130. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  116131. float dc2,ai1,ai2,ar1,ar2,ds2;
  116132. int nbd;
  116133. float dcp,arg,dsp,ar1h,ar2h;
  116134. int idp2,ipp2;
  116135. arg=tpi/(float)ip;
  116136. dcp=cos(arg);
  116137. dsp=sin(arg);
  116138. ipph=(ip+1)>>1;
  116139. ipp2=ip;
  116140. idp2=ido;
  116141. nbd=(ido-1)>>1;
  116142. t0=l1*ido;
  116143. t10=ip*ido;
  116144. if(ido==1)goto L119;
  116145. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  116146. t1=0;
  116147. for(j=1;j<ip;j++){
  116148. t1+=t0;
  116149. t2=t1;
  116150. for(k=0;k<l1;k++){
  116151. ch[t2]=c1[t2];
  116152. t2+=ido;
  116153. }
  116154. }
  116155. is=-ido;
  116156. t1=0;
  116157. if(nbd>l1){
  116158. for(j=1;j<ip;j++){
  116159. t1+=t0;
  116160. is+=ido;
  116161. t2= -ido+t1;
  116162. for(k=0;k<l1;k++){
  116163. idij=is-1;
  116164. t2+=ido;
  116165. t3=t2;
  116166. for(i=2;i<ido;i+=2){
  116167. idij+=2;
  116168. t3+=2;
  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. }
  116172. }
  116173. }
  116174. }else{
  116175. for(j=1;j<ip;j++){
  116176. is+=ido;
  116177. idij=is-1;
  116178. t1+=t0;
  116179. t2=t1;
  116180. for(i=2;i<ido;i+=2){
  116181. idij+=2;
  116182. t2+=2;
  116183. t3=t2;
  116184. for(k=0;k<l1;k++){
  116185. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116186. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116187. t3+=ido;
  116188. }
  116189. }
  116190. }
  116191. }
  116192. t1=0;
  116193. t2=ipp2*t0;
  116194. if(nbd<l1){
  116195. for(j=1;j<ipph;j++){
  116196. t1+=t0;
  116197. t2-=t0;
  116198. t3=t1;
  116199. t4=t2;
  116200. for(i=2;i<ido;i+=2){
  116201. t3+=2;
  116202. t4+=2;
  116203. t5=t3-ido;
  116204. t6=t4-ido;
  116205. for(k=0;k<l1;k++){
  116206. t5+=ido;
  116207. t6+=ido;
  116208. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116209. c1[t6-1]=ch[t5]-ch[t6];
  116210. c1[t5]=ch[t5]+ch[t6];
  116211. c1[t6]=ch[t6-1]-ch[t5-1];
  116212. }
  116213. }
  116214. }
  116215. }else{
  116216. for(j=1;j<ipph;j++){
  116217. t1+=t0;
  116218. t2-=t0;
  116219. t3=t1;
  116220. t4=t2;
  116221. for(k=0;k<l1;k++){
  116222. t5=t3;
  116223. t6=t4;
  116224. for(i=2;i<ido;i+=2){
  116225. t5+=2;
  116226. t6+=2;
  116227. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116228. c1[t6-1]=ch[t5]-ch[t6];
  116229. c1[t5]=ch[t5]+ch[t6];
  116230. c1[t6]=ch[t6-1]-ch[t5-1];
  116231. }
  116232. t3+=ido;
  116233. t4+=ido;
  116234. }
  116235. }
  116236. }
  116237. L119:
  116238. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116239. t1=0;
  116240. t2=ipp2*idl1;
  116241. for(j=1;j<ipph;j++){
  116242. t1+=t0;
  116243. t2-=t0;
  116244. t3=t1-ido;
  116245. t4=t2-ido;
  116246. for(k=0;k<l1;k++){
  116247. t3+=ido;
  116248. t4+=ido;
  116249. c1[t3]=ch[t3]+ch[t4];
  116250. c1[t4]=ch[t4]-ch[t3];
  116251. }
  116252. }
  116253. ar1=1.f;
  116254. ai1=0.f;
  116255. t1=0;
  116256. t2=ipp2*idl1;
  116257. t3=(ip-1)*idl1;
  116258. for(l=1;l<ipph;l++){
  116259. t1+=idl1;
  116260. t2-=idl1;
  116261. ar1h=dcp*ar1-dsp*ai1;
  116262. ai1=dcp*ai1+dsp*ar1;
  116263. ar1=ar1h;
  116264. t4=t1;
  116265. t5=t2;
  116266. t6=t3;
  116267. t7=idl1;
  116268. for(ik=0;ik<idl1;ik++){
  116269. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  116270. ch2[t5++]=ai1*c2[t6++];
  116271. }
  116272. dc2=ar1;
  116273. ds2=ai1;
  116274. ar2=ar1;
  116275. ai2=ai1;
  116276. t4=idl1;
  116277. t5=(ipp2-1)*idl1;
  116278. for(j=2;j<ipph;j++){
  116279. t4+=idl1;
  116280. t5-=idl1;
  116281. ar2h=dc2*ar2-ds2*ai2;
  116282. ai2=dc2*ai2+ds2*ar2;
  116283. ar2=ar2h;
  116284. t6=t1;
  116285. t7=t2;
  116286. t8=t4;
  116287. t9=t5;
  116288. for(ik=0;ik<idl1;ik++){
  116289. ch2[t6++]+=ar2*c2[t8++];
  116290. ch2[t7++]+=ai2*c2[t9++];
  116291. }
  116292. }
  116293. }
  116294. t1=0;
  116295. for(j=1;j<ipph;j++){
  116296. t1+=idl1;
  116297. t2=t1;
  116298. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  116299. }
  116300. if(ido<l1)goto L132;
  116301. t1=0;
  116302. t2=0;
  116303. for(k=0;k<l1;k++){
  116304. t3=t1;
  116305. t4=t2;
  116306. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  116307. t1+=ido;
  116308. t2+=t10;
  116309. }
  116310. goto L135;
  116311. L132:
  116312. for(i=0;i<ido;i++){
  116313. t1=i;
  116314. t2=i;
  116315. for(k=0;k<l1;k++){
  116316. cc[t2]=ch[t1];
  116317. t1+=ido;
  116318. t2+=t10;
  116319. }
  116320. }
  116321. L135:
  116322. t1=0;
  116323. t2=ido<<1;
  116324. t3=0;
  116325. t4=ipp2*t0;
  116326. for(j=1;j<ipph;j++){
  116327. t1+=t2;
  116328. t3+=t0;
  116329. t4-=t0;
  116330. t5=t1;
  116331. t6=t3;
  116332. t7=t4;
  116333. for(k=0;k<l1;k++){
  116334. cc[t5-1]=ch[t6];
  116335. cc[t5]=ch[t7];
  116336. t5+=t10;
  116337. t6+=ido;
  116338. t7+=ido;
  116339. }
  116340. }
  116341. if(ido==1)return;
  116342. if(nbd<l1)goto L141;
  116343. t1=-ido;
  116344. t3=0;
  116345. t4=0;
  116346. t5=ipp2*t0;
  116347. for(j=1;j<ipph;j++){
  116348. t1+=t2;
  116349. t3+=t2;
  116350. t4+=t0;
  116351. t5-=t0;
  116352. t6=t1;
  116353. t7=t3;
  116354. t8=t4;
  116355. t9=t5;
  116356. for(k=0;k<l1;k++){
  116357. for(i=2;i<ido;i+=2){
  116358. ic=idp2-i;
  116359. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  116360. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  116361. cc[i+t7]=ch[i+t8]+ch[i+t9];
  116362. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  116363. }
  116364. t6+=t10;
  116365. t7+=t10;
  116366. t8+=ido;
  116367. t9+=ido;
  116368. }
  116369. }
  116370. return;
  116371. L141:
  116372. t1=-ido;
  116373. t3=0;
  116374. t4=0;
  116375. t5=ipp2*t0;
  116376. for(j=1;j<ipph;j++){
  116377. t1+=t2;
  116378. t3+=t2;
  116379. t4+=t0;
  116380. t5-=t0;
  116381. for(i=2;i<ido;i+=2){
  116382. t6=idp2+t1-i;
  116383. t7=i+t3;
  116384. t8=i+t4;
  116385. t9=i+t5;
  116386. for(k=0;k<l1;k++){
  116387. cc[t7-1]=ch[t8-1]+ch[t9-1];
  116388. cc[t6-1]=ch[t8-1]-ch[t9-1];
  116389. cc[t7]=ch[t8]+ch[t9];
  116390. cc[t6]=ch[t9]-ch[t8];
  116391. t6+=t10;
  116392. t7+=t10;
  116393. t8+=ido;
  116394. t9+=ido;
  116395. }
  116396. }
  116397. }
  116398. }
  116399. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  116400. int i,k1,l1,l2;
  116401. int na,kh,nf;
  116402. int ip,iw,ido,idl1,ix2,ix3;
  116403. nf=ifac[1];
  116404. na=1;
  116405. l2=n;
  116406. iw=n;
  116407. for(k1=0;k1<nf;k1++){
  116408. kh=nf-k1;
  116409. ip=ifac[kh+1];
  116410. l1=l2/ip;
  116411. ido=n/l2;
  116412. idl1=ido*l1;
  116413. iw-=(ip-1)*ido;
  116414. na=1-na;
  116415. if(ip!=4)goto L102;
  116416. ix2=iw+ido;
  116417. ix3=ix2+ido;
  116418. if(na!=0)
  116419. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116420. else
  116421. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116422. goto L110;
  116423. L102:
  116424. if(ip!=2)goto L104;
  116425. if(na!=0)goto L103;
  116426. dradf2(ido,l1,c,ch,wa+iw-1);
  116427. goto L110;
  116428. L103:
  116429. dradf2(ido,l1,ch,c,wa+iw-1);
  116430. goto L110;
  116431. L104:
  116432. if(ido==1)na=1-na;
  116433. if(na!=0)goto L109;
  116434. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116435. na=1;
  116436. goto L110;
  116437. L109:
  116438. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116439. na=0;
  116440. L110:
  116441. l2=l1;
  116442. }
  116443. if(na==1)return;
  116444. for(i=0;i<n;i++)c[i]=ch[i];
  116445. }
  116446. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  116447. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116448. float ti2,tr2;
  116449. t0=l1*ido;
  116450. t1=0;
  116451. t2=0;
  116452. t3=(ido<<1)-1;
  116453. for(k=0;k<l1;k++){
  116454. ch[t1]=cc[t2]+cc[t3+t2];
  116455. ch[t1+t0]=cc[t2]-cc[t3+t2];
  116456. t2=(t1+=ido)<<1;
  116457. }
  116458. if(ido<2)return;
  116459. if(ido==2)goto L105;
  116460. t1=0;
  116461. t2=0;
  116462. for(k=0;k<l1;k++){
  116463. t3=t1;
  116464. t5=(t4=t2)+(ido<<1);
  116465. t6=t0+t1;
  116466. for(i=2;i<ido;i+=2){
  116467. t3+=2;
  116468. t4+=2;
  116469. t5-=2;
  116470. t6+=2;
  116471. ch[t3-1]=cc[t4-1]+cc[t5-1];
  116472. tr2=cc[t4-1]-cc[t5-1];
  116473. ch[t3]=cc[t4]-cc[t5];
  116474. ti2=cc[t4]+cc[t5];
  116475. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  116476. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  116477. }
  116478. t2=(t1+=ido)<<1;
  116479. }
  116480. if(ido%2==1)return;
  116481. L105:
  116482. t1=ido-1;
  116483. t2=ido-1;
  116484. for(k=0;k<l1;k++){
  116485. ch[t1]=cc[t2]+cc[t2];
  116486. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  116487. t1+=ido;
  116488. t2+=ido<<1;
  116489. }
  116490. }
  116491. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  116492. float *wa2){
  116493. static float taur = -.5f;
  116494. static float taui = .8660254037844386f;
  116495. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  116496. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  116497. t0=l1*ido;
  116498. t1=0;
  116499. t2=t0<<1;
  116500. t3=ido<<1;
  116501. t4=ido+(ido<<1);
  116502. t5=0;
  116503. for(k=0;k<l1;k++){
  116504. tr2=cc[t3-1]+cc[t3-1];
  116505. cr2=cc[t5]+(taur*tr2);
  116506. ch[t1]=cc[t5]+tr2;
  116507. ci3=taui*(cc[t3]+cc[t3]);
  116508. ch[t1+t0]=cr2-ci3;
  116509. ch[t1+t2]=cr2+ci3;
  116510. t1+=ido;
  116511. t3+=t4;
  116512. t5+=t4;
  116513. }
  116514. if(ido==1)return;
  116515. t1=0;
  116516. t3=ido<<1;
  116517. for(k=0;k<l1;k++){
  116518. t7=t1+(t1<<1);
  116519. t6=(t5=t7+t3);
  116520. t8=t1;
  116521. t10=(t9=t1+t0)+t0;
  116522. for(i=2;i<ido;i+=2){
  116523. t5+=2;
  116524. t6-=2;
  116525. t7+=2;
  116526. t8+=2;
  116527. t9+=2;
  116528. t10+=2;
  116529. tr2=cc[t5-1]+cc[t6-1];
  116530. cr2=cc[t7-1]+(taur*tr2);
  116531. ch[t8-1]=cc[t7-1]+tr2;
  116532. ti2=cc[t5]-cc[t6];
  116533. ci2=cc[t7]+(taur*ti2);
  116534. ch[t8]=cc[t7]+ti2;
  116535. cr3=taui*(cc[t5-1]-cc[t6-1]);
  116536. ci3=taui*(cc[t5]+cc[t6]);
  116537. dr2=cr2-ci3;
  116538. dr3=cr2+ci3;
  116539. di2=ci2+cr3;
  116540. di3=ci2-cr3;
  116541. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  116542. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  116543. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  116544. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  116545. }
  116546. t1+=ido;
  116547. }
  116548. }
  116549. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  116550. float *wa2,float *wa3){
  116551. static float sqrt2=1.414213562373095f;
  116552. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  116553. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  116554. t0=l1*ido;
  116555. t1=0;
  116556. t2=ido<<2;
  116557. t3=0;
  116558. t6=ido<<1;
  116559. for(k=0;k<l1;k++){
  116560. t4=t3+t6;
  116561. t5=t1;
  116562. tr3=cc[t4-1]+cc[t4-1];
  116563. tr4=cc[t4]+cc[t4];
  116564. tr1=cc[t3]-cc[(t4+=t6)-1];
  116565. tr2=cc[t3]+cc[t4-1];
  116566. ch[t5]=tr2+tr3;
  116567. ch[t5+=t0]=tr1-tr4;
  116568. ch[t5+=t0]=tr2-tr3;
  116569. ch[t5+=t0]=tr1+tr4;
  116570. t1+=ido;
  116571. t3+=t2;
  116572. }
  116573. if(ido<2)return;
  116574. if(ido==2)goto L105;
  116575. t1=0;
  116576. for(k=0;k<l1;k++){
  116577. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  116578. t7=t1;
  116579. for(i=2;i<ido;i+=2){
  116580. t2+=2;
  116581. t3+=2;
  116582. t4-=2;
  116583. t5-=2;
  116584. t7+=2;
  116585. ti1=cc[t2]+cc[t5];
  116586. ti2=cc[t2]-cc[t5];
  116587. ti3=cc[t3]-cc[t4];
  116588. tr4=cc[t3]+cc[t4];
  116589. tr1=cc[t2-1]-cc[t5-1];
  116590. tr2=cc[t2-1]+cc[t5-1];
  116591. ti4=cc[t3-1]-cc[t4-1];
  116592. tr3=cc[t3-1]+cc[t4-1];
  116593. ch[t7-1]=tr2+tr3;
  116594. cr3=tr2-tr3;
  116595. ch[t7]=ti2+ti3;
  116596. ci3=ti2-ti3;
  116597. cr2=tr1-tr4;
  116598. cr4=tr1+tr4;
  116599. ci2=ti1+ti4;
  116600. ci4=ti1-ti4;
  116601. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  116602. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  116603. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  116604. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  116605. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  116606. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  116607. }
  116608. t1+=ido;
  116609. }
  116610. if(ido%2 == 1)return;
  116611. L105:
  116612. t1=ido;
  116613. t2=ido<<2;
  116614. t3=ido-1;
  116615. t4=ido+(ido<<1);
  116616. for(k=0;k<l1;k++){
  116617. t5=t3;
  116618. ti1=cc[t1]+cc[t4];
  116619. ti2=cc[t4]-cc[t1];
  116620. tr1=cc[t1-1]-cc[t4-1];
  116621. tr2=cc[t1-1]+cc[t4-1];
  116622. ch[t5]=tr2+tr2;
  116623. ch[t5+=t0]=sqrt2*(tr1-ti1);
  116624. ch[t5+=t0]=ti2+ti2;
  116625. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  116626. t3+=ido;
  116627. t1+=t2;
  116628. t4+=t2;
  116629. }
  116630. }
  116631. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  116632. float *c2,float *ch,float *ch2,float *wa){
  116633. static float tpi=6.283185307179586f;
  116634. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  116635. t11,t12;
  116636. float dc2,ai1,ai2,ar1,ar2,ds2;
  116637. int nbd;
  116638. float dcp,arg,dsp,ar1h,ar2h;
  116639. int ipp2;
  116640. t10=ip*ido;
  116641. t0=l1*ido;
  116642. arg=tpi/(float)ip;
  116643. dcp=cos(arg);
  116644. dsp=sin(arg);
  116645. nbd=(ido-1)>>1;
  116646. ipp2=ip;
  116647. ipph=(ip+1)>>1;
  116648. if(ido<l1)goto L103;
  116649. t1=0;
  116650. t2=0;
  116651. for(k=0;k<l1;k++){
  116652. t3=t1;
  116653. t4=t2;
  116654. for(i=0;i<ido;i++){
  116655. ch[t3]=cc[t4];
  116656. t3++;
  116657. t4++;
  116658. }
  116659. t1+=ido;
  116660. t2+=t10;
  116661. }
  116662. goto L106;
  116663. L103:
  116664. t1=0;
  116665. for(i=0;i<ido;i++){
  116666. t2=t1;
  116667. t3=t1;
  116668. for(k=0;k<l1;k++){
  116669. ch[t2]=cc[t3];
  116670. t2+=ido;
  116671. t3+=t10;
  116672. }
  116673. t1++;
  116674. }
  116675. L106:
  116676. t1=0;
  116677. t2=ipp2*t0;
  116678. t7=(t5=ido<<1);
  116679. for(j=1;j<ipph;j++){
  116680. t1+=t0;
  116681. t2-=t0;
  116682. t3=t1;
  116683. t4=t2;
  116684. t6=t5;
  116685. for(k=0;k<l1;k++){
  116686. ch[t3]=cc[t6-1]+cc[t6-1];
  116687. ch[t4]=cc[t6]+cc[t6];
  116688. t3+=ido;
  116689. t4+=ido;
  116690. t6+=t10;
  116691. }
  116692. t5+=t7;
  116693. }
  116694. if (ido == 1)goto L116;
  116695. if(nbd<l1)goto L112;
  116696. t1=0;
  116697. t2=ipp2*t0;
  116698. t7=0;
  116699. for(j=1;j<ipph;j++){
  116700. t1+=t0;
  116701. t2-=t0;
  116702. t3=t1;
  116703. t4=t2;
  116704. t7+=(ido<<1);
  116705. t8=t7;
  116706. for(k=0;k<l1;k++){
  116707. t5=t3;
  116708. t6=t4;
  116709. t9=t8;
  116710. t11=t8;
  116711. for(i=2;i<ido;i+=2){
  116712. t5+=2;
  116713. t6+=2;
  116714. t9+=2;
  116715. t11-=2;
  116716. ch[t5-1]=cc[t9-1]+cc[t11-1];
  116717. ch[t6-1]=cc[t9-1]-cc[t11-1];
  116718. ch[t5]=cc[t9]-cc[t11];
  116719. ch[t6]=cc[t9]+cc[t11];
  116720. }
  116721. t3+=ido;
  116722. t4+=ido;
  116723. t8+=t10;
  116724. }
  116725. }
  116726. goto L116;
  116727. L112:
  116728. t1=0;
  116729. t2=ipp2*t0;
  116730. t7=0;
  116731. for(j=1;j<ipph;j++){
  116732. t1+=t0;
  116733. t2-=t0;
  116734. t3=t1;
  116735. t4=t2;
  116736. t7+=(ido<<1);
  116737. t8=t7;
  116738. t9=t7;
  116739. for(i=2;i<ido;i+=2){
  116740. t3+=2;
  116741. t4+=2;
  116742. t8+=2;
  116743. t9-=2;
  116744. t5=t3;
  116745. t6=t4;
  116746. t11=t8;
  116747. t12=t9;
  116748. for(k=0;k<l1;k++){
  116749. ch[t5-1]=cc[t11-1]+cc[t12-1];
  116750. ch[t6-1]=cc[t11-1]-cc[t12-1];
  116751. ch[t5]=cc[t11]-cc[t12];
  116752. ch[t6]=cc[t11]+cc[t12];
  116753. t5+=ido;
  116754. t6+=ido;
  116755. t11+=t10;
  116756. t12+=t10;
  116757. }
  116758. }
  116759. }
  116760. L116:
  116761. ar1=1.f;
  116762. ai1=0.f;
  116763. t1=0;
  116764. t9=(t2=ipp2*idl1);
  116765. t3=(ip-1)*idl1;
  116766. for(l=1;l<ipph;l++){
  116767. t1+=idl1;
  116768. t2-=idl1;
  116769. ar1h=dcp*ar1-dsp*ai1;
  116770. ai1=dcp*ai1+dsp*ar1;
  116771. ar1=ar1h;
  116772. t4=t1;
  116773. t5=t2;
  116774. t6=0;
  116775. t7=idl1;
  116776. t8=t3;
  116777. for(ik=0;ik<idl1;ik++){
  116778. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  116779. c2[t5++]=ai1*ch2[t8++];
  116780. }
  116781. dc2=ar1;
  116782. ds2=ai1;
  116783. ar2=ar1;
  116784. ai2=ai1;
  116785. t6=idl1;
  116786. t7=t9-idl1;
  116787. for(j=2;j<ipph;j++){
  116788. t6+=idl1;
  116789. t7-=idl1;
  116790. ar2h=dc2*ar2-ds2*ai2;
  116791. ai2=dc2*ai2+ds2*ar2;
  116792. ar2=ar2h;
  116793. t4=t1;
  116794. t5=t2;
  116795. t11=t6;
  116796. t12=t7;
  116797. for(ik=0;ik<idl1;ik++){
  116798. c2[t4++]+=ar2*ch2[t11++];
  116799. c2[t5++]+=ai2*ch2[t12++];
  116800. }
  116801. }
  116802. }
  116803. t1=0;
  116804. for(j=1;j<ipph;j++){
  116805. t1+=idl1;
  116806. t2=t1;
  116807. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  116808. }
  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. ch[t3]=c1[t3]-c1[t4];
  116818. ch[t4]=c1[t3]+c1[t4];
  116819. t3+=ido;
  116820. t4+=ido;
  116821. }
  116822. }
  116823. if(ido==1)goto L132;
  116824. if(nbd<l1)goto L128;
  116825. t1=0;
  116826. t2=ipp2*t0;
  116827. for(j=1;j<ipph;j++){
  116828. t1+=t0;
  116829. t2-=t0;
  116830. t3=t1;
  116831. t4=t2;
  116832. for(k=0;k<l1;k++){
  116833. t5=t3;
  116834. t6=t4;
  116835. for(i=2;i<ido;i+=2){
  116836. t5+=2;
  116837. t6+=2;
  116838. ch[t5-1]=c1[t5-1]-c1[t6];
  116839. ch[t6-1]=c1[t5-1]+c1[t6];
  116840. ch[t5]=c1[t5]+c1[t6-1];
  116841. ch[t6]=c1[t5]-c1[t6-1];
  116842. }
  116843. t3+=ido;
  116844. t4+=ido;
  116845. }
  116846. }
  116847. goto L132;
  116848. L128:
  116849. t1=0;
  116850. t2=ipp2*t0;
  116851. for(j=1;j<ipph;j++){
  116852. t1+=t0;
  116853. t2-=t0;
  116854. t3=t1;
  116855. t4=t2;
  116856. for(i=2;i<ido;i+=2){
  116857. t3+=2;
  116858. t4+=2;
  116859. t5=t3;
  116860. t6=t4;
  116861. for(k=0;k<l1;k++){
  116862. ch[t5-1]=c1[t5-1]-c1[t6];
  116863. ch[t6-1]=c1[t5-1]+c1[t6];
  116864. ch[t5]=c1[t5]+c1[t6-1];
  116865. ch[t6]=c1[t5]-c1[t6-1];
  116866. t5+=ido;
  116867. t6+=ido;
  116868. }
  116869. }
  116870. }
  116871. L132:
  116872. if(ido==1)return;
  116873. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116874. t1=0;
  116875. for(j=1;j<ip;j++){
  116876. t2=(t1+=t0);
  116877. for(k=0;k<l1;k++){
  116878. c1[t2]=ch[t2];
  116879. t2+=ido;
  116880. }
  116881. }
  116882. if(nbd>l1)goto L139;
  116883. is= -ido-1;
  116884. t1=0;
  116885. for(j=1;j<ip;j++){
  116886. is+=ido;
  116887. t1+=t0;
  116888. idij=is;
  116889. t2=t1;
  116890. for(i=2;i<ido;i+=2){
  116891. t2+=2;
  116892. idij+=2;
  116893. t3=t2;
  116894. for(k=0;k<l1;k++){
  116895. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116896. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116897. t3+=ido;
  116898. }
  116899. }
  116900. }
  116901. return;
  116902. L139:
  116903. is= -ido-1;
  116904. t1=0;
  116905. for(j=1;j<ip;j++){
  116906. is+=ido;
  116907. t1+=t0;
  116908. t2=t1;
  116909. for(k=0;k<l1;k++){
  116910. idij=is;
  116911. t3=t2;
  116912. for(i=2;i<ido;i+=2){
  116913. idij+=2;
  116914. t3+=2;
  116915. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116916. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116917. }
  116918. t2+=ido;
  116919. }
  116920. }
  116921. }
  116922. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  116923. int i,k1,l1,l2;
  116924. int na;
  116925. int nf,ip,iw,ix2,ix3,ido,idl1;
  116926. nf=ifac[1];
  116927. na=0;
  116928. l1=1;
  116929. iw=1;
  116930. for(k1=0;k1<nf;k1++){
  116931. ip=ifac[k1 + 2];
  116932. l2=ip*l1;
  116933. ido=n/l2;
  116934. idl1=ido*l1;
  116935. if(ip!=4)goto L103;
  116936. ix2=iw+ido;
  116937. ix3=ix2+ido;
  116938. if(na!=0)
  116939. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116940. else
  116941. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116942. na=1-na;
  116943. goto L115;
  116944. L103:
  116945. if(ip!=2)goto L106;
  116946. if(na!=0)
  116947. dradb2(ido,l1,ch,c,wa+iw-1);
  116948. else
  116949. dradb2(ido,l1,c,ch,wa+iw-1);
  116950. na=1-na;
  116951. goto L115;
  116952. L106:
  116953. if(ip!=3)goto L109;
  116954. ix2=iw+ido;
  116955. if(na!=0)
  116956. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  116957. else
  116958. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  116959. na=1-na;
  116960. goto L115;
  116961. L109:
  116962. /* The radix five case can be translated later..... */
  116963. /* if(ip!=5)goto L112;
  116964. ix2=iw+ido;
  116965. ix3=ix2+ido;
  116966. ix4=ix3+ido;
  116967. if(na!=0)
  116968. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116969. else
  116970. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116971. na=1-na;
  116972. goto L115;
  116973. L112:*/
  116974. if(na!=0)
  116975. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116976. else
  116977. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116978. if(ido==1)na=1-na;
  116979. L115:
  116980. l1=l2;
  116981. iw+=(ip-1)*ido;
  116982. }
  116983. if(na==0)return;
  116984. for(i=0;i<n;i++)c[i]=ch[i];
  116985. }
  116986. void drft_forward(drft_lookup *l,float *data){
  116987. if(l->n==1)return;
  116988. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116989. }
  116990. void drft_backward(drft_lookup *l,float *data){
  116991. if (l->n==1)return;
  116992. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116993. }
  116994. void drft_init(drft_lookup *l,int n){
  116995. l->n=n;
  116996. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  116997. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  116998. fdrffti(n, l->trigcache, l->splitcache);
  116999. }
  117000. void drft_clear(drft_lookup *l){
  117001. if(l){
  117002. if(l->trigcache)_ogg_free(l->trigcache);
  117003. if(l->splitcache)_ogg_free(l->splitcache);
  117004. memset(l,0,sizeof(*l));
  117005. }
  117006. }
  117007. #endif
  117008. /*** End of inlined file: smallft.c ***/
  117009. /*** Start of inlined file: synthesis.c ***/
  117010. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117011. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117012. // tasks..
  117013. #if JUCE_MSVC
  117014. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117015. #endif
  117016. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117017. #if JUCE_USE_OGGVORBIS
  117018. #include <stdio.h>
  117019. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  117020. vorbis_dsp_state *vd=vb->vd;
  117021. private_state *b=(private_state*)vd->backend_state;
  117022. vorbis_info *vi=vd->vi;
  117023. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117024. oggpack_buffer *opb=&vb->opb;
  117025. int type,mode,i;
  117026. /* first things first. Make sure decode is ready */
  117027. _vorbis_block_ripcord(vb);
  117028. oggpack_readinit(opb,op->packet,op->bytes);
  117029. /* Check the packet type */
  117030. if(oggpack_read(opb,1)!=0){
  117031. /* Oops. This is not an audio data packet */
  117032. return(OV_ENOTAUDIO);
  117033. }
  117034. /* read our mode and pre/post windowsize */
  117035. mode=oggpack_read(opb,b->modebits);
  117036. if(mode==-1)return(OV_EBADPACKET);
  117037. vb->mode=mode;
  117038. vb->W=ci->mode_param[mode]->blockflag;
  117039. if(vb->W){
  117040. /* this doesn;t get mapped through mode selection as it's used
  117041. only for window selection */
  117042. vb->lW=oggpack_read(opb,1);
  117043. vb->nW=oggpack_read(opb,1);
  117044. if(vb->nW==-1) return(OV_EBADPACKET);
  117045. }else{
  117046. vb->lW=0;
  117047. vb->nW=0;
  117048. }
  117049. /* more setup */
  117050. vb->granulepos=op->granulepos;
  117051. vb->sequence=op->packetno;
  117052. vb->eofflag=op->e_o_s;
  117053. /* alloc pcm passback storage */
  117054. vb->pcmend=ci->blocksizes[vb->W];
  117055. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  117056. for(i=0;i<vi->channels;i++)
  117057. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  117058. /* unpack_header enforces range checking */
  117059. type=ci->map_type[ci->mode_param[mode]->mapping];
  117060. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  117061. mapping]));
  117062. }
  117063. /* used to track pcm position without actually performing decode.
  117064. Useful for sequential 'fast forward' */
  117065. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  117066. vorbis_dsp_state *vd=vb->vd;
  117067. private_state *b=(private_state*)vd->backend_state;
  117068. vorbis_info *vi=vd->vi;
  117069. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117070. oggpack_buffer *opb=&vb->opb;
  117071. int mode;
  117072. /* first things first. Make sure decode is ready */
  117073. _vorbis_block_ripcord(vb);
  117074. oggpack_readinit(opb,op->packet,op->bytes);
  117075. /* Check the packet type */
  117076. if(oggpack_read(opb,1)!=0){
  117077. /* Oops. This is not an audio data packet */
  117078. return(OV_ENOTAUDIO);
  117079. }
  117080. /* read our mode and pre/post windowsize */
  117081. mode=oggpack_read(opb,b->modebits);
  117082. if(mode==-1)return(OV_EBADPACKET);
  117083. vb->mode=mode;
  117084. vb->W=ci->mode_param[mode]->blockflag;
  117085. if(vb->W){
  117086. vb->lW=oggpack_read(opb,1);
  117087. vb->nW=oggpack_read(opb,1);
  117088. if(vb->nW==-1) return(OV_EBADPACKET);
  117089. }else{
  117090. vb->lW=0;
  117091. vb->nW=0;
  117092. }
  117093. /* more setup */
  117094. vb->granulepos=op->granulepos;
  117095. vb->sequence=op->packetno;
  117096. vb->eofflag=op->e_o_s;
  117097. /* no pcm */
  117098. vb->pcmend=0;
  117099. vb->pcm=NULL;
  117100. return(0);
  117101. }
  117102. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  117103. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117104. oggpack_buffer opb;
  117105. int mode;
  117106. oggpack_readinit(&opb,op->packet,op->bytes);
  117107. /* Check the packet type */
  117108. if(oggpack_read(&opb,1)!=0){
  117109. /* Oops. This is not an audio data packet */
  117110. return(OV_ENOTAUDIO);
  117111. }
  117112. {
  117113. int modebits=0;
  117114. int v=ci->modes;
  117115. while(v>1){
  117116. modebits++;
  117117. v>>=1;
  117118. }
  117119. /* read our mode and pre/post windowsize */
  117120. mode=oggpack_read(&opb,modebits);
  117121. }
  117122. if(mode==-1)return(OV_EBADPACKET);
  117123. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  117124. }
  117125. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  117126. /* set / clear half-sample-rate mode */
  117127. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117128. /* right now, our MDCT can't handle < 64 sample windows. */
  117129. if(ci->blocksizes[0]<=64 && flag)return -1;
  117130. ci->halfrate_flag=(flag?1:0);
  117131. return 0;
  117132. }
  117133. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  117134. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117135. return ci->halfrate_flag;
  117136. }
  117137. #endif
  117138. /*** End of inlined file: synthesis.c ***/
  117139. /*** Start of inlined file: vorbisenc.c ***/
  117140. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117141. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117142. // tasks..
  117143. #if JUCE_MSVC
  117144. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117145. #endif
  117146. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117147. #if JUCE_USE_OGGVORBIS
  117148. #include <stdlib.h>
  117149. #include <string.h>
  117150. #include <math.h>
  117151. /* careful with this; it's using static array sizing to make managing
  117152. all the modes a little less annoying. If we use a residue backend
  117153. with > 12 partition types, or a different division of iteration,
  117154. this needs to be updated. */
  117155. typedef struct {
  117156. static_codebook *books[12][3];
  117157. } static_bookblock;
  117158. typedef struct {
  117159. int res_type;
  117160. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  117161. vorbis_info_residue0 *res;
  117162. static_codebook *book_aux;
  117163. static_codebook *book_aux_managed;
  117164. static_bookblock *books_base;
  117165. static_bookblock *books_base_managed;
  117166. } vorbis_residue_template;
  117167. typedef struct {
  117168. vorbis_info_mapping0 *map;
  117169. vorbis_residue_template *res;
  117170. } vorbis_mapping_template;
  117171. typedef struct vp_adjblock{
  117172. int block[P_BANDS];
  117173. } vp_adjblock;
  117174. typedef struct {
  117175. int data[NOISE_COMPAND_LEVELS];
  117176. } compandblock;
  117177. /* high level configuration information for setting things up
  117178. step-by-step with the detailed vorbis_encode_ctl interface.
  117179. There's a fair amount of redundancy such that interactive setup
  117180. does not directly deal with any vorbis_info or codec_setup_info
  117181. initialization; it's all stored (until full init) in this highlevel
  117182. setup, then flushed out to the real codec setup structs later. */
  117183. typedef struct {
  117184. int att[P_NOISECURVES];
  117185. float boost;
  117186. float decay;
  117187. } att3;
  117188. typedef struct { int data[P_NOISECURVES]; } adj3;
  117189. typedef struct {
  117190. int pre[PACKETBLOBS];
  117191. int post[PACKETBLOBS];
  117192. float kHz[PACKETBLOBS];
  117193. float lowpasskHz[PACKETBLOBS];
  117194. } adj_stereo;
  117195. typedef struct {
  117196. int lo;
  117197. int hi;
  117198. int fixed;
  117199. } noiseguard;
  117200. typedef struct {
  117201. int data[P_NOISECURVES][17];
  117202. } noise3;
  117203. typedef struct {
  117204. int mappings;
  117205. double *rate_mapping;
  117206. double *quality_mapping;
  117207. int coupling_restriction;
  117208. long samplerate_min_restriction;
  117209. long samplerate_max_restriction;
  117210. int *blocksize_short;
  117211. int *blocksize_long;
  117212. att3 *psy_tone_masteratt;
  117213. int *psy_tone_0dB;
  117214. int *psy_tone_dBsuppress;
  117215. vp_adjblock *psy_tone_adj_impulse;
  117216. vp_adjblock *psy_tone_adj_long;
  117217. vp_adjblock *psy_tone_adj_other;
  117218. noiseguard *psy_noiseguards;
  117219. noise3 *psy_noise_bias_impulse;
  117220. noise3 *psy_noise_bias_padding;
  117221. noise3 *psy_noise_bias_trans;
  117222. noise3 *psy_noise_bias_long;
  117223. int *psy_noise_dBsuppress;
  117224. compandblock *psy_noise_compand;
  117225. double *psy_noise_compand_short_mapping;
  117226. double *psy_noise_compand_long_mapping;
  117227. int *psy_noise_normal_start[2];
  117228. int *psy_noise_normal_partition[2];
  117229. double *psy_noise_normal_thresh;
  117230. int *psy_ath_float;
  117231. int *psy_ath_abs;
  117232. double *psy_lowpass;
  117233. vorbis_info_psy_global *global_params;
  117234. double *global_mapping;
  117235. adj_stereo *stereo_modes;
  117236. static_codebook ***floor_books;
  117237. vorbis_info_floor1 *floor_params;
  117238. int *floor_short_mapping;
  117239. int *floor_long_mapping;
  117240. vorbis_mapping_template *maps;
  117241. } ve_setup_data_template;
  117242. /* a few static coder conventions */
  117243. static vorbis_info_mode _mode_template[2]={
  117244. {0,0,0,0},
  117245. {1,0,0,1}
  117246. };
  117247. static vorbis_info_mapping0 _map_nominal[2]={
  117248. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  117249. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  117250. };
  117251. /*** Start of inlined file: setup_44.h ***/
  117252. /*** Start of inlined file: floor_all.h ***/
  117253. /*** Start of inlined file: floor_books.h ***/
  117254. static long _huff_lengthlist_line_256x7_0sub1[] = {
  117255. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  117256. };
  117257. static static_codebook _huff_book_line_256x7_0sub1 = {
  117258. 1, 9,
  117259. _huff_lengthlist_line_256x7_0sub1,
  117260. 0, 0, 0, 0, 0,
  117261. NULL,
  117262. NULL,
  117263. NULL,
  117264. NULL,
  117265. 0
  117266. };
  117267. static long _huff_lengthlist_line_256x7_0sub2[] = {
  117268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  117269. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  117270. };
  117271. static static_codebook _huff_book_line_256x7_0sub2 = {
  117272. 1, 25,
  117273. _huff_lengthlist_line_256x7_0sub2,
  117274. 0, 0, 0, 0, 0,
  117275. NULL,
  117276. NULL,
  117277. NULL,
  117278. NULL,
  117279. 0
  117280. };
  117281. static long _huff_lengthlist_line_256x7_0sub3[] = {
  117282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  117284. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  117285. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  117286. };
  117287. static static_codebook _huff_book_line_256x7_0sub3 = {
  117288. 1, 64,
  117289. _huff_lengthlist_line_256x7_0sub3,
  117290. 0, 0, 0, 0, 0,
  117291. NULL,
  117292. NULL,
  117293. NULL,
  117294. NULL,
  117295. 0
  117296. };
  117297. static long _huff_lengthlist_line_256x7_1sub1[] = {
  117298. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  117299. };
  117300. static static_codebook _huff_book_line_256x7_1sub1 = {
  117301. 1, 9,
  117302. _huff_lengthlist_line_256x7_1sub1,
  117303. 0, 0, 0, 0, 0,
  117304. NULL,
  117305. NULL,
  117306. NULL,
  117307. NULL,
  117308. 0
  117309. };
  117310. static long _huff_lengthlist_line_256x7_1sub2[] = {
  117311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  117312. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  117313. };
  117314. static static_codebook _huff_book_line_256x7_1sub2 = {
  117315. 1, 25,
  117316. _huff_lengthlist_line_256x7_1sub2,
  117317. 0, 0, 0, 0, 0,
  117318. NULL,
  117319. NULL,
  117320. NULL,
  117321. NULL,
  117322. 0
  117323. };
  117324. static long _huff_lengthlist_line_256x7_1sub3[] = {
  117325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  117327. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117328. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  117329. };
  117330. static static_codebook _huff_book_line_256x7_1sub3 = {
  117331. 1, 64,
  117332. _huff_lengthlist_line_256x7_1sub3,
  117333. 0, 0, 0, 0, 0,
  117334. NULL,
  117335. NULL,
  117336. NULL,
  117337. NULL,
  117338. 0
  117339. };
  117340. static long _huff_lengthlist_line_256x7_class0[] = {
  117341. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  117342. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  117343. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  117344. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  117345. };
  117346. static static_codebook _huff_book_line_256x7_class0 = {
  117347. 1, 64,
  117348. _huff_lengthlist_line_256x7_class0,
  117349. 0, 0, 0, 0, 0,
  117350. NULL,
  117351. NULL,
  117352. NULL,
  117353. NULL,
  117354. 0
  117355. };
  117356. static long _huff_lengthlist_line_256x7_class1[] = {
  117357. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  117358. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  117359. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  117360. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  117361. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  117362. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  117363. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  117364. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  117365. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  117366. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  117367. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  117368. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  117369. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117370. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117371. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  117372. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  117373. };
  117374. static static_codebook _huff_book_line_256x7_class1 = {
  117375. 1, 256,
  117376. _huff_lengthlist_line_256x7_class1,
  117377. 0, 0, 0, 0, 0,
  117378. NULL,
  117379. NULL,
  117380. NULL,
  117381. NULL,
  117382. 0
  117383. };
  117384. static long _huff_lengthlist_line_512x17_0sub0[] = {
  117385. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  117386. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  117387. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  117388. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  117389. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  117390. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  117391. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  117392. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117393. };
  117394. static static_codebook _huff_book_line_512x17_0sub0 = {
  117395. 1, 128,
  117396. _huff_lengthlist_line_512x17_0sub0,
  117397. 0, 0, 0, 0, 0,
  117398. NULL,
  117399. NULL,
  117400. NULL,
  117401. NULL,
  117402. 0
  117403. };
  117404. static long _huff_lengthlist_line_512x17_1sub0[] = {
  117405. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117406. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  117407. };
  117408. static static_codebook _huff_book_line_512x17_1sub0 = {
  117409. 1, 32,
  117410. _huff_lengthlist_line_512x17_1sub0,
  117411. 0, 0, 0, 0, 0,
  117412. NULL,
  117413. NULL,
  117414. NULL,
  117415. NULL,
  117416. 0
  117417. };
  117418. static long _huff_lengthlist_line_512x17_1sub1[] = {
  117419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117421. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  117422. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  117423. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  117424. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  117425. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  117426. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117427. };
  117428. static static_codebook _huff_book_line_512x17_1sub1 = {
  117429. 1, 128,
  117430. _huff_lengthlist_line_512x17_1sub1,
  117431. 0, 0, 0, 0, 0,
  117432. NULL,
  117433. NULL,
  117434. NULL,
  117435. NULL,
  117436. 0
  117437. };
  117438. static long _huff_lengthlist_line_512x17_2sub1[] = {
  117439. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  117440. 5, 3,
  117441. };
  117442. static static_codebook _huff_book_line_512x17_2sub1 = {
  117443. 1, 18,
  117444. _huff_lengthlist_line_512x17_2sub1,
  117445. 0, 0, 0, 0, 0,
  117446. NULL,
  117447. NULL,
  117448. NULL,
  117449. NULL,
  117450. 0
  117451. };
  117452. static long _huff_lengthlist_line_512x17_2sub2[] = {
  117453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117454. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  117455. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  117456. 9, 8,
  117457. };
  117458. static static_codebook _huff_book_line_512x17_2sub2 = {
  117459. 1, 50,
  117460. _huff_lengthlist_line_512x17_2sub2,
  117461. 0, 0, 0, 0, 0,
  117462. NULL,
  117463. NULL,
  117464. NULL,
  117465. NULL,
  117466. 0
  117467. };
  117468. static long _huff_lengthlist_line_512x17_2sub3[] = {
  117469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117472. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  117473. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  117474. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117475. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117476. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117477. };
  117478. static static_codebook _huff_book_line_512x17_2sub3 = {
  117479. 1, 128,
  117480. _huff_lengthlist_line_512x17_2sub3,
  117481. 0, 0, 0, 0, 0,
  117482. NULL,
  117483. NULL,
  117484. NULL,
  117485. NULL,
  117486. 0
  117487. };
  117488. static long _huff_lengthlist_line_512x17_3sub1[] = {
  117489. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  117490. 5, 5,
  117491. };
  117492. static static_codebook _huff_book_line_512x17_3sub1 = {
  117493. 1, 18,
  117494. _huff_lengthlist_line_512x17_3sub1,
  117495. 0, 0, 0, 0, 0,
  117496. NULL,
  117497. NULL,
  117498. NULL,
  117499. NULL,
  117500. 0
  117501. };
  117502. static long _huff_lengthlist_line_512x17_3sub2[] = {
  117503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117504. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  117505. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  117506. 11,14,
  117507. };
  117508. static static_codebook _huff_book_line_512x17_3sub2 = {
  117509. 1, 50,
  117510. _huff_lengthlist_line_512x17_3sub2,
  117511. 0, 0, 0, 0, 0,
  117512. NULL,
  117513. NULL,
  117514. NULL,
  117515. NULL,
  117516. 0
  117517. };
  117518. static long _huff_lengthlist_line_512x17_3sub3[] = {
  117519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117522. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  117523. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117524. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117525. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117526. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117527. };
  117528. static static_codebook _huff_book_line_512x17_3sub3 = {
  117529. 1, 128,
  117530. _huff_lengthlist_line_512x17_3sub3,
  117531. 0, 0, 0, 0, 0,
  117532. NULL,
  117533. NULL,
  117534. NULL,
  117535. NULL,
  117536. 0
  117537. };
  117538. static long _huff_lengthlist_line_512x17_class1[] = {
  117539. 1, 2, 3, 6, 5, 4, 7, 7,
  117540. };
  117541. static static_codebook _huff_book_line_512x17_class1 = {
  117542. 1, 8,
  117543. _huff_lengthlist_line_512x17_class1,
  117544. 0, 0, 0, 0, 0,
  117545. NULL,
  117546. NULL,
  117547. NULL,
  117548. NULL,
  117549. 0
  117550. };
  117551. static long _huff_lengthlist_line_512x17_class2[] = {
  117552. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  117553. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  117554. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  117555. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  117556. };
  117557. static static_codebook _huff_book_line_512x17_class2 = {
  117558. 1, 64,
  117559. _huff_lengthlist_line_512x17_class2,
  117560. 0, 0, 0, 0, 0,
  117561. NULL,
  117562. NULL,
  117563. NULL,
  117564. NULL,
  117565. 0
  117566. };
  117567. static long _huff_lengthlist_line_512x17_class3[] = {
  117568. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  117569. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  117570. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  117571. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  117572. };
  117573. static static_codebook _huff_book_line_512x17_class3 = {
  117574. 1, 64,
  117575. _huff_lengthlist_line_512x17_class3,
  117576. 0, 0, 0, 0, 0,
  117577. NULL,
  117578. NULL,
  117579. NULL,
  117580. NULL,
  117581. 0
  117582. };
  117583. static long _huff_lengthlist_line_128x4_class0[] = {
  117584. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  117585. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  117586. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  117587. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  117588. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  117589. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  117590. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  117591. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  117592. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  117593. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  117594. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  117595. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  117596. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  117597. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  117598. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  117599. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  117600. };
  117601. static static_codebook _huff_book_line_128x4_class0 = {
  117602. 1, 256,
  117603. _huff_lengthlist_line_128x4_class0,
  117604. 0, 0, 0, 0, 0,
  117605. NULL,
  117606. NULL,
  117607. NULL,
  117608. NULL,
  117609. 0
  117610. };
  117611. static long _huff_lengthlist_line_128x4_0sub0[] = {
  117612. 2, 2, 2, 2,
  117613. };
  117614. static static_codebook _huff_book_line_128x4_0sub0 = {
  117615. 1, 4,
  117616. _huff_lengthlist_line_128x4_0sub0,
  117617. 0, 0, 0, 0, 0,
  117618. NULL,
  117619. NULL,
  117620. NULL,
  117621. NULL,
  117622. 0
  117623. };
  117624. static long _huff_lengthlist_line_128x4_0sub1[] = {
  117625. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  117626. };
  117627. static static_codebook _huff_book_line_128x4_0sub1 = {
  117628. 1, 10,
  117629. _huff_lengthlist_line_128x4_0sub1,
  117630. 0, 0, 0, 0, 0,
  117631. NULL,
  117632. NULL,
  117633. NULL,
  117634. NULL,
  117635. 0
  117636. };
  117637. static long _huff_lengthlist_line_128x4_0sub2[] = {
  117638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  117639. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  117640. };
  117641. static static_codebook _huff_book_line_128x4_0sub2 = {
  117642. 1, 25,
  117643. _huff_lengthlist_line_128x4_0sub2,
  117644. 0, 0, 0, 0, 0,
  117645. NULL,
  117646. NULL,
  117647. NULL,
  117648. NULL,
  117649. 0
  117650. };
  117651. static long _huff_lengthlist_line_128x4_0sub3[] = {
  117652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  117654. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  117655. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  117656. };
  117657. static static_codebook _huff_book_line_128x4_0sub3 = {
  117658. 1, 64,
  117659. _huff_lengthlist_line_128x4_0sub3,
  117660. 0, 0, 0, 0, 0,
  117661. NULL,
  117662. NULL,
  117663. NULL,
  117664. NULL,
  117665. 0
  117666. };
  117667. static long _huff_lengthlist_line_256x4_class0[] = {
  117668. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  117669. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  117670. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  117671. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  117672. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  117673. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  117674. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  117675. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  117676. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  117677. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  117678. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  117679. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  117680. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  117681. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  117682. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  117683. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  117684. };
  117685. static static_codebook _huff_book_line_256x4_class0 = {
  117686. 1, 256,
  117687. _huff_lengthlist_line_256x4_class0,
  117688. 0, 0, 0, 0, 0,
  117689. NULL,
  117690. NULL,
  117691. NULL,
  117692. NULL,
  117693. 0
  117694. };
  117695. static long _huff_lengthlist_line_256x4_0sub0[] = {
  117696. 2, 2, 2, 2,
  117697. };
  117698. static static_codebook _huff_book_line_256x4_0sub0 = {
  117699. 1, 4,
  117700. _huff_lengthlist_line_256x4_0sub0,
  117701. 0, 0, 0, 0, 0,
  117702. NULL,
  117703. NULL,
  117704. NULL,
  117705. NULL,
  117706. 0
  117707. };
  117708. static long _huff_lengthlist_line_256x4_0sub1[] = {
  117709. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  117710. };
  117711. static static_codebook _huff_book_line_256x4_0sub1 = {
  117712. 1, 10,
  117713. _huff_lengthlist_line_256x4_0sub1,
  117714. 0, 0, 0, 0, 0,
  117715. NULL,
  117716. NULL,
  117717. NULL,
  117718. NULL,
  117719. 0
  117720. };
  117721. static long _huff_lengthlist_line_256x4_0sub2[] = {
  117722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  117723. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  117724. };
  117725. static static_codebook _huff_book_line_256x4_0sub2 = {
  117726. 1, 25,
  117727. _huff_lengthlist_line_256x4_0sub2,
  117728. 0, 0, 0, 0, 0,
  117729. NULL,
  117730. NULL,
  117731. NULL,
  117732. NULL,
  117733. 0
  117734. };
  117735. static long _huff_lengthlist_line_256x4_0sub3[] = {
  117736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  117738. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  117739. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  117740. };
  117741. static static_codebook _huff_book_line_256x4_0sub3 = {
  117742. 1, 64,
  117743. _huff_lengthlist_line_256x4_0sub3,
  117744. 0, 0, 0, 0, 0,
  117745. NULL,
  117746. NULL,
  117747. NULL,
  117748. NULL,
  117749. 0
  117750. };
  117751. static long _huff_lengthlist_line_128x7_class0[] = {
  117752. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  117753. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  117754. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  117755. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  117756. };
  117757. static static_codebook _huff_book_line_128x7_class0 = {
  117758. 1, 64,
  117759. _huff_lengthlist_line_128x7_class0,
  117760. 0, 0, 0, 0, 0,
  117761. NULL,
  117762. NULL,
  117763. NULL,
  117764. NULL,
  117765. 0
  117766. };
  117767. static long _huff_lengthlist_line_128x7_class1[] = {
  117768. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  117769. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  117770. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  117771. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117772. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  117773. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  117774. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  117775. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  117776. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  117777. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  117778. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  117779. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  117780. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  117781. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  117782. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  117783. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  117784. };
  117785. static static_codebook _huff_book_line_128x7_class1 = {
  117786. 1, 256,
  117787. _huff_lengthlist_line_128x7_class1,
  117788. 0, 0, 0, 0, 0,
  117789. NULL,
  117790. NULL,
  117791. NULL,
  117792. NULL,
  117793. 0
  117794. };
  117795. static long _huff_lengthlist_line_128x7_0sub1[] = {
  117796. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  117797. };
  117798. static static_codebook _huff_book_line_128x7_0sub1 = {
  117799. 1, 9,
  117800. _huff_lengthlist_line_128x7_0sub1,
  117801. 0, 0, 0, 0, 0,
  117802. NULL,
  117803. NULL,
  117804. NULL,
  117805. NULL,
  117806. 0
  117807. };
  117808. static long _huff_lengthlist_line_128x7_0sub2[] = {
  117809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  117810. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  117811. };
  117812. static static_codebook _huff_book_line_128x7_0sub2 = {
  117813. 1, 25,
  117814. _huff_lengthlist_line_128x7_0sub2,
  117815. 0, 0, 0, 0, 0,
  117816. NULL,
  117817. NULL,
  117818. NULL,
  117819. NULL,
  117820. 0
  117821. };
  117822. static long _huff_lengthlist_line_128x7_0sub3[] = {
  117823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  117825. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117826. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  117827. };
  117828. static static_codebook _huff_book_line_128x7_0sub3 = {
  117829. 1, 64,
  117830. _huff_lengthlist_line_128x7_0sub3,
  117831. 0, 0, 0, 0, 0,
  117832. NULL,
  117833. NULL,
  117834. NULL,
  117835. NULL,
  117836. 0
  117837. };
  117838. static long _huff_lengthlist_line_128x7_1sub1[] = {
  117839. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  117840. };
  117841. static static_codebook _huff_book_line_128x7_1sub1 = {
  117842. 1, 9,
  117843. _huff_lengthlist_line_128x7_1sub1,
  117844. 0, 0, 0, 0, 0,
  117845. NULL,
  117846. NULL,
  117847. NULL,
  117848. NULL,
  117849. 0
  117850. };
  117851. static long _huff_lengthlist_line_128x7_1sub2[] = {
  117852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  117853. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  117854. };
  117855. static static_codebook _huff_book_line_128x7_1sub2 = {
  117856. 1, 25,
  117857. _huff_lengthlist_line_128x7_1sub2,
  117858. 0, 0, 0, 0, 0,
  117859. NULL,
  117860. NULL,
  117861. NULL,
  117862. NULL,
  117863. 0
  117864. };
  117865. static long _huff_lengthlist_line_128x7_1sub3[] = {
  117866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  117868. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  117869. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  117870. };
  117871. static static_codebook _huff_book_line_128x7_1sub3 = {
  117872. 1, 64,
  117873. _huff_lengthlist_line_128x7_1sub3,
  117874. 0, 0, 0, 0, 0,
  117875. NULL,
  117876. NULL,
  117877. NULL,
  117878. NULL,
  117879. 0
  117880. };
  117881. static long _huff_lengthlist_line_128x11_class1[] = {
  117882. 1, 6, 3, 7, 2, 4, 5, 7,
  117883. };
  117884. static static_codebook _huff_book_line_128x11_class1 = {
  117885. 1, 8,
  117886. _huff_lengthlist_line_128x11_class1,
  117887. 0, 0, 0, 0, 0,
  117888. NULL,
  117889. NULL,
  117890. NULL,
  117891. NULL,
  117892. 0
  117893. };
  117894. static long _huff_lengthlist_line_128x11_class2[] = {
  117895. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  117896. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  117897. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  117898. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  117899. };
  117900. static static_codebook _huff_book_line_128x11_class2 = {
  117901. 1, 64,
  117902. _huff_lengthlist_line_128x11_class2,
  117903. 0, 0, 0, 0, 0,
  117904. NULL,
  117905. NULL,
  117906. NULL,
  117907. NULL,
  117908. 0
  117909. };
  117910. static long _huff_lengthlist_line_128x11_class3[] = {
  117911. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  117912. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  117913. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  117914. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  117915. };
  117916. static static_codebook _huff_book_line_128x11_class3 = {
  117917. 1, 64,
  117918. _huff_lengthlist_line_128x11_class3,
  117919. 0, 0, 0, 0, 0,
  117920. NULL,
  117921. NULL,
  117922. NULL,
  117923. NULL,
  117924. 0
  117925. };
  117926. static long _huff_lengthlist_line_128x11_0sub0[] = {
  117927. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117928. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  117929. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  117930. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  117931. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  117932. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  117933. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  117934. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117935. };
  117936. static static_codebook _huff_book_line_128x11_0sub0 = {
  117937. 1, 128,
  117938. _huff_lengthlist_line_128x11_0sub0,
  117939. 0, 0, 0, 0, 0,
  117940. NULL,
  117941. NULL,
  117942. NULL,
  117943. NULL,
  117944. 0
  117945. };
  117946. static long _huff_lengthlist_line_128x11_1sub0[] = {
  117947. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117948. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  117949. };
  117950. static static_codebook _huff_book_line_128x11_1sub0 = {
  117951. 1, 32,
  117952. _huff_lengthlist_line_128x11_1sub0,
  117953. 0, 0, 0, 0, 0,
  117954. NULL,
  117955. NULL,
  117956. NULL,
  117957. NULL,
  117958. 0
  117959. };
  117960. static long _huff_lengthlist_line_128x11_1sub1[] = {
  117961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117963. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117964. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  117965. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  117966. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  117967. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  117968. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  117969. };
  117970. static static_codebook _huff_book_line_128x11_1sub1 = {
  117971. 1, 128,
  117972. _huff_lengthlist_line_128x11_1sub1,
  117973. 0, 0, 0, 0, 0,
  117974. NULL,
  117975. NULL,
  117976. NULL,
  117977. NULL,
  117978. 0
  117979. };
  117980. static long _huff_lengthlist_line_128x11_2sub1[] = {
  117981. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  117982. 5, 5,
  117983. };
  117984. static static_codebook _huff_book_line_128x11_2sub1 = {
  117985. 1, 18,
  117986. _huff_lengthlist_line_128x11_2sub1,
  117987. 0, 0, 0, 0, 0,
  117988. NULL,
  117989. NULL,
  117990. NULL,
  117991. NULL,
  117992. 0
  117993. };
  117994. static long _huff_lengthlist_line_128x11_2sub2[] = {
  117995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117996. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  117997. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  117998. 8,11,
  117999. };
  118000. static static_codebook _huff_book_line_128x11_2sub2 = {
  118001. 1, 50,
  118002. _huff_lengthlist_line_128x11_2sub2,
  118003. 0, 0, 0, 0, 0,
  118004. NULL,
  118005. NULL,
  118006. NULL,
  118007. NULL,
  118008. 0
  118009. };
  118010. static long _huff_lengthlist_line_128x11_2sub3[] = {
  118011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118014. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  118015. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118016. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118017. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118018. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118019. };
  118020. static static_codebook _huff_book_line_128x11_2sub3 = {
  118021. 1, 128,
  118022. _huff_lengthlist_line_128x11_2sub3,
  118023. 0, 0, 0, 0, 0,
  118024. NULL,
  118025. NULL,
  118026. NULL,
  118027. NULL,
  118028. 0
  118029. };
  118030. static long _huff_lengthlist_line_128x11_3sub1[] = {
  118031. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  118032. 5, 4,
  118033. };
  118034. static static_codebook _huff_book_line_128x11_3sub1 = {
  118035. 1, 18,
  118036. _huff_lengthlist_line_128x11_3sub1,
  118037. 0, 0, 0, 0, 0,
  118038. NULL,
  118039. NULL,
  118040. NULL,
  118041. NULL,
  118042. 0
  118043. };
  118044. static long _huff_lengthlist_line_128x11_3sub2[] = {
  118045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118046. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  118047. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  118048. 12, 6,
  118049. };
  118050. static static_codebook _huff_book_line_128x11_3sub2 = {
  118051. 1, 50,
  118052. _huff_lengthlist_line_128x11_3sub2,
  118053. 0, 0, 0, 0, 0,
  118054. NULL,
  118055. NULL,
  118056. NULL,
  118057. NULL,
  118058. 0
  118059. };
  118060. static long _huff_lengthlist_line_128x11_3sub3[] = {
  118061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118064. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  118065. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  118066. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118067. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118068. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  118069. };
  118070. static static_codebook _huff_book_line_128x11_3sub3 = {
  118071. 1, 128,
  118072. _huff_lengthlist_line_128x11_3sub3,
  118073. 0, 0, 0, 0, 0,
  118074. NULL,
  118075. NULL,
  118076. NULL,
  118077. NULL,
  118078. 0
  118079. };
  118080. static long _huff_lengthlist_line_128x17_class1[] = {
  118081. 1, 3, 4, 7, 2, 5, 6, 7,
  118082. };
  118083. static static_codebook _huff_book_line_128x17_class1 = {
  118084. 1, 8,
  118085. _huff_lengthlist_line_128x17_class1,
  118086. 0, 0, 0, 0, 0,
  118087. NULL,
  118088. NULL,
  118089. NULL,
  118090. NULL,
  118091. 0
  118092. };
  118093. static long _huff_lengthlist_line_128x17_class2[] = {
  118094. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  118095. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  118096. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  118097. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  118098. };
  118099. static static_codebook _huff_book_line_128x17_class2 = {
  118100. 1, 64,
  118101. _huff_lengthlist_line_128x17_class2,
  118102. 0, 0, 0, 0, 0,
  118103. NULL,
  118104. NULL,
  118105. NULL,
  118106. NULL,
  118107. 0
  118108. };
  118109. static long _huff_lengthlist_line_128x17_class3[] = {
  118110. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  118111. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  118112. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  118113. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  118114. };
  118115. static static_codebook _huff_book_line_128x17_class3 = {
  118116. 1, 64,
  118117. _huff_lengthlist_line_128x17_class3,
  118118. 0, 0, 0, 0, 0,
  118119. NULL,
  118120. NULL,
  118121. NULL,
  118122. NULL,
  118123. 0
  118124. };
  118125. static long _huff_lengthlist_line_128x17_0sub0[] = {
  118126. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118127. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  118128. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  118129. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  118130. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  118131. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  118132. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  118133. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118134. };
  118135. static static_codebook _huff_book_line_128x17_0sub0 = {
  118136. 1, 128,
  118137. _huff_lengthlist_line_128x17_0sub0,
  118138. 0, 0, 0, 0, 0,
  118139. NULL,
  118140. NULL,
  118141. NULL,
  118142. NULL,
  118143. 0
  118144. };
  118145. static long _huff_lengthlist_line_128x17_1sub0[] = {
  118146. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118147. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  118148. };
  118149. static static_codebook _huff_book_line_128x17_1sub0 = {
  118150. 1, 32,
  118151. _huff_lengthlist_line_128x17_1sub0,
  118152. 0, 0, 0, 0, 0,
  118153. NULL,
  118154. NULL,
  118155. NULL,
  118156. NULL,
  118157. 0
  118158. };
  118159. static long _huff_lengthlist_line_128x17_1sub1[] = {
  118160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118162. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  118163. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  118164. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  118165. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  118166. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  118167. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  118168. };
  118169. static static_codebook _huff_book_line_128x17_1sub1 = {
  118170. 1, 128,
  118171. _huff_lengthlist_line_128x17_1sub1,
  118172. 0, 0, 0, 0, 0,
  118173. NULL,
  118174. NULL,
  118175. NULL,
  118176. NULL,
  118177. 0
  118178. };
  118179. static long _huff_lengthlist_line_128x17_2sub1[] = {
  118180. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  118181. 9, 4,
  118182. };
  118183. static static_codebook _huff_book_line_128x17_2sub1 = {
  118184. 1, 18,
  118185. _huff_lengthlist_line_128x17_2sub1,
  118186. 0, 0, 0, 0, 0,
  118187. NULL,
  118188. NULL,
  118189. NULL,
  118190. NULL,
  118191. 0
  118192. };
  118193. static long _huff_lengthlist_line_128x17_2sub2[] = {
  118194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118195. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  118196. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  118197. 13,13,
  118198. };
  118199. static static_codebook _huff_book_line_128x17_2sub2 = {
  118200. 1, 50,
  118201. _huff_lengthlist_line_128x17_2sub2,
  118202. 0, 0, 0, 0, 0,
  118203. NULL,
  118204. NULL,
  118205. NULL,
  118206. NULL,
  118207. 0
  118208. };
  118209. static long _huff_lengthlist_line_128x17_2sub3[] = {
  118210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118213. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118214. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  118215. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118216. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118217. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118218. };
  118219. static static_codebook _huff_book_line_128x17_2sub3 = {
  118220. 1, 128,
  118221. _huff_lengthlist_line_128x17_2sub3,
  118222. 0, 0, 0, 0, 0,
  118223. NULL,
  118224. NULL,
  118225. NULL,
  118226. NULL,
  118227. 0
  118228. };
  118229. static long _huff_lengthlist_line_128x17_3sub1[] = {
  118230. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  118231. 6, 4,
  118232. };
  118233. static static_codebook _huff_book_line_128x17_3sub1 = {
  118234. 1, 18,
  118235. _huff_lengthlist_line_128x17_3sub1,
  118236. 0, 0, 0, 0, 0,
  118237. NULL,
  118238. NULL,
  118239. NULL,
  118240. NULL,
  118241. 0
  118242. };
  118243. static long _huff_lengthlist_line_128x17_3sub2[] = {
  118244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118245. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  118246. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  118247. 10, 8,
  118248. };
  118249. static static_codebook _huff_book_line_128x17_3sub2 = {
  118250. 1, 50,
  118251. _huff_lengthlist_line_128x17_3sub2,
  118252. 0, 0, 0, 0, 0,
  118253. NULL,
  118254. NULL,
  118255. NULL,
  118256. NULL,
  118257. 0
  118258. };
  118259. static long _huff_lengthlist_line_128x17_3sub3[] = {
  118260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118263. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  118264. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  118265. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118268. };
  118269. static static_codebook _huff_book_line_128x17_3sub3 = {
  118270. 1, 128,
  118271. _huff_lengthlist_line_128x17_3sub3,
  118272. 0, 0, 0, 0, 0,
  118273. NULL,
  118274. NULL,
  118275. NULL,
  118276. NULL,
  118277. 0
  118278. };
  118279. static long _huff_lengthlist_line_1024x27_class1[] = {
  118280. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  118281. };
  118282. static static_codebook _huff_book_line_1024x27_class1 = {
  118283. 1, 16,
  118284. _huff_lengthlist_line_1024x27_class1,
  118285. 0, 0, 0, 0, 0,
  118286. NULL,
  118287. NULL,
  118288. NULL,
  118289. NULL,
  118290. 0
  118291. };
  118292. static long _huff_lengthlist_line_1024x27_class2[] = {
  118293. 1, 4, 2, 6, 3, 7, 5, 7,
  118294. };
  118295. static static_codebook _huff_book_line_1024x27_class2 = {
  118296. 1, 8,
  118297. _huff_lengthlist_line_1024x27_class2,
  118298. 0, 0, 0, 0, 0,
  118299. NULL,
  118300. NULL,
  118301. NULL,
  118302. NULL,
  118303. 0
  118304. };
  118305. static long _huff_lengthlist_line_1024x27_class3[] = {
  118306. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  118307. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  118308. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  118309. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  118310. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  118311. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  118312. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  118313. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  118314. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  118315. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  118316. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  118317. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118318. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  118319. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  118320. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  118321. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118322. };
  118323. static static_codebook _huff_book_line_1024x27_class3 = {
  118324. 1, 256,
  118325. _huff_lengthlist_line_1024x27_class3,
  118326. 0, 0, 0, 0, 0,
  118327. NULL,
  118328. NULL,
  118329. NULL,
  118330. NULL,
  118331. 0
  118332. };
  118333. static long _huff_lengthlist_line_1024x27_class4[] = {
  118334. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  118335. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  118336. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  118337. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  118338. };
  118339. static static_codebook _huff_book_line_1024x27_class4 = {
  118340. 1, 64,
  118341. _huff_lengthlist_line_1024x27_class4,
  118342. 0, 0, 0, 0, 0,
  118343. NULL,
  118344. NULL,
  118345. NULL,
  118346. NULL,
  118347. 0
  118348. };
  118349. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  118350. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118351. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  118352. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  118353. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  118354. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  118355. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  118356. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  118357. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  118358. };
  118359. static static_codebook _huff_book_line_1024x27_0sub0 = {
  118360. 1, 128,
  118361. _huff_lengthlist_line_1024x27_0sub0,
  118362. 0, 0, 0, 0, 0,
  118363. NULL,
  118364. NULL,
  118365. NULL,
  118366. NULL,
  118367. 0
  118368. };
  118369. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  118370. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  118371. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  118372. };
  118373. static static_codebook _huff_book_line_1024x27_1sub0 = {
  118374. 1, 32,
  118375. _huff_lengthlist_line_1024x27_1sub0,
  118376. 0, 0, 0, 0, 0,
  118377. NULL,
  118378. NULL,
  118379. NULL,
  118380. NULL,
  118381. 0
  118382. };
  118383. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  118384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118386. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  118387. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  118388. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  118389. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  118390. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  118391. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  118392. };
  118393. static static_codebook _huff_book_line_1024x27_1sub1 = {
  118394. 1, 128,
  118395. _huff_lengthlist_line_1024x27_1sub1,
  118396. 0, 0, 0, 0, 0,
  118397. NULL,
  118398. NULL,
  118399. NULL,
  118400. NULL,
  118401. 0
  118402. };
  118403. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  118404. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118405. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  118406. };
  118407. static static_codebook _huff_book_line_1024x27_2sub0 = {
  118408. 1, 32,
  118409. _huff_lengthlist_line_1024x27_2sub0,
  118410. 0, 0, 0, 0, 0,
  118411. NULL,
  118412. NULL,
  118413. NULL,
  118414. NULL,
  118415. 0
  118416. };
  118417. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  118418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118420. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  118421. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  118422. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  118423. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  118424. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  118425. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  118426. };
  118427. static static_codebook _huff_book_line_1024x27_2sub1 = {
  118428. 1, 128,
  118429. _huff_lengthlist_line_1024x27_2sub1,
  118430. 0, 0, 0, 0, 0,
  118431. NULL,
  118432. NULL,
  118433. NULL,
  118434. NULL,
  118435. 0
  118436. };
  118437. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  118438. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  118439. 5, 5,
  118440. };
  118441. static static_codebook _huff_book_line_1024x27_3sub1 = {
  118442. 1, 18,
  118443. _huff_lengthlist_line_1024x27_3sub1,
  118444. 0, 0, 0, 0, 0,
  118445. NULL,
  118446. NULL,
  118447. NULL,
  118448. NULL,
  118449. 0
  118450. };
  118451. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  118452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118453. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  118454. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  118455. 9,11,
  118456. };
  118457. static static_codebook _huff_book_line_1024x27_3sub2 = {
  118458. 1, 50,
  118459. _huff_lengthlist_line_1024x27_3sub2,
  118460. 0, 0, 0, 0, 0,
  118461. NULL,
  118462. NULL,
  118463. NULL,
  118464. NULL,
  118465. 0
  118466. };
  118467. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  118468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118471. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  118472. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  118473. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118474. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118475. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118476. };
  118477. static static_codebook _huff_book_line_1024x27_3sub3 = {
  118478. 1, 128,
  118479. _huff_lengthlist_line_1024x27_3sub3,
  118480. 0, 0, 0, 0, 0,
  118481. NULL,
  118482. NULL,
  118483. NULL,
  118484. NULL,
  118485. 0
  118486. };
  118487. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  118488. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  118489. 5, 4,
  118490. };
  118491. static static_codebook _huff_book_line_1024x27_4sub1 = {
  118492. 1, 18,
  118493. _huff_lengthlist_line_1024x27_4sub1,
  118494. 0, 0, 0, 0, 0,
  118495. NULL,
  118496. NULL,
  118497. NULL,
  118498. NULL,
  118499. 0
  118500. };
  118501. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  118502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118503. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  118504. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  118505. 9,12,
  118506. };
  118507. static static_codebook _huff_book_line_1024x27_4sub2 = {
  118508. 1, 50,
  118509. _huff_lengthlist_line_1024x27_4sub2,
  118510. 0, 0, 0, 0, 0,
  118511. NULL,
  118512. NULL,
  118513. NULL,
  118514. NULL,
  118515. 0
  118516. };
  118517. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  118518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118521. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  118522. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  118523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118524. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118525. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  118526. };
  118527. static static_codebook _huff_book_line_1024x27_4sub3 = {
  118528. 1, 128,
  118529. _huff_lengthlist_line_1024x27_4sub3,
  118530. 0, 0, 0, 0, 0,
  118531. NULL,
  118532. NULL,
  118533. NULL,
  118534. NULL,
  118535. 0
  118536. };
  118537. static long _huff_lengthlist_line_2048x27_class1[] = {
  118538. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  118539. };
  118540. static static_codebook _huff_book_line_2048x27_class1 = {
  118541. 1, 16,
  118542. _huff_lengthlist_line_2048x27_class1,
  118543. 0, 0, 0, 0, 0,
  118544. NULL,
  118545. NULL,
  118546. NULL,
  118547. NULL,
  118548. 0
  118549. };
  118550. static long _huff_lengthlist_line_2048x27_class2[] = {
  118551. 1, 2, 3, 6, 4, 7, 5, 7,
  118552. };
  118553. static static_codebook _huff_book_line_2048x27_class2 = {
  118554. 1, 8,
  118555. _huff_lengthlist_line_2048x27_class2,
  118556. 0, 0, 0, 0, 0,
  118557. NULL,
  118558. NULL,
  118559. NULL,
  118560. NULL,
  118561. 0
  118562. };
  118563. static long _huff_lengthlist_line_2048x27_class3[] = {
  118564. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  118565. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  118566. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  118567. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  118568. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  118569. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  118570. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  118571. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  118572. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  118573. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  118574. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  118575. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  118576. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  118577. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  118578. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  118579. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  118580. };
  118581. static static_codebook _huff_book_line_2048x27_class3 = {
  118582. 1, 256,
  118583. _huff_lengthlist_line_2048x27_class3,
  118584. 0, 0, 0, 0, 0,
  118585. NULL,
  118586. NULL,
  118587. NULL,
  118588. NULL,
  118589. 0
  118590. };
  118591. static long _huff_lengthlist_line_2048x27_class4[] = {
  118592. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  118593. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  118594. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  118595. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  118596. };
  118597. static static_codebook _huff_book_line_2048x27_class4 = {
  118598. 1, 64,
  118599. _huff_lengthlist_line_2048x27_class4,
  118600. 0, 0, 0, 0, 0,
  118601. NULL,
  118602. NULL,
  118603. NULL,
  118604. NULL,
  118605. 0
  118606. };
  118607. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  118608. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118609. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  118610. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  118611. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  118612. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  118613. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  118614. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  118615. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  118616. };
  118617. static static_codebook _huff_book_line_2048x27_0sub0 = {
  118618. 1, 128,
  118619. _huff_lengthlist_line_2048x27_0sub0,
  118620. 0, 0, 0, 0, 0,
  118621. NULL,
  118622. NULL,
  118623. NULL,
  118624. NULL,
  118625. 0
  118626. };
  118627. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  118628. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  118629. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  118630. };
  118631. static static_codebook _huff_book_line_2048x27_1sub0 = {
  118632. 1, 32,
  118633. _huff_lengthlist_line_2048x27_1sub0,
  118634. 0, 0, 0, 0, 0,
  118635. NULL,
  118636. NULL,
  118637. NULL,
  118638. NULL,
  118639. 0
  118640. };
  118641. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  118642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118644. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  118645. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  118646. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  118647. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  118648. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  118649. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  118650. };
  118651. static static_codebook _huff_book_line_2048x27_1sub1 = {
  118652. 1, 128,
  118653. _huff_lengthlist_line_2048x27_1sub1,
  118654. 0, 0, 0, 0, 0,
  118655. NULL,
  118656. NULL,
  118657. NULL,
  118658. NULL,
  118659. 0
  118660. };
  118661. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  118662. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118663. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  118664. };
  118665. static static_codebook _huff_book_line_2048x27_2sub0 = {
  118666. 1, 32,
  118667. _huff_lengthlist_line_2048x27_2sub0,
  118668. 0, 0, 0, 0, 0,
  118669. NULL,
  118670. NULL,
  118671. NULL,
  118672. NULL,
  118673. 0
  118674. };
  118675. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  118676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118678. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  118679. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  118680. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  118681. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  118682. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  118683. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118684. };
  118685. static static_codebook _huff_book_line_2048x27_2sub1 = {
  118686. 1, 128,
  118687. _huff_lengthlist_line_2048x27_2sub1,
  118688. 0, 0, 0, 0, 0,
  118689. NULL,
  118690. NULL,
  118691. NULL,
  118692. NULL,
  118693. 0
  118694. };
  118695. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  118696. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  118697. 5, 5,
  118698. };
  118699. static static_codebook _huff_book_line_2048x27_3sub1 = {
  118700. 1, 18,
  118701. _huff_lengthlist_line_2048x27_3sub1,
  118702. 0, 0, 0, 0, 0,
  118703. NULL,
  118704. NULL,
  118705. NULL,
  118706. NULL,
  118707. 0
  118708. };
  118709. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  118710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118711. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  118712. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  118713. 10,12,
  118714. };
  118715. static static_codebook _huff_book_line_2048x27_3sub2 = {
  118716. 1, 50,
  118717. _huff_lengthlist_line_2048x27_3sub2,
  118718. 0, 0, 0, 0, 0,
  118719. NULL,
  118720. NULL,
  118721. NULL,
  118722. NULL,
  118723. 0
  118724. };
  118725. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  118726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118729. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  118730. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118731. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118732. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118733. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118734. };
  118735. static static_codebook _huff_book_line_2048x27_3sub3 = {
  118736. 1, 128,
  118737. _huff_lengthlist_line_2048x27_3sub3,
  118738. 0, 0, 0, 0, 0,
  118739. NULL,
  118740. NULL,
  118741. NULL,
  118742. NULL,
  118743. 0
  118744. };
  118745. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  118746. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  118747. 4, 5,
  118748. };
  118749. static static_codebook _huff_book_line_2048x27_4sub1 = {
  118750. 1, 18,
  118751. _huff_lengthlist_line_2048x27_4sub1,
  118752. 0, 0, 0, 0, 0,
  118753. NULL,
  118754. NULL,
  118755. NULL,
  118756. NULL,
  118757. 0
  118758. };
  118759. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  118760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118761. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  118762. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  118763. 10,10,
  118764. };
  118765. static static_codebook _huff_book_line_2048x27_4sub2 = {
  118766. 1, 50,
  118767. _huff_lengthlist_line_2048x27_4sub2,
  118768. 0, 0, 0, 0, 0,
  118769. NULL,
  118770. NULL,
  118771. NULL,
  118772. NULL,
  118773. 0
  118774. };
  118775. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  118776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118779. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  118780. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  118781. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118782. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118783. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118784. };
  118785. static static_codebook _huff_book_line_2048x27_4sub3 = {
  118786. 1, 128,
  118787. _huff_lengthlist_line_2048x27_4sub3,
  118788. 0, 0, 0, 0, 0,
  118789. NULL,
  118790. NULL,
  118791. NULL,
  118792. NULL,
  118793. 0
  118794. };
  118795. static long _huff_lengthlist_line_256x4low_class0[] = {
  118796. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  118797. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  118798. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  118799. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  118800. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  118801. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  118802. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  118803. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  118804. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  118805. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  118806. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  118807. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  118808. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  118809. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  118810. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  118811. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  118812. };
  118813. static static_codebook _huff_book_line_256x4low_class0 = {
  118814. 1, 256,
  118815. _huff_lengthlist_line_256x4low_class0,
  118816. 0, 0, 0, 0, 0,
  118817. NULL,
  118818. NULL,
  118819. NULL,
  118820. NULL,
  118821. 0
  118822. };
  118823. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  118824. 1, 3, 2, 3,
  118825. };
  118826. static static_codebook _huff_book_line_256x4low_0sub0 = {
  118827. 1, 4,
  118828. _huff_lengthlist_line_256x4low_0sub0,
  118829. 0, 0, 0, 0, 0,
  118830. NULL,
  118831. NULL,
  118832. NULL,
  118833. NULL,
  118834. 0
  118835. };
  118836. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  118837. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  118838. };
  118839. static static_codebook _huff_book_line_256x4low_0sub1 = {
  118840. 1, 10,
  118841. _huff_lengthlist_line_256x4low_0sub1,
  118842. 0, 0, 0, 0, 0,
  118843. NULL,
  118844. NULL,
  118845. NULL,
  118846. NULL,
  118847. 0
  118848. };
  118849. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  118850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  118851. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  118852. };
  118853. static static_codebook _huff_book_line_256x4low_0sub2 = {
  118854. 1, 25,
  118855. _huff_lengthlist_line_256x4low_0sub2,
  118856. 0, 0, 0, 0, 0,
  118857. NULL,
  118858. NULL,
  118859. NULL,
  118860. NULL,
  118861. 0
  118862. };
  118863. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  118864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  118866. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  118867. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  118868. };
  118869. static static_codebook _huff_book_line_256x4low_0sub3 = {
  118870. 1, 64,
  118871. _huff_lengthlist_line_256x4low_0sub3,
  118872. 0, 0, 0, 0, 0,
  118873. NULL,
  118874. NULL,
  118875. NULL,
  118876. NULL,
  118877. 0
  118878. };
  118879. /*** End of inlined file: floor_books.h ***/
  118880. static static_codebook *_floor_128x4_books[]={
  118881. &_huff_book_line_128x4_class0,
  118882. &_huff_book_line_128x4_0sub0,
  118883. &_huff_book_line_128x4_0sub1,
  118884. &_huff_book_line_128x4_0sub2,
  118885. &_huff_book_line_128x4_0sub3,
  118886. };
  118887. static static_codebook *_floor_256x4_books[]={
  118888. &_huff_book_line_256x4_class0,
  118889. &_huff_book_line_256x4_0sub0,
  118890. &_huff_book_line_256x4_0sub1,
  118891. &_huff_book_line_256x4_0sub2,
  118892. &_huff_book_line_256x4_0sub3,
  118893. };
  118894. static static_codebook *_floor_128x7_books[]={
  118895. &_huff_book_line_128x7_class0,
  118896. &_huff_book_line_128x7_class1,
  118897. &_huff_book_line_128x7_0sub1,
  118898. &_huff_book_line_128x7_0sub2,
  118899. &_huff_book_line_128x7_0sub3,
  118900. &_huff_book_line_128x7_1sub1,
  118901. &_huff_book_line_128x7_1sub2,
  118902. &_huff_book_line_128x7_1sub3,
  118903. };
  118904. static static_codebook *_floor_256x7_books[]={
  118905. &_huff_book_line_256x7_class0,
  118906. &_huff_book_line_256x7_class1,
  118907. &_huff_book_line_256x7_0sub1,
  118908. &_huff_book_line_256x7_0sub2,
  118909. &_huff_book_line_256x7_0sub3,
  118910. &_huff_book_line_256x7_1sub1,
  118911. &_huff_book_line_256x7_1sub2,
  118912. &_huff_book_line_256x7_1sub3,
  118913. };
  118914. static static_codebook *_floor_128x11_books[]={
  118915. &_huff_book_line_128x11_class1,
  118916. &_huff_book_line_128x11_class2,
  118917. &_huff_book_line_128x11_class3,
  118918. &_huff_book_line_128x11_0sub0,
  118919. &_huff_book_line_128x11_1sub0,
  118920. &_huff_book_line_128x11_1sub1,
  118921. &_huff_book_line_128x11_2sub1,
  118922. &_huff_book_line_128x11_2sub2,
  118923. &_huff_book_line_128x11_2sub3,
  118924. &_huff_book_line_128x11_3sub1,
  118925. &_huff_book_line_128x11_3sub2,
  118926. &_huff_book_line_128x11_3sub3,
  118927. };
  118928. static static_codebook *_floor_128x17_books[]={
  118929. &_huff_book_line_128x17_class1,
  118930. &_huff_book_line_128x17_class2,
  118931. &_huff_book_line_128x17_class3,
  118932. &_huff_book_line_128x17_0sub0,
  118933. &_huff_book_line_128x17_1sub0,
  118934. &_huff_book_line_128x17_1sub1,
  118935. &_huff_book_line_128x17_2sub1,
  118936. &_huff_book_line_128x17_2sub2,
  118937. &_huff_book_line_128x17_2sub3,
  118938. &_huff_book_line_128x17_3sub1,
  118939. &_huff_book_line_128x17_3sub2,
  118940. &_huff_book_line_128x17_3sub3,
  118941. };
  118942. static static_codebook *_floor_256x4low_books[]={
  118943. &_huff_book_line_256x4low_class0,
  118944. &_huff_book_line_256x4low_0sub0,
  118945. &_huff_book_line_256x4low_0sub1,
  118946. &_huff_book_line_256x4low_0sub2,
  118947. &_huff_book_line_256x4low_0sub3,
  118948. };
  118949. static static_codebook *_floor_1024x27_books[]={
  118950. &_huff_book_line_1024x27_class1,
  118951. &_huff_book_line_1024x27_class2,
  118952. &_huff_book_line_1024x27_class3,
  118953. &_huff_book_line_1024x27_class4,
  118954. &_huff_book_line_1024x27_0sub0,
  118955. &_huff_book_line_1024x27_1sub0,
  118956. &_huff_book_line_1024x27_1sub1,
  118957. &_huff_book_line_1024x27_2sub0,
  118958. &_huff_book_line_1024x27_2sub1,
  118959. &_huff_book_line_1024x27_3sub1,
  118960. &_huff_book_line_1024x27_3sub2,
  118961. &_huff_book_line_1024x27_3sub3,
  118962. &_huff_book_line_1024x27_4sub1,
  118963. &_huff_book_line_1024x27_4sub2,
  118964. &_huff_book_line_1024x27_4sub3,
  118965. };
  118966. static static_codebook *_floor_2048x27_books[]={
  118967. &_huff_book_line_2048x27_class1,
  118968. &_huff_book_line_2048x27_class2,
  118969. &_huff_book_line_2048x27_class3,
  118970. &_huff_book_line_2048x27_class4,
  118971. &_huff_book_line_2048x27_0sub0,
  118972. &_huff_book_line_2048x27_1sub0,
  118973. &_huff_book_line_2048x27_1sub1,
  118974. &_huff_book_line_2048x27_2sub0,
  118975. &_huff_book_line_2048x27_2sub1,
  118976. &_huff_book_line_2048x27_3sub1,
  118977. &_huff_book_line_2048x27_3sub2,
  118978. &_huff_book_line_2048x27_3sub3,
  118979. &_huff_book_line_2048x27_4sub1,
  118980. &_huff_book_line_2048x27_4sub2,
  118981. &_huff_book_line_2048x27_4sub3,
  118982. };
  118983. static static_codebook *_floor_512x17_books[]={
  118984. &_huff_book_line_512x17_class1,
  118985. &_huff_book_line_512x17_class2,
  118986. &_huff_book_line_512x17_class3,
  118987. &_huff_book_line_512x17_0sub0,
  118988. &_huff_book_line_512x17_1sub0,
  118989. &_huff_book_line_512x17_1sub1,
  118990. &_huff_book_line_512x17_2sub1,
  118991. &_huff_book_line_512x17_2sub2,
  118992. &_huff_book_line_512x17_2sub3,
  118993. &_huff_book_line_512x17_3sub1,
  118994. &_huff_book_line_512x17_3sub2,
  118995. &_huff_book_line_512x17_3sub3,
  118996. };
  118997. static static_codebook **_floor_books[10]={
  118998. _floor_128x4_books,
  118999. _floor_256x4_books,
  119000. _floor_128x7_books,
  119001. _floor_256x7_books,
  119002. _floor_128x11_books,
  119003. _floor_128x17_books,
  119004. _floor_256x4low_books,
  119005. _floor_1024x27_books,
  119006. _floor_2048x27_books,
  119007. _floor_512x17_books,
  119008. };
  119009. static vorbis_info_floor1 _floor[10]={
  119010. /* 128 x 4 */
  119011. {
  119012. 1,{0},{4},{2},{0},
  119013. {{1,2,3,4}},
  119014. 4,{0,128, 33,8,16,70},
  119015. 60,30,500, 1.,18., -1
  119016. },
  119017. /* 256 x 4 */
  119018. {
  119019. 1,{0},{4},{2},{0},
  119020. {{1,2,3,4}},
  119021. 4,{0,256, 66,16,32,140},
  119022. 60,30,500, 1.,18., -1
  119023. },
  119024. /* 128 x 7 */
  119025. {
  119026. 2,{0,1},{3,4},{2,2},{0,1},
  119027. {{-1,2,3,4},{-1,5,6,7}},
  119028. 4,{0,128, 14,4,58, 2,8,28,90},
  119029. 60,30,500, 1.,18., -1
  119030. },
  119031. /* 256 x 7 */
  119032. {
  119033. 2,{0,1},{3,4},{2,2},{0,1},
  119034. {{-1,2,3,4},{-1,5,6,7}},
  119035. 4,{0,256, 28,8,116, 4,16,56,180},
  119036. 60,30,500, 1.,18., -1
  119037. },
  119038. /* 128 x 11 */
  119039. {
  119040. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119041. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119042. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  119043. 60,30,500, 1,18., -1
  119044. },
  119045. /* 128 x 17 */
  119046. {
  119047. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119048. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119049. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  119050. 60,30,500, 1,18., -1
  119051. },
  119052. /* 256 x 4 (low bitrate version) */
  119053. {
  119054. 1,{0},{4},{2},{0},
  119055. {{1,2,3,4}},
  119056. 4,{0,256, 66,16,32,140},
  119057. 60,30,500, 1.,18., -1
  119058. },
  119059. /* 1024 x 27 */
  119060. {
  119061. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119062. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119063. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  119064. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  119065. 60,30,500, 3,18., -1 /* lowpass */
  119066. },
  119067. /* 2048 x 27 */
  119068. {
  119069. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119070. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119071. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  119072. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  119073. 60,30,500, 3,18., -1 /* lowpass */
  119074. },
  119075. /* 512 x 17 */
  119076. {
  119077. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119078. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119079. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  119080. 7,23,39, 55,79,110, 156,232,360},
  119081. 60,30,500, 1,18., -1 /* lowpass! */
  119082. },
  119083. };
  119084. /*** End of inlined file: floor_all.h ***/
  119085. /*** Start of inlined file: residue_44.h ***/
  119086. /*** Start of inlined file: res_books_stereo.h ***/
  119087. static long _vq_quantlist__16c0_s_p1_0[] = {
  119088. 1,
  119089. 0,
  119090. 2,
  119091. };
  119092. static long _vq_lengthlist__16c0_s_p1_0[] = {
  119093. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119094. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  119099. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119104. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  119123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  119128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  119133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  119139. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  119144. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  119149. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119169. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119174. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119185. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119190. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119195. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119503. 0,
  119504. };
  119505. static float _vq_quantthresh__16c0_s_p1_0[] = {
  119506. -0.5, 0.5,
  119507. };
  119508. static long _vq_quantmap__16c0_s_p1_0[] = {
  119509. 1, 0, 2,
  119510. };
  119511. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  119512. _vq_quantthresh__16c0_s_p1_0,
  119513. _vq_quantmap__16c0_s_p1_0,
  119514. 3,
  119515. 3
  119516. };
  119517. static static_codebook _16c0_s_p1_0 = {
  119518. 8, 6561,
  119519. _vq_lengthlist__16c0_s_p1_0,
  119520. 1, -535822336, 1611661312, 2, 0,
  119521. _vq_quantlist__16c0_s_p1_0,
  119522. NULL,
  119523. &_vq_auxt__16c0_s_p1_0,
  119524. NULL,
  119525. 0
  119526. };
  119527. static long _vq_quantlist__16c0_s_p2_0[] = {
  119528. 2,
  119529. 1,
  119530. 3,
  119531. 0,
  119532. 4,
  119533. };
  119534. static long _vq_lengthlist__16c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119574. 0,
  119575. };
  119576. static float _vq_quantthresh__16c0_s_p2_0[] = {
  119577. -1.5, -0.5, 0.5, 1.5,
  119578. };
  119579. static long _vq_quantmap__16c0_s_p2_0[] = {
  119580. 3, 1, 0, 2, 4,
  119581. };
  119582. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  119583. _vq_quantthresh__16c0_s_p2_0,
  119584. _vq_quantmap__16c0_s_p2_0,
  119585. 5,
  119586. 5
  119587. };
  119588. static static_codebook _16c0_s_p2_0 = {
  119589. 4, 625,
  119590. _vq_lengthlist__16c0_s_p2_0,
  119591. 1, -533725184, 1611661312, 3, 0,
  119592. _vq_quantlist__16c0_s_p2_0,
  119593. NULL,
  119594. &_vq_auxt__16c0_s_p2_0,
  119595. NULL,
  119596. 0
  119597. };
  119598. static long _vq_quantlist__16c0_s_p3_0[] = {
  119599. 2,
  119600. 1,
  119601. 3,
  119602. 0,
  119603. 4,
  119604. };
  119605. static long _vq_lengthlist__16c0_s_p3_0[] = {
  119606. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  119608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119609. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  119611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119612. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119645. 0,
  119646. };
  119647. static float _vq_quantthresh__16c0_s_p3_0[] = {
  119648. -1.5, -0.5, 0.5, 1.5,
  119649. };
  119650. static long _vq_quantmap__16c0_s_p3_0[] = {
  119651. 3, 1, 0, 2, 4,
  119652. };
  119653. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  119654. _vq_quantthresh__16c0_s_p3_0,
  119655. _vq_quantmap__16c0_s_p3_0,
  119656. 5,
  119657. 5
  119658. };
  119659. static static_codebook _16c0_s_p3_0 = {
  119660. 4, 625,
  119661. _vq_lengthlist__16c0_s_p3_0,
  119662. 1, -533725184, 1611661312, 3, 0,
  119663. _vq_quantlist__16c0_s_p3_0,
  119664. NULL,
  119665. &_vq_auxt__16c0_s_p3_0,
  119666. NULL,
  119667. 0
  119668. };
  119669. static long _vq_quantlist__16c0_s_p4_0[] = {
  119670. 4,
  119671. 3,
  119672. 5,
  119673. 2,
  119674. 6,
  119675. 1,
  119676. 7,
  119677. 0,
  119678. 8,
  119679. };
  119680. static long _vq_lengthlist__16c0_s_p4_0[] = {
  119681. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119682. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119683. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119684. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  119685. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119686. 0,
  119687. };
  119688. static float _vq_quantthresh__16c0_s_p4_0[] = {
  119689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119690. };
  119691. static long _vq_quantmap__16c0_s_p4_0[] = {
  119692. 7, 5, 3, 1, 0, 2, 4, 6,
  119693. 8,
  119694. };
  119695. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  119696. _vq_quantthresh__16c0_s_p4_0,
  119697. _vq_quantmap__16c0_s_p4_0,
  119698. 9,
  119699. 9
  119700. };
  119701. static static_codebook _16c0_s_p4_0 = {
  119702. 2, 81,
  119703. _vq_lengthlist__16c0_s_p4_0,
  119704. 1, -531628032, 1611661312, 4, 0,
  119705. _vq_quantlist__16c0_s_p4_0,
  119706. NULL,
  119707. &_vq_auxt__16c0_s_p4_0,
  119708. NULL,
  119709. 0
  119710. };
  119711. static long _vq_quantlist__16c0_s_p5_0[] = {
  119712. 4,
  119713. 3,
  119714. 5,
  119715. 2,
  119716. 6,
  119717. 1,
  119718. 7,
  119719. 0,
  119720. 8,
  119721. };
  119722. static long _vq_lengthlist__16c0_s_p5_0[] = {
  119723. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119724. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  119725. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  119726. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  119727. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119728. 10,
  119729. };
  119730. static float _vq_quantthresh__16c0_s_p5_0[] = {
  119731. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119732. };
  119733. static long _vq_quantmap__16c0_s_p5_0[] = {
  119734. 7, 5, 3, 1, 0, 2, 4, 6,
  119735. 8,
  119736. };
  119737. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  119738. _vq_quantthresh__16c0_s_p5_0,
  119739. _vq_quantmap__16c0_s_p5_0,
  119740. 9,
  119741. 9
  119742. };
  119743. static static_codebook _16c0_s_p5_0 = {
  119744. 2, 81,
  119745. _vq_lengthlist__16c0_s_p5_0,
  119746. 1, -531628032, 1611661312, 4, 0,
  119747. _vq_quantlist__16c0_s_p5_0,
  119748. NULL,
  119749. &_vq_auxt__16c0_s_p5_0,
  119750. NULL,
  119751. 0
  119752. };
  119753. static long _vq_quantlist__16c0_s_p6_0[] = {
  119754. 8,
  119755. 7,
  119756. 9,
  119757. 6,
  119758. 10,
  119759. 5,
  119760. 11,
  119761. 4,
  119762. 12,
  119763. 3,
  119764. 13,
  119765. 2,
  119766. 14,
  119767. 1,
  119768. 15,
  119769. 0,
  119770. 16,
  119771. };
  119772. static long _vq_lengthlist__16c0_s_p6_0[] = {
  119773. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  119774. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  119775. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  119776. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  119777. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  119778. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119779. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119780. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119781. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  119782. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119783. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  119784. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  119785. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  119786. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  119787. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  119788. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  119789. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  119790. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  119791. 14,
  119792. };
  119793. static float _vq_quantthresh__16c0_s_p6_0[] = {
  119794. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119795. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119796. };
  119797. static long _vq_quantmap__16c0_s_p6_0[] = {
  119798. 15, 13, 11, 9, 7, 5, 3, 1,
  119799. 0, 2, 4, 6, 8, 10, 12, 14,
  119800. 16,
  119801. };
  119802. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  119803. _vq_quantthresh__16c0_s_p6_0,
  119804. _vq_quantmap__16c0_s_p6_0,
  119805. 17,
  119806. 17
  119807. };
  119808. static static_codebook _16c0_s_p6_0 = {
  119809. 2, 289,
  119810. _vq_lengthlist__16c0_s_p6_0,
  119811. 1, -529530880, 1611661312, 5, 0,
  119812. _vq_quantlist__16c0_s_p6_0,
  119813. NULL,
  119814. &_vq_auxt__16c0_s_p6_0,
  119815. NULL,
  119816. 0
  119817. };
  119818. static long _vq_quantlist__16c0_s_p7_0[] = {
  119819. 1,
  119820. 0,
  119821. 2,
  119822. };
  119823. static long _vq_lengthlist__16c0_s_p7_0[] = {
  119824. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  119825. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  119826. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  119827. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  119828. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  119829. 13,
  119830. };
  119831. static float _vq_quantthresh__16c0_s_p7_0[] = {
  119832. -5.5, 5.5,
  119833. };
  119834. static long _vq_quantmap__16c0_s_p7_0[] = {
  119835. 1, 0, 2,
  119836. };
  119837. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  119838. _vq_quantthresh__16c0_s_p7_0,
  119839. _vq_quantmap__16c0_s_p7_0,
  119840. 3,
  119841. 3
  119842. };
  119843. static static_codebook _16c0_s_p7_0 = {
  119844. 4, 81,
  119845. _vq_lengthlist__16c0_s_p7_0,
  119846. 1, -529137664, 1618345984, 2, 0,
  119847. _vq_quantlist__16c0_s_p7_0,
  119848. NULL,
  119849. &_vq_auxt__16c0_s_p7_0,
  119850. NULL,
  119851. 0
  119852. };
  119853. static long _vq_quantlist__16c0_s_p7_1[] = {
  119854. 5,
  119855. 4,
  119856. 6,
  119857. 3,
  119858. 7,
  119859. 2,
  119860. 8,
  119861. 1,
  119862. 9,
  119863. 0,
  119864. 10,
  119865. };
  119866. static long _vq_lengthlist__16c0_s_p7_1[] = {
  119867. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  119868. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  119869. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  119870. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  119871. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  119872. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  119873. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  119874. 11,11,11, 9, 9, 9, 9,10,10,
  119875. };
  119876. static float _vq_quantthresh__16c0_s_p7_1[] = {
  119877. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119878. 3.5, 4.5,
  119879. };
  119880. static long _vq_quantmap__16c0_s_p7_1[] = {
  119881. 9, 7, 5, 3, 1, 0, 2, 4,
  119882. 6, 8, 10,
  119883. };
  119884. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  119885. _vq_quantthresh__16c0_s_p7_1,
  119886. _vq_quantmap__16c0_s_p7_1,
  119887. 11,
  119888. 11
  119889. };
  119890. static static_codebook _16c0_s_p7_1 = {
  119891. 2, 121,
  119892. _vq_lengthlist__16c0_s_p7_1,
  119893. 1, -531365888, 1611661312, 4, 0,
  119894. _vq_quantlist__16c0_s_p7_1,
  119895. NULL,
  119896. &_vq_auxt__16c0_s_p7_1,
  119897. NULL,
  119898. 0
  119899. };
  119900. static long _vq_quantlist__16c0_s_p8_0[] = {
  119901. 6,
  119902. 5,
  119903. 7,
  119904. 4,
  119905. 8,
  119906. 3,
  119907. 9,
  119908. 2,
  119909. 10,
  119910. 1,
  119911. 11,
  119912. 0,
  119913. 12,
  119914. };
  119915. static long _vq_lengthlist__16c0_s_p8_0[] = {
  119916. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  119917. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  119918. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  119919. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  119920. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  119921. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  119922. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  119923. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  119924. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  119925. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  119926. 0,12,13,13,12,13,14,14,14,
  119927. };
  119928. static float _vq_quantthresh__16c0_s_p8_0[] = {
  119929. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119930. 12.5, 17.5, 22.5, 27.5,
  119931. };
  119932. static long _vq_quantmap__16c0_s_p8_0[] = {
  119933. 11, 9, 7, 5, 3, 1, 0, 2,
  119934. 4, 6, 8, 10, 12,
  119935. };
  119936. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  119937. _vq_quantthresh__16c0_s_p8_0,
  119938. _vq_quantmap__16c0_s_p8_0,
  119939. 13,
  119940. 13
  119941. };
  119942. static static_codebook _16c0_s_p8_0 = {
  119943. 2, 169,
  119944. _vq_lengthlist__16c0_s_p8_0,
  119945. 1, -526516224, 1616117760, 4, 0,
  119946. _vq_quantlist__16c0_s_p8_0,
  119947. NULL,
  119948. &_vq_auxt__16c0_s_p8_0,
  119949. NULL,
  119950. 0
  119951. };
  119952. static long _vq_quantlist__16c0_s_p8_1[] = {
  119953. 2,
  119954. 1,
  119955. 3,
  119956. 0,
  119957. 4,
  119958. };
  119959. static long _vq_lengthlist__16c0_s_p8_1[] = {
  119960. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  119961. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119962. };
  119963. static float _vq_quantthresh__16c0_s_p8_1[] = {
  119964. -1.5, -0.5, 0.5, 1.5,
  119965. };
  119966. static long _vq_quantmap__16c0_s_p8_1[] = {
  119967. 3, 1, 0, 2, 4,
  119968. };
  119969. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  119970. _vq_quantthresh__16c0_s_p8_1,
  119971. _vq_quantmap__16c0_s_p8_1,
  119972. 5,
  119973. 5
  119974. };
  119975. static static_codebook _16c0_s_p8_1 = {
  119976. 2, 25,
  119977. _vq_lengthlist__16c0_s_p8_1,
  119978. 1, -533725184, 1611661312, 3, 0,
  119979. _vq_quantlist__16c0_s_p8_1,
  119980. NULL,
  119981. &_vq_auxt__16c0_s_p8_1,
  119982. NULL,
  119983. 0
  119984. };
  119985. static long _vq_quantlist__16c0_s_p9_0[] = {
  119986. 1,
  119987. 0,
  119988. 2,
  119989. };
  119990. static long _vq_lengthlist__16c0_s_p9_0[] = {
  119991. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119992. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119993. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119994. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119995. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119996. 7,
  119997. };
  119998. static float _vq_quantthresh__16c0_s_p9_0[] = {
  119999. -157.5, 157.5,
  120000. };
  120001. static long _vq_quantmap__16c0_s_p9_0[] = {
  120002. 1, 0, 2,
  120003. };
  120004. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  120005. _vq_quantthresh__16c0_s_p9_0,
  120006. _vq_quantmap__16c0_s_p9_0,
  120007. 3,
  120008. 3
  120009. };
  120010. static static_codebook _16c0_s_p9_0 = {
  120011. 4, 81,
  120012. _vq_lengthlist__16c0_s_p9_0,
  120013. 1, -518803456, 1628680192, 2, 0,
  120014. _vq_quantlist__16c0_s_p9_0,
  120015. NULL,
  120016. &_vq_auxt__16c0_s_p9_0,
  120017. NULL,
  120018. 0
  120019. };
  120020. static long _vq_quantlist__16c0_s_p9_1[] = {
  120021. 7,
  120022. 6,
  120023. 8,
  120024. 5,
  120025. 9,
  120026. 4,
  120027. 10,
  120028. 3,
  120029. 11,
  120030. 2,
  120031. 12,
  120032. 1,
  120033. 13,
  120034. 0,
  120035. 14,
  120036. };
  120037. static long _vq_lengthlist__16c0_s_p9_1[] = {
  120038. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  120039. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  120040. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  120041. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  120042. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120043. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120044. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120045. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120046. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120047. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120048. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120049. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120050. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120051. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120052. 10,
  120053. };
  120054. static float _vq_quantthresh__16c0_s_p9_1[] = {
  120055. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120056. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120057. };
  120058. static long _vq_quantmap__16c0_s_p9_1[] = {
  120059. 13, 11, 9, 7, 5, 3, 1, 0,
  120060. 2, 4, 6, 8, 10, 12, 14,
  120061. };
  120062. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  120063. _vq_quantthresh__16c0_s_p9_1,
  120064. _vq_quantmap__16c0_s_p9_1,
  120065. 15,
  120066. 15
  120067. };
  120068. static static_codebook _16c0_s_p9_1 = {
  120069. 2, 225,
  120070. _vq_lengthlist__16c0_s_p9_1,
  120071. 1, -520986624, 1620377600, 4, 0,
  120072. _vq_quantlist__16c0_s_p9_1,
  120073. NULL,
  120074. &_vq_auxt__16c0_s_p9_1,
  120075. NULL,
  120076. 0
  120077. };
  120078. static long _vq_quantlist__16c0_s_p9_2[] = {
  120079. 10,
  120080. 9,
  120081. 11,
  120082. 8,
  120083. 12,
  120084. 7,
  120085. 13,
  120086. 6,
  120087. 14,
  120088. 5,
  120089. 15,
  120090. 4,
  120091. 16,
  120092. 3,
  120093. 17,
  120094. 2,
  120095. 18,
  120096. 1,
  120097. 19,
  120098. 0,
  120099. 20,
  120100. };
  120101. static long _vq_lengthlist__16c0_s_p9_2[] = {
  120102. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  120103. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  120104. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  120105. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  120106. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  120107. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  120108. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  120109. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  120110. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  120111. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  120112. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  120113. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  120114. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  120115. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  120116. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  120117. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  120118. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  120119. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  120120. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  120121. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  120122. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  120123. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  120124. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  120125. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  120126. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  120127. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  120128. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  120129. 10,11,10,10,11, 9,10,10,10,
  120130. };
  120131. static float _vq_quantthresh__16c0_s_p9_2[] = {
  120132. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120133. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120134. 6.5, 7.5, 8.5, 9.5,
  120135. };
  120136. static long _vq_quantmap__16c0_s_p9_2[] = {
  120137. 19, 17, 15, 13, 11, 9, 7, 5,
  120138. 3, 1, 0, 2, 4, 6, 8, 10,
  120139. 12, 14, 16, 18, 20,
  120140. };
  120141. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  120142. _vq_quantthresh__16c0_s_p9_2,
  120143. _vq_quantmap__16c0_s_p9_2,
  120144. 21,
  120145. 21
  120146. };
  120147. static static_codebook _16c0_s_p9_2 = {
  120148. 2, 441,
  120149. _vq_lengthlist__16c0_s_p9_2,
  120150. 1, -529268736, 1611661312, 5, 0,
  120151. _vq_quantlist__16c0_s_p9_2,
  120152. NULL,
  120153. &_vq_auxt__16c0_s_p9_2,
  120154. NULL,
  120155. 0
  120156. };
  120157. static long _huff_lengthlist__16c0_s_single[] = {
  120158. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  120159. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  120160. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  120161. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  120162. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  120163. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  120164. 16,16,18,18,
  120165. };
  120166. static static_codebook _huff_book__16c0_s_single = {
  120167. 2, 100,
  120168. _huff_lengthlist__16c0_s_single,
  120169. 0, 0, 0, 0, 0,
  120170. NULL,
  120171. NULL,
  120172. NULL,
  120173. NULL,
  120174. 0
  120175. };
  120176. static long _huff_lengthlist__16c1_s_long[] = {
  120177. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  120178. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  120179. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  120180. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  120181. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  120182. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  120183. 12,11,11,13,
  120184. };
  120185. static static_codebook _huff_book__16c1_s_long = {
  120186. 2, 100,
  120187. _huff_lengthlist__16c1_s_long,
  120188. 0, 0, 0, 0, 0,
  120189. NULL,
  120190. NULL,
  120191. NULL,
  120192. NULL,
  120193. 0
  120194. };
  120195. static long _vq_quantlist__16c1_s_p1_0[] = {
  120196. 1,
  120197. 0,
  120198. 2,
  120199. };
  120200. static long _vq_lengthlist__16c1_s_p1_0[] = {
  120201. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120202. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120207. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120212. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  120231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  120236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  120241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  120247. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  120252. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  120257. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120289. 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120293. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120298. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120303. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120611. 0,
  120612. };
  120613. static float _vq_quantthresh__16c1_s_p1_0[] = {
  120614. -0.5, 0.5,
  120615. };
  120616. static long _vq_quantmap__16c1_s_p1_0[] = {
  120617. 1, 0, 2,
  120618. };
  120619. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  120620. _vq_quantthresh__16c1_s_p1_0,
  120621. _vq_quantmap__16c1_s_p1_0,
  120622. 3,
  120623. 3
  120624. };
  120625. static static_codebook _16c1_s_p1_0 = {
  120626. 8, 6561,
  120627. _vq_lengthlist__16c1_s_p1_0,
  120628. 1, -535822336, 1611661312, 2, 0,
  120629. _vq_quantlist__16c1_s_p1_0,
  120630. NULL,
  120631. &_vq_auxt__16c1_s_p1_0,
  120632. NULL,
  120633. 0
  120634. };
  120635. static long _vq_quantlist__16c1_s_p2_0[] = {
  120636. 2,
  120637. 1,
  120638. 3,
  120639. 0,
  120640. 4,
  120641. };
  120642. static long _vq_lengthlist__16c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120682. 0,
  120683. };
  120684. static float _vq_quantthresh__16c1_s_p2_0[] = {
  120685. -1.5, -0.5, 0.5, 1.5,
  120686. };
  120687. static long _vq_quantmap__16c1_s_p2_0[] = {
  120688. 3, 1, 0, 2, 4,
  120689. };
  120690. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  120691. _vq_quantthresh__16c1_s_p2_0,
  120692. _vq_quantmap__16c1_s_p2_0,
  120693. 5,
  120694. 5
  120695. };
  120696. static static_codebook _16c1_s_p2_0 = {
  120697. 4, 625,
  120698. _vq_lengthlist__16c1_s_p2_0,
  120699. 1, -533725184, 1611661312, 3, 0,
  120700. _vq_quantlist__16c1_s_p2_0,
  120701. NULL,
  120702. &_vq_auxt__16c1_s_p2_0,
  120703. NULL,
  120704. 0
  120705. };
  120706. static long _vq_quantlist__16c1_s_p3_0[] = {
  120707. 2,
  120708. 1,
  120709. 3,
  120710. 0,
  120711. 4,
  120712. };
  120713. static long _vq_lengthlist__16c1_s_p3_0[] = {
  120714. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  120716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120717. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  120719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120720. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120753. 0,
  120754. };
  120755. static float _vq_quantthresh__16c1_s_p3_0[] = {
  120756. -1.5, -0.5, 0.5, 1.5,
  120757. };
  120758. static long _vq_quantmap__16c1_s_p3_0[] = {
  120759. 3, 1, 0, 2, 4,
  120760. };
  120761. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  120762. _vq_quantthresh__16c1_s_p3_0,
  120763. _vq_quantmap__16c1_s_p3_0,
  120764. 5,
  120765. 5
  120766. };
  120767. static static_codebook _16c1_s_p3_0 = {
  120768. 4, 625,
  120769. _vq_lengthlist__16c1_s_p3_0,
  120770. 1, -533725184, 1611661312, 3, 0,
  120771. _vq_quantlist__16c1_s_p3_0,
  120772. NULL,
  120773. &_vq_auxt__16c1_s_p3_0,
  120774. NULL,
  120775. 0
  120776. };
  120777. static long _vq_quantlist__16c1_s_p4_0[] = {
  120778. 4,
  120779. 3,
  120780. 5,
  120781. 2,
  120782. 6,
  120783. 1,
  120784. 7,
  120785. 0,
  120786. 8,
  120787. };
  120788. static long _vq_lengthlist__16c1_s_p4_0[] = {
  120789. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120790. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120791. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120792. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  120793. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120794. 0,
  120795. };
  120796. static float _vq_quantthresh__16c1_s_p4_0[] = {
  120797. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120798. };
  120799. static long _vq_quantmap__16c1_s_p4_0[] = {
  120800. 7, 5, 3, 1, 0, 2, 4, 6,
  120801. 8,
  120802. };
  120803. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  120804. _vq_quantthresh__16c1_s_p4_0,
  120805. _vq_quantmap__16c1_s_p4_0,
  120806. 9,
  120807. 9
  120808. };
  120809. static static_codebook _16c1_s_p4_0 = {
  120810. 2, 81,
  120811. _vq_lengthlist__16c1_s_p4_0,
  120812. 1, -531628032, 1611661312, 4, 0,
  120813. _vq_quantlist__16c1_s_p4_0,
  120814. NULL,
  120815. &_vq_auxt__16c1_s_p4_0,
  120816. NULL,
  120817. 0
  120818. };
  120819. static long _vq_quantlist__16c1_s_p5_0[] = {
  120820. 4,
  120821. 3,
  120822. 5,
  120823. 2,
  120824. 6,
  120825. 1,
  120826. 7,
  120827. 0,
  120828. 8,
  120829. };
  120830. static long _vq_lengthlist__16c1_s_p5_0[] = {
  120831. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120832. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  120833. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  120834. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120835. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120836. 10,
  120837. };
  120838. static float _vq_quantthresh__16c1_s_p5_0[] = {
  120839. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120840. };
  120841. static long _vq_quantmap__16c1_s_p5_0[] = {
  120842. 7, 5, 3, 1, 0, 2, 4, 6,
  120843. 8,
  120844. };
  120845. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  120846. _vq_quantthresh__16c1_s_p5_0,
  120847. _vq_quantmap__16c1_s_p5_0,
  120848. 9,
  120849. 9
  120850. };
  120851. static static_codebook _16c1_s_p5_0 = {
  120852. 2, 81,
  120853. _vq_lengthlist__16c1_s_p5_0,
  120854. 1, -531628032, 1611661312, 4, 0,
  120855. _vq_quantlist__16c1_s_p5_0,
  120856. NULL,
  120857. &_vq_auxt__16c1_s_p5_0,
  120858. NULL,
  120859. 0
  120860. };
  120861. static long _vq_quantlist__16c1_s_p6_0[] = {
  120862. 8,
  120863. 7,
  120864. 9,
  120865. 6,
  120866. 10,
  120867. 5,
  120868. 11,
  120869. 4,
  120870. 12,
  120871. 3,
  120872. 13,
  120873. 2,
  120874. 14,
  120875. 1,
  120876. 15,
  120877. 0,
  120878. 16,
  120879. };
  120880. static long _vq_lengthlist__16c1_s_p6_0[] = {
  120881. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  120882. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120883. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120884. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  120885. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  120886. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  120887. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  120888. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  120889. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  120890. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120891. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  120892. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  120893. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  120894. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  120895. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  120896. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  120897. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  120898. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  120899. 14,
  120900. };
  120901. static float _vq_quantthresh__16c1_s_p6_0[] = {
  120902. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120903. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120904. };
  120905. static long _vq_quantmap__16c1_s_p6_0[] = {
  120906. 15, 13, 11, 9, 7, 5, 3, 1,
  120907. 0, 2, 4, 6, 8, 10, 12, 14,
  120908. 16,
  120909. };
  120910. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  120911. _vq_quantthresh__16c1_s_p6_0,
  120912. _vq_quantmap__16c1_s_p6_0,
  120913. 17,
  120914. 17
  120915. };
  120916. static static_codebook _16c1_s_p6_0 = {
  120917. 2, 289,
  120918. _vq_lengthlist__16c1_s_p6_0,
  120919. 1, -529530880, 1611661312, 5, 0,
  120920. _vq_quantlist__16c1_s_p6_0,
  120921. NULL,
  120922. &_vq_auxt__16c1_s_p6_0,
  120923. NULL,
  120924. 0
  120925. };
  120926. static long _vq_quantlist__16c1_s_p7_0[] = {
  120927. 1,
  120928. 0,
  120929. 2,
  120930. };
  120931. static long _vq_lengthlist__16c1_s_p7_0[] = {
  120932. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  120933. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120934. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  120935. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  120936. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  120937. 11,
  120938. };
  120939. static float _vq_quantthresh__16c1_s_p7_0[] = {
  120940. -5.5, 5.5,
  120941. };
  120942. static long _vq_quantmap__16c1_s_p7_0[] = {
  120943. 1, 0, 2,
  120944. };
  120945. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  120946. _vq_quantthresh__16c1_s_p7_0,
  120947. _vq_quantmap__16c1_s_p7_0,
  120948. 3,
  120949. 3
  120950. };
  120951. static static_codebook _16c1_s_p7_0 = {
  120952. 4, 81,
  120953. _vq_lengthlist__16c1_s_p7_0,
  120954. 1, -529137664, 1618345984, 2, 0,
  120955. _vq_quantlist__16c1_s_p7_0,
  120956. NULL,
  120957. &_vq_auxt__16c1_s_p7_0,
  120958. NULL,
  120959. 0
  120960. };
  120961. static long _vq_quantlist__16c1_s_p7_1[] = {
  120962. 5,
  120963. 4,
  120964. 6,
  120965. 3,
  120966. 7,
  120967. 2,
  120968. 8,
  120969. 1,
  120970. 9,
  120971. 0,
  120972. 10,
  120973. };
  120974. static long _vq_lengthlist__16c1_s_p7_1[] = {
  120975. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  120976. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  120977. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120978. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  120979. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  120980. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  120981. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  120982. 10,10,10, 8, 8, 8, 8, 9, 9,
  120983. };
  120984. static float _vq_quantthresh__16c1_s_p7_1[] = {
  120985. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120986. 3.5, 4.5,
  120987. };
  120988. static long _vq_quantmap__16c1_s_p7_1[] = {
  120989. 9, 7, 5, 3, 1, 0, 2, 4,
  120990. 6, 8, 10,
  120991. };
  120992. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  120993. _vq_quantthresh__16c1_s_p7_1,
  120994. _vq_quantmap__16c1_s_p7_1,
  120995. 11,
  120996. 11
  120997. };
  120998. static static_codebook _16c1_s_p7_1 = {
  120999. 2, 121,
  121000. _vq_lengthlist__16c1_s_p7_1,
  121001. 1, -531365888, 1611661312, 4, 0,
  121002. _vq_quantlist__16c1_s_p7_1,
  121003. NULL,
  121004. &_vq_auxt__16c1_s_p7_1,
  121005. NULL,
  121006. 0
  121007. };
  121008. static long _vq_quantlist__16c1_s_p8_0[] = {
  121009. 6,
  121010. 5,
  121011. 7,
  121012. 4,
  121013. 8,
  121014. 3,
  121015. 9,
  121016. 2,
  121017. 10,
  121018. 1,
  121019. 11,
  121020. 0,
  121021. 12,
  121022. };
  121023. static long _vq_lengthlist__16c1_s_p8_0[] = {
  121024. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  121025. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  121026. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  121027. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  121028. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  121029. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  121030. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  121031. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  121032. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  121033. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  121034. 0,12,12,12,12,13,13,14,15,
  121035. };
  121036. static float _vq_quantthresh__16c1_s_p8_0[] = {
  121037. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121038. 12.5, 17.5, 22.5, 27.5,
  121039. };
  121040. static long _vq_quantmap__16c1_s_p8_0[] = {
  121041. 11, 9, 7, 5, 3, 1, 0, 2,
  121042. 4, 6, 8, 10, 12,
  121043. };
  121044. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  121045. _vq_quantthresh__16c1_s_p8_0,
  121046. _vq_quantmap__16c1_s_p8_0,
  121047. 13,
  121048. 13
  121049. };
  121050. static static_codebook _16c1_s_p8_0 = {
  121051. 2, 169,
  121052. _vq_lengthlist__16c1_s_p8_0,
  121053. 1, -526516224, 1616117760, 4, 0,
  121054. _vq_quantlist__16c1_s_p8_0,
  121055. NULL,
  121056. &_vq_auxt__16c1_s_p8_0,
  121057. NULL,
  121058. 0
  121059. };
  121060. static long _vq_quantlist__16c1_s_p8_1[] = {
  121061. 2,
  121062. 1,
  121063. 3,
  121064. 0,
  121065. 4,
  121066. };
  121067. static long _vq_lengthlist__16c1_s_p8_1[] = {
  121068. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121069. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121070. };
  121071. static float _vq_quantthresh__16c1_s_p8_1[] = {
  121072. -1.5, -0.5, 0.5, 1.5,
  121073. };
  121074. static long _vq_quantmap__16c1_s_p8_1[] = {
  121075. 3, 1, 0, 2, 4,
  121076. };
  121077. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  121078. _vq_quantthresh__16c1_s_p8_1,
  121079. _vq_quantmap__16c1_s_p8_1,
  121080. 5,
  121081. 5
  121082. };
  121083. static static_codebook _16c1_s_p8_1 = {
  121084. 2, 25,
  121085. _vq_lengthlist__16c1_s_p8_1,
  121086. 1, -533725184, 1611661312, 3, 0,
  121087. _vq_quantlist__16c1_s_p8_1,
  121088. NULL,
  121089. &_vq_auxt__16c1_s_p8_1,
  121090. NULL,
  121091. 0
  121092. };
  121093. static long _vq_quantlist__16c1_s_p9_0[] = {
  121094. 6,
  121095. 5,
  121096. 7,
  121097. 4,
  121098. 8,
  121099. 3,
  121100. 9,
  121101. 2,
  121102. 10,
  121103. 1,
  121104. 11,
  121105. 0,
  121106. 12,
  121107. };
  121108. static long _vq_lengthlist__16c1_s_p9_0[] = {
  121109. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121110. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121111. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121112. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121113. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121114. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121115. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121116. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121117. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121118. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121119. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121120. };
  121121. static float _vq_quantthresh__16c1_s_p9_0[] = {
  121122. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121123. 787.5, 1102.5, 1417.5, 1732.5,
  121124. };
  121125. static long _vq_quantmap__16c1_s_p9_0[] = {
  121126. 11, 9, 7, 5, 3, 1, 0, 2,
  121127. 4, 6, 8, 10, 12,
  121128. };
  121129. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  121130. _vq_quantthresh__16c1_s_p9_0,
  121131. _vq_quantmap__16c1_s_p9_0,
  121132. 13,
  121133. 13
  121134. };
  121135. static static_codebook _16c1_s_p9_0 = {
  121136. 2, 169,
  121137. _vq_lengthlist__16c1_s_p9_0,
  121138. 1, -513964032, 1628680192, 4, 0,
  121139. _vq_quantlist__16c1_s_p9_0,
  121140. NULL,
  121141. &_vq_auxt__16c1_s_p9_0,
  121142. NULL,
  121143. 0
  121144. };
  121145. static long _vq_quantlist__16c1_s_p9_1[] = {
  121146. 7,
  121147. 6,
  121148. 8,
  121149. 5,
  121150. 9,
  121151. 4,
  121152. 10,
  121153. 3,
  121154. 11,
  121155. 2,
  121156. 12,
  121157. 1,
  121158. 13,
  121159. 0,
  121160. 14,
  121161. };
  121162. static long _vq_lengthlist__16c1_s_p9_1[] = {
  121163. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  121164. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  121165. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  121166. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  121167. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  121168. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  121169. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  121170. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121171. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121172. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121173. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121174. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121175. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  121176. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121177. 13,
  121178. };
  121179. static float _vq_quantthresh__16c1_s_p9_1[] = {
  121180. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121181. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121182. };
  121183. static long _vq_quantmap__16c1_s_p9_1[] = {
  121184. 13, 11, 9, 7, 5, 3, 1, 0,
  121185. 2, 4, 6, 8, 10, 12, 14,
  121186. };
  121187. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  121188. _vq_quantthresh__16c1_s_p9_1,
  121189. _vq_quantmap__16c1_s_p9_1,
  121190. 15,
  121191. 15
  121192. };
  121193. static static_codebook _16c1_s_p9_1 = {
  121194. 2, 225,
  121195. _vq_lengthlist__16c1_s_p9_1,
  121196. 1, -520986624, 1620377600, 4, 0,
  121197. _vq_quantlist__16c1_s_p9_1,
  121198. NULL,
  121199. &_vq_auxt__16c1_s_p9_1,
  121200. NULL,
  121201. 0
  121202. };
  121203. static long _vq_quantlist__16c1_s_p9_2[] = {
  121204. 10,
  121205. 9,
  121206. 11,
  121207. 8,
  121208. 12,
  121209. 7,
  121210. 13,
  121211. 6,
  121212. 14,
  121213. 5,
  121214. 15,
  121215. 4,
  121216. 16,
  121217. 3,
  121218. 17,
  121219. 2,
  121220. 18,
  121221. 1,
  121222. 19,
  121223. 0,
  121224. 20,
  121225. };
  121226. static long _vq_lengthlist__16c1_s_p9_2[] = {
  121227. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  121228. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  121229. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  121230. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  121231. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  121232. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  121233. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  121234. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  121235. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  121236. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  121237. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  121238. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  121239. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  121240. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  121241. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  121242. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  121243. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  121244. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  121245. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  121246. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  121247. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  121248. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  121249. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  121250. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  121251. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  121252. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  121253. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  121254. 11,11,11,11,12,11,11,12,11,
  121255. };
  121256. static float _vq_quantthresh__16c1_s_p9_2[] = {
  121257. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121258. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121259. 6.5, 7.5, 8.5, 9.5,
  121260. };
  121261. static long _vq_quantmap__16c1_s_p9_2[] = {
  121262. 19, 17, 15, 13, 11, 9, 7, 5,
  121263. 3, 1, 0, 2, 4, 6, 8, 10,
  121264. 12, 14, 16, 18, 20,
  121265. };
  121266. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  121267. _vq_quantthresh__16c1_s_p9_2,
  121268. _vq_quantmap__16c1_s_p9_2,
  121269. 21,
  121270. 21
  121271. };
  121272. static static_codebook _16c1_s_p9_2 = {
  121273. 2, 441,
  121274. _vq_lengthlist__16c1_s_p9_2,
  121275. 1, -529268736, 1611661312, 5, 0,
  121276. _vq_quantlist__16c1_s_p9_2,
  121277. NULL,
  121278. &_vq_auxt__16c1_s_p9_2,
  121279. NULL,
  121280. 0
  121281. };
  121282. static long _huff_lengthlist__16c1_s_short[] = {
  121283. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  121284. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  121285. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  121286. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  121287. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  121288. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  121289. 9, 9,10,13,
  121290. };
  121291. static static_codebook _huff_book__16c1_s_short = {
  121292. 2, 100,
  121293. _huff_lengthlist__16c1_s_short,
  121294. 0, 0, 0, 0, 0,
  121295. NULL,
  121296. NULL,
  121297. NULL,
  121298. NULL,
  121299. 0
  121300. };
  121301. static long _huff_lengthlist__16c2_s_long[] = {
  121302. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  121303. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  121304. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  121305. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  121306. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  121307. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  121308. 14,14,16,18,
  121309. };
  121310. static static_codebook _huff_book__16c2_s_long = {
  121311. 2, 100,
  121312. _huff_lengthlist__16c2_s_long,
  121313. 0, 0, 0, 0, 0,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. NULL,
  121318. 0
  121319. };
  121320. static long _vq_quantlist__16c2_s_p1_0[] = {
  121321. 1,
  121322. 0,
  121323. 2,
  121324. };
  121325. static long _vq_lengthlist__16c2_s_p1_0[] = {
  121326. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  121327. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121331. 0,
  121332. };
  121333. static float _vq_quantthresh__16c2_s_p1_0[] = {
  121334. -0.5, 0.5,
  121335. };
  121336. static long _vq_quantmap__16c2_s_p1_0[] = {
  121337. 1, 0, 2,
  121338. };
  121339. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  121340. _vq_quantthresh__16c2_s_p1_0,
  121341. _vq_quantmap__16c2_s_p1_0,
  121342. 3,
  121343. 3
  121344. };
  121345. static static_codebook _16c2_s_p1_0 = {
  121346. 4, 81,
  121347. _vq_lengthlist__16c2_s_p1_0,
  121348. 1, -535822336, 1611661312, 2, 0,
  121349. _vq_quantlist__16c2_s_p1_0,
  121350. NULL,
  121351. &_vq_auxt__16c2_s_p1_0,
  121352. NULL,
  121353. 0
  121354. };
  121355. static long _vq_quantlist__16c2_s_p2_0[] = {
  121356. 2,
  121357. 1,
  121358. 3,
  121359. 0,
  121360. 4,
  121361. };
  121362. static long _vq_lengthlist__16c2_s_p2_0[] = {
  121363. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  121364. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  121365. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  121366. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  121367. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  121368. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  121369. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  121370. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121375. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  121376. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  121377. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  121378. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  121384. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  121385. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  121386. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121391. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  121392. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  121393. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  121394. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  121399. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  121400. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  121401. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  121402. 13,
  121403. };
  121404. static float _vq_quantthresh__16c2_s_p2_0[] = {
  121405. -1.5, -0.5, 0.5, 1.5,
  121406. };
  121407. static long _vq_quantmap__16c2_s_p2_0[] = {
  121408. 3, 1, 0, 2, 4,
  121409. };
  121410. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  121411. _vq_quantthresh__16c2_s_p2_0,
  121412. _vq_quantmap__16c2_s_p2_0,
  121413. 5,
  121414. 5
  121415. };
  121416. static static_codebook _16c2_s_p2_0 = {
  121417. 4, 625,
  121418. _vq_lengthlist__16c2_s_p2_0,
  121419. 1, -533725184, 1611661312, 3, 0,
  121420. _vq_quantlist__16c2_s_p2_0,
  121421. NULL,
  121422. &_vq_auxt__16c2_s_p2_0,
  121423. NULL,
  121424. 0
  121425. };
  121426. static long _vq_quantlist__16c2_s_p3_0[] = {
  121427. 4,
  121428. 3,
  121429. 5,
  121430. 2,
  121431. 6,
  121432. 1,
  121433. 7,
  121434. 0,
  121435. 8,
  121436. };
  121437. static long _vq_lengthlist__16c2_s_p3_0[] = {
  121438. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  121439. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  121440. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  121441. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  121442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121443. 0,
  121444. };
  121445. static float _vq_quantthresh__16c2_s_p3_0[] = {
  121446. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121447. };
  121448. static long _vq_quantmap__16c2_s_p3_0[] = {
  121449. 7, 5, 3, 1, 0, 2, 4, 6,
  121450. 8,
  121451. };
  121452. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  121453. _vq_quantthresh__16c2_s_p3_0,
  121454. _vq_quantmap__16c2_s_p3_0,
  121455. 9,
  121456. 9
  121457. };
  121458. static static_codebook _16c2_s_p3_0 = {
  121459. 2, 81,
  121460. _vq_lengthlist__16c2_s_p3_0,
  121461. 1, -531628032, 1611661312, 4, 0,
  121462. _vq_quantlist__16c2_s_p3_0,
  121463. NULL,
  121464. &_vq_auxt__16c2_s_p3_0,
  121465. NULL,
  121466. 0
  121467. };
  121468. static long _vq_quantlist__16c2_s_p4_0[] = {
  121469. 8,
  121470. 7,
  121471. 9,
  121472. 6,
  121473. 10,
  121474. 5,
  121475. 11,
  121476. 4,
  121477. 12,
  121478. 3,
  121479. 13,
  121480. 2,
  121481. 14,
  121482. 1,
  121483. 15,
  121484. 0,
  121485. 16,
  121486. };
  121487. static long _vq_lengthlist__16c2_s_p4_0[] = {
  121488. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  121489. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  121490. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  121491. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  121492. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  121493. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  121494. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  121495. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  121496. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  121497. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0,
  121507. };
  121508. static float _vq_quantthresh__16c2_s_p4_0[] = {
  121509. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121510. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121511. };
  121512. static long _vq_quantmap__16c2_s_p4_0[] = {
  121513. 15, 13, 11, 9, 7, 5, 3, 1,
  121514. 0, 2, 4, 6, 8, 10, 12, 14,
  121515. 16,
  121516. };
  121517. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  121518. _vq_quantthresh__16c2_s_p4_0,
  121519. _vq_quantmap__16c2_s_p4_0,
  121520. 17,
  121521. 17
  121522. };
  121523. static static_codebook _16c2_s_p4_0 = {
  121524. 2, 289,
  121525. _vq_lengthlist__16c2_s_p4_0,
  121526. 1, -529530880, 1611661312, 5, 0,
  121527. _vq_quantlist__16c2_s_p4_0,
  121528. NULL,
  121529. &_vq_auxt__16c2_s_p4_0,
  121530. NULL,
  121531. 0
  121532. };
  121533. static long _vq_quantlist__16c2_s_p5_0[] = {
  121534. 1,
  121535. 0,
  121536. 2,
  121537. };
  121538. static long _vq_lengthlist__16c2_s_p5_0[] = {
  121539. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  121540. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  121541. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  121542. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  121543. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  121544. 12,
  121545. };
  121546. static float _vq_quantthresh__16c2_s_p5_0[] = {
  121547. -5.5, 5.5,
  121548. };
  121549. static long _vq_quantmap__16c2_s_p5_0[] = {
  121550. 1, 0, 2,
  121551. };
  121552. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  121553. _vq_quantthresh__16c2_s_p5_0,
  121554. _vq_quantmap__16c2_s_p5_0,
  121555. 3,
  121556. 3
  121557. };
  121558. static static_codebook _16c2_s_p5_0 = {
  121559. 4, 81,
  121560. _vq_lengthlist__16c2_s_p5_0,
  121561. 1, -529137664, 1618345984, 2, 0,
  121562. _vq_quantlist__16c2_s_p5_0,
  121563. NULL,
  121564. &_vq_auxt__16c2_s_p5_0,
  121565. NULL,
  121566. 0
  121567. };
  121568. static long _vq_quantlist__16c2_s_p5_1[] = {
  121569. 5,
  121570. 4,
  121571. 6,
  121572. 3,
  121573. 7,
  121574. 2,
  121575. 8,
  121576. 1,
  121577. 9,
  121578. 0,
  121579. 10,
  121580. };
  121581. static long _vq_lengthlist__16c2_s_p5_1[] = {
  121582. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  121583. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  121584. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  121585. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  121586. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  121587. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  121588. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  121589. 11,11,11, 7, 7, 8, 8, 8, 8,
  121590. };
  121591. static float _vq_quantthresh__16c2_s_p5_1[] = {
  121592. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121593. 3.5, 4.5,
  121594. };
  121595. static long _vq_quantmap__16c2_s_p5_1[] = {
  121596. 9, 7, 5, 3, 1, 0, 2, 4,
  121597. 6, 8, 10,
  121598. };
  121599. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  121600. _vq_quantthresh__16c2_s_p5_1,
  121601. _vq_quantmap__16c2_s_p5_1,
  121602. 11,
  121603. 11
  121604. };
  121605. static static_codebook _16c2_s_p5_1 = {
  121606. 2, 121,
  121607. _vq_lengthlist__16c2_s_p5_1,
  121608. 1, -531365888, 1611661312, 4, 0,
  121609. _vq_quantlist__16c2_s_p5_1,
  121610. NULL,
  121611. &_vq_auxt__16c2_s_p5_1,
  121612. NULL,
  121613. 0
  121614. };
  121615. static long _vq_quantlist__16c2_s_p6_0[] = {
  121616. 6,
  121617. 5,
  121618. 7,
  121619. 4,
  121620. 8,
  121621. 3,
  121622. 9,
  121623. 2,
  121624. 10,
  121625. 1,
  121626. 11,
  121627. 0,
  121628. 12,
  121629. };
  121630. static long _vq_lengthlist__16c2_s_p6_0[] = {
  121631. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  121632. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  121633. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  121634. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  121635. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  121636. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. };
  121643. static float _vq_quantthresh__16c2_s_p6_0[] = {
  121644. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121645. 12.5, 17.5, 22.5, 27.5,
  121646. };
  121647. static long _vq_quantmap__16c2_s_p6_0[] = {
  121648. 11, 9, 7, 5, 3, 1, 0, 2,
  121649. 4, 6, 8, 10, 12,
  121650. };
  121651. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  121652. _vq_quantthresh__16c2_s_p6_0,
  121653. _vq_quantmap__16c2_s_p6_0,
  121654. 13,
  121655. 13
  121656. };
  121657. static static_codebook _16c2_s_p6_0 = {
  121658. 2, 169,
  121659. _vq_lengthlist__16c2_s_p6_0,
  121660. 1, -526516224, 1616117760, 4, 0,
  121661. _vq_quantlist__16c2_s_p6_0,
  121662. NULL,
  121663. &_vq_auxt__16c2_s_p6_0,
  121664. NULL,
  121665. 0
  121666. };
  121667. static long _vq_quantlist__16c2_s_p6_1[] = {
  121668. 2,
  121669. 1,
  121670. 3,
  121671. 0,
  121672. 4,
  121673. };
  121674. static long _vq_lengthlist__16c2_s_p6_1[] = {
  121675. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121676. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121677. };
  121678. static float _vq_quantthresh__16c2_s_p6_1[] = {
  121679. -1.5, -0.5, 0.5, 1.5,
  121680. };
  121681. static long _vq_quantmap__16c2_s_p6_1[] = {
  121682. 3, 1, 0, 2, 4,
  121683. };
  121684. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  121685. _vq_quantthresh__16c2_s_p6_1,
  121686. _vq_quantmap__16c2_s_p6_1,
  121687. 5,
  121688. 5
  121689. };
  121690. static static_codebook _16c2_s_p6_1 = {
  121691. 2, 25,
  121692. _vq_lengthlist__16c2_s_p6_1,
  121693. 1, -533725184, 1611661312, 3, 0,
  121694. _vq_quantlist__16c2_s_p6_1,
  121695. NULL,
  121696. &_vq_auxt__16c2_s_p6_1,
  121697. NULL,
  121698. 0
  121699. };
  121700. static long _vq_quantlist__16c2_s_p7_0[] = {
  121701. 6,
  121702. 5,
  121703. 7,
  121704. 4,
  121705. 8,
  121706. 3,
  121707. 9,
  121708. 2,
  121709. 10,
  121710. 1,
  121711. 11,
  121712. 0,
  121713. 12,
  121714. };
  121715. static long _vq_lengthlist__16c2_s_p7_0[] = {
  121716. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  121717. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  121718. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  121719. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  121720. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  121721. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  121722. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  121723. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  121724. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  121725. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  121726. 18,13,14,13,13,14,13,15,14,
  121727. };
  121728. static float _vq_quantthresh__16c2_s_p7_0[] = {
  121729. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  121730. 27.5, 38.5, 49.5, 60.5,
  121731. };
  121732. static long _vq_quantmap__16c2_s_p7_0[] = {
  121733. 11, 9, 7, 5, 3, 1, 0, 2,
  121734. 4, 6, 8, 10, 12,
  121735. };
  121736. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  121737. _vq_quantthresh__16c2_s_p7_0,
  121738. _vq_quantmap__16c2_s_p7_0,
  121739. 13,
  121740. 13
  121741. };
  121742. static static_codebook _16c2_s_p7_0 = {
  121743. 2, 169,
  121744. _vq_lengthlist__16c2_s_p7_0,
  121745. 1, -523206656, 1618345984, 4, 0,
  121746. _vq_quantlist__16c2_s_p7_0,
  121747. NULL,
  121748. &_vq_auxt__16c2_s_p7_0,
  121749. NULL,
  121750. 0
  121751. };
  121752. static long _vq_quantlist__16c2_s_p7_1[] = {
  121753. 5,
  121754. 4,
  121755. 6,
  121756. 3,
  121757. 7,
  121758. 2,
  121759. 8,
  121760. 1,
  121761. 9,
  121762. 0,
  121763. 10,
  121764. };
  121765. static long _vq_lengthlist__16c2_s_p7_1[] = {
  121766. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  121767. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  121768. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  121769. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121770. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  121771. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  121772. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  121773. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121774. };
  121775. static float _vq_quantthresh__16c2_s_p7_1[] = {
  121776. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121777. 3.5, 4.5,
  121778. };
  121779. static long _vq_quantmap__16c2_s_p7_1[] = {
  121780. 9, 7, 5, 3, 1, 0, 2, 4,
  121781. 6, 8, 10,
  121782. };
  121783. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  121784. _vq_quantthresh__16c2_s_p7_1,
  121785. _vq_quantmap__16c2_s_p7_1,
  121786. 11,
  121787. 11
  121788. };
  121789. static static_codebook _16c2_s_p7_1 = {
  121790. 2, 121,
  121791. _vq_lengthlist__16c2_s_p7_1,
  121792. 1, -531365888, 1611661312, 4, 0,
  121793. _vq_quantlist__16c2_s_p7_1,
  121794. NULL,
  121795. &_vq_auxt__16c2_s_p7_1,
  121796. NULL,
  121797. 0
  121798. };
  121799. static long _vq_quantlist__16c2_s_p8_0[] = {
  121800. 7,
  121801. 6,
  121802. 8,
  121803. 5,
  121804. 9,
  121805. 4,
  121806. 10,
  121807. 3,
  121808. 11,
  121809. 2,
  121810. 12,
  121811. 1,
  121812. 13,
  121813. 0,
  121814. 14,
  121815. };
  121816. static long _vq_lengthlist__16c2_s_p8_0[] = {
  121817. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  121818. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  121819. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  121820. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  121821. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  121822. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  121823. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  121824. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  121825. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  121826. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  121827. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  121828. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  121829. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  121830. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  121831. 13,
  121832. };
  121833. static float _vq_quantthresh__16c2_s_p8_0[] = {
  121834. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121835. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121836. };
  121837. static long _vq_quantmap__16c2_s_p8_0[] = {
  121838. 13, 11, 9, 7, 5, 3, 1, 0,
  121839. 2, 4, 6, 8, 10, 12, 14,
  121840. };
  121841. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  121842. _vq_quantthresh__16c2_s_p8_0,
  121843. _vq_quantmap__16c2_s_p8_0,
  121844. 15,
  121845. 15
  121846. };
  121847. static static_codebook _16c2_s_p8_0 = {
  121848. 2, 225,
  121849. _vq_lengthlist__16c2_s_p8_0,
  121850. 1, -520986624, 1620377600, 4, 0,
  121851. _vq_quantlist__16c2_s_p8_0,
  121852. NULL,
  121853. &_vq_auxt__16c2_s_p8_0,
  121854. NULL,
  121855. 0
  121856. };
  121857. static long _vq_quantlist__16c2_s_p8_1[] = {
  121858. 10,
  121859. 9,
  121860. 11,
  121861. 8,
  121862. 12,
  121863. 7,
  121864. 13,
  121865. 6,
  121866. 14,
  121867. 5,
  121868. 15,
  121869. 4,
  121870. 16,
  121871. 3,
  121872. 17,
  121873. 2,
  121874. 18,
  121875. 1,
  121876. 19,
  121877. 0,
  121878. 20,
  121879. };
  121880. static long _vq_lengthlist__16c2_s_p8_1[] = {
  121881. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  121882. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  121883. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  121884. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  121885. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  121886. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  121887. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  121888. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  121889. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  121890. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  121891. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  121892. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  121893. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  121894. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  121895. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  121896. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  121897. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  121898. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  121899. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  121900. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  121901. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  121902. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  121903. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  121904. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  121905. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  121906. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  121907. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  121908. 10,11,10,10,10,10,10,10,10,
  121909. };
  121910. static float _vq_quantthresh__16c2_s_p8_1[] = {
  121911. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121912. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121913. 6.5, 7.5, 8.5, 9.5,
  121914. };
  121915. static long _vq_quantmap__16c2_s_p8_1[] = {
  121916. 19, 17, 15, 13, 11, 9, 7, 5,
  121917. 3, 1, 0, 2, 4, 6, 8, 10,
  121918. 12, 14, 16, 18, 20,
  121919. };
  121920. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  121921. _vq_quantthresh__16c2_s_p8_1,
  121922. _vq_quantmap__16c2_s_p8_1,
  121923. 21,
  121924. 21
  121925. };
  121926. static static_codebook _16c2_s_p8_1 = {
  121927. 2, 441,
  121928. _vq_lengthlist__16c2_s_p8_1,
  121929. 1, -529268736, 1611661312, 5, 0,
  121930. _vq_quantlist__16c2_s_p8_1,
  121931. NULL,
  121932. &_vq_auxt__16c2_s_p8_1,
  121933. NULL,
  121934. 0
  121935. };
  121936. static long _vq_quantlist__16c2_s_p9_0[] = {
  121937. 6,
  121938. 5,
  121939. 7,
  121940. 4,
  121941. 8,
  121942. 3,
  121943. 9,
  121944. 2,
  121945. 10,
  121946. 1,
  121947. 11,
  121948. 0,
  121949. 12,
  121950. };
  121951. static long _vq_lengthlist__16c2_s_p9_0[] = {
  121952. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121953. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121954. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121955. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121956. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121957. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121958. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121959. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121960. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121961. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121962. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121963. };
  121964. static float _vq_quantthresh__16c2_s_p9_0[] = {
  121965. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  121966. 2327.5, 3258.5, 4189.5, 5120.5,
  121967. };
  121968. static long _vq_quantmap__16c2_s_p9_0[] = {
  121969. 11, 9, 7, 5, 3, 1, 0, 2,
  121970. 4, 6, 8, 10, 12,
  121971. };
  121972. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  121973. _vq_quantthresh__16c2_s_p9_0,
  121974. _vq_quantmap__16c2_s_p9_0,
  121975. 13,
  121976. 13
  121977. };
  121978. static static_codebook _16c2_s_p9_0 = {
  121979. 2, 169,
  121980. _vq_lengthlist__16c2_s_p9_0,
  121981. 1, -510275072, 1631393792, 4, 0,
  121982. _vq_quantlist__16c2_s_p9_0,
  121983. NULL,
  121984. &_vq_auxt__16c2_s_p9_0,
  121985. NULL,
  121986. 0
  121987. };
  121988. static long _vq_quantlist__16c2_s_p9_1[] = {
  121989. 8,
  121990. 7,
  121991. 9,
  121992. 6,
  121993. 10,
  121994. 5,
  121995. 11,
  121996. 4,
  121997. 12,
  121998. 3,
  121999. 13,
  122000. 2,
  122001. 14,
  122002. 1,
  122003. 15,
  122004. 0,
  122005. 16,
  122006. };
  122007. static long _vq_lengthlist__16c2_s_p9_1[] = {
  122008. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  122009. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  122010. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  122011. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  122012. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  122013. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  122014. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  122015. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  122016. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  122017. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  122018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122019. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122021. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122023. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  122024. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  122025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122026. 10,
  122027. };
  122028. static float _vq_quantthresh__16c2_s_p9_1[] = {
  122029. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  122030. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  122031. };
  122032. static long _vq_quantmap__16c2_s_p9_1[] = {
  122033. 15, 13, 11, 9, 7, 5, 3, 1,
  122034. 0, 2, 4, 6, 8, 10, 12, 14,
  122035. 16,
  122036. };
  122037. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  122038. _vq_quantthresh__16c2_s_p9_1,
  122039. _vq_quantmap__16c2_s_p9_1,
  122040. 17,
  122041. 17
  122042. };
  122043. static static_codebook _16c2_s_p9_1 = {
  122044. 2, 289,
  122045. _vq_lengthlist__16c2_s_p9_1,
  122046. 1, -518488064, 1622704128, 5, 0,
  122047. _vq_quantlist__16c2_s_p9_1,
  122048. NULL,
  122049. &_vq_auxt__16c2_s_p9_1,
  122050. NULL,
  122051. 0
  122052. };
  122053. static long _vq_quantlist__16c2_s_p9_2[] = {
  122054. 13,
  122055. 12,
  122056. 14,
  122057. 11,
  122058. 15,
  122059. 10,
  122060. 16,
  122061. 9,
  122062. 17,
  122063. 8,
  122064. 18,
  122065. 7,
  122066. 19,
  122067. 6,
  122068. 20,
  122069. 5,
  122070. 21,
  122071. 4,
  122072. 22,
  122073. 3,
  122074. 23,
  122075. 2,
  122076. 24,
  122077. 1,
  122078. 25,
  122079. 0,
  122080. 26,
  122081. };
  122082. static long _vq_lengthlist__16c2_s_p9_2[] = {
  122083. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  122084. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  122085. };
  122086. static float _vq_quantthresh__16c2_s_p9_2[] = {
  122087. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  122088. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122089. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  122090. 11.5, 12.5,
  122091. };
  122092. static long _vq_quantmap__16c2_s_p9_2[] = {
  122093. 25, 23, 21, 19, 17, 15, 13, 11,
  122094. 9, 7, 5, 3, 1, 0, 2, 4,
  122095. 6, 8, 10, 12, 14, 16, 18, 20,
  122096. 22, 24, 26,
  122097. };
  122098. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  122099. _vq_quantthresh__16c2_s_p9_2,
  122100. _vq_quantmap__16c2_s_p9_2,
  122101. 27,
  122102. 27
  122103. };
  122104. static static_codebook _16c2_s_p9_2 = {
  122105. 1, 27,
  122106. _vq_lengthlist__16c2_s_p9_2,
  122107. 1, -528875520, 1611661312, 5, 0,
  122108. _vq_quantlist__16c2_s_p9_2,
  122109. NULL,
  122110. &_vq_auxt__16c2_s_p9_2,
  122111. NULL,
  122112. 0
  122113. };
  122114. static long _huff_lengthlist__16c2_s_short[] = {
  122115. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  122116. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  122117. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  122118. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  122119. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  122120. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  122121. 15,12,14,14,
  122122. };
  122123. static static_codebook _huff_book__16c2_s_short = {
  122124. 2, 100,
  122125. _huff_lengthlist__16c2_s_short,
  122126. 0, 0, 0, 0, 0,
  122127. NULL,
  122128. NULL,
  122129. NULL,
  122130. NULL,
  122131. 0
  122132. };
  122133. static long _vq_quantlist__8c0_s_p1_0[] = {
  122134. 1,
  122135. 0,
  122136. 2,
  122137. };
  122138. static long _vq_lengthlist__8c0_s_p1_0[] = {
  122139. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122140. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122145. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122150. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122185. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  122190. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  122195. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122231. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  122236. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  122241. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0,
  122550. };
  122551. static float _vq_quantthresh__8c0_s_p1_0[] = {
  122552. -0.5, 0.5,
  122553. };
  122554. static long _vq_quantmap__8c0_s_p1_0[] = {
  122555. 1, 0, 2,
  122556. };
  122557. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  122558. _vq_quantthresh__8c0_s_p1_0,
  122559. _vq_quantmap__8c0_s_p1_0,
  122560. 3,
  122561. 3
  122562. };
  122563. static static_codebook _8c0_s_p1_0 = {
  122564. 8, 6561,
  122565. _vq_lengthlist__8c0_s_p1_0,
  122566. 1, -535822336, 1611661312, 2, 0,
  122567. _vq_quantlist__8c0_s_p1_0,
  122568. NULL,
  122569. &_vq_auxt__8c0_s_p1_0,
  122570. NULL,
  122571. 0
  122572. };
  122573. static long _vq_quantlist__8c0_s_p2_0[] = {
  122574. 2,
  122575. 1,
  122576. 3,
  122577. 0,
  122578. 4,
  122579. };
  122580. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0,
  122621. };
  122622. static float _vq_quantthresh__8c0_s_p2_0[] = {
  122623. -1.5, -0.5, 0.5, 1.5,
  122624. };
  122625. static long _vq_quantmap__8c0_s_p2_0[] = {
  122626. 3, 1, 0, 2, 4,
  122627. };
  122628. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  122629. _vq_quantthresh__8c0_s_p2_0,
  122630. _vq_quantmap__8c0_s_p2_0,
  122631. 5,
  122632. 5
  122633. };
  122634. static static_codebook _8c0_s_p2_0 = {
  122635. 4, 625,
  122636. _vq_lengthlist__8c0_s_p2_0,
  122637. 1, -533725184, 1611661312, 3, 0,
  122638. _vq_quantlist__8c0_s_p2_0,
  122639. NULL,
  122640. &_vq_auxt__8c0_s_p2_0,
  122641. NULL,
  122642. 0
  122643. };
  122644. static long _vq_quantlist__8c0_s_p3_0[] = {
  122645. 2,
  122646. 1,
  122647. 3,
  122648. 0,
  122649. 4,
  122650. };
  122651. static long _vq_lengthlist__8c0_s_p3_0[] = {
  122652. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0,
  122692. };
  122693. static float _vq_quantthresh__8c0_s_p3_0[] = {
  122694. -1.5, -0.5, 0.5, 1.5,
  122695. };
  122696. static long _vq_quantmap__8c0_s_p3_0[] = {
  122697. 3, 1, 0, 2, 4,
  122698. };
  122699. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  122700. _vq_quantthresh__8c0_s_p3_0,
  122701. _vq_quantmap__8c0_s_p3_0,
  122702. 5,
  122703. 5
  122704. };
  122705. static static_codebook _8c0_s_p3_0 = {
  122706. 4, 625,
  122707. _vq_lengthlist__8c0_s_p3_0,
  122708. 1, -533725184, 1611661312, 3, 0,
  122709. _vq_quantlist__8c0_s_p3_0,
  122710. NULL,
  122711. &_vq_auxt__8c0_s_p3_0,
  122712. NULL,
  122713. 0
  122714. };
  122715. static long _vq_quantlist__8c0_s_p4_0[] = {
  122716. 4,
  122717. 3,
  122718. 5,
  122719. 2,
  122720. 6,
  122721. 1,
  122722. 7,
  122723. 0,
  122724. 8,
  122725. };
  122726. static long _vq_lengthlist__8c0_s_p4_0[] = {
  122727. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122728. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122729. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122730. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122731. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0,
  122733. };
  122734. static float _vq_quantthresh__8c0_s_p4_0[] = {
  122735. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122736. };
  122737. static long _vq_quantmap__8c0_s_p4_0[] = {
  122738. 7, 5, 3, 1, 0, 2, 4, 6,
  122739. 8,
  122740. };
  122741. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  122742. _vq_quantthresh__8c0_s_p4_0,
  122743. _vq_quantmap__8c0_s_p4_0,
  122744. 9,
  122745. 9
  122746. };
  122747. static static_codebook _8c0_s_p4_0 = {
  122748. 2, 81,
  122749. _vq_lengthlist__8c0_s_p4_0,
  122750. 1, -531628032, 1611661312, 4, 0,
  122751. _vq_quantlist__8c0_s_p4_0,
  122752. NULL,
  122753. &_vq_auxt__8c0_s_p4_0,
  122754. NULL,
  122755. 0
  122756. };
  122757. static long _vq_quantlist__8c0_s_p5_0[] = {
  122758. 4,
  122759. 3,
  122760. 5,
  122761. 2,
  122762. 6,
  122763. 1,
  122764. 7,
  122765. 0,
  122766. 8,
  122767. };
  122768. static long _vq_lengthlist__8c0_s_p5_0[] = {
  122769. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122770. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  122771. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  122772. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122773. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122774. 10,
  122775. };
  122776. static float _vq_quantthresh__8c0_s_p5_0[] = {
  122777. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122778. };
  122779. static long _vq_quantmap__8c0_s_p5_0[] = {
  122780. 7, 5, 3, 1, 0, 2, 4, 6,
  122781. 8,
  122782. };
  122783. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  122784. _vq_quantthresh__8c0_s_p5_0,
  122785. _vq_quantmap__8c0_s_p5_0,
  122786. 9,
  122787. 9
  122788. };
  122789. static static_codebook _8c0_s_p5_0 = {
  122790. 2, 81,
  122791. _vq_lengthlist__8c0_s_p5_0,
  122792. 1, -531628032, 1611661312, 4, 0,
  122793. _vq_quantlist__8c0_s_p5_0,
  122794. NULL,
  122795. &_vq_auxt__8c0_s_p5_0,
  122796. NULL,
  122797. 0
  122798. };
  122799. static long _vq_quantlist__8c0_s_p6_0[] = {
  122800. 8,
  122801. 7,
  122802. 9,
  122803. 6,
  122804. 10,
  122805. 5,
  122806. 11,
  122807. 4,
  122808. 12,
  122809. 3,
  122810. 13,
  122811. 2,
  122812. 14,
  122813. 1,
  122814. 15,
  122815. 0,
  122816. 16,
  122817. };
  122818. static long _vq_lengthlist__8c0_s_p6_0[] = {
  122819. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  122820. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122821. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122822. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  122823. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  122824. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  122825. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  122826. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  122827. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  122828. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122829. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  122830. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  122831. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  122832. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  122833. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  122834. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  122835. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  122837. 14,
  122838. };
  122839. static float _vq_quantthresh__8c0_s_p6_0[] = {
  122840. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122841. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122842. };
  122843. static long _vq_quantmap__8c0_s_p6_0[] = {
  122844. 15, 13, 11, 9, 7, 5, 3, 1,
  122845. 0, 2, 4, 6, 8, 10, 12, 14,
  122846. 16,
  122847. };
  122848. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  122849. _vq_quantthresh__8c0_s_p6_0,
  122850. _vq_quantmap__8c0_s_p6_0,
  122851. 17,
  122852. 17
  122853. };
  122854. static static_codebook _8c0_s_p6_0 = {
  122855. 2, 289,
  122856. _vq_lengthlist__8c0_s_p6_0,
  122857. 1, -529530880, 1611661312, 5, 0,
  122858. _vq_quantlist__8c0_s_p6_0,
  122859. NULL,
  122860. &_vq_auxt__8c0_s_p6_0,
  122861. NULL,
  122862. 0
  122863. };
  122864. static long _vq_quantlist__8c0_s_p7_0[] = {
  122865. 1,
  122866. 0,
  122867. 2,
  122868. };
  122869. static long _vq_lengthlist__8c0_s_p7_0[] = {
  122870. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  122871. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  122872. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  122873. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  122874. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  122875. 10,
  122876. };
  122877. static float _vq_quantthresh__8c0_s_p7_0[] = {
  122878. -5.5, 5.5,
  122879. };
  122880. static long _vq_quantmap__8c0_s_p7_0[] = {
  122881. 1, 0, 2,
  122882. };
  122883. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  122884. _vq_quantthresh__8c0_s_p7_0,
  122885. _vq_quantmap__8c0_s_p7_0,
  122886. 3,
  122887. 3
  122888. };
  122889. static static_codebook _8c0_s_p7_0 = {
  122890. 4, 81,
  122891. _vq_lengthlist__8c0_s_p7_0,
  122892. 1, -529137664, 1618345984, 2, 0,
  122893. _vq_quantlist__8c0_s_p7_0,
  122894. NULL,
  122895. &_vq_auxt__8c0_s_p7_0,
  122896. NULL,
  122897. 0
  122898. };
  122899. static long _vq_quantlist__8c0_s_p7_1[] = {
  122900. 5,
  122901. 4,
  122902. 6,
  122903. 3,
  122904. 7,
  122905. 2,
  122906. 8,
  122907. 1,
  122908. 9,
  122909. 0,
  122910. 10,
  122911. };
  122912. static long _vq_lengthlist__8c0_s_p7_1[] = {
  122913. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  122914. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  122915. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  122916. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  122917. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  122918. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  122919. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  122920. 10,10,10, 9, 9, 9,10,10,10,
  122921. };
  122922. static float _vq_quantthresh__8c0_s_p7_1[] = {
  122923. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122924. 3.5, 4.5,
  122925. };
  122926. static long _vq_quantmap__8c0_s_p7_1[] = {
  122927. 9, 7, 5, 3, 1, 0, 2, 4,
  122928. 6, 8, 10,
  122929. };
  122930. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  122931. _vq_quantthresh__8c0_s_p7_1,
  122932. _vq_quantmap__8c0_s_p7_1,
  122933. 11,
  122934. 11
  122935. };
  122936. static static_codebook _8c0_s_p7_1 = {
  122937. 2, 121,
  122938. _vq_lengthlist__8c0_s_p7_1,
  122939. 1, -531365888, 1611661312, 4, 0,
  122940. _vq_quantlist__8c0_s_p7_1,
  122941. NULL,
  122942. &_vq_auxt__8c0_s_p7_1,
  122943. NULL,
  122944. 0
  122945. };
  122946. static long _vq_quantlist__8c0_s_p8_0[] = {
  122947. 6,
  122948. 5,
  122949. 7,
  122950. 4,
  122951. 8,
  122952. 3,
  122953. 9,
  122954. 2,
  122955. 10,
  122956. 1,
  122957. 11,
  122958. 0,
  122959. 12,
  122960. };
  122961. static long _vq_lengthlist__8c0_s_p8_0[] = {
  122962. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  122963. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  122964. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  122965. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  122966. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  122967. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  122968. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  122969. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  122970. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  122971. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  122972. 0, 0,13,13,11,13,13,11,12,
  122973. };
  122974. static float _vq_quantthresh__8c0_s_p8_0[] = {
  122975. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122976. 12.5, 17.5, 22.5, 27.5,
  122977. };
  122978. static long _vq_quantmap__8c0_s_p8_0[] = {
  122979. 11, 9, 7, 5, 3, 1, 0, 2,
  122980. 4, 6, 8, 10, 12,
  122981. };
  122982. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  122983. _vq_quantthresh__8c0_s_p8_0,
  122984. _vq_quantmap__8c0_s_p8_0,
  122985. 13,
  122986. 13
  122987. };
  122988. static static_codebook _8c0_s_p8_0 = {
  122989. 2, 169,
  122990. _vq_lengthlist__8c0_s_p8_0,
  122991. 1, -526516224, 1616117760, 4, 0,
  122992. _vq_quantlist__8c0_s_p8_0,
  122993. NULL,
  122994. &_vq_auxt__8c0_s_p8_0,
  122995. NULL,
  122996. 0
  122997. };
  122998. static long _vq_quantlist__8c0_s_p8_1[] = {
  122999. 2,
  123000. 1,
  123001. 3,
  123002. 0,
  123003. 4,
  123004. };
  123005. static long _vq_lengthlist__8c0_s_p8_1[] = {
  123006. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  123007. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123008. };
  123009. static float _vq_quantthresh__8c0_s_p8_1[] = {
  123010. -1.5, -0.5, 0.5, 1.5,
  123011. };
  123012. static long _vq_quantmap__8c0_s_p8_1[] = {
  123013. 3, 1, 0, 2, 4,
  123014. };
  123015. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  123016. _vq_quantthresh__8c0_s_p8_1,
  123017. _vq_quantmap__8c0_s_p8_1,
  123018. 5,
  123019. 5
  123020. };
  123021. static static_codebook _8c0_s_p8_1 = {
  123022. 2, 25,
  123023. _vq_lengthlist__8c0_s_p8_1,
  123024. 1, -533725184, 1611661312, 3, 0,
  123025. _vq_quantlist__8c0_s_p8_1,
  123026. NULL,
  123027. &_vq_auxt__8c0_s_p8_1,
  123028. NULL,
  123029. 0
  123030. };
  123031. static long _vq_quantlist__8c0_s_p9_0[] = {
  123032. 1,
  123033. 0,
  123034. 2,
  123035. };
  123036. static long _vq_lengthlist__8c0_s_p9_0[] = {
  123037. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123038. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123039. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123040. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123041. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123042. 7,
  123043. };
  123044. static float _vq_quantthresh__8c0_s_p9_0[] = {
  123045. -157.5, 157.5,
  123046. };
  123047. static long _vq_quantmap__8c0_s_p9_0[] = {
  123048. 1, 0, 2,
  123049. };
  123050. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  123051. _vq_quantthresh__8c0_s_p9_0,
  123052. _vq_quantmap__8c0_s_p9_0,
  123053. 3,
  123054. 3
  123055. };
  123056. static static_codebook _8c0_s_p9_0 = {
  123057. 4, 81,
  123058. _vq_lengthlist__8c0_s_p9_0,
  123059. 1, -518803456, 1628680192, 2, 0,
  123060. _vq_quantlist__8c0_s_p9_0,
  123061. NULL,
  123062. &_vq_auxt__8c0_s_p9_0,
  123063. NULL,
  123064. 0
  123065. };
  123066. static long _vq_quantlist__8c0_s_p9_1[] = {
  123067. 7,
  123068. 6,
  123069. 8,
  123070. 5,
  123071. 9,
  123072. 4,
  123073. 10,
  123074. 3,
  123075. 11,
  123076. 2,
  123077. 12,
  123078. 1,
  123079. 13,
  123080. 0,
  123081. 14,
  123082. };
  123083. static long _vq_lengthlist__8c0_s_p9_1[] = {
  123084. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  123085. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  123086. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  123087. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  123088. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123089. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123098. 11,
  123099. };
  123100. static float _vq_quantthresh__8c0_s_p9_1[] = {
  123101. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123102. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123103. };
  123104. static long _vq_quantmap__8c0_s_p9_1[] = {
  123105. 13, 11, 9, 7, 5, 3, 1, 0,
  123106. 2, 4, 6, 8, 10, 12, 14,
  123107. };
  123108. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  123109. _vq_quantthresh__8c0_s_p9_1,
  123110. _vq_quantmap__8c0_s_p9_1,
  123111. 15,
  123112. 15
  123113. };
  123114. static static_codebook _8c0_s_p9_1 = {
  123115. 2, 225,
  123116. _vq_lengthlist__8c0_s_p9_1,
  123117. 1, -520986624, 1620377600, 4, 0,
  123118. _vq_quantlist__8c0_s_p9_1,
  123119. NULL,
  123120. &_vq_auxt__8c0_s_p9_1,
  123121. NULL,
  123122. 0
  123123. };
  123124. static long _vq_quantlist__8c0_s_p9_2[] = {
  123125. 10,
  123126. 9,
  123127. 11,
  123128. 8,
  123129. 12,
  123130. 7,
  123131. 13,
  123132. 6,
  123133. 14,
  123134. 5,
  123135. 15,
  123136. 4,
  123137. 16,
  123138. 3,
  123139. 17,
  123140. 2,
  123141. 18,
  123142. 1,
  123143. 19,
  123144. 0,
  123145. 20,
  123146. };
  123147. static long _vq_lengthlist__8c0_s_p9_2[] = {
  123148. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  123149. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  123150. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  123151. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  123152. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  123153. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  123154. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  123155. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  123156. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  123157. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  123158. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  123159. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  123160. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  123161. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  123162. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  123163. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  123164. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  123165. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  123166. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  123167. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  123168. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  123169. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  123170. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  123171. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  123172. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  123173. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  123174. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  123175. 10,11, 9,11,10, 9,10, 9,10,
  123176. };
  123177. static float _vq_quantthresh__8c0_s_p9_2[] = {
  123178. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123179. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123180. 6.5, 7.5, 8.5, 9.5,
  123181. };
  123182. static long _vq_quantmap__8c0_s_p9_2[] = {
  123183. 19, 17, 15, 13, 11, 9, 7, 5,
  123184. 3, 1, 0, 2, 4, 6, 8, 10,
  123185. 12, 14, 16, 18, 20,
  123186. };
  123187. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  123188. _vq_quantthresh__8c0_s_p9_2,
  123189. _vq_quantmap__8c0_s_p9_2,
  123190. 21,
  123191. 21
  123192. };
  123193. static static_codebook _8c0_s_p9_2 = {
  123194. 2, 441,
  123195. _vq_lengthlist__8c0_s_p9_2,
  123196. 1, -529268736, 1611661312, 5, 0,
  123197. _vq_quantlist__8c0_s_p9_2,
  123198. NULL,
  123199. &_vq_auxt__8c0_s_p9_2,
  123200. NULL,
  123201. 0
  123202. };
  123203. static long _huff_lengthlist__8c0_s_single[] = {
  123204. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  123205. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  123206. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  123207. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  123208. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  123209. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  123210. 17,16,17,17,
  123211. };
  123212. static static_codebook _huff_book__8c0_s_single = {
  123213. 2, 100,
  123214. _huff_lengthlist__8c0_s_single,
  123215. 0, 0, 0, 0, 0,
  123216. NULL,
  123217. NULL,
  123218. NULL,
  123219. NULL,
  123220. 0
  123221. };
  123222. static long _vq_quantlist__8c1_s_p1_0[] = {
  123223. 1,
  123224. 0,
  123225. 2,
  123226. };
  123227. static long _vq_lengthlist__8c1_s_p1_0[] = {
  123228. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123229. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  123234. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123239. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  123274. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123279. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  123284. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  123320. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  123325. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123330. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0,
  123639. };
  123640. static float _vq_quantthresh__8c1_s_p1_0[] = {
  123641. -0.5, 0.5,
  123642. };
  123643. static long _vq_quantmap__8c1_s_p1_0[] = {
  123644. 1, 0, 2,
  123645. };
  123646. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  123647. _vq_quantthresh__8c1_s_p1_0,
  123648. _vq_quantmap__8c1_s_p1_0,
  123649. 3,
  123650. 3
  123651. };
  123652. static static_codebook _8c1_s_p1_0 = {
  123653. 8, 6561,
  123654. _vq_lengthlist__8c1_s_p1_0,
  123655. 1, -535822336, 1611661312, 2, 0,
  123656. _vq_quantlist__8c1_s_p1_0,
  123657. NULL,
  123658. &_vq_auxt__8c1_s_p1_0,
  123659. NULL,
  123660. 0
  123661. };
  123662. static long _vq_quantlist__8c1_s_p2_0[] = {
  123663. 2,
  123664. 1,
  123665. 3,
  123666. 0,
  123667. 4,
  123668. };
  123669. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0,
  123710. };
  123711. static float _vq_quantthresh__8c1_s_p2_0[] = {
  123712. -1.5, -0.5, 0.5, 1.5,
  123713. };
  123714. static long _vq_quantmap__8c1_s_p2_0[] = {
  123715. 3, 1, 0, 2, 4,
  123716. };
  123717. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  123718. _vq_quantthresh__8c1_s_p2_0,
  123719. _vq_quantmap__8c1_s_p2_0,
  123720. 5,
  123721. 5
  123722. };
  123723. static static_codebook _8c1_s_p2_0 = {
  123724. 4, 625,
  123725. _vq_lengthlist__8c1_s_p2_0,
  123726. 1, -533725184, 1611661312, 3, 0,
  123727. _vq_quantlist__8c1_s_p2_0,
  123728. NULL,
  123729. &_vq_auxt__8c1_s_p2_0,
  123730. NULL,
  123731. 0
  123732. };
  123733. static long _vq_quantlist__8c1_s_p3_0[] = {
  123734. 2,
  123735. 1,
  123736. 3,
  123737. 0,
  123738. 4,
  123739. };
  123740. static long _vq_lengthlist__8c1_s_p3_0[] = {
  123741. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0,
  123781. };
  123782. static float _vq_quantthresh__8c1_s_p3_0[] = {
  123783. -1.5, -0.5, 0.5, 1.5,
  123784. };
  123785. static long _vq_quantmap__8c1_s_p3_0[] = {
  123786. 3, 1, 0, 2, 4,
  123787. };
  123788. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  123789. _vq_quantthresh__8c1_s_p3_0,
  123790. _vq_quantmap__8c1_s_p3_0,
  123791. 5,
  123792. 5
  123793. };
  123794. static static_codebook _8c1_s_p3_0 = {
  123795. 4, 625,
  123796. _vq_lengthlist__8c1_s_p3_0,
  123797. 1, -533725184, 1611661312, 3, 0,
  123798. _vq_quantlist__8c1_s_p3_0,
  123799. NULL,
  123800. &_vq_auxt__8c1_s_p3_0,
  123801. NULL,
  123802. 0
  123803. };
  123804. static long _vq_quantlist__8c1_s_p4_0[] = {
  123805. 4,
  123806. 3,
  123807. 5,
  123808. 2,
  123809. 6,
  123810. 1,
  123811. 7,
  123812. 0,
  123813. 8,
  123814. };
  123815. static long _vq_lengthlist__8c1_s_p4_0[] = {
  123816. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123817. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123818. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123819. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  123820. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0,
  123822. };
  123823. static float _vq_quantthresh__8c1_s_p4_0[] = {
  123824. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123825. };
  123826. static long _vq_quantmap__8c1_s_p4_0[] = {
  123827. 7, 5, 3, 1, 0, 2, 4, 6,
  123828. 8,
  123829. };
  123830. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  123831. _vq_quantthresh__8c1_s_p4_0,
  123832. _vq_quantmap__8c1_s_p4_0,
  123833. 9,
  123834. 9
  123835. };
  123836. static static_codebook _8c1_s_p4_0 = {
  123837. 2, 81,
  123838. _vq_lengthlist__8c1_s_p4_0,
  123839. 1, -531628032, 1611661312, 4, 0,
  123840. _vq_quantlist__8c1_s_p4_0,
  123841. NULL,
  123842. &_vq_auxt__8c1_s_p4_0,
  123843. NULL,
  123844. 0
  123845. };
  123846. static long _vq_quantlist__8c1_s_p5_0[] = {
  123847. 4,
  123848. 3,
  123849. 5,
  123850. 2,
  123851. 6,
  123852. 1,
  123853. 7,
  123854. 0,
  123855. 8,
  123856. };
  123857. static long _vq_lengthlist__8c1_s_p5_0[] = {
  123858. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  123859. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  123860. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  123861. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  123862. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123863. 10,
  123864. };
  123865. static float _vq_quantthresh__8c1_s_p5_0[] = {
  123866. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123867. };
  123868. static long _vq_quantmap__8c1_s_p5_0[] = {
  123869. 7, 5, 3, 1, 0, 2, 4, 6,
  123870. 8,
  123871. };
  123872. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  123873. _vq_quantthresh__8c1_s_p5_0,
  123874. _vq_quantmap__8c1_s_p5_0,
  123875. 9,
  123876. 9
  123877. };
  123878. static static_codebook _8c1_s_p5_0 = {
  123879. 2, 81,
  123880. _vq_lengthlist__8c1_s_p5_0,
  123881. 1, -531628032, 1611661312, 4, 0,
  123882. _vq_quantlist__8c1_s_p5_0,
  123883. NULL,
  123884. &_vq_auxt__8c1_s_p5_0,
  123885. NULL,
  123886. 0
  123887. };
  123888. static long _vq_quantlist__8c1_s_p6_0[] = {
  123889. 8,
  123890. 7,
  123891. 9,
  123892. 6,
  123893. 10,
  123894. 5,
  123895. 11,
  123896. 4,
  123897. 12,
  123898. 3,
  123899. 13,
  123900. 2,
  123901. 14,
  123902. 1,
  123903. 15,
  123904. 0,
  123905. 16,
  123906. };
  123907. static long _vq_lengthlist__8c1_s_p6_0[] = {
  123908. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  123909. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123910. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123911. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  123912. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  123913. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  123914. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  123915. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  123916. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123917. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123918. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123919. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  123920. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123921. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123922. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123923. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  123924. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123926. 14,
  123927. };
  123928. static float _vq_quantthresh__8c1_s_p6_0[] = {
  123929. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123930. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123931. };
  123932. static long _vq_quantmap__8c1_s_p6_0[] = {
  123933. 15, 13, 11, 9, 7, 5, 3, 1,
  123934. 0, 2, 4, 6, 8, 10, 12, 14,
  123935. 16,
  123936. };
  123937. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  123938. _vq_quantthresh__8c1_s_p6_0,
  123939. _vq_quantmap__8c1_s_p6_0,
  123940. 17,
  123941. 17
  123942. };
  123943. static static_codebook _8c1_s_p6_0 = {
  123944. 2, 289,
  123945. _vq_lengthlist__8c1_s_p6_0,
  123946. 1, -529530880, 1611661312, 5, 0,
  123947. _vq_quantlist__8c1_s_p6_0,
  123948. NULL,
  123949. &_vq_auxt__8c1_s_p6_0,
  123950. NULL,
  123951. 0
  123952. };
  123953. static long _vq_quantlist__8c1_s_p7_0[] = {
  123954. 1,
  123955. 0,
  123956. 2,
  123957. };
  123958. static long _vq_lengthlist__8c1_s_p7_0[] = {
  123959. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  123960. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  123961. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  123962. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  123963. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  123964. 9,
  123965. };
  123966. static float _vq_quantthresh__8c1_s_p7_0[] = {
  123967. -5.5, 5.5,
  123968. };
  123969. static long _vq_quantmap__8c1_s_p7_0[] = {
  123970. 1, 0, 2,
  123971. };
  123972. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  123973. _vq_quantthresh__8c1_s_p7_0,
  123974. _vq_quantmap__8c1_s_p7_0,
  123975. 3,
  123976. 3
  123977. };
  123978. static static_codebook _8c1_s_p7_0 = {
  123979. 4, 81,
  123980. _vq_lengthlist__8c1_s_p7_0,
  123981. 1, -529137664, 1618345984, 2, 0,
  123982. _vq_quantlist__8c1_s_p7_0,
  123983. NULL,
  123984. &_vq_auxt__8c1_s_p7_0,
  123985. NULL,
  123986. 0
  123987. };
  123988. static long _vq_quantlist__8c1_s_p7_1[] = {
  123989. 5,
  123990. 4,
  123991. 6,
  123992. 3,
  123993. 7,
  123994. 2,
  123995. 8,
  123996. 1,
  123997. 9,
  123998. 0,
  123999. 10,
  124000. };
  124001. static long _vq_lengthlist__8c1_s_p7_1[] = {
  124002. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  124003. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  124004. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124005. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  124006. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124007. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124008. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  124009. 10,10,10, 8, 8, 8, 8, 8, 8,
  124010. };
  124011. static float _vq_quantthresh__8c1_s_p7_1[] = {
  124012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124013. 3.5, 4.5,
  124014. };
  124015. static long _vq_quantmap__8c1_s_p7_1[] = {
  124016. 9, 7, 5, 3, 1, 0, 2, 4,
  124017. 6, 8, 10,
  124018. };
  124019. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  124020. _vq_quantthresh__8c1_s_p7_1,
  124021. _vq_quantmap__8c1_s_p7_1,
  124022. 11,
  124023. 11
  124024. };
  124025. static static_codebook _8c1_s_p7_1 = {
  124026. 2, 121,
  124027. _vq_lengthlist__8c1_s_p7_1,
  124028. 1, -531365888, 1611661312, 4, 0,
  124029. _vq_quantlist__8c1_s_p7_1,
  124030. NULL,
  124031. &_vq_auxt__8c1_s_p7_1,
  124032. NULL,
  124033. 0
  124034. };
  124035. static long _vq_quantlist__8c1_s_p8_0[] = {
  124036. 6,
  124037. 5,
  124038. 7,
  124039. 4,
  124040. 8,
  124041. 3,
  124042. 9,
  124043. 2,
  124044. 10,
  124045. 1,
  124046. 11,
  124047. 0,
  124048. 12,
  124049. };
  124050. static long _vq_lengthlist__8c1_s_p8_0[] = {
  124051. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  124052. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124053. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124054. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124055. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  124056. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  124057. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  124058. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  124059. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  124060. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  124061. 0,12,12,11,10,12,11,13,12,
  124062. };
  124063. static float _vq_quantthresh__8c1_s_p8_0[] = {
  124064. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124065. 12.5, 17.5, 22.5, 27.5,
  124066. };
  124067. static long _vq_quantmap__8c1_s_p8_0[] = {
  124068. 11, 9, 7, 5, 3, 1, 0, 2,
  124069. 4, 6, 8, 10, 12,
  124070. };
  124071. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  124072. _vq_quantthresh__8c1_s_p8_0,
  124073. _vq_quantmap__8c1_s_p8_0,
  124074. 13,
  124075. 13
  124076. };
  124077. static static_codebook _8c1_s_p8_0 = {
  124078. 2, 169,
  124079. _vq_lengthlist__8c1_s_p8_0,
  124080. 1, -526516224, 1616117760, 4, 0,
  124081. _vq_quantlist__8c1_s_p8_0,
  124082. NULL,
  124083. &_vq_auxt__8c1_s_p8_0,
  124084. NULL,
  124085. 0
  124086. };
  124087. static long _vq_quantlist__8c1_s_p8_1[] = {
  124088. 2,
  124089. 1,
  124090. 3,
  124091. 0,
  124092. 4,
  124093. };
  124094. static long _vq_lengthlist__8c1_s_p8_1[] = {
  124095. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124096. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124097. };
  124098. static float _vq_quantthresh__8c1_s_p8_1[] = {
  124099. -1.5, -0.5, 0.5, 1.5,
  124100. };
  124101. static long _vq_quantmap__8c1_s_p8_1[] = {
  124102. 3, 1, 0, 2, 4,
  124103. };
  124104. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  124105. _vq_quantthresh__8c1_s_p8_1,
  124106. _vq_quantmap__8c1_s_p8_1,
  124107. 5,
  124108. 5
  124109. };
  124110. static static_codebook _8c1_s_p8_1 = {
  124111. 2, 25,
  124112. _vq_lengthlist__8c1_s_p8_1,
  124113. 1, -533725184, 1611661312, 3, 0,
  124114. _vq_quantlist__8c1_s_p8_1,
  124115. NULL,
  124116. &_vq_auxt__8c1_s_p8_1,
  124117. NULL,
  124118. 0
  124119. };
  124120. static long _vq_quantlist__8c1_s_p9_0[] = {
  124121. 6,
  124122. 5,
  124123. 7,
  124124. 4,
  124125. 8,
  124126. 3,
  124127. 9,
  124128. 2,
  124129. 10,
  124130. 1,
  124131. 11,
  124132. 0,
  124133. 12,
  124134. };
  124135. static long _vq_lengthlist__8c1_s_p9_0[] = {
  124136. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  124137. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  124138. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124139. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124140. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124141. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124142. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124143. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124144. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124145. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124146. 10,10,10,10,10, 9, 9, 9, 9,
  124147. };
  124148. static float _vq_quantthresh__8c1_s_p9_0[] = {
  124149. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124150. 787.5, 1102.5, 1417.5, 1732.5,
  124151. };
  124152. static long _vq_quantmap__8c1_s_p9_0[] = {
  124153. 11, 9, 7, 5, 3, 1, 0, 2,
  124154. 4, 6, 8, 10, 12,
  124155. };
  124156. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  124157. _vq_quantthresh__8c1_s_p9_0,
  124158. _vq_quantmap__8c1_s_p9_0,
  124159. 13,
  124160. 13
  124161. };
  124162. static static_codebook _8c1_s_p9_0 = {
  124163. 2, 169,
  124164. _vq_lengthlist__8c1_s_p9_0,
  124165. 1, -513964032, 1628680192, 4, 0,
  124166. _vq_quantlist__8c1_s_p9_0,
  124167. NULL,
  124168. &_vq_auxt__8c1_s_p9_0,
  124169. NULL,
  124170. 0
  124171. };
  124172. static long _vq_quantlist__8c1_s_p9_1[] = {
  124173. 7,
  124174. 6,
  124175. 8,
  124176. 5,
  124177. 9,
  124178. 4,
  124179. 10,
  124180. 3,
  124181. 11,
  124182. 2,
  124183. 12,
  124184. 1,
  124185. 13,
  124186. 0,
  124187. 14,
  124188. };
  124189. static long _vq_lengthlist__8c1_s_p9_1[] = {
  124190. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  124191. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  124192. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  124193. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  124194. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  124195. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  124196. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  124197. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  124198. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  124199. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  124200. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  124201. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  124202. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  124203. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  124204. 15,
  124205. };
  124206. static float _vq_quantthresh__8c1_s_p9_1[] = {
  124207. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124208. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124209. };
  124210. static long _vq_quantmap__8c1_s_p9_1[] = {
  124211. 13, 11, 9, 7, 5, 3, 1, 0,
  124212. 2, 4, 6, 8, 10, 12, 14,
  124213. };
  124214. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  124215. _vq_quantthresh__8c1_s_p9_1,
  124216. _vq_quantmap__8c1_s_p9_1,
  124217. 15,
  124218. 15
  124219. };
  124220. static static_codebook _8c1_s_p9_1 = {
  124221. 2, 225,
  124222. _vq_lengthlist__8c1_s_p9_1,
  124223. 1, -520986624, 1620377600, 4, 0,
  124224. _vq_quantlist__8c1_s_p9_1,
  124225. NULL,
  124226. &_vq_auxt__8c1_s_p9_1,
  124227. NULL,
  124228. 0
  124229. };
  124230. static long _vq_quantlist__8c1_s_p9_2[] = {
  124231. 10,
  124232. 9,
  124233. 11,
  124234. 8,
  124235. 12,
  124236. 7,
  124237. 13,
  124238. 6,
  124239. 14,
  124240. 5,
  124241. 15,
  124242. 4,
  124243. 16,
  124244. 3,
  124245. 17,
  124246. 2,
  124247. 18,
  124248. 1,
  124249. 19,
  124250. 0,
  124251. 20,
  124252. };
  124253. static long _vq_lengthlist__8c1_s_p9_2[] = {
  124254. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  124255. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  124256. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  124257. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  124258. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  124259. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124260. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  124261. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  124262. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  124263. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  124264. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  124265. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  124266. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  124267. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  124268. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  124269. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  124270. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124271. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  124272. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  124273. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  124274. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124275. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  124276. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  124277. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  124278. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  124279. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  124280. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  124281. 10,10,10,10,10,10,10,10,10,
  124282. };
  124283. static float _vq_quantthresh__8c1_s_p9_2[] = {
  124284. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124285. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124286. 6.5, 7.5, 8.5, 9.5,
  124287. };
  124288. static long _vq_quantmap__8c1_s_p9_2[] = {
  124289. 19, 17, 15, 13, 11, 9, 7, 5,
  124290. 3, 1, 0, 2, 4, 6, 8, 10,
  124291. 12, 14, 16, 18, 20,
  124292. };
  124293. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  124294. _vq_quantthresh__8c1_s_p9_2,
  124295. _vq_quantmap__8c1_s_p9_2,
  124296. 21,
  124297. 21
  124298. };
  124299. static static_codebook _8c1_s_p9_2 = {
  124300. 2, 441,
  124301. _vq_lengthlist__8c1_s_p9_2,
  124302. 1, -529268736, 1611661312, 5, 0,
  124303. _vq_quantlist__8c1_s_p9_2,
  124304. NULL,
  124305. &_vq_auxt__8c1_s_p9_2,
  124306. NULL,
  124307. 0
  124308. };
  124309. static long _huff_lengthlist__8c1_s_single[] = {
  124310. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  124311. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  124312. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  124313. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  124314. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  124315. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  124316. 9, 7, 7, 8,
  124317. };
  124318. static static_codebook _huff_book__8c1_s_single = {
  124319. 2, 100,
  124320. _huff_lengthlist__8c1_s_single,
  124321. 0, 0, 0, 0, 0,
  124322. NULL,
  124323. NULL,
  124324. NULL,
  124325. NULL,
  124326. 0
  124327. };
  124328. static long _huff_lengthlist__44c2_s_long[] = {
  124329. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  124330. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  124331. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  124332. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  124333. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  124334. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  124335. 10, 8, 8, 9,
  124336. };
  124337. static static_codebook _huff_book__44c2_s_long = {
  124338. 2, 100,
  124339. _huff_lengthlist__44c2_s_long,
  124340. 0, 0, 0, 0, 0,
  124341. NULL,
  124342. NULL,
  124343. NULL,
  124344. NULL,
  124345. 0
  124346. };
  124347. static long _vq_quantlist__44c2_s_p1_0[] = {
  124348. 1,
  124349. 0,
  124350. 2,
  124351. };
  124352. static long _vq_lengthlist__44c2_s_p1_0[] = {
  124353. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124354. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124359. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124364. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124399. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  124404. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  124409. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124429. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124434. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124445. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124450. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124455. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0,
  124764. };
  124765. static float _vq_quantthresh__44c2_s_p1_0[] = {
  124766. -0.5, 0.5,
  124767. };
  124768. static long _vq_quantmap__44c2_s_p1_0[] = {
  124769. 1, 0, 2,
  124770. };
  124771. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  124772. _vq_quantthresh__44c2_s_p1_0,
  124773. _vq_quantmap__44c2_s_p1_0,
  124774. 3,
  124775. 3
  124776. };
  124777. static static_codebook _44c2_s_p1_0 = {
  124778. 8, 6561,
  124779. _vq_lengthlist__44c2_s_p1_0,
  124780. 1, -535822336, 1611661312, 2, 0,
  124781. _vq_quantlist__44c2_s_p1_0,
  124782. NULL,
  124783. &_vq_auxt__44c2_s_p1_0,
  124784. NULL,
  124785. 0
  124786. };
  124787. static long _vq_quantlist__44c2_s_p2_0[] = {
  124788. 2,
  124789. 1,
  124790. 3,
  124791. 0,
  124792. 4,
  124793. };
  124794. static long _vq_lengthlist__44c2_s_p2_0[] = {
  124795. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  124796. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  124797. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  124798. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  124799. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  124805. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  124806. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  124807. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  124813. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  124814. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  124821. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  124822. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0,
  124835. };
  124836. static float _vq_quantthresh__44c2_s_p2_0[] = {
  124837. -1.5, -0.5, 0.5, 1.5,
  124838. };
  124839. static long _vq_quantmap__44c2_s_p2_0[] = {
  124840. 3, 1, 0, 2, 4,
  124841. };
  124842. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  124843. _vq_quantthresh__44c2_s_p2_0,
  124844. _vq_quantmap__44c2_s_p2_0,
  124845. 5,
  124846. 5
  124847. };
  124848. static static_codebook _44c2_s_p2_0 = {
  124849. 4, 625,
  124850. _vq_lengthlist__44c2_s_p2_0,
  124851. 1, -533725184, 1611661312, 3, 0,
  124852. _vq_quantlist__44c2_s_p2_0,
  124853. NULL,
  124854. &_vq_auxt__44c2_s_p2_0,
  124855. NULL,
  124856. 0
  124857. };
  124858. static long _vq_quantlist__44c2_s_p3_0[] = {
  124859. 2,
  124860. 1,
  124861. 3,
  124862. 0,
  124863. 4,
  124864. };
  124865. static long _vq_lengthlist__44c2_s_p3_0[] = {
  124866. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0,
  124906. };
  124907. static float _vq_quantthresh__44c2_s_p3_0[] = {
  124908. -1.5, -0.5, 0.5, 1.5,
  124909. };
  124910. static long _vq_quantmap__44c2_s_p3_0[] = {
  124911. 3, 1, 0, 2, 4,
  124912. };
  124913. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  124914. _vq_quantthresh__44c2_s_p3_0,
  124915. _vq_quantmap__44c2_s_p3_0,
  124916. 5,
  124917. 5
  124918. };
  124919. static static_codebook _44c2_s_p3_0 = {
  124920. 4, 625,
  124921. _vq_lengthlist__44c2_s_p3_0,
  124922. 1, -533725184, 1611661312, 3, 0,
  124923. _vq_quantlist__44c2_s_p3_0,
  124924. NULL,
  124925. &_vq_auxt__44c2_s_p3_0,
  124926. NULL,
  124927. 0
  124928. };
  124929. static long _vq_quantlist__44c2_s_p4_0[] = {
  124930. 4,
  124931. 3,
  124932. 5,
  124933. 2,
  124934. 6,
  124935. 1,
  124936. 7,
  124937. 0,
  124938. 8,
  124939. };
  124940. static long _vq_lengthlist__44c2_s_p4_0[] = {
  124941. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  124942. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  124943. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  124944. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  124945. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0,
  124947. };
  124948. static float _vq_quantthresh__44c2_s_p4_0[] = {
  124949. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124950. };
  124951. static long _vq_quantmap__44c2_s_p4_0[] = {
  124952. 7, 5, 3, 1, 0, 2, 4, 6,
  124953. 8,
  124954. };
  124955. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  124956. _vq_quantthresh__44c2_s_p4_0,
  124957. _vq_quantmap__44c2_s_p4_0,
  124958. 9,
  124959. 9
  124960. };
  124961. static static_codebook _44c2_s_p4_0 = {
  124962. 2, 81,
  124963. _vq_lengthlist__44c2_s_p4_0,
  124964. 1, -531628032, 1611661312, 4, 0,
  124965. _vq_quantlist__44c2_s_p4_0,
  124966. NULL,
  124967. &_vq_auxt__44c2_s_p4_0,
  124968. NULL,
  124969. 0
  124970. };
  124971. static long _vq_quantlist__44c2_s_p5_0[] = {
  124972. 4,
  124973. 3,
  124974. 5,
  124975. 2,
  124976. 6,
  124977. 1,
  124978. 7,
  124979. 0,
  124980. 8,
  124981. };
  124982. static long _vq_lengthlist__44c2_s_p5_0[] = {
  124983. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  124984. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  124985. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124986. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124987. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  124988. 11,
  124989. };
  124990. static float _vq_quantthresh__44c2_s_p5_0[] = {
  124991. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124992. };
  124993. static long _vq_quantmap__44c2_s_p5_0[] = {
  124994. 7, 5, 3, 1, 0, 2, 4, 6,
  124995. 8,
  124996. };
  124997. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  124998. _vq_quantthresh__44c2_s_p5_0,
  124999. _vq_quantmap__44c2_s_p5_0,
  125000. 9,
  125001. 9
  125002. };
  125003. static static_codebook _44c2_s_p5_0 = {
  125004. 2, 81,
  125005. _vq_lengthlist__44c2_s_p5_0,
  125006. 1, -531628032, 1611661312, 4, 0,
  125007. _vq_quantlist__44c2_s_p5_0,
  125008. NULL,
  125009. &_vq_auxt__44c2_s_p5_0,
  125010. NULL,
  125011. 0
  125012. };
  125013. static long _vq_quantlist__44c2_s_p6_0[] = {
  125014. 8,
  125015. 7,
  125016. 9,
  125017. 6,
  125018. 10,
  125019. 5,
  125020. 11,
  125021. 4,
  125022. 12,
  125023. 3,
  125024. 13,
  125025. 2,
  125026. 14,
  125027. 1,
  125028. 15,
  125029. 0,
  125030. 16,
  125031. };
  125032. static long _vq_lengthlist__44c2_s_p6_0[] = {
  125033. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  125034. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125035. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125036. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  125037. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  125038. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  125039. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  125040. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125041. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125042. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125043. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  125044. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125045. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  125046. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  125047. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  125048. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  125049. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  125051. 14,
  125052. };
  125053. static float _vq_quantthresh__44c2_s_p6_0[] = {
  125054. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125055. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125056. };
  125057. static long _vq_quantmap__44c2_s_p6_0[] = {
  125058. 15, 13, 11, 9, 7, 5, 3, 1,
  125059. 0, 2, 4, 6, 8, 10, 12, 14,
  125060. 16,
  125061. };
  125062. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  125063. _vq_quantthresh__44c2_s_p6_0,
  125064. _vq_quantmap__44c2_s_p6_0,
  125065. 17,
  125066. 17
  125067. };
  125068. static static_codebook _44c2_s_p6_0 = {
  125069. 2, 289,
  125070. _vq_lengthlist__44c2_s_p6_0,
  125071. 1, -529530880, 1611661312, 5, 0,
  125072. _vq_quantlist__44c2_s_p6_0,
  125073. NULL,
  125074. &_vq_auxt__44c2_s_p6_0,
  125075. NULL,
  125076. 0
  125077. };
  125078. static long _vq_quantlist__44c2_s_p7_0[] = {
  125079. 1,
  125080. 0,
  125081. 2,
  125082. };
  125083. static long _vq_lengthlist__44c2_s_p7_0[] = {
  125084. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125085. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  125086. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125087. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  125088. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  125089. 11,
  125090. };
  125091. static float _vq_quantthresh__44c2_s_p7_0[] = {
  125092. -5.5, 5.5,
  125093. };
  125094. static long _vq_quantmap__44c2_s_p7_0[] = {
  125095. 1, 0, 2,
  125096. };
  125097. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  125098. _vq_quantthresh__44c2_s_p7_0,
  125099. _vq_quantmap__44c2_s_p7_0,
  125100. 3,
  125101. 3
  125102. };
  125103. static static_codebook _44c2_s_p7_0 = {
  125104. 4, 81,
  125105. _vq_lengthlist__44c2_s_p7_0,
  125106. 1, -529137664, 1618345984, 2, 0,
  125107. _vq_quantlist__44c2_s_p7_0,
  125108. NULL,
  125109. &_vq_auxt__44c2_s_p7_0,
  125110. NULL,
  125111. 0
  125112. };
  125113. static long _vq_quantlist__44c2_s_p7_1[] = {
  125114. 5,
  125115. 4,
  125116. 6,
  125117. 3,
  125118. 7,
  125119. 2,
  125120. 8,
  125121. 1,
  125122. 9,
  125123. 0,
  125124. 10,
  125125. };
  125126. static long _vq_lengthlist__44c2_s_p7_1[] = {
  125127. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  125128. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  125129. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  125130. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125131. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125132. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125133. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  125134. 10,10,10, 8, 8, 8, 8, 8, 8,
  125135. };
  125136. static float _vq_quantthresh__44c2_s_p7_1[] = {
  125137. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125138. 3.5, 4.5,
  125139. };
  125140. static long _vq_quantmap__44c2_s_p7_1[] = {
  125141. 9, 7, 5, 3, 1, 0, 2, 4,
  125142. 6, 8, 10,
  125143. };
  125144. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  125145. _vq_quantthresh__44c2_s_p7_1,
  125146. _vq_quantmap__44c2_s_p7_1,
  125147. 11,
  125148. 11
  125149. };
  125150. static static_codebook _44c2_s_p7_1 = {
  125151. 2, 121,
  125152. _vq_lengthlist__44c2_s_p7_1,
  125153. 1, -531365888, 1611661312, 4, 0,
  125154. _vq_quantlist__44c2_s_p7_1,
  125155. NULL,
  125156. &_vq_auxt__44c2_s_p7_1,
  125157. NULL,
  125158. 0
  125159. };
  125160. static long _vq_quantlist__44c2_s_p8_0[] = {
  125161. 6,
  125162. 5,
  125163. 7,
  125164. 4,
  125165. 8,
  125166. 3,
  125167. 9,
  125168. 2,
  125169. 10,
  125170. 1,
  125171. 11,
  125172. 0,
  125173. 12,
  125174. };
  125175. static long _vq_lengthlist__44c2_s_p8_0[] = {
  125176. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  125177. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  125178. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125179. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125180. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  125181. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125182. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  125183. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  125184. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  125185. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  125186. 0,12,12,12,12,13,12,14,14,
  125187. };
  125188. static float _vq_quantthresh__44c2_s_p8_0[] = {
  125189. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125190. 12.5, 17.5, 22.5, 27.5,
  125191. };
  125192. static long _vq_quantmap__44c2_s_p8_0[] = {
  125193. 11, 9, 7, 5, 3, 1, 0, 2,
  125194. 4, 6, 8, 10, 12,
  125195. };
  125196. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  125197. _vq_quantthresh__44c2_s_p8_0,
  125198. _vq_quantmap__44c2_s_p8_0,
  125199. 13,
  125200. 13
  125201. };
  125202. static static_codebook _44c2_s_p8_0 = {
  125203. 2, 169,
  125204. _vq_lengthlist__44c2_s_p8_0,
  125205. 1, -526516224, 1616117760, 4, 0,
  125206. _vq_quantlist__44c2_s_p8_0,
  125207. NULL,
  125208. &_vq_auxt__44c2_s_p8_0,
  125209. NULL,
  125210. 0
  125211. };
  125212. static long _vq_quantlist__44c2_s_p8_1[] = {
  125213. 2,
  125214. 1,
  125215. 3,
  125216. 0,
  125217. 4,
  125218. };
  125219. static long _vq_lengthlist__44c2_s_p8_1[] = {
  125220. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  125221. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125222. };
  125223. static float _vq_quantthresh__44c2_s_p8_1[] = {
  125224. -1.5, -0.5, 0.5, 1.5,
  125225. };
  125226. static long _vq_quantmap__44c2_s_p8_1[] = {
  125227. 3, 1, 0, 2, 4,
  125228. };
  125229. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  125230. _vq_quantthresh__44c2_s_p8_1,
  125231. _vq_quantmap__44c2_s_p8_1,
  125232. 5,
  125233. 5
  125234. };
  125235. static static_codebook _44c2_s_p8_1 = {
  125236. 2, 25,
  125237. _vq_lengthlist__44c2_s_p8_1,
  125238. 1, -533725184, 1611661312, 3, 0,
  125239. _vq_quantlist__44c2_s_p8_1,
  125240. NULL,
  125241. &_vq_auxt__44c2_s_p8_1,
  125242. NULL,
  125243. 0
  125244. };
  125245. static long _vq_quantlist__44c2_s_p9_0[] = {
  125246. 6,
  125247. 5,
  125248. 7,
  125249. 4,
  125250. 8,
  125251. 3,
  125252. 9,
  125253. 2,
  125254. 10,
  125255. 1,
  125256. 11,
  125257. 0,
  125258. 12,
  125259. };
  125260. static long _vq_lengthlist__44c2_s_p9_0[] = {
  125261. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125262. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  125263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125264. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  125265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125271. 11,11,11,11,11,11,11,11,11,
  125272. };
  125273. static float _vq_quantthresh__44c2_s_p9_0[] = {
  125274. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  125275. 552.5, 773.5, 994.5, 1215.5,
  125276. };
  125277. static long _vq_quantmap__44c2_s_p9_0[] = {
  125278. 11, 9, 7, 5, 3, 1, 0, 2,
  125279. 4, 6, 8, 10, 12,
  125280. };
  125281. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  125282. _vq_quantthresh__44c2_s_p9_0,
  125283. _vq_quantmap__44c2_s_p9_0,
  125284. 13,
  125285. 13
  125286. };
  125287. static static_codebook _44c2_s_p9_0 = {
  125288. 2, 169,
  125289. _vq_lengthlist__44c2_s_p9_0,
  125290. 1, -514541568, 1627103232, 4, 0,
  125291. _vq_quantlist__44c2_s_p9_0,
  125292. NULL,
  125293. &_vq_auxt__44c2_s_p9_0,
  125294. NULL,
  125295. 0
  125296. };
  125297. static long _vq_quantlist__44c2_s_p9_1[] = {
  125298. 6,
  125299. 5,
  125300. 7,
  125301. 4,
  125302. 8,
  125303. 3,
  125304. 9,
  125305. 2,
  125306. 10,
  125307. 1,
  125308. 11,
  125309. 0,
  125310. 12,
  125311. };
  125312. static long _vq_lengthlist__44c2_s_p9_1[] = {
  125313. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  125314. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  125315. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  125316. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  125317. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  125318. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  125319. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  125320. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  125321. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  125322. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  125323. 17,13,12,12,10,13,11,14,14,
  125324. };
  125325. static float _vq_quantthresh__44c2_s_p9_1[] = {
  125326. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  125327. 42.5, 59.5, 76.5, 93.5,
  125328. };
  125329. static long _vq_quantmap__44c2_s_p9_1[] = {
  125330. 11, 9, 7, 5, 3, 1, 0, 2,
  125331. 4, 6, 8, 10, 12,
  125332. };
  125333. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  125334. _vq_quantthresh__44c2_s_p9_1,
  125335. _vq_quantmap__44c2_s_p9_1,
  125336. 13,
  125337. 13
  125338. };
  125339. static static_codebook _44c2_s_p9_1 = {
  125340. 2, 169,
  125341. _vq_lengthlist__44c2_s_p9_1,
  125342. 1, -522616832, 1620115456, 4, 0,
  125343. _vq_quantlist__44c2_s_p9_1,
  125344. NULL,
  125345. &_vq_auxt__44c2_s_p9_1,
  125346. NULL,
  125347. 0
  125348. };
  125349. static long _vq_quantlist__44c2_s_p9_2[] = {
  125350. 8,
  125351. 7,
  125352. 9,
  125353. 6,
  125354. 10,
  125355. 5,
  125356. 11,
  125357. 4,
  125358. 12,
  125359. 3,
  125360. 13,
  125361. 2,
  125362. 14,
  125363. 1,
  125364. 15,
  125365. 0,
  125366. 16,
  125367. };
  125368. static long _vq_lengthlist__44c2_s_p9_2[] = {
  125369. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125370. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125371. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  125372. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  125373. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  125374. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125375. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  125376. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  125377. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  125378. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  125379. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  125380. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  125381. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  125382. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  125383. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  125384. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125385. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  125386. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  125387. 10,
  125388. };
  125389. static float _vq_quantthresh__44c2_s_p9_2[] = {
  125390. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125391. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125392. };
  125393. static long _vq_quantmap__44c2_s_p9_2[] = {
  125394. 15, 13, 11, 9, 7, 5, 3, 1,
  125395. 0, 2, 4, 6, 8, 10, 12, 14,
  125396. 16,
  125397. };
  125398. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  125399. _vq_quantthresh__44c2_s_p9_2,
  125400. _vq_quantmap__44c2_s_p9_2,
  125401. 17,
  125402. 17
  125403. };
  125404. static static_codebook _44c2_s_p9_2 = {
  125405. 2, 289,
  125406. _vq_lengthlist__44c2_s_p9_2,
  125407. 1, -529530880, 1611661312, 5, 0,
  125408. _vq_quantlist__44c2_s_p9_2,
  125409. NULL,
  125410. &_vq_auxt__44c2_s_p9_2,
  125411. NULL,
  125412. 0
  125413. };
  125414. static long _huff_lengthlist__44c2_s_short[] = {
  125415. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  125416. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  125417. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  125418. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  125419. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  125420. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  125421. 6, 8, 9,12,
  125422. };
  125423. static static_codebook _huff_book__44c2_s_short = {
  125424. 2, 100,
  125425. _huff_lengthlist__44c2_s_short,
  125426. 0, 0, 0, 0, 0,
  125427. NULL,
  125428. NULL,
  125429. NULL,
  125430. NULL,
  125431. 0
  125432. };
  125433. static long _huff_lengthlist__44c3_s_long[] = {
  125434. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  125435. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  125436. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  125437. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  125438. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  125439. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  125440. 9, 8, 8, 8,
  125441. };
  125442. static static_codebook _huff_book__44c3_s_long = {
  125443. 2, 100,
  125444. _huff_lengthlist__44c3_s_long,
  125445. 0, 0, 0, 0, 0,
  125446. NULL,
  125447. NULL,
  125448. NULL,
  125449. NULL,
  125450. 0
  125451. };
  125452. static long _vq_quantlist__44c3_s_p1_0[] = {
  125453. 1,
  125454. 0,
  125455. 2,
  125456. };
  125457. static long _vq_lengthlist__44c3_s_p1_0[] = {
  125458. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125459. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125464. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125469. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125504. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  125509. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  125514. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125550. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125555. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125560. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0,
  125869. };
  125870. static float _vq_quantthresh__44c3_s_p1_0[] = {
  125871. -0.5, 0.5,
  125872. };
  125873. static long _vq_quantmap__44c3_s_p1_0[] = {
  125874. 1, 0, 2,
  125875. };
  125876. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  125877. _vq_quantthresh__44c3_s_p1_0,
  125878. _vq_quantmap__44c3_s_p1_0,
  125879. 3,
  125880. 3
  125881. };
  125882. static static_codebook _44c3_s_p1_0 = {
  125883. 8, 6561,
  125884. _vq_lengthlist__44c3_s_p1_0,
  125885. 1, -535822336, 1611661312, 2, 0,
  125886. _vq_quantlist__44c3_s_p1_0,
  125887. NULL,
  125888. &_vq_auxt__44c3_s_p1_0,
  125889. NULL,
  125890. 0
  125891. };
  125892. static long _vq_quantlist__44c3_s_p2_0[] = {
  125893. 2,
  125894. 1,
  125895. 3,
  125896. 0,
  125897. 4,
  125898. };
  125899. static long _vq_lengthlist__44c3_s_p2_0[] = {
  125900. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125901. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125902. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125903. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125904. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  125910. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125911. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125912. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125918. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125919. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125926. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125927. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0,
  125940. };
  125941. static float _vq_quantthresh__44c3_s_p2_0[] = {
  125942. -1.5, -0.5, 0.5, 1.5,
  125943. };
  125944. static long _vq_quantmap__44c3_s_p2_0[] = {
  125945. 3, 1, 0, 2, 4,
  125946. };
  125947. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  125948. _vq_quantthresh__44c3_s_p2_0,
  125949. _vq_quantmap__44c3_s_p2_0,
  125950. 5,
  125951. 5
  125952. };
  125953. static static_codebook _44c3_s_p2_0 = {
  125954. 4, 625,
  125955. _vq_lengthlist__44c3_s_p2_0,
  125956. 1, -533725184, 1611661312, 3, 0,
  125957. _vq_quantlist__44c3_s_p2_0,
  125958. NULL,
  125959. &_vq_auxt__44c3_s_p2_0,
  125960. NULL,
  125961. 0
  125962. };
  125963. static long _vq_quantlist__44c3_s_p3_0[] = {
  125964. 2,
  125965. 1,
  125966. 3,
  125967. 0,
  125968. 4,
  125969. };
  125970. static long _vq_lengthlist__44c3_s_p3_0[] = {
  125971. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0,
  126011. };
  126012. static float _vq_quantthresh__44c3_s_p3_0[] = {
  126013. -1.5, -0.5, 0.5, 1.5,
  126014. };
  126015. static long _vq_quantmap__44c3_s_p3_0[] = {
  126016. 3, 1, 0, 2, 4,
  126017. };
  126018. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  126019. _vq_quantthresh__44c3_s_p3_0,
  126020. _vq_quantmap__44c3_s_p3_0,
  126021. 5,
  126022. 5
  126023. };
  126024. static static_codebook _44c3_s_p3_0 = {
  126025. 4, 625,
  126026. _vq_lengthlist__44c3_s_p3_0,
  126027. 1, -533725184, 1611661312, 3, 0,
  126028. _vq_quantlist__44c3_s_p3_0,
  126029. NULL,
  126030. &_vq_auxt__44c3_s_p3_0,
  126031. NULL,
  126032. 0
  126033. };
  126034. static long _vq_quantlist__44c3_s_p4_0[] = {
  126035. 4,
  126036. 3,
  126037. 5,
  126038. 2,
  126039. 6,
  126040. 1,
  126041. 7,
  126042. 0,
  126043. 8,
  126044. };
  126045. static long _vq_lengthlist__44c3_s_p4_0[] = {
  126046. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126047. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126048. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126049. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126050. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0,
  126052. };
  126053. static float _vq_quantthresh__44c3_s_p4_0[] = {
  126054. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126055. };
  126056. static long _vq_quantmap__44c3_s_p4_0[] = {
  126057. 7, 5, 3, 1, 0, 2, 4, 6,
  126058. 8,
  126059. };
  126060. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  126061. _vq_quantthresh__44c3_s_p4_0,
  126062. _vq_quantmap__44c3_s_p4_0,
  126063. 9,
  126064. 9
  126065. };
  126066. static static_codebook _44c3_s_p4_0 = {
  126067. 2, 81,
  126068. _vq_lengthlist__44c3_s_p4_0,
  126069. 1, -531628032, 1611661312, 4, 0,
  126070. _vq_quantlist__44c3_s_p4_0,
  126071. NULL,
  126072. &_vq_auxt__44c3_s_p4_0,
  126073. NULL,
  126074. 0
  126075. };
  126076. static long _vq_quantlist__44c3_s_p5_0[] = {
  126077. 4,
  126078. 3,
  126079. 5,
  126080. 2,
  126081. 6,
  126082. 1,
  126083. 7,
  126084. 0,
  126085. 8,
  126086. };
  126087. static long _vq_lengthlist__44c3_s_p5_0[] = {
  126088. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  126089. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  126090. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  126091. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  126092. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  126093. 11,
  126094. };
  126095. static float _vq_quantthresh__44c3_s_p5_0[] = {
  126096. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126097. };
  126098. static long _vq_quantmap__44c3_s_p5_0[] = {
  126099. 7, 5, 3, 1, 0, 2, 4, 6,
  126100. 8,
  126101. };
  126102. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  126103. _vq_quantthresh__44c3_s_p5_0,
  126104. _vq_quantmap__44c3_s_p5_0,
  126105. 9,
  126106. 9
  126107. };
  126108. static static_codebook _44c3_s_p5_0 = {
  126109. 2, 81,
  126110. _vq_lengthlist__44c3_s_p5_0,
  126111. 1, -531628032, 1611661312, 4, 0,
  126112. _vq_quantlist__44c3_s_p5_0,
  126113. NULL,
  126114. &_vq_auxt__44c3_s_p5_0,
  126115. NULL,
  126116. 0
  126117. };
  126118. static long _vq_quantlist__44c3_s_p6_0[] = {
  126119. 8,
  126120. 7,
  126121. 9,
  126122. 6,
  126123. 10,
  126124. 5,
  126125. 11,
  126126. 4,
  126127. 12,
  126128. 3,
  126129. 13,
  126130. 2,
  126131. 14,
  126132. 1,
  126133. 15,
  126134. 0,
  126135. 16,
  126136. };
  126137. static long _vq_lengthlist__44c3_s_p6_0[] = {
  126138. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  126139. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126140. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  126141. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126142. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126143. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126144. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126145. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126146. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126147. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  126148. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  126149. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  126150. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  126151. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  126152. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126153. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126154. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126156. 13,
  126157. };
  126158. static float _vq_quantthresh__44c3_s_p6_0[] = {
  126159. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126160. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126161. };
  126162. static long _vq_quantmap__44c3_s_p6_0[] = {
  126163. 15, 13, 11, 9, 7, 5, 3, 1,
  126164. 0, 2, 4, 6, 8, 10, 12, 14,
  126165. 16,
  126166. };
  126167. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  126168. _vq_quantthresh__44c3_s_p6_0,
  126169. _vq_quantmap__44c3_s_p6_0,
  126170. 17,
  126171. 17
  126172. };
  126173. static static_codebook _44c3_s_p6_0 = {
  126174. 2, 289,
  126175. _vq_lengthlist__44c3_s_p6_0,
  126176. 1, -529530880, 1611661312, 5, 0,
  126177. _vq_quantlist__44c3_s_p6_0,
  126178. NULL,
  126179. &_vq_auxt__44c3_s_p6_0,
  126180. NULL,
  126181. 0
  126182. };
  126183. static long _vq_quantlist__44c3_s_p7_0[] = {
  126184. 1,
  126185. 0,
  126186. 2,
  126187. };
  126188. static long _vq_lengthlist__44c3_s_p7_0[] = {
  126189. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126190. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126191. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126192. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  126193. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126194. 10,
  126195. };
  126196. static float _vq_quantthresh__44c3_s_p7_0[] = {
  126197. -5.5, 5.5,
  126198. };
  126199. static long _vq_quantmap__44c3_s_p7_0[] = {
  126200. 1, 0, 2,
  126201. };
  126202. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  126203. _vq_quantthresh__44c3_s_p7_0,
  126204. _vq_quantmap__44c3_s_p7_0,
  126205. 3,
  126206. 3
  126207. };
  126208. static static_codebook _44c3_s_p7_0 = {
  126209. 4, 81,
  126210. _vq_lengthlist__44c3_s_p7_0,
  126211. 1, -529137664, 1618345984, 2, 0,
  126212. _vq_quantlist__44c3_s_p7_0,
  126213. NULL,
  126214. &_vq_auxt__44c3_s_p7_0,
  126215. NULL,
  126216. 0
  126217. };
  126218. static long _vq_quantlist__44c3_s_p7_1[] = {
  126219. 5,
  126220. 4,
  126221. 6,
  126222. 3,
  126223. 7,
  126224. 2,
  126225. 8,
  126226. 1,
  126227. 9,
  126228. 0,
  126229. 10,
  126230. };
  126231. static long _vq_lengthlist__44c3_s_p7_1[] = {
  126232. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126233. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126234. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126235. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126236. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126237. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126238. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126239. 10,10,10, 8, 8, 8, 8, 8, 8,
  126240. };
  126241. static float _vq_quantthresh__44c3_s_p7_1[] = {
  126242. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126243. 3.5, 4.5,
  126244. };
  126245. static long _vq_quantmap__44c3_s_p7_1[] = {
  126246. 9, 7, 5, 3, 1, 0, 2, 4,
  126247. 6, 8, 10,
  126248. };
  126249. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  126250. _vq_quantthresh__44c3_s_p7_1,
  126251. _vq_quantmap__44c3_s_p7_1,
  126252. 11,
  126253. 11
  126254. };
  126255. static static_codebook _44c3_s_p7_1 = {
  126256. 2, 121,
  126257. _vq_lengthlist__44c3_s_p7_1,
  126258. 1, -531365888, 1611661312, 4, 0,
  126259. _vq_quantlist__44c3_s_p7_1,
  126260. NULL,
  126261. &_vq_auxt__44c3_s_p7_1,
  126262. NULL,
  126263. 0
  126264. };
  126265. static long _vq_quantlist__44c3_s_p8_0[] = {
  126266. 6,
  126267. 5,
  126268. 7,
  126269. 4,
  126270. 8,
  126271. 3,
  126272. 9,
  126273. 2,
  126274. 10,
  126275. 1,
  126276. 11,
  126277. 0,
  126278. 12,
  126279. };
  126280. static long _vq_lengthlist__44c3_s_p8_0[] = {
  126281. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126282. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  126283. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126284. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126285. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  126286. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  126287. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  126288. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126289. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  126290. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  126291. 0,13,13,12,12,13,12,14,13,
  126292. };
  126293. static float _vq_quantthresh__44c3_s_p8_0[] = {
  126294. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126295. 12.5, 17.5, 22.5, 27.5,
  126296. };
  126297. static long _vq_quantmap__44c3_s_p8_0[] = {
  126298. 11, 9, 7, 5, 3, 1, 0, 2,
  126299. 4, 6, 8, 10, 12,
  126300. };
  126301. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  126302. _vq_quantthresh__44c3_s_p8_0,
  126303. _vq_quantmap__44c3_s_p8_0,
  126304. 13,
  126305. 13
  126306. };
  126307. static static_codebook _44c3_s_p8_0 = {
  126308. 2, 169,
  126309. _vq_lengthlist__44c3_s_p8_0,
  126310. 1, -526516224, 1616117760, 4, 0,
  126311. _vq_quantlist__44c3_s_p8_0,
  126312. NULL,
  126313. &_vq_auxt__44c3_s_p8_0,
  126314. NULL,
  126315. 0
  126316. };
  126317. static long _vq_quantlist__44c3_s_p8_1[] = {
  126318. 2,
  126319. 1,
  126320. 3,
  126321. 0,
  126322. 4,
  126323. };
  126324. static long _vq_lengthlist__44c3_s_p8_1[] = {
  126325. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126326. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126327. };
  126328. static float _vq_quantthresh__44c3_s_p8_1[] = {
  126329. -1.5, -0.5, 0.5, 1.5,
  126330. };
  126331. static long _vq_quantmap__44c3_s_p8_1[] = {
  126332. 3, 1, 0, 2, 4,
  126333. };
  126334. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  126335. _vq_quantthresh__44c3_s_p8_1,
  126336. _vq_quantmap__44c3_s_p8_1,
  126337. 5,
  126338. 5
  126339. };
  126340. static static_codebook _44c3_s_p8_1 = {
  126341. 2, 25,
  126342. _vq_lengthlist__44c3_s_p8_1,
  126343. 1, -533725184, 1611661312, 3, 0,
  126344. _vq_quantlist__44c3_s_p8_1,
  126345. NULL,
  126346. &_vq_auxt__44c3_s_p8_1,
  126347. NULL,
  126348. 0
  126349. };
  126350. static long _vq_quantlist__44c3_s_p9_0[] = {
  126351. 6,
  126352. 5,
  126353. 7,
  126354. 4,
  126355. 8,
  126356. 3,
  126357. 9,
  126358. 2,
  126359. 10,
  126360. 1,
  126361. 11,
  126362. 0,
  126363. 12,
  126364. };
  126365. static long _vq_lengthlist__44c3_s_p9_0[] = {
  126366. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  126367. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  126368. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126369. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  126370. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126371. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126372. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126373. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126374. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  126375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126376. 11,11,11,11,11,11,11,11,11,
  126377. };
  126378. static float _vq_quantthresh__44c3_s_p9_0[] = {
  126379. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  126380. 637.5, 892.5, 1147.5, 1402.5,
  126381. };
  126382. static long _vq_quantmap__44c3_s_p9_0[] = {
  126383. 11, 9, 7, 5, 3, 1, 0, 2,
  126384. 4, 6, 8, 10, 12,
  126385. };
  126386. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  126387. _vq_quantthresh__44c3_s_p9_0,
  126388. _vq_quantmap__44c3_s_p9_0,
  126389. 13,
  126390. 13
  126391. };
  126392. static static_codebook _44c3_s_p9_0 = {
  126393. 2, 169,
  126394. _vq_lengthlist__44c3_s_p9_0,
  126395. 1, -514332672, 1627381760, 4, 0,
  126396. _vq_quantlist__44c3_s_p9_0,
  126397. NULL,
  126398. &_vq_auxt__44c3_s_p9_0,
  126399. NULL,
  126400. 0
  126401. };
  126402. static long _vq_quantlist__44c3_s_p9_1[] = {
  126403. 7,
  126404. 6,
  126405. 8,
  126406. 5,
  126407. 9,
  126408. 4,
  126409. 10,
  126410. 3,
  126411. 11,
  126412. 2,
  126413. 12,
  126414. 1,
  126415. 13,
  126416. 0,
  126417. 14,
  126418. };
  126419. static long _vq_lengthlist__44c3_s_p9_1[] = {
  126420. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  126421. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  126422. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  126423. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  126424. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  126425. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  126426. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  126427. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  126428. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  126429. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  126430. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  126431. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  126432. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  126433. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  126434. 15,
  126435. };
  126436. static float _vq_quantthresh__44c3_s_p9_1[] = {
  126437. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  126438. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  126439. };
  126440. static long _vq_quantmap__44c3_s_p9_1[] = {
  126441. 13, 11, 9, 7, 5, 3, 1, 0,
  126442. 2, 4, 6, 8, 10, 12, 14,
  126443. };
  126444. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  126445. _vq_quantthresh__44c3_s_p9_1,
  126446. _vq_quantmap__44c3_s_p9_1,
  126447. 15,
  126448. 15
  126449. };
  126450. static static_codebook _44c3_s_p9_1 = {
  126451. 2, 225,
  126452. _vq_lengthlist__44c3_s_p9_1,
  126453. 1, -522338304, 1620115456, 4, 0,
  126454. _vq_quantlist__44c3_s_p9_1,
  126455. NULL,
  126456. &_vq_auxt__44c3_s_p9_1,
  126457. NULL,
  126458. 0
  126459. };
  126460. static long _vq_quantlist__44c3_s_p9_2[] = {
  126461. 8,
  126462. 7,
  126463. 9,
  126464. 6,
  126465. 10,
  126466. 5,
  126467. 11,
  126468. 4,
  126469. 12,
  126470. 3,
  126471. 13,
  126472. 2,
  126473. 14,
  126474. 1,
  126475. 15,
  126476. 0,
  126477. 16,
  126478. };
  126479. static long _vq_lengthlist__44c3_s_p9_2[] = {
  126480. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  126481. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  126482. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126483. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  126484. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  126485. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  126486. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  126487. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  126488. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  126489. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  126490. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  126491. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  126492. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  126493. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  126494. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  126495. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  126496. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  126497. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  126498. 10,
  126499. };
  126500. static float _vq_quantthresh__44c3_s_p9_2[] = {
  126501. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126502. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126503. };
  126504. static long _vq_quantmap__44c3_s_p9_2[] = {
  126505. 15, 13, 11, 9, 7, 5, 3, 1,
  126506. 0, 2, 4, 6, 8, 10, 12, 14,
  126507. 16,
  126508. };
  126509. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  126510. _vq_quantthresh__44c3_s_p9_2,
  126511. _vq_quantmap__44c3_s_p9_2,
  126512. 17,
  126513. 17
  126514. };
  126515. static static_codebook _44c3_s_p9_2 = {
  126516. 2, 289,
  126517. _vq_lengthlist__44c3_s_p9_2,
  126518. 1, -529530880, 1611661312, 5, 0,
  126519. _vq_quantlist__44c3_s_p9_2,
  126520. NULL,
  126521. &_vq_auxt__44c3_s_p9_2,
  126522. NULL,
  126523. 0
  126524. };
  126525. static long _huff_lengthlist__44c3_s_short[] = {
  126526. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  126527. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  126528. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  126529. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  126530. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  126531. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  126532. 6, 8, 9,11,
  126533. };
  126534. static static_codebook _huff_book__44c3_s_short = {
  126535. 2, 100,
  126536. _huff_lengthlist__44c3_s_short,
  126537. 0, 0, 0, 0, 0,
  126538. NULL,
  126539. NULL,
  126540. NULL,
  126541. NULL,
  126542. 0
  126543. };
  126544. static long _huff_lengthlist__44c4_s_long[] = {
  126545. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  126546. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  126547. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  126548. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  126549. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  126550. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  126551. 9, 8, 7, 7,
  126552. };
  126553. static static_codebook _huff_book__44c4_s_long = {
  126554. 2, 100,
  126555. _huff_lengthlist__44c4_s_long,
  126556. 0, 0, 0, 0, 0,
  126557. NULL,
  126558. NULL,
  126559. NULL,
  126560. NULL,
  126561. 0
  126562. };
  126563. static long _vq_quantlist__44c4_s_p1_0[] = {
  126564. 1,
  126565. 0,
  126566. 2,
  126567. };
  126568. static long _vq_lengthlist__44c4_s_p1_0[] = {
  126569. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  126570. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126575. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  126580. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126615. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  126620. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  126625. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126661. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126666. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126671. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0,
  126980. };
  126981. static float _vq_quantthresh__44c4_s_p1_0[] = {
  126982. -0.5, 0.5,
  126983. };
  126984. static long _vq_quantmap__44c4_s_p1_0[] = {
  126985. 1, 0, 2,
  126986. };
  126987. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  126988. _vq_quantthresh__44c4_s_p1_0,
  126989. _vq_quantmap__44c4_s_p1_0,
  126990. 3,
  126991. 3
  126992. };
  126993. static static_codebook _44c4_s_p1_0 = {
  126994. 8, 6561,
  126995. _vq_lengthlist__44c4_s_p1_0,
  126996. 1, -535822336, 1611661312, 2, 0,
  126997. _vq_quantlist__44c4_s_p1_0,
  126998. NULL,
  126999. &_vq_auxt__44c4_s_p1_0,
  127000. NULL,
  127001. 0
  127002. };
  127003. static long _vq_quantlist__44c4_s_p2_0[] = {
  127004. 2,
  127005. 1,
  127006. 3,
  127007. 0,
  127008. 4,
  127009. };
  127010. static long _vq_lengthlist__44c4_s_p2_0[] = {
  127011. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127012. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  127013. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127014. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  127015. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  127021. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  127022. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  127023. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  127029. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  127030. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  127037. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  127038. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0,
  127051. };
  127052. static float _vq_quantthresh__44c4_s_p2_0[] = {
  127053. -1.5, -0.5, 0.5, 1.5,
  127054. };
  127055. static long _vq_quantmap__44c4_s_p2_0[] = {
  127056. 3, 1, 0, 2, 4,
  127057. };
  127058. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  127059. _vq_quantthresh__44c4_s_p2_0,
  127060. _vq_quantmap__44c4_s_p2_0,
  127061. 5,
  127062. 5
  127063. };
  127064. static static_codebook _44c4_s_p2_0 = {
  127065. 4, 625,
  127066. _vq_lengthlist__44c4_s_p2_0,
  127067. 1, -533725184, 1611661312, 3, 0,
  127068. _vq_quantlist__44c4_s_p2_0,
  127069. NULL,
  127070. &_vq_auxt__44c4_s_p2_0,
  127071. NULL,
  127072. 0
  127073. };
  127074. static long _vq_quantlist__44c4_s_p3_0[] = {
  127075. 2,
  127076. 1,
  127077. 3,
  127078. 0,
  127079. 4,
  127080. };
  127081. static long _vq_lengthlist__44c4_s_p3_0[] = {
  127082. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0,
  127122. };
  127123. static float _vq_quantthresh__44c4_s_p3_0[] = {
  127124. -1.5, -0.5, 0.5, 1.5,
  127125. };
  127126. static long _vq_quantmap__44c4_s_p3_0[] = {
  127127. 3, 1, 0, 2, 4,
  127128. };
  127129. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  127130. _vq_quantthresh__44c4_s_p3_0,
  127131. _vq_quantmap__44c4_s_p3_0,
  127132. 5,
  127133. 5
  127134. };
  127135. static static_codebook _44c4_s_p3_0 = {
  127136. 4, 625,
  127137. _vq_lengthlist__44c4_s_p3_0,
  127138. 1, -533725184, 1611661312, 3, 0,
  127139. _vq_quantlist__44c4_s_p3_0,
  127140. NULL,
  127141. &_vq_auxt__44c4_s_p3_0,
  127142. NULL,
  127143. 0
  127144. };
  127145. static long _vq_quantlist__44c4_s_p4_0[] = {
  127146. 4,
  127147. 3,
  127148. 5,
  127149. 2,
  127150. 6,
  127151. 1,
  127152. 7,
  127153. 0,
  127154. 8,
  127155. };
  127156. static long _vq_lengthlist__44c4_s_p4_0[] = {
  127157. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127158. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127159. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127160. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  127161. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0,
  127163. };
  127164. static float _vq_quantthresh__44c4_s_p4_0[] = {
  127165. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127166. };
  127167. static long _vq_quantmap__44c4_s_p4_0[] = {
  127168. 7, 5, 3, 1, 0, 2, 4, 6,
  127169. 8,
  127170. };
  127171. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  127172. _vq_quantthresh__44c4_s_p4_0,
  127173. _vq_quantmap__44c4_s_p4_0,
  127174. 9,
  127175. 9
  127176. };
  127177. static static_codebook _44c4_s_p4_0 = {
  127178. 2, 81,
  127179. _vq_lengthlist__44c4_s_p4_0,
  127180. 1, -531628032, 1611661312, 4, 0,
  127181. _vq_quantlist__44c4_s_p4_0,
  127182. NULL,
  127183. &_vq_auxt__44c4_s_p4_0,
  127184. NULL,
  127185. 0
  127186. };
  127187. static long _vq_quantlist__44c4_s_p5_0[] = {
  127188. 4,
  127189. 3,
  127190. 5,
  127191. 2,
  127192. 6,
  127193. 1,
  127194. 7,
  127195. 0,
  127196. 8,
  127197. };
  127198. static long _vq_lengthlist__44c4_s_p5_0[] = {
  127199. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127200. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127201. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  127202. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127203. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  127204. 10,
  127205. };
  127206. static float _vq_quantthresh__44c4_s_p5_0[] = {
  127207. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127208. };
  127209. static long _vq_quantmap__44c4_s_p5_0[] = {
  127210. 7, 5, 3, 1, 0, 2, 4, 6,
  127211. 8,
  127212. };
  127213. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  127214. _vq_quantthresh__44c4_s_p5_0,
  127215. _vq_quantmap__44c4_s_p5_0,
  127216. 9,
  127217. 9
  127218. };
  127219. static static_codebook _44c4_s_p5_0 = {
  127220. 2, 81,
  127221. _vq_lengthlist__44c4_s_p5_0,
  127222. 1, -531628032, 1611661312, 4, 0,
  127223. _vq_quantlist__44c4_s_p5_0,
  127224. NULL,
  127225. &_vq_auxt__44c4_s_p5_0,
  127226. NULL,
  127227. 0
  127228. };
  127229. static long _vq_quantlist__44c4_s_p6_0[] = {
  127230. 8,
  127231. 7,
  127232. 9,
  127233. 6,
  127234. 10,
  127235. 5,
  127236. 11,
  127237. 4,
  127238. 12,
  127239. 3,
  127240. 13,
  127241. 2,
  127242. 14,
  127243. 1,
  127244. 15,
  127245. 0,
  127246. 16,
  127247. };
  127248. static long _vq_lengthlist__44c4_s_p6_0[] = {
  127249. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  127250. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127251. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127252. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127253. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127254. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127255. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  127256. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127257. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127258. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  127259. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  127260. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  127261. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  127262. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  127263. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  127264. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127265. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  127267. 13,
  127268. };
  127269. static float _vq_quantthresh__44c4_s_p6_0[] = {
  127270. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127271. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127272. };
  127273. static long _vq_quantmap__44c4_s_p6_0[] = {
  127274. 15, 13, 11, 9, 7, 5, 3, 1,
  127275. 0, 2, 4, 6, 8, 10, 12, 14,
  127276. 16,
  127277. };
  127278. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  127279. _vq_quantthresh__44c4_s_p6_0,
  127280. _vq_quantmap__44c4_s_p6_0,
  127281. 17,
  127282. 17
  127283. };
  127284. static static_codebook _44c4_s_p6_0 = {
  127285. 2, 289,
  127286. _vq_lengthlist__44c4_s_p6_0,
  127287. 1, -529530880, 1611661312, 5, 0,
  127288. _vq_quantlist__44c4_s_p6_0,
  127289. NULL,
  127290. &_vq_auxt__44c4_s_p6_0,
  127291. NULL,
  127292. 0
  127293. };
  127294. static long _vq_quantlist__44c4_s_p7_0[] = {
  127295. 1,
  127296. 0,
  127297. 2,
  127298. };
  127299. static long _vq_lengthlist__44c4_s_p7_0[] = {
  127300. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127301. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127302. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127303. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127304. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127305. 10,
  127306. };
  127307. static float _vq_quantthresh__44c4_s_p7_0[] = {
  127308. -5.5, 5.5,
  127309. };
  127310. static long _vq_quantmap__44c4_s_p7_0[] = {
  127311. 1, 0, 2,
  127312. };
  127313. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  127314. _vq_quantthresh__44c4_s_p7_0,
  127315. _vq_quantmap__44c4_s_p7_0,
  127316. 3,
  127317. 3
  127318. };
  127319. static static_codebook _44c4_s_p7_0 = {
  127320. 4, 81,
  127321. _vq_lengthlist__44c4_s_p7_0,
  127322. 1, -529137664, 1618345984, 2, 0,
  127323. _vq_quantlist__44c4_s_p7_0,
  127324. NULL,
  127325. &_vq_auxt__44c4_s_p7_0,
  127326. NULL,
  127327. 0
  127328. };
  127329. static long _vq_quantlist__44c4_s_p7_1[] = {
  127330. 5,
  127331. 4,
  127332. 6,
  127333. 3,
  127334. 7,
  127335. 2,
  127336. 8,
  127337. 1,
  127338. 9,
  127339. 0,
  127340. 10,
  127341. };
  127342. static long _vq_lengthlist__44c4_s_p7_1[] = {
  127343. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  127344. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127345. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127346. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  127347. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127348. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127349. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  127350. 10,10,10, 8, 8, 8, 8, 9, 9,
  127351. };
  127352. static float _vq_quantthresh__44c4_s_p7_1[] = {
  127353. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127354. 3.5, 4.5,
  127355. };
  127356. static long _vq_quantmap__44c4_s_p7_1[] = {
  127357. 9, 7, 5, 3, 1, 0, 2, 4,
  127358. 6, 8, 10,
  127359. };
  127360. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  127361. _vq_quantthresh__44c4_s_p7_1,
  127362. _vq_quantmap__44c4_s_p7_1,
  127363. 11,
  127364. 11
  127365. };
  127366. static static_codebook _44c4_s_p7_1 = {
  127367. 2, 121,
  127368. _vq_lengthlist__44c4_s_p7_1,
  127369. 1, -531365888, 1611661312, 4, 0,
  127370. _vq_quantlist__44c4_s_p7_1,
  127371. NULL,
  127372. &_vq_auxt__44c4_s_p7_1,
  127373. NULL,
  127374. 0
  127375. };
  127376. static long _vq_quantlist__44c4_s_p8_0[] = {
  127377. 6,
  127378. 5,
  127379. 7,
  127380. 4,
  127381. 8,
  127382. 3,
  127383. 9,
  127384. 2,
  127385. 10,
  127386. 1,
  127387. 11,
  127388. 0,
  127389. 12,
  127390. };
  127391. static long _vq_lengthlist__44c4_s_p8_0[] = {
  127392. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127393. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127394. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127395. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127396. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  127397. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  127398. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  127399. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127400. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  127401. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127402. 0,13,12,12,12,12,12,13,13,
  127403. };
  127404. static float _vq_quantthresh__44c4_s_p8_0[] = {
  127405. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127406. 12.5, 17.5, 22.5, 27.5,
  127407. };
  127408. static long _vq_quantmap__44c4_s_p8_0[] = {
  127409. 11, 9, 7, 5, 3, 1, 0, 2,
  127410. 4, 6, 8, 10, 12,
  127411. };
  127412. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  127413. _vq_quantthresh__44c4_s_p8_0,
  127414. _vq_quantmap__44c4_s_p8_0,
  127415. 13,
  127416. 13
  127417. };
  127418. static static_codebook _44c4_s_p8_0 = {
  127419. 2, 169,
  127420. _vq_lengthlist__44c4_s_p8_0,
  127421. 1, -526516224, 1616117760, 4, 0,
  127422. _vq_quantlist__44c4_s_p8_0,
  127423. NULL,
  127424. &_vq_auxt__44c4_s_p8_0,
  127425. NULL,
  127426. 0
  127427. };
  127428. static long _vq_quantlist__44c4_s_p8_1[] = {
  127429. 2,
  127430. 1,
  127431. 3,
  127432. 0,
  127433. 4,
  127434. };
  127435. static long _vq_lengthlist__44c4_s_p8_1[] = {
  127436. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  127437. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127438. };
  127439. static float _vq_quantthresh__44c4_s_p8_1[] = {
  127440. -1.5, -0.5, 0.5, 1.5,
  127441. };
  127442. static long _vq_quantmap__44c4_s_p8_1[] = {
  127443. 3, 1, 0, 2, 4,
  127444. };
  127445. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  127446. _vq_quantthresh__44c4_s_p8_1,
  127447. _vq_quantmap__44c4_s_p8_1,
  127448. 5,
  127449. 5
  127450. };
  127451. static static_codebook _44c4_s_p8_1 = {
  127452. 2, 25,
  127453. _vq_lengthlist__44c4_s_p8_1,
  127454. 1, -533725184, 1611661312, 3, 0,
  127455. _vq_quantlist__44c4_s_p8_1,
  127456. NULL,
  127457. &_vq_auxt__44c4_s_p8_1,
  127458. NULL,
  127459. 0
  127460. };
  127461. static long _vq_quantlist__44c4_s_p9_0[] = {
  127462. 6,
  127463. 5,
  127464. 7,
  127465. 4,
  127466. 8,
  127467. 3,
  127468. 9,
  127469. 2,
  127470. 10,
  127471. 1,
  127472. 11,
  127473. 0,
  127474. 12,
  127475. };
  127476. static long _vq_lengthlist__44c4_s_p9_0[] = {
  127477. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  127478. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  127479. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127480. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127481. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127482. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127483. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127484. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127485. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127486. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127487. 12,12,12,12,12,12,12,12,12,
  127488. };
  127489. static float _vq_quantthresh__44c4_s_p9_0[] = {
  127490. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127491. 787.5, 1102.5, 1417.5, 1732.5,
  127492. };
  127493. static long _vq_quantmap__44c4_s_p9_0[] = {
  127494. 11, 9, 7, 5, 3, 1, 0, 2,
  127495. 4, 6, 8, 10, 12,
  127496. };
  127497. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  127498. _vq_quantthresh__44c4_s_p9_0,
  127499. _vq_quantmap__44c4_s_p9_0,
  127500. 13,
  127501. 13
  127502. };
  127503. static static_codebook _44c4_s_p9_0 = {
  127504. 2, 169,
  127505. _vq_lengthlist__44c4_s_p9_0,
  127506. 1, -513964032, 1628680192, 4, 0,
  127507. _vq_quantlist__44c4_s_p9_0,
  127508. NULL,
  127509. &_vq_auxt__44c4_s_p9_0,
  127510. NULL,
  127511. 0
  127512. };
  127513. static long _vq_quantlist__44c4_s_p9_1[] = {
  127514. 7,
  127515. 6,
  127516. 8,
  127517. 5,
  127518. 9,
  127519. 4,
  127520. 10,
  127521. 3,
  127522. 11,
  127523. 2,
  127524. 12,
  127525. 1,
  127526. 13,
  127527. 0,
  127528. 14,
  127529. };
  127530. static long _vq_lengthlist__44c4_s_p9_1[] = {
  127531. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  127532. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  127533. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  127534. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  127535. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  127536. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  127537. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  127538. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  127539. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  127540. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  127541. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  127542. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  127543. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  127544. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  127545. 15,
  127546. };
  127547. static float _vq_quantthresh__44c4_s_p9_1[] = {
  127548. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127549. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127550. };
  127551. static long _vq_quantmap__44c4_s_p9_1[] = {
  127552. 13, 11, 9, 7, 5, 3, 1, 0,
  127553. 2, 4, 6, 8, 10, 12, 14,
  127554. };
  127555. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  127556. _vq_quantthresh__44c4_s_p9_1,
  127557. _vq_quantmap__44c4_s_p9_1,
  127558. 15,
  127559. 15
  127560. };
  127561. static static_codebook _44c4_s_p9_1 = {
  127562. 2, 225,
  127563. _vq_lengthlist__44c4_s_p9_1,
  127564. 1, -520986624, 1620377600, 4, 0,
  127565. _vq_quantlist__44c4_s_p9_1,
  127566. NULL,
  127567. &_vq_auxt__44c4_s_p9_1,
  127568. NULL,
  127569. 0
  127570. };
  127571. static long _vq_quantlist__44c4_s_p9_2[] = {
  127572. 10,
  127573. 9,
  127574. 11,
  127575. 8,
  127576. 12,
  127577. 7,
  127578. 13,
  127579. 6,
  127580. 14,
  127581. 5,
  127582. 15,
  127583. 4,
  127584. 16,
  127585. 3,
  127586. 17,
  127587. 2,
  127588. 18,
  127589. 1,
  127590. 19,
  127591. 0,
  127592. 20,
  127593. };
  127594. static long _vq_lengthlist__44c4_s_p9_2[] = {
  127595. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127596. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127597. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  127598. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  127599. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  127600. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  127601. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  127602. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  127603. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  127604. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  127605. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127606. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127607. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127608. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127609. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  127610. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  127611. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  127612. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127613. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  127614. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  127615. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127616. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127617. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  127618. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  127619. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  127620. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  127621. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  127622. 10,10,10,10,10,10,10,10,10,
  127623. };
  127624. static float _vq_quantthresh__44c4_s_p9_2[] = {
  127625. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127626. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127627. 6.5, 7.5, 8.5, 9.5,
  127628. };
  127629. static long _vq_quantmap__44c4_s_p9_2[] = {
  127630. 19, 17, 15, 13, 11, 9, 7, 5,
  127631. 3, 1, 0, 2, 4, 6, 8, 10,
  127632. 12, 14, 16, 18, 20,
  127633. };
  127634. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  127635. _vq_quantthresh__44c4_s_p9_2,
  127636. _vq_quantmap__44c4_s_p9_2,
  127637. 21,
  127638. 21
  127639. };
  127640. static static_codebook _44c4_s_p9_2 = {
  127641. 2, 441,
  127642. _vq_lengthlist__44c4_s_p9_2,
  127643. 1, -529268736, 1611661312, 5, 0,
  127644. _vq_quantlist__44c4_s_p9_2,
  127645. NULL,
  127646. &_vq_auxt__44c4_s_p9_2,
  127647. NULL,
  127648. 0
  127649. };
  127650. static long _huff_lengthlist__44c4_s_short[] = {
  127651. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  127652. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  127653. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  127654. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  127655. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  127656. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  127657. 7, 9,12,17,
  127658. };
  127659. static static_codebook _huff_book__44c4_s_short = {
  127660. 2, 100,
  127661. _huff_lengthlist__44c4_s_short,
  127662. 0, 0, 0, 0, 0,
  127663. NULL,
  127664. NULL,
  127665. NULL,
  127666. NULL,
  127667. 0
  127668. };
  127669. static long _huff_lengthlist__44c5_s_long[] = {
  127670. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  127671. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  127672. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  127673. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  127674. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  127675. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  127676. 9, 8, 7, 7,
  127677. };
  127678. static static_codebook _huff_book__44c5_s_long = {
  127679. 2, 100,
  127680. _huff_lengthlist__44c5_s_long,
  127681. 0, 0, 0, 0, 0,
  127682. NULL,
  127683. NULL,
  127684. NULL,
  127685. NULL,
  127686. 0
  127687. };
  127688. static long _vq_quantlist__44c5_s_p1_0[] = {
  127689. 1,
  127690. 0,
  127691. 2,
  127692. };
  127693. static long _vq_lengthlist__44c5_s_p1_0[] = {
  127694. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  127695. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  127700. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  127705. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  127740. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  127745. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  127750. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127786. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  127791. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127796. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0,
  128105. };
  128106. static float _vq_quantthresh__44c5_s_p1_0[] = {
  128107. -0.5, 0.5,
  128108. };
  128109. static long _vq_quantmap__44c5_s_p1_0[] = {
  128110. 1, 0, 2,
  128111. };
  128112. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  128113. _vq_quantthresh__44c5_s_p1_0,
  128114. _vq_quantmap__44c5_s_p1_0,
  128115. 3,
  128116. 3
  128117. };
  128118. static static_codebook _44c5_s_p1_0 = {
  128119. 8, 6561,
  128120. _vq_lengthlist__44c5_s_p1_0,
  128121. 1, -535822336, 1611661312, 2, 0,
  128122. _vq_quantlist__44c5_s_p1_0,
  128123. NULL,
  128124. &_vq_auxt__44c5_s_p1_0,
  128125. NULL,
  128126. 0
  128127. };
  128128. static long _vq_quantlist__44c5_s_p2_0[] = {
  128129. 2,
  128130. 1,
  128131. 3,
  128132. 0,
  128133. 4,
  128134. };
  128135. static long _vq_lengthlist__44c5_s_p2_0[] = {
  128136. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128137. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128138. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128139. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  128140. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  128146. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  128147. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  128148. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  128154. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  128155. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  128162. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  128163. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0,
  128176. };
  128177. static float _vq_quantthresh__44c5_s_p2_0[] = {
  128178. -1.5, -0.5, 0.5, 1.5,
  128179. };
  128180. static long _vq_quantmap__44c5_s_p2_0[] = {
  128181. 3, 1, 0, 2, 4,
  128182. };
  128183. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  128184. _vq_quantthresh__44c5_s_p2_0,
  128185. _vq_quantmap__44c5_s_p2_0,
  128186. 5,
  128187. 5
  128188. };
  128189. static static_codebook _44c5_s_p2_0 = {
  128190. 4, 625,
  128191. _vq_lengthlist__44c5_s_p2_0,
  128192. 1, -533725184, 1611661312, 3, 0,
  128193. _vq_quantlist__44c5_s_p2_0,
  128194. NULL,
  128195. &_vq_auxt__44c5_s_p2_0,
  128196. NULL,
  128197. 0
  128198. };
  128199. static long _vq_quantlist__44c5_s_p3_0[] = {
  128200. 2,
  128201. 1,
  128202. 3,
  128203. 0,
  128204. 4,
  128205. };
  128206. static long _vq_lengthlist__44c5_s_p3_0[] = {
  128207. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0,
  128247. };
  128248. static float _vq_quantthresh__44c5_s_p3_0[] = {
  128249. -1.5, -0.5, 0.5, 1.5,
  128250. };
  128251. static long _vq_quantmap__44c5_s_p3_0[] = {
  128252. 3, 1, 0, 2, 4,
  128253. };
  128254. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  128255. _vq_quantthresh__44c5_s_p3_0,
  128256. _vq_quantmap__44c5_s_p3_0,
  128257. 5,
  128258. 5
  128259. };
  128260. static static_codebook _44c5_s_p3_0 = {
  128261. 4, 625,
  128262. _vq_lengthlist__44c5_s_p3_0,
  128263. 1, -533725184, 1611661312, 3, 0,
  128264. _vq_quantlist__44c5_s_p3_0,
  128265. NULL,
  128266. &_vq_auxt__44c5_s_p3_0,
  128267. NULL,
  128268. 0
  128269. };
  128270. static long _vq_quantlist__44c5_s_p4_0[] = {
  128271. 4,
  128272. 3,
  128273. 5,
  128274. 2,
  128275. 6,
  128276. 1,
  128277. 7,
  128278. 0,
  128279. 8,
  128280. };
  128281. static long _vq_lengthlist__44c5_s_p4_0[] = {
  128282. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128283. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128284. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128285. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  128286. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0,
  128288. };
  128289. static float _vq_quantthresh__44c5_s_p4_0[] = {
  128290. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128291. };
  128292. static long _vq_quantmap__44c5_s_p4_0[] = {
  128293. 7, 5, 3, 1, 0, 2, 4, 6,
  128294. 8,
  128295. };
  128296. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  128297. _vq_quantthresh__44c5_s_p4_0,
  128298. _vq_quantmap__44c5_s_p4_0,
  128299. 9,
  128300. 9
  128301. };
  128302. static static_codebook _44c5_s_p4_0 = {
  128303. 2, 81,
  128304. _vq_lengthlist__44c5_s_p4_0,
  128305. 1, -531628032, 1611661312, 4, 0,
  128306. _vq_quantlist__44c5_s_p4_0,
  128307. NULL,
  128308. &_vq_auxt__44c5_s_p4_0,
  128309. NULL,
  128310. 0
  128311. };
  128312. static long _vq_quantlist__44c5_s_p5_0[] = {
  128313. 4,
  128314. 3,
  128315. 5,
  128316. 2,
  128317. 6,
  128318. 1,
  128319. 7,
  128320. 0,
  128321. 8,
  128322. };
  128323. static long _vq_lengthlist__44c5_s_p5_0[] = {
  128324. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128325. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  128326. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  128327. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  128328. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  128329. 10,
  128330. };
  128331. static float _vq_quantthresh__44c5_s_p5_0[] = {
  128332. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128333. };
  128334. static long _vq_quantmap__44c5_s_p5_0[] = {
  128335. 7, 5, 3, 1, 0, 2, 4, 6,
  128336. 8,
  128337. };
  128338. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  128339. _vq_quantthresh__44c5_s_p5_0,
  128340. _vq_quantmap__44c5_s_p5_0,
  128341. 9,
  128342. 9
  128343. };
  128344. static static_codebook _44c5_s_p5_0 = {
  128345. 2, 81,
  128346. _vq_lengthlist__44c5_s_p5_0,
  128347. 1, -531628032, 1611661312, 4, 0,
  128348. _vq_quantlist__44c5_s_p5_0,
  128349. NULL,
  128350. &_vq_auxt__44c5_s_p5_0,
  128351. NULL,
  128352. 0
  128353. };
  128354. static long _vq_quantlist__44c5_s_p6_0[] = {
  128355. 8,
  128356. 7,
  128357. 9,
  128358. 6,
  128359. 10,
  128360. 5,
  128361. 11,
  128362. 4,
  128363. 12,
  128364. 3,
  128365. 13,
  128366. 2,
  128367. 14,
  128368. 1,
  128369. 15,
  128370. 0,
  128371. 16,
  128372. };
  128373. static long _vq_lengthlist__44c5_s_p6_0[] = {
  128374. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  128375. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128376. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  128377. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128378. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128379. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128380. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  128381. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  128382. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128383. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  128384. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  128385. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  128386. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  128387. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  128388. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  128389. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128390. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128392. 13,
  128393. };
  128394. static float _vq_quantthresh__44c5_s_p6_0[] = {
  128395. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128396. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128397. };
  128398. static long _vq_quantmap__44c5_s_p6_0[] = {
  128399. 15, 13, 11, 9, 7, 5, 3, 1,
  128400. 0, 2, 4, 6, 8, 10, 12, 14,
  128401. 16,
  128402. };
  128403. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  128404. _vq_quantthresh__44c5_s_p6_0,
  128405. _vq_quantmap__44c5_s_p6_0,
  128406. 17,
  128407. 17
  128408. };
  128409. static static_codebook _44c5_s_p6_0 = {
  128410. 2, 289,
  128411. _vq_lengthlist__44c5_s_p6_0,
  128412. 1, -529530880, 1611661312, 5, 0,
  128413. _vq_quantlist__44c5_s_p6_0,
  128414. NULL,
  128415. &_vq_auxt__44c5_s_p6_0,
  128416. NULL,
  128417. 0
  128418. };
  128419. static long _vq_quantlist__44c5_s_p7_0[] = {
  128420. 1,
  128421. 0,
  128422. 2,
  128423. };
  128424. static long _vq_lengthlist__44c5_s_p7_0[] = {
  128425. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128426. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128427. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128428. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  128429. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128430. 10,
  128431. };
  128432. static float _vq_quantthresh__44c5_s_p7_0[] = {
  128433. -5.5, 5.5,
  128434. };
  128435. static long _vq_quantmap__44c5_s_p7_0[] = {
  128436. 1, 0, 2,
  128437. };
  128438. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  128439. _vq_quantthresh__44c5_s_p7_0,
  128440. _vq_quantmap__44c5_s_p7_0,
  128441. 3,
  128442. 3
  128443. };
  128444. static static_codebook _44c5_s_p7_0 = {
  128445. 4, 81,
  128446. _vq_lengthlist__44c5_s_p7_0,
  128447. 1, -529137664, 1618345984, 2, 0,
  128448. _vq_quantlist__44c5_s_p7_0,
  128449. NULL,
  128450. &_vq_auxt__44c5_s_p7_0,
  128451. NULL,
  128452. 0
  128453. };
  128454. static long _vq_quantlist__44c5_s_p7_1[] = {
  128455. 5,
  128456. 4,
  128457. 6,
  128458. 3,
  128459. 7,
  128460. 2,
  128461. 8,
  128462. 1,
  128463. 9,
  128464. 0,
  128465. 10,
  128466. };
  128467. static long _vq_lengthlist__44c5_s_p7_1[] = {
  128468. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  128469. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128470. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128471. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128472. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  128473. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  128474. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128475. 10,10,10, 8, 8, 8, 8, 8, 8,
  128476. };
  128477. static float _vq_quantthresh__44c5_s_p7_1[] = {
  128478. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128479. 3.5, 4.5,
  128480. };
  128481. static long _vq_quantmap__44c5_s_p7_1[] = {
  128482. 9, 7, 5, 3, 1, 0, 2, 4,
  128483. 6, 8, 10,
  128484. };
  128485. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  128486. _vq_quantthresh__44c5_s_p7_1,
  128487. _vq_quantmap__44c5_s_p7_1,
  128488. 11,
  128489. 11
  128490. };
  128491. static static_codebook _44c5_s_p7_1 = {
  128492. 2, 121,
  128493. _vq_lengthlist__44c5_s_p7_1,
  128494. 1, -531365888, 1611661312, 4, 0,
  128495. _vq_quantlist__44c5_s_p7_1,
  128496. NULL,
  128497. &_vq_auxt__44c5_s_p7_1,
  128498. NULL,
  128499. 0
  128500. };
  128501. static long _vq_quantlist__44c5_s_p8_0[] = {
  128502. 6,
  128503. 5,
  128504. 7,
  128505. 4,
  128506. 8,
  128507. 3,
  128508. 9,
  128509. 2,
  128510. 10,
  128511. 1,
  128512. 11,
  128513. 0,
  128514. 12,
  128515. };
  128516. static long _vq_lengthlist__44c5_s_p8_0[] = {
  128517. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128518. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  128519. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128520. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128521. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  128522. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  128523. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  128524. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128525. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  128526. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  128527. 0,12,12,12,12,12,12,13,13,
  128528. };
  128529. static float _vq_quantthresh__44c5_s_p8_0[] = {
  128530. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128531. 12.5, 17.5, 22.5, 27.5,
  128532. };
  128533. static long _vq_quantmap__44c5_s_p8_0[] = {
  128534. 11, 9, 7, 5, 3, 1, 0, 2,
  128535. 4, 6, 8, 10, 12,
  128536. };
  128537. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  128538. _vq_quantthresh__44c5_s_p8_0,
  128539. _vq_quantmap__44c5_s_p8_0,
  128540. 13,
  128541. 13
  128542. };
  128543. static static_codebook _44c5_s_p8_0 = {
  128544. 2, 169,
  128545. _vq_lengthlist__44c5_s_p8_0,
  128546. 1, -526516224, 1616117760, 4, 0,
  128547. _vq_quantlist__44c5_s_p8_0,
  128548. NULL,
  128549. &_vq_auxt__44c5_s_p8_0,
  128550. NULL,
  128551. 0
  128552. };
  128553. static long _vq_quantlist__44c5_s_p8_1[] = {
  128554. 2,
  128555. 1,
  128556. 3,
  128557. 0,
  128558. 4,
  128559. };
  128560. static long _vq_lengthlist__44c5_s_p8_1[] = {
  128561. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  128562. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128563. };
  128564. static float _vq_quantthresh__44c5_s_p8_1[] = {
  128565. -1.5, -0.5, 0.5, 1.5,
  128566. };
  128567. static long _vq_quantmap__44c5_s_p8_1[] = {
  128568. 3, 1, 0, 2, 4,
  128569. };
  128570. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  128571. _vq_quantthresh__44c5_s_p8_1,
  128572. _vq_quantmap__44c5_s_p8_1,
  128573. 5,
  128574. 5
  128575. };
  128576. static static_codebook _44c5_s_p8_1 = {
  128577. 2, 25,
  128578. _vq_lengthlist__44c5_s_p8_1,
  128579. 1, -533725184, 1611661312, 3, 0,
  128580. _vq_quantlist__44c5_s_p8_1,
  128581. NULL,
  128582. &_vq_auxt__44c5_s_p8_1,
  128583. NULL,
  128584. 0
  128585. };
  128586. static long _vq_quantlist__44c5_s_p9_0[] = {
  128587. 7,
  128588. 6,
  128589. 8,
  128590. 5,
  128591. 9,
  128592. 4,
  128593. 10,
  128594. 3,
  128595. 11,
  128596. 2,
  128597. 12,
  128598. 1,
  128599. 13,
  128600. 0,
  128601. 14,
  128602. };
  128603. static long _vq_lengthlist__44c5_s_p9_0[] = {
  128604. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  128605. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  128606. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128607. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128608. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128609. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128610. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128611. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128612. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128613. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128614. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128615. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128616. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128617. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  128618. 12,
  128619. };
  128620. static float _vq_quantthresh__44c5_s_p9_0[] = {
  128621. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  128622. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  128623. };
  128624. static long _vq_quantmap__44c5_s_p9_0[] = {
  128625. 13, 11, 9, 7, 5, 3, 1, 0,
  128626. 2, 4, 6, 8, 10, 12, 14,
  128627. };
  128628. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  128629. _vq_quantthresh__44c5_s_p9_0,
  128630. _vq_quantmap__44c5_s_p9_0,
  128631. 15,
  128632. 15
  128633. };
  128634. static static_codebook _44c5_s_p9_0 = {
  128635. 2, 225,
  128636. _vq_lengthlist__44c5_s_p9_0,
  128637. 1, -512522752, 1628852224, 4, 0,
  128638. _vq_quantlist__44c5_s_p9_0,
  128639. NULL,
  128640. &_vq_auxt__44c5_s_p9_0,
  128641. NULL,
  128642. 0
  128643. };
  128644. static long _vq_quantlist__44c5_s_p9_1[] = {
  128645. 8,
  128646. 7,
  128647. 9,
  128648. 6,
  128649. 10,
  128650. 5,
  128651. 11,
  128652. 4,
  128653. 12,
  128654. 3,
  128655. 13,
  128656. 2,
  128657. 14,
  128658. 1,
  128659. 15,
  128660. 0,
  128661. 16,
  128662. };
  128663. static long _vq_lengthlist__44c5_s_p9_1[] = {
  128664. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  128665. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  128666. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  128667. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  128668. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  128669. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  128670. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  128671. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  128672. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  128673. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  128674. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  128675. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  128676. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  128677. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  128678. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  128679. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  128680. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  128681. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  128682. 15,
  128683. };
  128684. static float _vq_quantthresh__44c5_s_p9_1[] = {
  128685. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  128686. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  128687. };
  128688. static long _vq_quantmap__44c5_s_p9_1[] = {
  128689. 15, 13, 11, 9, 7, 5, 3, 1,
  128690. 0, 2, 4, 6, 8, 10, 12, 14,
  128691. 16,
  128692. };
  128693. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  128694. _vq_quantthresh__44c5_s_p9_1,
  128695. _vq_quantmap__44c5_s_p9_1,
  128696. 17,
  128697. 17
  128698. };
  128699. static static_codebook _44c5_s_p9_1 = {
  128700. 2, 289,
  128701. _vq_lengthlist__44c5_s_p9_1,
  128702. 1, -520814592, 1620377600, 5, 0,
  128703. _vq_quantlist__44c5_s_p9_1,
  128704. NULL,
  128705. &_vq_auxt__44c5_s_p9_1,
  128706. NULL,
  128707. 0
  128708. };
  128709. static long _vq_quantlist__44c5_s_p9_2[] = {
  128710. 10,
  128711. 9,
  128712. 11,
  128713. 8,
  128714. 12,
  128715. 7,
  128716. 13,
  128717. 6,
  128718. 14,
  128719. 5,
  128720. 15,
  128721. 4,
  128722. 16,
  128723. 3,
  128724. 17,
  128725. 2,
  128726. 18,
  128727. 1,
  128728. 19,
  128729. 0,
  128730. 20,
  128731. };
  128732. static long _vq_lengthlist__44c5_s_p9_2[] = {
  128733. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  128734. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  128735. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  128736. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  128737. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  128738. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128739. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128740. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  128741. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128742. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128743. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  128744. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  128745. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  128746. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  128747. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  128748. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  128749. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128750. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128751. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  128752. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  128753. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128754. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128755. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128756. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128757. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  128758. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128759. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  128760. 10,10,10,10,10,10,10,10,10,
  128761. };
  128762. static float _vq_quantthresh__44c5_s_p9_2[] = {
  128763. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128764. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128765. 6.5, 7.5, 8.5, 9.5,
  128766. };
  128767. static long _vq_quantmap__44c5_s_p9_2[] = {
  128768. 19, 17, 15, 13, 11, 9, 7, 5,
  128769. 3, 1, 0, 2, 4, 6, 8, 10,
  128770. 12, 14, 16, 18, 20,
  128771. };
  128772. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  128773. _vq_quantthresh__44c5_s_p9_2,
  128774. _vq_quantmap__44c5_s_p9_2,
  128775. 21,
  128776. 21
  128777. };
  128778. static static_codebook _44c5_s_p9_2 = {
  128779. 2, 441,
  128780. _vq_lengthlist__44c5_s_p9_2,
  128781. 1, -529268736, 1611661312, 5, 0,
  128782. _vq_quantlist__44c5_s_p9_2,
  128783. NULL,
  128784. &_vq_auxt__44c5_s_p9_2,
  128785. NULL,
  128786. 0
  128787. };
  128788. static long _huff_lengthlist__44c5_s_short[] = {
  128789. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  128790. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  128791. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  128792. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  128793. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  128794. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  128795. 6, 8,11,16,
  128796. };
  128797. static static_codebook _huff_book__44c5_s_short = {
  128798. 2, 100,
  128799. _huff_lengthlist__44c5_s_short,
  128800. 0, 0, 0, 0, 0,
  128801. NULL,
  128802. NULL,
  128803. NULL,
  128804. NULL,
  128805. 0
  128806. };
  128807. static long _huff_lengthlist__44c6_s_long[] = {
  128808. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  128809. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  128810. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  128811. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  128812. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  128813. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  128814. 11,10,10,12,
  128815. };
  128816. static static_codebook _huff_book__44c6_s_long = {
  128817. 2, 100,
  128818. _huff_lengthlist__44c6_s_long,
  128819. 0, 0, 0, 0, 0,
  128820. NULL,
  128821. NULL,
  128822. NULL,
  128823. NULL,
  128824. 0
  128825. };
  128826. static long _vq_quantlist__44c6_s_p1_0[] = {
  128827. 1,
  128828. 0,
  128829. 2,
  128830. };
  128831. static long _vq_lengthlist__44c6_s_p1_0[] = {
  128832. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128833. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128835. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128836. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  128837. 8,
  128838. };
  128839. static float _vq_quantthresh__44c6_s_p1_0[] = {
  128840. -0.5, 0.5,
  128841. };
  128842. static long _vq_quantmap__44c6_s_p1_0[] = {
  128843. 1, 0, 2,
  128844. };
  128845. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  128846. _vq_quantthresh__44c6_s_p1_0,
  128847. _vq_quantmap__44c6_s_p1_0,
  128848. 3,
  128849. 3
  128850. };
  128851. static static_codebook _44c6_s_p1_0 = {
  128852. 4, 81,
  128853. _vq_lengthlist__44c6_s_p1_0,
  128854. 1, -535822336, 1611661312, 2, 0,
  128855. _vq_quantlist__44c6_s_p1_0,
  128856. NULL,
  128857. &_vq_auxt__44c6_s_p1_0,
  128858. NULL,
  128859. 0
  128860. };
  128861. static long _vq_quantlist__44c6_s_p2_0[] = {
  128862. 2,
  128863. 1,
  128864. 3,
  128865. 0,
  128866. 4,
  128867. };
  128868. static long _vq_lengthlist__44c6_s_p2_0[] = {
  128869. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128870. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128871. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128872. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128873. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  128874. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128875. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  128876. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128879. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128880. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128881. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128882. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128883. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  128884. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128887. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  128888. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  128889. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  128890. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  128891. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128892. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  128895. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128896. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128897. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  128898. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128899. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  128900. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128905. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  128906. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  128907. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128908. 13,
  128909. };
  128910. static float _vq_quantthresh__44c6_s_p2_0[] = {
  128911. -1.5, -0.5, 0.5, 1.5,
  128912. };
  128913. static long _vq_quantmap__44c6_s_p2_0[] = {
  128914. 3, 1, 0, 2, 4,
  128915. };
  128916. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  128917. _vq_quantthresh__44c6_s_p2_0,
  128918. _vq_quantmap__44c6_s_p2_0,
  128919. 5,
  128920. 5
  128921. };
  128922. static static_codebook _44c6_s_p2_0 = {
  128923. 4, 625,
  128924. _vq_lengthlist__44c6_s_p2_0,
  128925. 1, -533725184, 1611661312, 3, 0,
  128926. _vq_quantlist__44c6_s_p2_0,
  128927. NULL,
  128928. &_vq_auxt__44c6_s_p2_0,
  128929. NULL,
  128930. 0
  128931. };
  128932. static long _vq_quantlist__44c6_s_p3_0[] = {
  128933. 4,
  128934. 3,
  128935. 5,
  128936. 2,
  128937. 6,
  128938. 1,
  128939. 7,
  128940. 0,
  128941. 8,
  128942. };
  128943. static long _vq_lengthlist__44c6_s_p3_0[] = {
  128944. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128945. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  128946. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  128947. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0,
  128950. };
  128951. static float _vq_quantthresh__44c6_s_p3_0[] = {
  128952. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128953. };
  128954. static long _vq_quantmap__44c6_s_p3_0[] = {
  128955. 7, 5, 3, 1, 0, 2, 4, 6,
  128956. 8,
  128957. };
  128958. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  128959. _vq_quantthresh__44c6_s_p3_0,
  128960. _vq_quantmap__44c6_s_p3_0,
  128961. 9,
  128962. 9
  128963. };
  128964. static static_codebook _44c6_s_p3_0 = {
  128965. 2, 81,
  128966. _vq_lengthlist__44c6_s_p3_0,
  128967. 1, -531628032, 1611661312, 4, 0,
  128968. _vq_quantlist__44c6_s_p3_0,
  128969. NULL,
  128970. &_vq_auxt__44c6_s_p3_0,
  128971. NULL,
  128972. 0
  128973. };
  128974. static long _vq_quantlist__44c6_s_p4_0[] = {
  128975. 8,
  128976. 7,
  128977. 9,
  128978. 6,
  128979. 10,
  128980. 5,
  128981. 11,
  128982. 4,
  128983. 12,
  128984. 3,
  128985. 13,
  128986. 2,
  128987. 14,
  128988. 1,
  128989. 15,
  128990. 0,
  128991. 16,
  128992. };
  128993. static long _vq_lengthlist__44c6_s_p4_0[] = {
  128994. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  128995. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128996. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  128997. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128998. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128999. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  129000. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  129001. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129002. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  129003. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0,
  129013. };
  129014. static float _vq_quantthresh__44c6_s_p4_0[] = {
  129015. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129016. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129017. };
  129018. static long _vq_quantmap__44c6_s_p4_0[] = {
  129019. 15, 13, 11, 9, 7, 5, 3, 1,
  129020. 0, 2, 4, 6, 8, 10, 12, 14,
  129021. 16,
  129022. };
  129023. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  129024. _vq_quantthresh__44c6_s_p4_0,
  129025. _vq_quantmap__44c6_s_p4_0,
  129026. 17,
  129027. 17
  129028. };
  129029. static static_codebook _44c6_s_p4_0 = {
  129030. 2, 289,
  129031. _vq_lengthlist__44c6_s_p4_0,
  129032. 1, -529530880, 1611661312, 5, 0,
  129033. _vq_quantlist__44c6_s_p4_0,
  129034. NULL,
  129035. &_vq_auxt__44c6_s_p4_0,
  129036. NULL,
  129037. 0
  129038. };
  129039. static long _vq_quantlist__44c6_s_p5_0[] = {
  129040. 1,
  129041. 0,
  129042. 2,
  129043. };
  129044. static long _vq_lengthlist__44c6_s_p5_0[] = {
  129045. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  129046. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  129047. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  129048. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129049. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  129050. 12,
  129051. };
  129052. static float _vq_quantthresh__44c6_s_p5_0[] = {
  129053. -5.5, 5.5,
  129054. };
  129055. static long _vq_quantmap__44c6_s_p5_0[] = {
  129056. 1, 0, 2,
  129057. };
  129058. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  129059. _vq_quantthresh__44c6_s_p5_0,
  129060. _vq_quantmap__44c6_s_p5_0,
  129061. 3,
  129062. 3
  129063. };
  129064. static static_codebook _44c6_s_p5_0 = {
  129065. 4, 81,
  129066. _vq_lengthlist__44c6_s_p5_0,
  129067. 1, -529137664, 1618345984, 2, 0,
  129068. _vq_quantlist__44c6_s_p5_0,
  129069. NULL,
  129070. &_vq_auxt__44c6_s_p5_0,
  129071. NULL,
  129072. 0
  129073. };
  129074. static long _vq_quantlist__44c6_s_p5_1[] = {
  129075. 5,
  129076. 4,
  129077. 6,
  129078. 3,
  129079. 7,
  129080. 2,
  129081. 8,
  129082. 1,
  129083. 9,
  129084. 0,
  129085. 10,
  129086. };
  129087. static long _vq_lengthlist__44c6_s_p5_1[] = {
  129088. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129089. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  129090. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  129091. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  129092. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  129093. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  129094. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  129095. 11,10,10, 7, 7, 8, 8, 8, 8,
  129096. };
  129097. static float _vq_quantthresh__44c6_s_p5_1[] = {
  129098. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129099. 3.5, 4.5,
  129100. };
  129101. static long _vq_quantmap__44c6_s_p5_1[] = {
  129102. 9, 7, 5, 3, 1, 0, 2, 4,
  129103. 6, 8, 10,
  129104. };
  129105. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  129106. _vq_quantthresh__44c6_s_p5_1,
  129107. _vq_quantmap__44c6_s_p5_1,
  129108. 11,
  129109. 11
  129110. };
  129111. static static_codebook _44c6_s_p5_1 = {
  129112. 2, 121,
  129113. _vq_lengthlist__44c6_s_p5_1,
  129114. 1, -531365888, 1611661312, 4, 0,
  129115. _vq_quantlist__44c6_s_p5_1,
  129116. NULL,
  129117. &_vq_auxt__44c6_s_p5_1,
  129118. NULL,
  129119. 0
  129120. };
  129121. static long _vq_quantlist__44c6_s_p6_0[] = {
  129122. 6,
  129123. 5,
  129124. 7,
  129125. 4,
  129126. 8,
  129127. 3,
  129128. 9,
  129129. 2,
  129130. 10,
  129131. 1,
  129132. 11,
  129133. 0,
  129134. 12,
  129135. };
  129136. static long _vq_lengthlist__44c6_s_p6_0[] = {
  129137. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  129138. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  129139. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  129140. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129141. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  129142. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. };
  129149. static float _vq_quantthresh__44c6_s_p6_0[] = {
  129150. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129151. 12.5, 17.5, 22.5, 27.5,
  129152. };
  129153. static long _vq_quantmap__44c6_s_p6_0[] = {
  129154. 11, 9, 7, 5, 3, 1, 0, 2,
  129155. 4, 6, 8, 10, 12,
  129156. };
  129157. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  129158. _vq_quantthresh__44c6_s_p6_0,
  129159. _vq_quantmap__44c6_s_p6_0,
  129160. 13,
  129161. 13
  129162. };
  129163. static static_codebook _44c6_s_p6_0 = {
  129164. 2, 169,
  129165. _vq_lengthlist__44c6_s_p6_0,
  129166. 1, -526516224, 1616117760, 4, 0,
  129167. _vq_quantlist__44c6_s_p6_0,
  129168. NULL,
  129169. &_vq_auxt__44c6_s_p6_0,
  129170. NULL,
  129171. 0
  129172. };
  129173. static long _vq_quantlist__44c6_s_p6_1[] = {
  129174. 2,
  129175. 1,
  129176. 3,
  129177. 0,
  129178. 4,
  129179. };
  129180. static long _vq_lengthlist__44c6_s_p6_1[] = {
  129181. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129182. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129183. };
  129184. static float _vq_quantthresh__44c6_s_p6_1[] = {
  129185. -1.5, -0.5, 0.5, 1.5,
  129186. };
  129187. static long _vq_quantmap__44c6_s_p6_1[] = {
  129188. 3, 1, 0, 2, 4,
  129189. };
  129190. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  129191. _vq_quantthresh__44c6_s_p6_1,
  129192. _vq_quantmap__44c6_s_p6_1,
  129193. 5,
  129194. 5
  129195. };
  129196. static static_codebook _44c6_s_p6_1 = {
  129197. 2, 25,
  129198. _vq_lengthlist__44c6_s_p6_1,
  129199. 1, -533725184, 1611661312, 3, 0,
  129200. _vq_quantlist__44c6_s_p6_1,
  129201. NULL,
  129202. &_vq_auxt__44c6_s_p6_1,
  129203. NULL,
  129204. 0
  129205. };
  129206. static long _vq_quantlist__44c6_s_p7_0[] = {
  129207. 6,
  129208. 5,
  129209. 7,
  129210. 4,
  129211. 8,
  129212. 3,
  129213. 9,
  129214. 2,
  129215. 10,
  129216. 1,
  129217. 11,
  129218. 0,
  129219. 12,
  129220. };
  129221. static long _vq_lengthlist__44c6_s_p7_0[] = {
  129222. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  129223. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  129224. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  129225. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129226. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  129227. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  129228. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  129229. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  129230. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  129231. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  129232. 20,13,13,13,13,13,13,14,14,
  129233. };
  129234. static float _vq_quantthresh__44c6_s_p7_0[] = {
  129235. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129236. 27.5, 38.5, 49.5, 60.5,
  129237. };
  129238. static long _vq_quantmap__44c6_s_p7_0[] = {
  129239. 11, 9, 7, 5, 3, 1, 0, 2,
  129240. 4, 6, 8, 10, 12,
  129241. };
  129242. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  129243. _vq_quantthresh__44c6_s_p7_0,
  129244. _vq_quantmap__44c6_s_p7_0,
  129245. 13,
  129246. 13
  129247. };
  129248. static static_codebook _44c6_s_p7_0 = {
  129249. 2, 169,
  129250. _vq_lengthlist__44c6_s_p7_0,
  129251. 1, -523206656, 1618345984, 4, 0,
  129252. _vq_quantlist__44c6_s_p7_0,
  129253. NULL,
  129254. &_vq_auxt__44c6_s_p7_0,
  129255. NULL,
  129256. 0
  129257. };
  129258. static long _vq_quantlist__44c6_s_p7_1[] = {
  129259. 5,
  129260. 4,
  129261. 6,
  129262. 3,
  129263. 7,
  129264. 2,
  129265. 8,
  129266. 1,
  129267. 9,
  129268. 0,
  129269. 10,
  129270. };
  129271. static long _vq_lengthlist__44c6_s_p7_1[] = {
  129272. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  129273. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  129274. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  129275. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  129276. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  129277. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  129278. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  129279. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  129280. };
  129281. static float _vq_quantthresh__44c6_s_p7_1[] = {
  129282. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129283. 3.5, 4.5,
  129284. };
  129285. static long _vq_quantmap__44c6_s_p7_1[] = {
  129286. 9, 7, 5, 3, 1, 0, 2, 4,
  129287. 6, 8, 10,
  129288. };
  129289. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  129290. _vq_quantthresh__44c6_s_p7_1,
  129291. _vq_quantmap__44c6_s_p7_1,
  129292. 11,
  129293. 11
  129294. };
  129295. static static_codebook _44c6_s_p7_1 = {
  129296. 2, 121,
  129297. _vq_lengthlist__44c6_s_p7_1,
  129298. 1, -531365888, 1611661312, 4, 0,
  129299. _vq_quantlist__44c6_s_p7_1,
  129300. NULL,
  129301. &_vq_auxt__44c6_s_p7_1,
  129302. NULL,
  129303. 0
  129304. };
  129305. static long _vq_quantlist__44c6_s_p8_0[] = {
  129306. 7,
  129307. 6,
  129308. 8,
  129309. 5,
  129310. 9,
  129311. 4,
  129312. 10,
  129313. 3,
  129314. 11,
  129315. 2,
  129316. 12,
  129317. 1,
  129318. 13,
  129319. 0,
  129320. 14,
  129321. };
  129322. static long _vq_lengthlist__44c6_s_p8_0[] = {
  129323. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  129324. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  129325. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  129326. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  129327. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  129328. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  129329. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  129330. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  129331. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  129332. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  129333. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  129334. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  129335. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  129336. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  129337. 14,
  129338. };
  129339. static float _vq_quantthresh__44c6_s_p8_0[] = {
  129340. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129341. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129342. };
  129343. static long _vq_quantmap__44c6_s_p8_0[] = {
  129344. 13, 11, 9, 7, 5, 3, 1, 0,
  129345. 2, 4, 6, 8, 10, 12, 14,
  129346. };
  129347. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  129348. _vq_quantthresh__44c6_s_p8_0,
  129349. _vq_quantmap__44c6_s_p8_0,
  129350. 15,
  129351. 15
  129352. };
  129353. static static_codebook _44c6_s_p8_0 = {
  129354. 2, 225,
  129355. _vq_lengthlist__44c6_s_p8_0,
  129356. 1, -520986624, 1620377600, 4, 0,
  129357. _vq_quantlist__44c6_s_p8_0,
  129358. NULL,
  129359. &_vq_auxt__44c6_s_p8_0,
  129360. NULL,
  129361. 0
  129362. };
  129363. static long _vq_quantlist__44c6_s_p8_1[] = {
  129364. 10,
  129365. 9,
  129366. 11,
  129367. 8,
  129368. 12,
  129369. 7,
  129370. 13,
  129371. 6,
  129372. 14,
  129373. 5,
  129374. 15,
  129375. 4,
  129376. 16,
  129377. 3,
  129378. 17,
  129379. 2,
  129380. 18,
  129381. 1,
  129382. 19,
  129383. 0,
  129384. 20,
  129385. };
  129386. static long _vq_lengthlist__44c6_s_p8_1[] = {
  129387. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  129388. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  129389. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129390. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129391. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129392. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  129393. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  129394. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  129395. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129396. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129397. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  129398. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  129399. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  129400. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  129401. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  129402. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  129403. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  129404. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  129405. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  129406. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  129407. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  129408. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  129409. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  129410. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  129411. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  129412. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  129413. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  129414. 10,10,10,10,10,10,10,10,10,
  129415. };
  129416. static float _vq_quantthresh__44c6_s_p8_1[] = {
  129417. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129418. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129419. 6.5, 7.5, 8.5, 9.5,
  129420. };
  129421. static long _vq_quantmap__44c6_s_p8_1[] = {
  129422. 19, 17, 15, 13, 11, 9, 7, 5,
  129423. 3, 1, 0, 2, 4, 6, 8, 10,
  129424. 12, 14, 16, 18, 20,
  129425. };
  129426. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  129427. _vq_quantthresh__44c6_s_p8_1,
  129428. _vq_quantmap__44c6_s_p8_1,
  129429. 21,
  129430. 21
  129431. };
  129432. static static_codebook _44c6_s_p8_1 = {
  129433. 2, 441,
  129434. _vq_lengthlist__44c6_s_p8_1,
  129435. 1, -529268736, 1611661312, 5, 0,
  129436. _vq_quantlist__44c6_s_p8_1,
  129437. NULL,
  129438. &_vq_auxt__44c6_s_p8_1,
  129439. NULL,
  129440. 0
  129441. };
  129442. static long _vq_quantlist__44c6_s_p9_0[] = {
  129443. 6,
  129444. 5,
  129445. 7,
  129446. 4,
  129447. 8,
  129448. 3,
  129449. 9,
  129450. 2,
  129451. 10,
  129452. 1,
  129453. 11,
  129454. 0,
  129455. 12,
  129456. };
  129457. static long _vq_lengthlist__44c6_s_p9_0[] = {
  129458. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  129459. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  129460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129461. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129462. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129463. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129464. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129465. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129466. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129467. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129468. 10,10,10,10,10,10,10,10,10,
  129469. };
  129470. static float _vq_quantthresh__44c6_s_p9_0[] = {
  129471. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129472. 1592.5, 2229.5, 2866.5, 3503.5,
  129473. };
  129474. static long _vq_quantmap__44c6_s_p9_0[] = {
  129475. 11, 9, 7, 5, 3, 1, 0, 2,
  129476. 4, 6, 8, 10, 12,
  129477. };
  129478. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  129479. _vq_quantthresh__44c6_s_p9_0,
  129480. _vq_quantmap__44c6_s_p9_0,
  129481. 13,
  129482. 13
  129483. };
  129484. static static_codebook _44c6_s_p9_0 = {
  129485. 2, 169,
  129486. _vq_lengthlist__44c6_s_p9_0,
  129487. 1, -511845376, 1630791680, 4, 0,
  129488. _vq_quantlist__44c6_s_p9_0,
  129489. NULL,
  129490. &_vq_auxt__44c6_s_p9_0,
  129491. NULL,
  129492. 0
  129493. };
  129494. static long _vq_quantlist__44c6_s_p9_1[] = {
  129495. 6,
  129496. 5,
  129497. 7,
  129498. 4,
  129499. 8,
  129500. 3,
  129501. 9,
  129502. 2,
  129503. 10,
  129504. 1,
  129505. 11,
  129506. 0,
  129507. 12,
  129508. };
  129509. static long _vq_lengthlist__44c6_s_p9_1[] = {
  129510. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  129511. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  129512. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  129513. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  129514. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  129515. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  129516. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  129517. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  129518. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  129519. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  129520. 15,12,10,11,11,13,11,12,13,
  129521. };
  129522. static float _vq_quantthresh__44c6_s_p9_1[] = {
  129523. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  129524. 122.5, 171.5, 220.5, 269.5,
  129525. };
  129526. static long _vq_quantmap__44c6_s_p9_1[] = {
  129527. 11, 9, 7, 5, 3, 1, 0, 2,
  129528. 4, 6, 8, 10, 12,
  129529. };
  129530. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  129531. _vq_quantthresh__44c6_s_p9_1,
  129532. _vq_quantmap__44c6_s_p9_1,
  129533. 13,
  129534. 13
  129535. };
  129536. static static_codebook _44c6_s_p9_1 = {
  129537. 2, 169,
  129538. _vq_lengthlist__44c6_s_p9_1,
  129539. 1, -518889472, 1622704128, 4, 0,
  129540. _vq_quantlist__44c6_s_p9_1,
  129541. NULL,
  129542. &_vq_auxt__44c6_s_p9_1,
  129543. NULL,
  129544. 0
  129545. };
  129546. static long _vq_quantlist__44c6_s_p9_2[] = {
  129547. 24,
  129548. 23,
  129549. 25,
  129550. 22,
  129551. 26,
  129552. 21,
  129553. 27,
  129554. 20,
  129555. 28,
  129556. 19,
  129557. 29,
  129558. 18,
  129559. 30,
  129560. 17,
  129561. 31,
  129562. 16,
  129563. 32,
  129564. 15,
  129565. 33,
  129566. 14,
  129567. 34,
  129568. 13,
  129569. 35,
  129570. 12,
  129571. 36,
  129572. 11,
  129573. 37,
  129574. 10,
  129575. 38,
  129576. 9,
  129577. 39,
  129578. 8,
  129579. 40,
  129580. 7,
  129581. 41,
  129582. 6,
  129583. 42,
  129584. 5,
  129585. 43,
  129586. 4,
  129587. 44,
  129588. 3,
  129589. 45,
  129590. 2,
  129591. 46,
  129592. 1,
  129593. 47,
  129594. 0,
  129595. 48,
  129596. };
  129597. static long _vq_lengthlist__44c6_s_p9_2[] = {
  129598. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129599. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129600. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129601. 7,
  129602. };
  129603. static float _vq_quantthresh__44c6_s_p9_2[] = {
  129604. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129605. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129606. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129607. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129608. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129609. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129610. };
  129611. static long _vq_quantmap__44c6_s_p9_2[] = {
  129612. 47, 45, 43, 41, 39, 37, 35, 33,
  129613. 31, 29, 27, 25, 23, 21, 19, 17,
  129614. 15, 13, 11, 9, 7, 5, 3, 1,
  129615. 0, 2, 4, 6, 8, 10, 12, 14,
  129616. 16, 18, 20, 22, 24, 26, 28, 30,
  129617. 32, 34, 36, 38, 40, 42, 44, 46,
  129618. 48,
  129619. };
  129620. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  129621. _vq_quantthresh__44c6_s_p9_2,
  129622. _vq_quantmap__44c6_s_p9_2,
  129623. 49,
  129624. 49
  129625. };
  129626. static static_codebook _44c6_s_p9_2 = {
  129627. 1, 49,
  129628. _vq_lengthlist__44c6_s_p9_2,
  129629. 1, -526909440, 1611661312, 6, 0,
  129630. _vq_quantlist__44c6_s_p9_2,
  129631. NULL,
  129632. &_vq_auxt__44c6_s_p9_2,
  129633. NULL,
  129634. 0
  129635. };
  129636. static long _huff_lengthlist__44c6_s_short[] = {
  129637. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  129638. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  129639. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  129640. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  129641. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  129642. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  129643. 9,10,17,18,
  129644. };
  129645. static static_codebook _huff_book__44c6_s_short = {
  129646. 2, 100,
  129647. _huff_lengthlist__44c6_s_short,
  129648. 0, 0, 0, 0, 0,
  129649. NULL,
  129650. NULL,
  129651. NULL,
  129652. NULL,
  129653. 0
  129654. };
  129655. static long _huff_lengthlist__44c7_s_long[] = {
  129656. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  129657. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  129658. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  129659. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  129660. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  129661. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  129662. 11,10,10,12,
  129663. };
  129664. static static_codebook _huff_book__44c7_s_long = {
  129665. 2, 100,
  129666. _huff_lengthlist__44c7_s_long,
  129667. 0, 0, 0, 0, 0,
  129668. NULL,
  129669. NULL,
  129670. NULL,
  129671. NULL,
  129672. 0
  129673. };
  129674. static long _vq_quantlist__44c7_s_p1_0[] = {
  129675. 1,
  129676. 0,
  129677. 2,
  129678. };
  129679. static long _vq_lengthlist__44c7_s_p1_0[] = {
  129680. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  129681. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129683. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129684. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129685. 8,
  129686. };
  129687. static float _vq_quantthresh__44c7_s_p1_0[] = {
  129688. -0.5, 0.5,
  129689. };
  129690. static long _vq_quantmap__44c7_s_p1_0[] = {
  129691. 1, 0, 2,
  129692. };
  129693. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  129694. _vq_quantthresh__44c7_s_p1_0,
  129695. _vq_quantmap__44c7_s_p1_0,
  129696. 3,
  129697. 3
  129698. };
  129699. static static_codebook _44c7_s_p1_0 = {
  129700. 4, 81,
  129701. _vq_lengthlist__44c7_s_p1_0,
  129702. 1, -535822336, 1611661312, 2, 0,
  129703. _vq_quantlist__44c7_s_p1_0,
  129704. NULL,
  129705. &_vq_auxt__44c7_s_p1_0,
  129706. NULL,
  129707. 0
  129708. };
  129709. static long _vq_quantlist__44c7_s_p2_0[] = {
  129710. 2,
  129711. 1,
  129712. 3,
  129713. 0,
  129714. 4,
  129715. };
  129716. static long _vq_lengthlist__44c7_s_p2_0[] = {
  129717. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129718. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129719. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129720. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  129721. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129722. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  129723. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  129724. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129727. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  129728. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129729. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  129730. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  129731. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  129732. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  129735. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  129736. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  129737. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  129738. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  129739. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  129740. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129743. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  129744. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129745. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  129746. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  129747. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  129748. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129753. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  129754. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129755. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  129756. 13,
  129757. };
  129758. static float _vq_quantthresh__44c7_s_p2_0[] = {
  129759. -1.5, -0.5, 0.5, 1.5,
  129760. };
  129761. static long _vq_quantmap__44c7_s_p2_0[] = {
  129762. 3, 1, 0, 2, 4,
  129763. };
  129764. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  129765. _vq_quantthresh__44c7_s_p2_0,
  129766. _vq_quantmap__44c7_s_p2_0,
  129767. 5,
  129768. 5
  129769. };
  129770. static static_codebook _44c7_s_p2_0 = {
  129771. 4, 625,
  129772. _vq_lengthlist__44c7_s_p2_0,
  129773. 1, -533725184, 1611661312, 3, 0,
  129774. _vq_quantlist__44c7_s_p2_0,
  129775. NULL,
  129776. &_vq_auxt__44c7_s_p2_0,
  129777. NULL,
  129778. 0
  129779. };
  129780. static long _vq_quantlist__44c7_s_p3_0[] = {
  129781. 4,
  129782. 3,
  129783. 5,
  129784. 2,
  129785. 6,
  129786. 1,
  129787. 7,
  129788. 0,
  129789. 8,
  129790. };
  129791. static long _vq_lengthlist__44c7_s_p3_0[] = {
  129792. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129793. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129794. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129795. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0,
  129798. };
  129799. static float _vq_quantthresh__44c7_s_p3_0[] = {
  129800. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129801. };
  129802. static long _vq_quantmap__44c7_s_p3_0[] = {
  129803. 7, 5, 3, 1, 0, 2, 4, 6,
  129804. 8,
  129805. };
  129806. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  129807. _vq_quantthresh__44c7_s_p3_0,
  129808. _vq_quantmap__44c7_s_p3_0,
  129809. 9,
  129810. 9
  129811. };
  129812. static static_codebook _44c7_s_p3_0 = {
  129813. 2, 81,
  129814. _vq_lengthlist__44c7_s_p3_0,
  129815. 1, -531628032, 1611661312, 4, 0,
  129816. _vq_quantlist__44c7_s_p3_0,
  129817. NULL,
  129818. &_vq_auxt__44c7_s_p3_0,
  129819. NULL,
  129820. 0
  129821. };
  129822. static long _vq_quantlist__44c7_s_p4_0[] = {
  129823. 8,
  129824. 7,
  129825. 9,
  129826. 6,
  129827. 10,
  129828. 5,
  129829. 11,
  129830. 4,
  129831. 12,
  129832. 3,
  129833. 13,
  129834. 2,
  129835. 14,
  129836. 1,
  129837. 15,
  129838. 0,
  129839. 16,
  129840. };
  129841. static long _vq_lengthlist__44c7_s_p4_0[] = {
  129842. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129843. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  129844. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129845. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  129846. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  129847. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129848. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129849. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129850. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129851. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0,
  129861. };
  129862. static float _vq_quantthresh__44c7_s_p4_0[] = {
  129863. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129864. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129865. };
  129866. static long _vq_quantmap__44c7_s_p4_0[] = {
  129867. 15, 13, 11, 9, 7, 5, 3, 1,
  129868. 0, 2, 4, 6, 8, 10, 12, 14,
  129869. 16,
  129870. };
  129871. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  129872. _vq_quantthresh__44c7_s_p4_0,
  129873. _vq_quantmap__44c7_s_p4_0,
  129874. 17,
  129875. 17
  129876. };
  129877. static static_codebook _44c7_s_p4_0 = {
  129878. 2, 289,
  129879. _vq_lengthlist__44c7_s_p4_0,
  129880. 1, -529530880, 1611661312, 5, 0,
  129881. _vq_quantlist__44c7_s_p4_0,
  129882. NULL,
  129883. &_vq_auxt__44c7_s_p4_0,
  129884. NULL,
  129885. 0
  129886. };
  129887. static long _vq_quantlist__44c7_s_p5_0[] = {
  129888. 1,
  129889. 0,
  129890. 2,
  129891. };
  129892. static long _vq_lengthlist__44c7_s_p5_0[] = {
  129893. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  129894. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129895. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129896. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129897. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  129898. 12,
  129899. };
  129900. static float _vq_quantthresh__44c7_s_p5_0[] = {
  129901. -5.5, 5.5,
  129902. };
  129903. static long _vq_quantmap__44c7_s_p5_0[] = {
  129904. 1, 0, 2,
  129905. };
  129906. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  129907. _vq_quantthresh__44c7_s_p5_0,
  129908. _vq_quantmap__44c7_s_p5_0,
  129909. 3,
  129910. 3
  129911. };
  129912. static static_codebook _44c7_s_p5_0 = {
  129913. 4, 81,
  129914. _vq_lengthlist__44c7_s_p5_0,
  129915. 1, -529137664, 1618345984, 2, 0,
  129916. _vq_quantlist__44c7_s_p5_0,
  129917. NULL,
  129918. &_vq_auxt__44c7_s_p5_0,
  129919. NULL,
  129920. 0
  129921. };
  129922. static long _vq_quantlist__44c7_s_p5_1[] = {
  129923. 5,
  129924. 4,
  129925. 6,
  129926. 3,
  129927. 7,
  129928. 2,
  129929. 8,
  129930. 1,
  129931. 9,
  129932. 0,
  129933. 10,
  129934. };
  129935. static long _vq_lengthlist__44c7_s_p5_1[] = {
  129936. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129937. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  129938. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  129939. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  129940. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  129941. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  129942. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  129943. 11,11,11, 7, 7, 8, 8, 8, 8,
  129944. };
  129945. static float _vq_quantthresh__44c7_s_p5_1[] = {
  129946. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129947. 3.5, 4.5,
  129948. };
  129949. static long _vq_quantmap__44c7_s_p5_1[] = {
  129950. 9, 7, 5, 3, 1, 0, 2, 4,
  129951. 6, 8, 10,
  129952. };
  129953. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  129954. _vq_quantthresh__44c7_s_p5_1,
  129955. _vq_quantmap__44c7_s_p5_1,
  129956. 11,
  129957. 11
  129958. };
  129959. static static_codebook _44c7_s_p5_1 = {
  129960. 2, 121,
  129961. _vq_lengthlist__44c7_s_p5_1,
  129962. 1, -531365888, 1611661312, 4, 0,
  129963. _vq_quantlist__44c7_s_p5_1,
  129964. NULL,
  129965. &_vq_auxt__44c7_s_p5_1,
  129966. NULL,
  129967. 0
  129968. };
  129969. static long _vq_quantlist__44c7_s_p6_0[] = {
  129970. 6,
  129971. 5,
  129972. 7,
  129973. 4,
  129974. 8,
  129975. 3,
  129976. 9,
  129977. 2,
  129978. 10,
  129979. 1,
  129980. 11,
  129981. 0,
  129982. 12,
  129983. };
  129984. static long _vq_lengthlist__44c7_s_p6_0[] = {
  129985. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  129986. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129987. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  129988. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  129989. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  129990. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. };
  129997. static float _vq_quantthresh__44c7_s_p6_0[] = {
  129998. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129999. 12.5, 17.5, 22.5, 27.5,
  130000. };
  130001. static long _vq_quantmap__44c7_s_p6_0[] = {
  130002. 11, 9, 7, 5, 3, 1, 0, 2,
  130003. 4, 6, 8, 10, 12,
  130004. };
  130005. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  130006. _vq_quantthresh__44c7_s_p6_0,
  130007. _vq_quantmap__44c7_s_p6_0,
  130008. 13,
  130009. 13
  130010. };
  130011. static static_codebook _44c7_s_p6_0 = {
  130012. 2, 169,
  130013. _vq_lengthlist__44c7_s_p6_0,
  130014. 1, -526516224, 1616117760, 4, 0,
  130015. _vq_quantlist__44c7_s_p6_0,
  130016. NULL,
  130017. &_vq_auxt__44c7_s_p6_0,
  130018. NULL,
  130019. 0
  130020. };
  130021. static long _vq_quantlist__44c7_s_p6_1[] = {
  130022. 2,
  130023. 1,
  130024. 3,
  130025. 0,
  130026. 4,
  130027. };
  130028. static long _vq_lengthlist__44c7_s_p6_1[] = {
  130029. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130030. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130031. };
  130032. static float _vq_quantthresh__44c7_s_p6_1[] = {
  130033. -1.5, -0.5, 0.5, 1.5,
  130034. };
  130035. static long _vq_quantmap__44c7_s_p6_1[] = {
  130036. 3, 1, 0, 2, 4,
  130037. };
  130038. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  130039. _vq_quantthresh__44c7_s_p6_1,
  130040. _vq_quantmap__44c7_s_p6_1,
  130041. 5,
  130042. 5
  130043. };
  130044. static static_codebook _44c7_s_p6_1 = {
  130045. 2, 25,
  130046. _vq_lengthlist__44c7_s_p6_1,
  130047. 1, -533725184, 1611661312, 3, 0,
  130048. _vq_quantlist__44c7_s_p6_1,
  130049. NULL,
  130050. &_vq_auxt__44c7_s_p6_1,
  130051. NULL,
  130052. 0
  130053. };
  130054. static long _vq_quantlist__44c7_s_p7_0[] = {
  130055. 6,
  130056. 5,
  130057. 7,
  130058. 4,
  130059. 8,
  130060. 3,
  130061. 9,
  130062. 2,
  130063. 10,
  130064. 1,
  130065. 11,
  130066. 0,
  130067. 12,
  130068. };
  130069. static long _vq_lengthlist__44c7_s_p7_0[] = {
  130070. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  130071. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130072. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  130073. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  130074. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  130075. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  130076. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  130077. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  130078. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  130079. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  130080. 19,13,13,13,13,14,14,15,15,
  130081. };
  130082. static float _vq_quantthresh__44c7_s_p7_0[] = {
  130083. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130084. 27.5, 38.5, 49.5, 60.5,
  130085. };
  130086. static long _vq_quantmap__44c7_s_p7_0[] = {
  130087. 11, 9, 7, 5, 3, 1, 0, 2,
  130088. 4, 6, 8, 10, 12,
  130089. };
  130090. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  130091. _vq_quantthresh__44c7_s_p7_0,
  130092. _vq_quantmap__44c7_s_p7_0,
  130093. 13,
  130094. 13
  130095. };
  130096. static static_codebook _44c7_s_p7_0 = {
  130097. 2, 169,
  130098. _vq_lengthlist__44c7_s_p7_0,
  130099. 1, -523206656, 1618345984, 4, 0,
  130100. _vq_quantlist__44c7_s_p7_0,
  130101. NULL,
  130102. &_vq_auxt__44c7_s_p7_0,
  130103. NULL,
  130104. 0
  130105. };
  130106. static long _vq_quantlist__44c7_s_p7_1[] = {
  130107. 5,
  130108. 4,
  130109. 6,
  130110. 3,
  130111. 7,
  130112. 2,
  130113. 8,
  130114. 1,
  130115. 9,
  130116. 0,
  130117. 10,
  130118. };
  130119. static long _vq_lengthlist__44c7_s_p7_1[] = {
  130120. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  130121. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  130122. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130123. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130124. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130125. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130126. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130127. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130128. };
  130129. static float _vq_quantthresh__44c7_s_p7_1[] = {
  130130. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130131. 3.5, 4.5,
  130132. };
  130133. static long _vq_quantmap__44c7_s_p7_1[] = {
  130134. 9, 7, 5, 3, 1, 0, 2, 4,
  130135. 6, 8, 10,
  130136. };
  130137. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  130138. _vq_quantthresh__44c7_s_p7_1,
  130139. _vq_quantmap__44c7_s_p7_1,
  130140. 11,
  130141. 11
  130142. };
  130143. static static_codebook _44c7_s_p7_1 = {
  130144. 2, 121,
  130145. _vq_lengthlist__44c7_s_p7_1,
  130146. 1, -531365888, 1611661312, 4, 0,
  130147. _vq_quantlist__44c7_s_p7_1,
  130148. NULL,
  130149. &_vq_auxt__44c7_s_p7_1,
  130150. NULL,
  130151. 0
  130152. };
  130153. static long _vq_quantlist__44c7_s_p8_0[] = {
  130154. 7,
  130155. 6,
  130156. 8,
  130157. 5,
  130158. 9,
  130159. 4,
  130160. 10,
  130161. 3,
  130162. 11,
  130163. 2,
  130164. 12,
  130165. 1,
  130166. 13,
  130167. 0,
  130168. 14,
  130169. };
  130170. static long _vq_lengthlist__44c7_s_p8_0[] = {
  130171. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  130172. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  130173. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  130174. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  130175. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  130176. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  130177. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  130178. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  130179. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  130180. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  130181. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  130182. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130183. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  130184. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  130185. 14,
  130186. };
  130187. static float _vq_quantthresh__44c7_s_p8_0[] = {
  130188. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130189. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130190. };
  130191. static long _vq_quantmap__44c7_s_p8_0[] = {
  130192. 13, 11, 9, 7, 5, 3, 1, 0,
  130193. 2, 4, 6, 8, 10, 12, 14,
  130194. };
  130195. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  130196. _vq_quantthresh__44c7_s_p8_0,
  130197. _vq_quantmap__44c7_s_p8_0,
  130198. 15,
  130199. 15
  130200. };
  130201. static static_codebook _44c7_s_p8_0 = {
  130202. 2, 225,
  130203. _vq_lengthlist__44c7_s_p8_0,
  130204. 1, -520986624, 1620377600, 4, 0,
  130205. _vq_quantlist__44c7_s_p8_0,
  130206. NULL,
  130207. &_vq_auxt__44c7_s_p8_0,
  130208. NULL,
  130209. 0
  130210. };
  130211. static long _vq_quantlist__44c7_s_p8_1[] = {
  130212. 10,
  130213. 9,
  130214. 11,
  130215. 8,
  130216. 12,
  130217. 7,
  130218. 13,
  130219. 6,
  130220. 14,
  130221. 5,
  130222. 15,
  130223. 4,
  130224. 16,
  130225. 3,
  130226. 17,
  130227. 2,
  130228. 18,
  130229. 1,
  130230. 19,
  130231. 0,
  130232. 20,
  130233. };
  130234. static long _vq_lengthlist__44c7_s_p8_1[] = {
  130235. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130236. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130237. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130238. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130239. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130240. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130241. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130242. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130243. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130244. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130245. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  130246. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  130247. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  130248. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  130249. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  130250. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  130251. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  130252. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  130253. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  130254. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  130255. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  130256. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  130257. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  130258. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  130259. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  130260. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  130261. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  130262. 10,10,10,10,10,10,10,10,10,
  130263. };
  130264. static float _vq_quantthresh__44c7_s_p8_1[] = {
  130265. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130266. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130267. 6.5, 7.5, 8.5, 9.5,
  130268. };
  130269. static long _vq_quantmap__44c7_s_p8_1[] = {
  130270. 19, 17, 15, 13, 11, 9, 7, 5,
  130271. 3, 1, 0, 2, 4, 6, 8, 10,
  130272. 12, 14, 16, 18, 20,
  130273. };
  130274. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  130275. _vq_quantthresh__44c7_s_p8_1,
  130276. _vq_quantmap__44c7_s_p8_1,
  130277. 21,
  130278. 21
  130279. };
  130280. static static_codebook _44c7_s_p8_1 = {
  130281. 2, 441,
  130282. _vq_lengthlist__44c7_s_p8_1,
  130283. 1, -529268736, 1611661312, 5, 0,
  130284. _vq_quantlist__44c7_s_p8_1,
  130285. NULL,
  130286. &_vq_auxt__44c7_s_p8_1,
  130287. NULL,
  130288. 0
  130289. };
  130290. static long _vq_quantlist__44c7_s_p9_0[] = {
  130291. 6,
  130292. 5,
  130293. 7,
  130294. 4,
  130295. 8,
  130296. 3,
  130297. 9,
  130298. 2,
  130299. 10,
  130300. 1,
  130301. 11,
  130302. 0,
  130303. 12,
  130304. };
  130305. static long _vq_lengthlist__44c7_s_p9_0[] = {
  130306. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  130307. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  130308. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130309. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130310. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130314. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130316. 11,11,11,11,11,11,11,11,11,
  130317. };
  130318. static float _vq_quantthresh__44c7_s_p9_0[] = {
  130319. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  130320. 1592.5, 2229.5, 2866.5, 3503.5,
  130321. };
  130322. static long _vq_quantmap__44c7_s_p9_0[] = {
  130323. 11, 9, 7, 5, 3, 1, 0, 2,
  130324. 4, 6, 8, 10, 12,
  130325. };
  130326. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  130327. _vq_quantthresh__44c7_s_p9_0,
  130328. _vq_quantmap__44c7_s_p9_0,
  130329. 13,
  130330. 13
  130331. };
  130332. static static_codebook _44c7_s_p9_0 = {
  130333. 2, 169,
  130334. _vq_lengthlist__44c7_s_p9_0,
  130335. 1, -511845376, 1630791680, 4, 0,
  130336. _vq_quantlist__44c7_s_p9_0,
  130337. NULL,
  130338. &_vq_auxt__44c7_s_p9_0,
  130339. NULL,
  130340. 0
  130341. };
  130342. static long _vq_quantlist__44c7_s_p9_1[] = {
  130343. 6,
  130344. 5,
  130345. 7,
  130346. 4,
  130347. 8,
  130348. 3,
  130349. 9,
  130350. 2,
  130351. 10,
  130352. 1,
  130353. 11,
  130354. 0,
  130355. 12,
  130356. };
  130357. static long _vq_lengthlist__44c7_s_p9_1[] = {
  130358. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  130359. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  130360. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  130361. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  130362. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  130363. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  130364. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  130365. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  130366. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  130367. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  130368. 15,11,11,10,10,12,12,12,12,
  130369. };
  130370. static float _vq_quantthresh__44c7_s_p9_1[] = {
  130371. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  130372. 122.5, 171.5, 220.5, 269.5,
  130373. };
  130374. static long _vq_quantmap__44c7_s_p9_1[] = {
  130375. 11, 9, 7, 5, 3, 1, 0, 2,
  130376. 4, 6, 8, 10, 12,
  130377. };
  130378. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  130379. _vq_quantthresh__44c7_s_p9_1,
  130380. _vq_quantmap__44c7_s_p9_1,
  130381. 13,
  130382. 13
  130383. };
  130384. static static_codebook _44c7_s_p9_1 = {
  130385. 2, 169,
  130386. _vq_lengthlist__44c7_s_p9_1,
  130387. 1, -518889472, 1622704128, 4, 0,
  130388. _vq_quantlist__44c7_s_p9_1,
  130389. NULL,
  130390. &_vq_auxt__44c7_s_p9_1,
  130391. NULL,
  130392. 0
  130393. };
  130394. static long _vq_quantlist__44c7_s_p9_2[] = {
  130395. 24,
  130396. 23,
  130397. 25,
  130398. 22,
  130399. 26,
  130400. 21,
  130401. 27,
  130402. 20,
  130403. 28,
  130404. 19,
  130405. 29,
  130406. 18,
  130407. 30,
  130408. 17,
  130409. 31,
  130410. 16,
  130411. 32,
  130412. 15,
  130413. 33,
  130414. 14,
  130415. 34,
  130416. 13,
  130417. 35,
  130418. 12,
  130419. 36,
  130420. 11,
  130421. 37,
  130422. 10,
  130423. 38,
  130424. 9,
  130425. 39,
  130426. 8,
  130427. 40,
  130428. 7,
  130429. 41,
  130430. 6,
  130431. 42,
  130432. 5,
  130433. 43,
  130434. 4,
  130435. 44,
  130436. 3,
  130437. 45,
  130438. 2,
  130439. 46,
  130440. 1,
  130441. 47,
  130442. 0,
  130443. 48,
  130444. };
  130445. static long _vq_lengthlist__44c7_s_p9_2[] = {
  130446. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  130447. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130448. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130449. 7,
  130450. };
  130451. static float _vq_quantthresh__44c7_s_p9_2[] = {
  130452. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130453. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130454. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130455. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130456. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130457. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130458. };
  130459. static long _vq_quantmap__44c7_s_p9_2[] = {
  130460. 47, 45, 43, 41, 39, 37, 35, 33,
  130461. 31, 29, 27, 25, 23, 21, 19, 17,
  130462. 15, 13, 11, 9, 7, 5, 3, 1,
  130463. 0, 2, 4, 6, 8, 10, 12, 14,
  130464. 16, 18, 20, 22, 24, 26, 28, 30,
  130465. 32, 34, 36, 38, 40, 42, 44, 46,
  130466. 48,
  130467. };
  130468. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  130469. _vq_quantthresh__44c7_s_p9_2,
  130470. _vq_quantmap__44c7_s_p9_2,
  130471. 49,
  130472. 49
  130473. };
  130474. static static_codebook _44c7_s_p9_2 = {
  130475. 1, 49,
  130476. _vq_lengthlist__44c7_s_p9_2,
  130477. 1, -526909440, 1611661312, 6, 0,
  130478. _vq_quantlist__44c7_s_p9_2,
  130479. NULL,
  130480. &_vq_auxt__44c7_s_p9_2,
  130481. NULL,
  130482. 0
  130483. };
  130484. static long _huff_lengthlist__44c7_s_short[] = {
  130485. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  130486. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  130487. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  130488. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  130489. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  130490. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  130491. 10, 9,11,14,
  130492. };
  130493. static static_codebook _huff_book__44c7_s_short = {
  130494. 2, 100,
  130495. _huff_lengthlist__44c7_s_short,
  130496. 0, 0, 0, 0, 0,
  130497. NULL,
  130498. NULL,
  130499. NULL,
  130500. NULL,
  130501. 0
  130502. };
  130503. static long _huff_lengthlist__44c8_s_long[] = {
  130504. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  130505. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  130506. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  130507. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  130508. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  130509. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  130510. 11, 9, 9,10,
  130511. };
  130512. static static_codebook _huff_book__44c8_s_long = {
  130513. 2, 100,
  130514. _huff_lengthlist__44c8_s_long,
  130515. 0, 0, 0, 0, 0,
  130516. NULL,
  130517. NULL,
  130518. NULL,
  130519. NULL,
  130520. 0
  130521. };
  130522. static long _vq_quantlist__44c8_s_p1_0[] = {
  130523. 1,
  130524. 0,
  130525. 2,
  130526. };
  130527. static long _vq_lengthlist__44c8_s_p1_0[] = {
  130528. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  130529. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  130531. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130532. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  130533. 8,
  130534. };
  130535. static float _vq_quantthresh__44c8_s_p1_0[] = {
  130536. -0.5, 0.5,
  130537. };
  130538. static long _vq_quantmap__44c8_s_p1_0[] = {
  130539. 1, 0, 2,
  130540. };
  130541. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  130542. _vq_quantthresh__44c8_s_p1_0,
  130543. _vq_quantmap__44c8_s_p1_0,
  130544. 3,
  130545. 3
  130546. };
  130547. static static_codebook _44c8_s_p1_0 = {
  130548. 4, 81,
  130549. _vq_lengthlist__44c8_s_p1_0,
  130550. 1, -535822336, 1611661312, 2, 0,
  130551. _vq_quantlist__44c8_s_p1_0,
  130552. NULL,
  130553. &_vq_auxt__44c8_s_p1_0,
  130554. NULL,
  130555. 0
  130556. };
  130557. static long _vq_quantlist__44c8_s_p2_0[] = {
  130558. 2,
  130559. 1,
  130560. 3,
  130561. 0,
  130562. 4,
  130563. };
  130564. static long _vq_lengthlist__44c8_s_p2_0[] = {
  130565. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130566. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  130567. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  130568. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  130569. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  130570. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  130571. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  130572. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  130575. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  130576. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  130577. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  130578. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  130579. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  130580. 0,12,12,13,13, 0, 0, 0,12,13, 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, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  130583. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  130584. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  130585. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  130586. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  130587. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  130588. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  130591. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  130592. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  130593. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  130594. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  130595. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  130596. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130601. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  130602. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  130603. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  130604. 13,
  130605. };
  130606. static float _vq_quantthresh__44c8_s_p2_0[] = {
  130607. -1.5, -0.5, 0.5, 1.5,
  130608. };
  130609. static long _vq_quantmap__44c8_s_p2_0[] = {
  130610. 3, 1, 0, 2, 4,
  130611. };
  130612. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  130613. _vq_quantthresh__44c8_s_p2_0,
  130614. _vq_quantmap__44c8_s_p2_0,
  130615. 5,
  130616. 5
  130617. };
  130618. static static_codebook _44c8_s_p2_0 = {
  130619. 4, 625,
  130620. _vq_lengthlist__44c8_s_p2_0,
  130621. 1, -533725184, 1611661312, 3, 0,
  130622. _vq_quantlist__44c8_s_p2_0,
  130623. NULL,
  130624. &_vq_auxt__44c8_s_p2_0,
  130625. NULL,
  130626. 0
  130627. };
  130628. static long _vq_quantlist__44c8_s_p3_0[] = {
  130629. 4,
  130630. 3,
  130631. 5,
  130632. 2,
  130633. 6,
  130634. 1,
  130635. 7,
  130636. 0,
  130637. 8,
  130638. };
  130639. static long _vq_lengthlist__44c8_s_p3_0[] = {
  130640. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130641. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  130642. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  130643. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0,
  130646. };
  130647. static float _vq_quantthresh__44c8_s_p3_0[] = {
  130648. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130649. };
  130650. static long _vq_quantmap__44c8_s_p3_0[] = {
  130651. 7, 5, 3, 1, 0, 2, 4, 6,
  130652. 8,
  130653. };
  130654. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  130655. _vq_quantthresh__44c8_s_p3_0,
  130656. _vq_quantmap__44c8_s_p3_0,
  130657. 9,
  130658. 9
  130659. };
  130660. static static_codebook _44c8_s_p3_0 = {
  130661. 2, 81,
  130662. _vq_lengthlist__44c8_s_p3_0,
  130663. 1, -531628032, 1611661312, 4, 0,
  130664. _vq_quantlist__44c8_s_p3_0,
  130665. NULL,
  130666. &_vq_auxt__44c8_s_p3_0,
  130667. NULL,
  130668. 0
  130669. };
  130670. static long _vq_quantlist__44c8_s_p4_0[] = {
  130671. 8,
  130672. 7,
  130673. 9,
  130674. 6,
  130675. 10,
  130676. 5,
  130677. 11,
  130678. 4,
  130679. 12,
  130680. 3,
  130681. 13,
  130682. 2,
  130683. 14,
  130684. 1,
  130685. 15,
  130686. 0,
  130687. 16,
  130688. };
  130689. static long _vq_lengthlist__44c8_s_p4_0[] = {
  130690. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130691. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  130692. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130693. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  130694. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  130695. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  130696. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  130697. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130698. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130699. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0,
  130709. };
  130710. static float _vq_quantthresh__44c8_s_p4_0[] = {
  130711. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130712. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130713. };
  130714. static long _vq_quantmap__44c8_s_p4_0[] = {
  130715. 15, 13, 11, 9, 7, 5, 3, 1,
  130716. 0, 2, 4, 6, 8, 10, 12, 14,
  130717. 16,
  130718. };
  130719. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  130720. _vq_quantthresh__44c8_s_p4_0,
  130721. _vq_quantmap__44c8_s_p4_0,
  130722. 17,
  130723. 17
  130724. };
  130725. static static_codebook _44c8_s_p4_0 = {
  130726. 2, 289,
  130727. _vq_lengthlist__44c8_s_p4_0,
  130728. 1, -529530880, 1611661312, 5, 0,
  130729. _vq_quantlist__44c8_s_p4_0,
  130730. NULL,
  130731. &_vq_auxt__44c8_s_p4_0,
  130732. NULL,
  130733. 0
  130734. };
  130735. static long _vq_quantlist__44c8_s_p5_0[] = {
  130736. 1,
  130737. 0,
  130738. 2,
  130739. };
  130740. static long _vq_lengthlist__44c8_s_p5_0[] = {
  130741. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  130742. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  130743. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  130744. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  130745. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  130746. 12,
  130747. };
  130748. static float _vq_quantthresh__44c8_s_p5_0[] = {
  130749. -5.5, 5.5,
  130750. };
  130751. static long _vq_quantmap__44c8_s_p5_0[] = {
  130752. 1, 0, 2,
  130753. };
  130754. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  130755. _vq_quantthresh__44c8_s_p5_0,
  130756. _vq_quantmap__44c8_s_p5_0,
  130757. 3,
  130758. 3
  130759. };
  130760. static static_codebook _44c8_s_p5_0 = {
  130761. 4, 81,
  130762. _vq_lengthlist__44c8_s_p5_0,
  130763. 1, -529137664, 1618345984, 2, 0,
  130764. _vq_quantlist__44c8_s_p5_0,
  130765. NULL,
  130766. &_vq_auxt__44c8_s_p5_0,
  130767. NULL,
  130768. 0
  130769. };
  130770. static long _vq_quantlist__44c8_s_p5_1[] = {
  130771. 5,
  130772. 4,
  130773. 6,
  130774. 3,
  130775. 7,
  130776. 2,
  130777. 8,
  130778. 1,
  130779. 9,
  130780. 0,
  130781. 10,
  130782. };
  130783. static long _vq_lengthlist__44c8_s_p5_1[] = {
  130784. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  130785. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130786. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  130787. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  130788. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  130789. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  130790. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  130791. 11,11,11, 7, 7, 7, 7, 8, 8,
  130792. };
  130793. static float _vq_quantthresh__44c8_s_p5_1[] = {
  130794. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130795. 3.5, 4.5,
  130796. };
  130797. static long _vq_quantmap__44c8_s_p5_1[] = {
  130798. 9, 7, 5, 3, 1, 0, 2, 4,
  130799. 6, 8, 10,
  130800. };
  130801. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  130802. _vq_quantthresh__44c8_s_p5_1,
  130803. _vq_quantmap__44c8_s_p5_1,
  130804. 11,
  130805. 11
  130806. };
  130807. static static_codebook _44c8_s_p5_1 = {
  130808. 2, 121,
  130809. _vq_lengthlist__44c8_s_p5_1,
  130810. 1, -531365888, 1611661312, 4, 0,
  130811. _vq_quantlist__44c8_s_p5_1,
  130812. NULL,
  130813. &_vq_auxt__44c8_s_p5_1,
  130814. NULL,
  130815. 0
  130816. };
  130817. static long _vq_quantlist__44c8_s_p6_0[] = {
  130818. 6,
  130819. 5,
  130820. 7,
  130821. 4,
  130822. 8,
  130823. 3,
  130824. 9,
  130825. 2,
  130826. 10,
  130827. 1,
  130828. 11,
  130829. 0,
  130830. 12,
  130831. };
  130832. static long _vq_lengthlist__44c8_s_p6_0[] = {
  130833. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130834. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  130835. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  130836. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  130837. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  130838. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. };
  130845. static float _vq_quantthresh__44c8_s_p6_0[] = {
  130846. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130847. 12.5, 17.5, 22.5, 27.5,
  130848. };
  130849. static long _vq_quantmap__44c8_s_p6_0[] = {
  130850. 11, 9, 7, 5, 3, 1, 0, 2,
  130851. 4, 6, 8, 10, 12,
  130852. };
  130853. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  130854. _vq_quantthresh__44c8_s_p6_0,
  130855. _vq_quantmap__44c8_s_p6_0,
  130856. 13,
  130857. 13
  130858. };
  130859. static static_codebook _44c8_s_p6_0 = {
  130860. 2, 169,
  130861. _vq_lengthlist__44c8_s_p6_0,
  130862. 1, -526516224, 1616117760, 4, 0,
  130863. _vq_quantlist__44c8_s_p6_0,
  130864. NULL,
  130865. &_vq_auxt__44c8_s_p6_0,
  130866. NULL,
  130867. 0
  130868. };
  130869. static long _vq_quantlist__44c8_s_p6_1[] = {
  130870. 2,
  130871. 1,
  130872. 3,
  130873. 0,
  130874. 4,
  130875. };
  130876. static long _vq_lengthlist__44c8_s_p6_1[] = {
  130877. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130878. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130879. };
  130880. static float _vq_quantthresh__44c8_s_p6_1[] = {
  130881. -1.5, -0.5, 0.5, 1.5,
  130882. };
  130883. static long _vq_quantmap__44c8_s_p6_1[] = {
  130884. 3, 1, 0, 2, 4,
  130885. };
  130886. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  130887. _vq_quantthresh__44c8_s_p6_1,
  130888. _vq_quantmap__44c8_s_p6_1,
  130889. 5,
  130890. 5
  130891. };
  130892. static static_codebook _44c8_s_p6_1 = {
  130893. 2, 25,
  130894. _vq_lengthlist__44c8_s_p6_1,
  130895. 1, -533725184, 1611661312, 3, 0,
  130896. _vq_quantlist__44c8_s_p6_1,
  130897. NULL,
  130898. &_vq_auxt__44c8_s_p6_1,
  130899. NULL,
  130900. 0
  130901. };
  130902. static long _vq_quantlist__44c8_s_p7_0[] = {
  130903. 6,
  130904. 5,
  130905. 7,
  130906. 4,
  130907. 8,
  130908. 3,
  130909. 9,
  130910. 2,
  130911. 10,
  130912. 1,
  130913. 11,
  130914. 0,
  130915. 12,
  130916. };
  130917. static long _vq_lengthlist__44c8_s_p7_0[] = {
  130918. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  130919. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130920. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  130921. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  130922. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  130923. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  130924. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  130925. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  130926. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  130927. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  130928. 20,13,13,13,13,14,13,15,15,
  130929. };
  130930. static float _vq_quantthresh__44c8_s_p7_0[] = {
  130931. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130932. 27.5, 38.5, 49.5, 60.5,
  130933. };
  130934. static long _vq_quantmap__44c8_s_p7_0[] = {
  130935. 11, 9, 7, 5, 3, 1, 0, 2,
  130936. 4, 6, 8, 10, 12,
  130937. };
  130938. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  130939. _vq_quantthresh__44c8_s_p7_0,
  130940. _vq_quantmap__44c8_s_p7_0,
  130941. 13,
  130942. 13
  130943. };
  130944. static static_codebook _44c8_s_p7_0 = {
  130945. 2, 169,
  130946. _vq_lengthlist__44c8_s_p7_0,
  130947. 1, -523206656, 1618345984, 4, 0,
  130948. _vq_quantlist__44c8_s_p7_0,
  130949. NULL,
  130950. &_vq_auxt__44c8_s_p7_0,
  130951. NULL,
  130952. 0
  130953. };
  130954. static long _vq_quantlist__44c8_s_p7_1[] = {
  130955. 5,
  130956. 4,
  130957. 6,
  130958. 3,
  130959. 7,
  130960. 2,
  130961. 8,
  130962. 1,
  130963. 9,
  130964. 0,
  130965. 10,
  130966. };
  130967. static long _vq_lengthlist__44c8_s_p7_1[] = {
  130968. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  130969. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130970. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130971. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130972. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130973. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130974. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130975. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130976. };
  130977. static float _vq_quantthresh__44c8_s_p7_1[] = {
  130978. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130979. 3.5, 4.5,
  130980. };
  130981. static long _vq_quantmap__44c8_s_p7_1[] = {
  130982. 9, 7, 5, 3, 1, 0, 2, 4,
  130983. 6, 8, 10,
  130984. };
  130985. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  130986. _vq_quantthresh__44c8_s_p7_1,
  130987. _vq_quantmap__44c8_s_p7_1,
  130988. 11,
  130989. 11
  130990. };
  130991. static static_codebook _44c8_s_p7_1 = {
  130992. 2, 121,
  130993. _vq_lengthlist__44c8_s_p7_1,
  130994. 1, -531365888, 1611661312, 4, 0,
  130995. _vq_quantlist__44c8_s_p7_1,
  130996. NULL,
  130997. &_vq_auxt__44c8_s_p7_1,
  130998. NULL,
  130999. 0
  131000. };
  131001. static long _vq_quantlist__44c8_s_p8_0[] = {
  131002. 7,
  131003. 6,
  131004. 8,
  131005. 5,
  131006. 9,
  131007. 4,
  131008. 10,
  131009. 3,
  131010. 11,
  131011. 2,
  131012. 12,
  131013. 1,
  131014. 13,
  131015. 0,
  131016. 14,
  131017. };
  131018. static long _vq_lengthlist__44c8_s_p8_0[] = {
  131019. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  131020. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  131021. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  131022. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  131023. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  131024. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  131025. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  131026. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  131027. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  131028. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  131029. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  131030. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  131031. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  131032. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  131033. 15,
  131034. };
  131035. static float _vq_quantthresh__44c8_s_p8_0[] = {
  131036. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131037. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131038. };
  131039. static long _vq_quantmap__44c8_s_p8_0[] = {
  131040. 13, 11, 9, 7, 5, 3, 1, 0,
  131041. 2, 4, 6, 8, 10, 12, 14,
  131042. };
  131043. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  131044. _vq_quantthresh__44c8_s_p8_0,
  131045. _vq_quantmap__44c8_s_p8_0,
  131046. 15,
  131047. 15
  131048. };
  131049. static static_codebook _44c8_s_p8_0 = {
  131050. 2, 225,
  131051. _vq_lengthlist__44c8_s_p8_0,
  131052. 1, -520986624, 1620377600, 4, 0,
  131053. _vq_quantlist__44c8_s_p8_0,
  131054. NULL,
  131055. &_vq_auxt__44c8_s_p8_0,
  131056. NULL,
  131057. 0
  131058. };
  131059. static long _vq_quantlist__44c8_s_p8_1[] = {
  131060. 10,
  131061. 9,
  131062. 11,
  131063. 8,
  131064. 12,
  131065. 7,
  131066. 13,
  131067. 6,
  131068. 14,
  131069. 5,
  131070. 15,
  131071. 4,
  131072. 16,
  131073. 3,
  131074. 17,
  131075. 2,
  131076. 18,
  131077. 1,
  131078. 19,
  131079. 0,
  131080. 20,
  131081. };
  131082. static long _vq_lengthlist__44c8_s_p8_1[] = {
  131083. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131084. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131085. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131086. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131087. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131088. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131089. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  131090. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131091. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131092. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131093. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131094. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131095. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  131096. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131097. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131098. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  131099. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  131100. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  131101. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  131102. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  131103. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  131104. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  131105. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131106. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  131107. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  131108. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  131109. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131110. 10, 9, 9,10,10, 9,10, 9, 9,
  131111. };
  131112. static float _vq_quantthresh__44c8_s_p8_1[] = {
  131113. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131114. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131115. 6.5, 7.5, 8.5, 9.5,
  131116. };
  131117. static long _vq_quantmap__44c8_s_p8_1[] = {
  131118. 19, 17, 15, 13, 11, 9, 7, 5,
  131119. 3, 1, 0, 2, 4, 6, 8, 10,
  131120. 12, 14, 16, 18, 20,
  131121. };
  131122. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  131123. _vq_quantthresh__44c8_s_p8_1,
  131124. _vq_quantmap__44c8_s_p8_1,
  131125. 21,
  131126. 21
  131127. };
  131128. static static_codebook _44c8_s_p8_1 = {
  131129. 2, 441,
  131130. _vq_lengthlist__44c8_s_p8_1,
  131131. 1, -529268736, 1611661312, 5, 0,
  131132. _vq_quantlist__44c8_s_p8_1,
  131133. NULL,
  131134. &_vq_auxt__44c8_s_p8_1,
  131135. NULL,
  131136. 0
  131137. };
  131138. static long _vq_quantlist__44c8_s_p9_0[] = {
  131139. 8,
  131140. 7,
  131141. 9,
  131142. 6,
  131143. 10,
  131144. 5,
  131145. 11,
  131146. 4,
  131147. 12,
  131148. 3,
  131149. 13,
  131150. 2,
  131151. 14,
  131152. 1,
  131153. 15,
  131154. 0,
  131155. 16,
  131156. };
  131157. static long _vq_lengthlist__44c8_s_p9_0[] = {
  131158. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131159. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  131160. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  131161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131172. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131173. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131174. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131175. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131176. 10,
  131177. };
  131178. static float _vq_quantthresh__44c8_s_p9_0[] = {
  131179. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  131180. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  131181. };
  131182. static long _vq_quantmap__44c8_s_p9_0[] = {
  131183. 15, 13, 11, 9, 7, 5, 3, 1,
  131184. 0, 2, 4, 6, 8, 10, 12, 14,
  131185. 16,
  131186. };
  131187. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  131188. _vq_quantthresh__44c8_s_p9_0,
  131189. _vq_quantmap__44c8_s_p9_0,
  131190. 17,
  131191. 17
  131192. };
  131193. static static_codebook _44c8_s_p9_0 = {
  131194. 2, 289,
  131195. _vq_lengthlist__44c8_s_p9_0,
  131196. 1, -509798400, 1631393792, 5, 0,
  131197. _vq_quantlist__44c8_s_p9_0,
  131198. NULL,
  131199. &_vq_auxt__44c8_s_p9_0,
  131200. NULL,
  131201. 0
  131202. };
  131203. static long _vq_quantlist__44c8_s_p9_1[] = {
  131204. 9,
  131205. 8,
  131206. 10,
  131207. 7,
  131208. 11,
  131209. 6,
  131210. 12,
  131211. 5,
  131212. 13,
  131213. 4,
  131214. 14,
  131215. 3,
  131216. 15,
  131217. 2,
  131218. 16,
  131219. 1,
  131220. 17,
  131221. 0,
  131222. 18,
  131223. };
  131224. static long _vq_lengthlist__44c8_s_p9_1[] = {
  131225. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  131226. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  131227. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  131228. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  131229. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  131230. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  131231. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  131232. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  131233. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  131234. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  131235. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  131236. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  131237. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  131238. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  131239. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  131240. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  131241. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  131242. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  131243. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  131244. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  131245. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  131246. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  131247. 14,13,13,14,14,15,14,15,14,
  131248. };
  131249. static float _vq_quantthresh__44c8_s_p9_1[] = {
  131250. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131251. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131252. 367.5, 416.5,
  131253. };
  131254. static long _vq_quantmap__44c8_s_p9_1[] = {
  131255. 17, 15, 13, 11, 9, 7, 5, 3,
  131256. 1, 0, 2, 4, 6, 8, 10, 12,
  131257. 14, 16, 18,
  131258. };
  131259. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  131260. _vq_quantthresh__44c8_s_p9_1,
  131261. _vq_quantmap__44c8_s_p9_1,
  131262. 19,
  131263. 19
  131264. };
  131265. static static_codebook _44c8_s_p9_1 = {
  131266. 2, 361,
  131267. _vq_lengthlist__44c8_s_p9_1,
  131268. 1, -518287360, 1622704128, 5, 0,
  131269. _vq_quantlist__44c8_s_p9_1,
  131270. NULL,
  131271. &_vq_auxt__44c8_s_p9_1,
  131272. NULL,
  131273. 0
  131274. };
  131275. static long _vq_quantlist__44c8_s_p9_2[] = {
  131276. 24,
  131277. 23,
  131278. 25,
  131279. 22,
  131280. 26,
  131281. 21,
  131282. 27,
  131283. 20,
  131284. 28,
  131285. 19,
  131286. 29,
  131287. 18,
  131288. 30,
  131289. 17,
  131290. 31,
  131291. 16,
  131292. 32,
  131293. 15,
  131294. 33,
  131295. 14,
  131296. 34,
  131297. 13,
  131298. 35,
  131299. 12,
  131300. 36,
  131301. 11,
  131302. 37,
  131303. 10,
  131304. 38,
  131305. 9,
  131306. 39,
  131307. 8,
  131308. 40,
  131309. 7,
  131310. 41,
  131311. 6,
  131312. 42,
  131313. 5,
  131314. 43,
  131315. 4,
  131316. 44,
  131317. 3,
  131318. 45,
  131319. 2,
  131320. 46,
  131321. 1,
  131322. 47,
  131323. 0,
  131324. 48,
  131325. };
  131326. static long _vq_lengthlist__44c8_s_p9_2[] = {
  131327. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131328. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131329. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131330. 7,
  131331. };
  131332. static float _vq_quantthresh__44c8_s_p9_2[] = {
  131333. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131334. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131335. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131336. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131337. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131338. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131339. };
  131340. static long _vq_quantmap__44c8_s_p9_2[] = {
  131341. 47, 45, 43, 41, 39, 37, 35, 33,
  131342. 31, 29, 27, 25, 23, 21, 19, 17,
  131343. 15, 13, 11, 9, 7, 5, 3, 1,
  131344. 0, 2, 4, 6, 8, 10, 12, 14,
  131345. 16, 18, 20, 22, 24, 26, 28, 30,
  131346. 32, 34, 36, 38, 40, 42, 44, 46,
  131347. 48,
  131348. };
  131349. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  131350. _vq_quantthresh__44c8_s_p9_2,
  131351. _vq_quantmap__44c8_s_p9_2,
  131352. 49,
  131353. 49
  131354. };
  131355. static static_codebook _44c8_s_p9_2 = {
  131356. 1, 49,
  131357. _vq_lengthlist__44c8_s_p9_2,
  131358. 1, -526909440, 1611661312, 6, 0,
  131359. _vq_quantlist__44c8_s_p9_2,
  131360. NULL,
  131361. &_vq_auxt__44c8_s_p9_2,
  131362. NULL,
  131363. 0
  131364. };
  131365. static long _huff_lengthlist__44c8_s_short[] = {
  131366. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  131367. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  131368. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  131369. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  131370. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  131371. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  131372. 10, 9,11,14,
  131373. };
  131374. static static_codebook _huff_book__44c8_s_short = {
  131375. 2, 100,
  131376. _huff_lengthlist__44c8_s_short,
  131377. 0, 0, 0, 0, 0,
  131378. NULL,
  131379. NULL,
  131380. NULL,
  131381. NULL,
  131382. 0
  131383. };
  131384. static long _huff_lengthlist__44c9_s_long[] = {
  131385. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  131386. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  131387. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  131388. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  131389. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  131390. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  131391. 10, 9, 8, 9,
  131392. };
  131393. static static_codebook _huff_book__44c9_s_long = {
  131394. 2, 100,
  131395. _huff_lengthlist__44c9_s_long,
  131396. 0, 0, 0, 0, 0,
  131397. NULL,
  131398. NULL,
  131399. NULL,
  131400. NULL,
  131401. 0
  131402. };
  131403. static long _vq_quantlist__44c9_s_p1_0[] = {
  131404. 1,
  131405. 0,
  131406. 2,
  131407. };
  131408. static long _vq_lengthlist__44c9_s_p1_0[] = {
  131409. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  131410. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  131412. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131413. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  131414. 7,
  131415. };
  131416. static float _vq_quantthresh__44c9_s_p1_0[] = {
  131417. -0.5, 0.5,
  131418. };
  131419. static long _vq_quantmap__44c9_s_p1_0[] = {
  131420. 1, 0, 2,
  131421. };
  131422. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  131423. _vq_quantthresh__44c9_s_p1_0,
  131424. _vq_quantmap__44c9_s_p1_0,
  131425. 3,
  131426. 3
  131427. };
  131428. static static_codebook _44c9_s_p1_0 = {
  131429. 4, 81,
  131430. _vq_lengthlist__44c9_s_p1_0,
  131431. 1, -535822336, 1611661312, 2, 0,
  131432. _vq_quantlist__44c9_s_p1_0,
  131433. NULL,
  131434. &_vq_auxt__44c9_s_p1_0,
  131435. NULL,
  131436. 0
  131437. };
  131438. static long _vq_quantlist__44c9_s_p2_0[] = {
  131439. 2,
  131440. 1,
  131441. 3,
  131442. 0,
  131443. 4,
  131444. };
  131445. static long _vq_lengthlist__44c9_s_p2_0[] = {
  131446. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131447. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  131448. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  131449. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  131450. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  131451. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  131452. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  131453. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  131456. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  131457. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  131458. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  131459. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  131460. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  131461. 0,12,12,12,12, 0, 0, 0,12,12, 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, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  131464. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  131465. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  131466. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  131467. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  131468. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  131469. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  131472. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  131473. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  131474. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  131475. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  131476. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  131477. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131482. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  131483. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  131484. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  131485. 12,
  131486. };
  131487. static float _vq_quantthresh__44c9_s_p2_0[] = {
  131488. -1.5, -0.5, 0.5, 1.5,
  131489. };
  131490. static long _vq_quantmap__44c9_s_p2_0[] = {
  131491. 3, 1, 0, 2, 4,
  131492. };
  131493. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  131494. _vq_quantthresh__44c9_s_p2_0,
  131495. _vq_quantmap__44c9_s_p2_0,
  131496. 5,
  131497. 5
  131498. };
  131499. static static_codebook _44c9_s_p2_0 = {
  131500. 4, 625,
  131501. _vq_lengthlist__44c9_s_p2_0,
  131502. 1, -533725184, 1611661312, 3, 0,
  131503. _vq_quantlist__44c9_s_p2_0,
  131504. NULL,
  131505. &_vq_auxt__44c9_s_p2_0,
  131506. NULL,
  131507. 0
  131508. };
  131509. static long _vq_quantlist__44c9_s_p3_0[] = {
  131510. 4,
  131511. 3,
  131512. 5,
  131513. 2,
  131514. 6,
  131515. 1,
  131516. 7,
  131517. 0,
  131518. 8,
  131519. };
  131520. static long _vq_lengthlist__44c9_s_p3_0[] = {
  131521. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  131522. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  131523. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  131524. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0,
  131527. };
  131528. static float _vq_quantthresh__44c9_s_p3_0[] = {
  131529. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131530. };
  131531. static long _vq_quantmap__44c9_s_p3_0[] = {
  131532. 7, 5, 3, 1, 0, 2, 4, 6,
  131533. 8,
  131534. };
  131535. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  131536. _vq_quantthresh__44c9_s_p3_0,
  131537. _vq_quantmap__44c9_s_p3_0,
  131538. 9,
  131539. 9
  131540. };
  131541. static static_codebook _44c9_s_p3_0 = {
  131542. 2, 81,
  131543. _vq_lengthlist__44c9_s_p3_0,
  131544. 1, -531628032, 1611661312, 4, 0,
  131545. _vq_quantlist__44c9_s_p3_0,
  131546. NULL,
  131547. &_vq_auxt__44c9_s_p3_0,
  131548. NULL,
  131549. 0
  131550. };
  131551. static long _vq_quantlist__44c9_s_p4_0[] = {
  131552. 8,
  131553. 7,
  131554. 9,
  131555. 6,
  131556. 10,
  131557. 5,
  131558. 11,
  131559. 4,
  131560. 12,
  131561. 3,
  131562. 13,
  131563. 2,
  131564. 14,
  131565. 1,
  131566. 15,
  131567. 0,
  131568. 16,
  131569. };
  131570. static long _vq_lengthlist__44c9_s_p4_0[] = {
  131571. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  131572. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  131573. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  131574. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  131575. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  131576. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  131577. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  131578. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131579. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  131580. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0,
  131590. };
  131591. static float _vq_quantthresh__44c9_s_p4_0[] = {
  131592. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131593. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131594. };
  131595. static long _vq_quantmap__44c9_s_p4_0[] = {
  131596. 15, 13, 11, 9, 7, 5, 3, 1,
  131597. 0, 2, 4, 6, 8, 10, 12, 14,
  131598. 16,
  131599. };
  131600. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  131601. _vq_quantthresh__44c9_s_p4_0,
  131602. _vq_quantmap__44c9_s_p4_0,
  131603. 17,
  131604. 17
  131605. };
  131606. static static_codebook _44c9_s_p4_0 = {
  131607. 2, 289,
  131608. _vq_lengthlist__44c9_s_p4_0,
  131609. 1, -529530880, 1611661312, 5, 0,
  131610. _vq_quantlist__44c9_s_p4_0,
  131611. NULL,
  131612. &_vq_auxt__44c9_s_p4_0,
  131613. NULL,
  131614. 0
  131615. };
  131616. static long _vq_quantlist__44c9_s_p5_0[] = {
  131617. 1,
  131618. 0,
  131619. 2,
  131620. };
  131621. static long _vq_lengthlist__44c9_s_p5_0[] = {
  131622. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  131623. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  131624. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  131625. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  131626. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  131627. 12,
  131628. };
  131629. static float _vq_quantthresh__44c9_s_p5_0[] = {
  131630. -5.5, 5.5,
  131631. };
  131632. static long _vq_quantmap__44c9_s_p5_0[] = {
  131633. 1, 0, 2,
  131634. };
  131635. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  131636. _vq_quantthresh__44c9_s_p5_0,
  131637. _vq_quantmap__44c9_s_p5_0,
  131638. 3,
  131639. 3
  131640. };
  131641. static static_codebook _44c9_s_p5_0 = {
  131642. 4, 81,
  131643. _vq_lengthlist__44c9_s_p5_0,
  131644. 1, -529137664, 1618345984, 2, 0,
  131645. _vq_quantlist__44c9_s_p5_0,
  131646. NULL,
  131647. &_vq_auxt__44c9_s_p5_0,
  131648. NULL,
  131649. 0
  131650. };
  131651. static long _vq_quantlist__44c9_s_p5_1[] = {
  131652. 5,
  131653. 4,
  131654. 6,
  131655. 3,
  131656. 7,
  131657. 2,
  131658. 8,
  131659. 1,
  131660. 9,
  131661. 0,
  131662. 10,
  131663. };
  131664. static long _vq_lengthlist__44c9_s_p5_1[] = {
  131665. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  131666. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  131667. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  131668. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  131669. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  131670. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  131671. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  131672. 11,11,11, 7, 7, 7, 7, 7, 7,
  131673. };
  131674. static float _vq_quantthresh__44c9_s_p5_1[] = {
  131675. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131676. 3.5, 4.5,
  131677. };
  131678. static long _vq_quantmap__44c9_s_p5_1[] = {
  131679. 9, 7, 5, 3, 1, 0, 2, 4,
  131680. 6, 8, 10,
  131681. };
  131682. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  131683. _vq_quantthresh__44c9_s_p5_1,
  131684. _vq_quantmap__44c9_s_p5_1,
  131685. 11,
  131686. 11
  131687. };
  131688. static static_codebook _44c9_s_p5_1 = {
  131689. 2, 121,
  131690. _vq_lengthlist__44c9_s_p5_1,
  131691. 1, -531365888, 1611661312, 4, 0,
  131692. _vq_quantlist__44c9_s_p5_1,
  131693. NULL,
  131694. &_vq_auxt__44c9_s_p5_1,
  131695. NULL,
  131696. 0
  131697. };
  131698. static long _vq_quantlist__44c9_s_p6_0[] = {
  131699. 6,
  131700. 5,
  131701. 7,
  131702. 4,
  131703. 8,
  131704. 3,
  131705. 9,
  131706. 2,
  131707. 10,
  131708. 1,
  131709. 11,
  131710. 0,
  131711. 12,
  131712. };
  131713. static long _vq_lengthlist__44c9_s_p6_0[] = {
  131714. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  131715. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  131716. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  131717. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  131718. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  131719. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. };
  131726. static float _vq_quantthresh__44c9_s_p6_0[] = {
  131727. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131728. 12.5, 17.5, 22.5, 27.5,
  131729. };
  131730. static long _vq_quantmap__44c9_s_p6_0[] = {
  131731. 11, 9, 7, 5, 3, 1, 0, 2,
  131732. 4, 6, 8, 10, 12,
  131733. };
  131734. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  131735. _vq_quantthresh__44c9_s_p6_0,
  131736. _vq_quantmap__44c9_s_p6_0,
  131737. 13,
  131738. 13
  131739. };
  131740. static static_codebook _44c9_s_p6_0 = {
  131741. 2, 169,
  131742. _vq_lengthlist__44c9_s_p6_0,
  131743. 1, -526516224, 1616117760, 4, 0,
  131744. _vq_quantlist__44c9_s_p6_0,
  131745. NULL,
  131746. &_vq_auxt__44c9_s_p6_0,
  131747. NULL,
  131748. 0
  131749. };
  131750. static long _vq_quantlist__44c9_s_p6_1[] = {
  131751. 2,
  131752. 1,
  131753. 3,
  131754. 0,
  131755. 4,
  131756. };
  131757. static long _vq_lengthlist__44c9_s_p6_1[] = {
  131758. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  131759. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  131760. };
  131761. static float _vq_quantthresh__44c9_s_p6_1[] = {
  131762. -1.5, -0.5, 0.5, 1.5,
  131763. };
  131764. static long _vq_quantmap__44c9_s_p6_1[] = {
  131765. 3, 1, 0, 2, 4,
  131766. };
  131767. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  131768. _vq_quantthresh__44c9_s_p6_1,
  131769. _vq_quantmap__44c9_s_p6_1,
  131770. 5,
  131771. 5
  131772. };
  131773. static static_codebook _44c9_s_p6_1 = {
  131774. 2, 25,
  131775. _vq_lengthlist__44c9_s_p6_1,
  131776. 1, -533725184, 1611661312, 3, 0,
  131777. _vq_quantlist__44c9_s_p6_1,
  131778. NULL,
  131779. &_vq_auxt__44c9_s_p6_1,
  131780. NULL,
  131781. 0
  131782. };
  131783. static long _vq_quantlist__44c9_s_p7_0[] = {
  131784. 6,
  131785. 5,
  131786. 7,
  131787. 4,
  131788. 8,
  131789. 3,
  131790. 9,
  131791. 2,
  131792. 10,
  131793. 1,
  131794. 11,
  131795. 0,
  131796. 12,
  131797. };
  131798. static long _vq_lengthlist__44c9_s_p7_0[] = {
  131799. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  131800. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  131801. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  131802. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  131803. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  131804. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  131805. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  131806. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  131807. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  131808. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  131809. 19,12,12,12,12,13,13,14,14,
  131810. };
  131811. static float _vq_quantthresh__44c9_s_p7_0[] = {
  131812. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131813. 27.5, 38.5, 49.5, 60.5,
  131814. };
  131815. static long _vq_quantmap__44c9_s_p7_0[] = {
  131816. 11, 9, 7, 5, 3, 1, 0, 2,
  131817. 4, 6, 8, 10, 12,
  131818. };
  131819. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  131820. _vq_quantthresh__44c9_s_p7_0,
  131821. _vq_quantmap__44c9_s_p7_0,
  131822. 13,
  131823. 13
  131824. };
  131825. static static_codebook _44c9_s_p7_0 = {
  131826. 2, 169,
  131827. _vq_lengthlist__44c9_s_p7_0,
  131828. 1, -523206656, 1618345984, 4, 0,
  131829. _vq_quantlist__44c9_s_p7_0,
  131830. NULL,
  131831. &_vq_auxt__44c9_s_p7_0,
  131832. NULL,
  131833. 0
  131834. };
  131835. static long _vq_quantlist__44c9_s_p7_1[] = {
  131836. 5,
  131837. 4,
  131838. 6,
  131839. 3,
  131840. 7,
  131841. 2,
  131842. 8,
  131843. 1,
  131844. 9,
  131845. 0,
  131846. 10,
  131847. };
  131848. static long _vq_lengthlist__44c9_s_p7_1[] = {
  131849. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  131850. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131851. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  131852. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131853. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  131854. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  131855. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  131856. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131857. };
  131858. static float _vq_quantthresh__44c9_s_p7_1[] = {
  131859. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131860. 3.5, 4.5,
  131861. };
  131862. static long _vq_quantmap__44c9_s_p7_1[] = {
  131863. 9, 7, 5, 3, 1, 0, 2, 4,
  131864. 6, 8, 10,
  131865. };
  131866. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  131867. _vq_quantthresh__44c9_s_p7_1,
  131868. _vq_quantmap__44c9_s_p7_1,
  131869. 11,
  131870. 11
  131871. };
  131872. static static_codebook _44c9_s_p7_1 = {
  131873. 2, 121,
  131874. _vq_lengthlist__44c9_s_p7_1,
  131875. 1, -531365888, 1611661312, 4, 0,
  131876. _vq_quantlist__44c9_s_p7_1,
  131877. NULL,
  131878. &_vq_auxt__44c9_s_p7_1,
  131879. NULL,
  131880. 0
  131881. };
  131882. static long _vq_quantlist__44c9_s_p8_0[] = {
  131883. 7,
  131884. 6,
  131885. 8,
  131886. 5,
  131887. 9,
  131888. 4,
  131889. 10,
  131890. 3,
  131891. 11,
  131892. 2,
  131893. 12,
  131894. 1,
  131895. 13,
  131896. 0,
  131897. 14,
  131898. };
  131899. static long _vq_lengthlist__44c9_s_p8_0[] = {
  131900. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  131901. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  131902. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  131903. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  131904. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  131905. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  131906. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  131907. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  131908. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  131909. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  131910. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  131911. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  131912. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  131913. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  131914. 14,
  131915. };
  131916. static float _vq_quantthresh__44c9_s_p8_0[] = {
  131917. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131918. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131919. };
  131920. static long _vq_quantmap__44c9_s_p8_0[] = {
  131921. 13, 11, 9, 7, 5, 3, 1, 0,
  131922. 2, 4, 6, 8, 10, 12, 14,
  131923. };
  131924. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  131925. _vq_quantthresh__44c9_s_p8_0,
  131926. _vq_quantmap__44c9_s_p8_0,
  131927. 15,
  131928. 15
  131929. };
  131930. static static_codebook _44c9_s_p8_0 = {
  131931. 2, 225,
  131932. _vq_lengthlist__44c9_s_p8_0,
  131933. 1, -520986624, 1620377600, 4, 0,
  131934. _vq_quantlist__44c9_s_p8_0,
  131935. NULL,
  131936. &_vq_auxt__44c9_s_p8_0,
  131937. NULL,
  131938. 0
  131939. };
  131940. static long _vq_quantlist__44c9_s_p8_1[] = {
  131941. 10,
  131942. 9,
  131943. 11,
  131944. 8,
  131945. 12,
  131946. 7,
  131947. 13,
  131948. 6,
  131949. 14,
  131950. 5,
  131951. 15,
  131952. 4,
  131953. 16,
  131954. 3,
  131955. 17,
  131956. 2,
  131957. 18,
  131958. 1,
  131959. 19,
  131960. 0,
  131961. 20,
  131962. };
  131963. static long _vq_lengthlist__44c9_s_p8_1[] = {
  131964. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131965. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131966. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131967. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131968. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131969. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131970. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  131971. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131972. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131973. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131974. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131975. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131976. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131977. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131978. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131979. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  131980. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  131981. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  131982. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  131983. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131984. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131985. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  131986. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131987. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131988. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  131989. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  131990. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  131991. 9, 9, 9,10, 9, 9, 9, 9, 9,
  131992. };
  131993. static float _vq_quantthresh__44c9_s_p8_1[] = {
  131994. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131995. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131996. 6.5, 7.5, 8.5, 9.5,
  131997. };
  131998. static long _vq_quantmap__44c9_s_p8_1[] = {
  131999. 19, 17, 15, 13, 11, 9, 7, 5,
  132000. 3, 1, 0, 2, 4, 6, 8, 10,
  132001. 12, 14, 16, 18, 20,
  132002. };
  132003. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  132004. _vq_quantthresh__44c9_s_p8_1,
  132005. _vq_quantmap__44c9_s_p8_1,
  132006. 21,
  132007. 21
  132008. };
  132009. static static_codebook _44c9_s_p8_1 = {
  132010. 2, 441,
  132011. _vq_lengthlist__44c9_s_p8_1,
  132012. 1, -529268736, 1611661312, 5, 0,
  132013. _vq_quantlist__44c9_s_p8_1,
  132014. NULL,
  132015. &_vq_auxt__44c9_s_p8_1,
  132016. NULL,
  132017. 0
  132018. };
  132019. static long _vq_quantlist__44c9_s_p9_0[] = {
  132020. 9,
  132021. 8,
  132022. 10,
  132023. 7,
  132024. 11,
  132025. 6,
  132026. 12,
  132027. 5,
  132028. 13,
  132029. 4,
  132030. 14,
  132031. 3,
  132032. 15,
  132033. 2,
  132034. 16,
  132035. 1,
  132036. 17,
  132037. 0,
  132038. 18,
  132039. };
  132040. static long _vq_lengthlist__44c9_s_p9_0[] = {
  132041. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132042. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  132043. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  132044. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  132045. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132046. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132047. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132048. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132049. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132050. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132051. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132052. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132053. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132054. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132055. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132056. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132057. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  132058. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132063. 11,11,11,11,11,11,11,11,11,
  132064. };
  132065. static float _vq_quantthresh__44c9_s_p9_0[] = {
  132066. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  132067. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  132068. 6982.5, 7913.5,
  132069. };
  132070. static long _vq_quantmap__44c9_s_p9_0[] = {
  132071. 17, 15, 13, 11, 9, 7, 5, 3,
  132072. 1, 0, 2, 4, 6, 8, 10, 12,
  132073. 14, 16, 18,
  132074. };
  132075. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  132076. _vq_quantthresh__44c9_s_p9_0,
  132077. _vq_quantmap__44c9_s_p9_0,
  132078. 19,
  132079. 19
  132080. };
  132081. static static_codebook _44c9_s_p9_0 = {
  132082. 2, 361,
  132083. _vq_lengthlist__44c9_s_p9_0,
  132084. 1, -508535424, 1631393792, 5, 0,
  132085. _vq_quantlist__44c9_s_p9_0,
  132086. NULL,
  132087. &_vq_auxt__44c9_s_p9_0,
  132088. NULL,
  132089. 0
  132090. };
  132091. static long _vq_quantlist__44c9_s_p9_1[] = {
  132092. 9,
  132093. 8,
  132094. 10,
  132095. 7,
  132096. 11,
  132097. 6,
  132098. 12,
  132099. 5,
  132100. 13,
  132101. 4,
  132102. 14,
  132103. 3,
  132104. 15,
  132105. 2,
  132106. 16,
  132107. 1,
  132108. 17,
  132109. 0,
  132110. 18,
  132111. };
  132112. static long _vq_lengthlist__44c9_s_p9_1[] = {
  132113. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  132114. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  132115. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  132116. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  132117. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  132118. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  132119. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  132120. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  132121. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  132122. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  132123. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  132124. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  132125. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  132126. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  132127. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  132128. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  132129. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  132130. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  132131. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  132132. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  132133. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  132134. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  132135. 13,13,13,14,13,14,15,15,15,
  132136. };
  132137. static float _vq_quantthresh__44c9_s_p9_1[] = {
  132138. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  132139. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  132140. 367.5, 416.5,
  132141. };
  132142. static long _vq_quantmap__44c9_s_p9_1[] = {
  132143. 17, 15, 13, 11, 9, 7, 5, 3,
  132144. 1, 0, 2, 4, 6, 8, 10, 12,
  132145. 14, 16, 18,
  132146. };
  132147. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  132148. _vq_quantthresh__44c9_s_p9_1,
  132149. _vq_quantmap__44c9_s_p9_1,
  132150. 19,
  132151. 19
  132152. };
  132153. static static_codebook _44c9_s_p9_1 = {
  132154. 2, 361,
  132155. _vq_lengthlist__44c9_s_p9_1,
  132156. 1, -518287360, 1622704128, 5, 0,
  132157. _vq_quantlist__44c9_s_p9_1,
  132158. NULL,
  132159. &_vq_auxt__44c9_s_p9_1,
  132160. NULL,
  132161. 0
  132162. };
  132163. static long _vq_quantlist__44c9_s_p9_2[] = {
  132164. 24,
  132165. 23,
  132166. 25,
  132167. 22,
  132168. 26,
  132169. 21,
  132170. 27,
  132171. 20,
  132172. 28,
  132173. 19,
  132174. 29,
  132175. 18,
  132176. 30,
  132177. 17,
  132178. 31,
  132179. 16,
  132180. 32,
  132181. 15,
  132182. 33,
  132183. 14,
  132184. 34,
  132185. 13,
  132186. 35,
  132187. 12,
  132188. 36,
  132189. 11,
  132190. 37,
  132191. 10,
  132192. 38,
  132193. 9,
  132194. 39,
  132195. 8,
  132196. 40,
  132197. 7,
  132198. 41,
  132199. 6,
  132200. 42,
  132201. 5,
  132202. 43,
  132203. 4,
  132204. 44,
  132205. 3,
  132206. 45,
  132207. 2,
  132208. 46,
  132209. 1,
  132210. 47,
  132211. 0,
  132212. 48,
  132213. };
  132214. static long _vq_lengthlist__44c9_s_p9_2[] = {
  132215. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  132216. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  132217. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132218. 7,
  132219. };
  132220. static float _vq_quantthresh__44c9_s_p9_2[] = {
  132221. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132222. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132223. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132224. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132225. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132226. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132227. };
  132228. static long _vq_quantmap__44c9_s_p9_2[] = {
  132229. 47, 45, 43, 41, 39, 37, 35, 33,
  132230. 31, 29, 27, 25, 23, 21, 19, 17,
  132231. 15, 13, 11, 9, 7, 5, 3, 1,
  132232. 0, 2, 4, 6, 8, 10, 12, 14,
  132233. 16, 18, 20, 22, 24, 26, 28, 30,
  132234. 32, 34, 36, 38, 40, 42, 44, 46,
  132235. 48,
  132236. };
  132237. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  132238. _vq_quantthresh__44c9_s_p9_2,
  132239. _vq_quantmap__44c9_s_p9_2,
  132240. 49,
  132241. 49
  132242. };
  132243. static static_codebook _44c9_s_p9_2 = {
  132244. 1, 49,
  132245. _vq_lengthlist__44c9_s_p9_2,
  132246. 1, -526909440, 1611661312, 6, 0,
  132247. _vq_quantlist__44c9_s_p9_2,
  132248. NULL,
  132249. &_vq_auxt__44c9_s_p9_2,
  132250. NULL,
  132251. 0
  132252. };
  132253. static long _huff_lengthlist__44c9_s_short[] = {
  132254. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  132255. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  132256. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  132257. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  132258. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  132259. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  132260. 9, 8,10,13,
  132261. };
  132262. static static_codebook _huff_book__44c9_s_short = {
  132263. 2, 100,
  132264. _huff_lengthlist__44c9_s_short,
  132265. 0, 0, 0, 0, 0,
  132266. NULL,
  132267. NULL,
  132268. NULL,
  132269. NULL,
  132270. 0
  132271. };
  132272. static long _huff_lengthlist__44c0_s_long[] = {
  132273. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  132274. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  132275. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  132276. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  132277. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  132278. 12,
  132279. };
  132280. static static_codebook _huff_book__44c0_s_long = {
  132281. 2, 81,
  132282. _huff_lengthlist__44c0_s_long,
  132283. 0, 0, 0, 0, 0,
  132284. NULL,
  132285. NULL,
  132286. NULL,
  132287. NULL,
  132288. 0
  132289. };
  132290. static long _vq_quantlist__44c0_s_p1_0[] = {
  132291. 1,
  132292. 0,
  132293. 2,
  132294. };
  132295. static long _vq_lengthlist__44c0_s_p1_0[] = {
  132296. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132297. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132302. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132307. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  132326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  132336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132342. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  132347. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  132352. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132372. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132377. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132388. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  132393. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  132398. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132706. 0,
  132707. };
  132708. static float _vq_quantthresh__44c0_s_p1_0[] = {
  132709. -0.5, 0.5,
  132710. };
  132711. static long _vq_quantmap__44c0_s_p1_0[] = {
  132712. 1, 0, 2,
  132713. };
  132714. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  132715. _vq_quantthresh__44c0_s_p1_0,
  132716. _vq_quantmap__44c0_s_p1_0,
  132717. 3,
  132718. 3
  132719. };
  132720. static static_codebook _44c0_s_p1_0 = {
  132721. 8, 6561,
  132722. _vq_lengthlist__44c0_s_p1_0,
  132723. 1, -535822336, 1611661312, 2, 0,
  132724. _vq_quantlist__44c0_s_p1_0,
  132725. NULL,
  132726. &_vq_auxt__44c0_s_p1_0,
  132727. NULL,
  132728. 0
  132729. };
  132730. static long _vq_quantlist__44c0_s_p2_0[] = {
  132731. 2,
  132732. 1,
  132733. 3,
  132734. 0,
  132735. 4,
  132736. };
  132737. static long _vq_lengthlist__44c0_s_p2_0[] = {
  132738. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132744. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132777. 0,
  132778. };
  132779. static float _vq_quantthresh__44c0_s_p2_0[] = {
  132780. -1.5, -0.5, 0.5, 1.5,
  132781. };
  132782. static long _vq_quantmap__44c0_s_p2_0[] = {
  132783. 3, 1, 0, 2, 4,
  132784. };
  132785. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  132786. _vq_quantthresh__44c0_s_p2_0,
  132787. _vq_quantmap__44c0_s_p2_0,
  132788. 5,
  132789. 5
  132790. };
  132791. static static_codebook _44c0_s_p2_0 = {
  132792. 4, 625,
  132793. _vq_lengthlist__44c0_s_p2_0,
  132794. 1, -533725184, 1611661312, 3, 0,
  132795. _vq_quantlist__44c0_s_p2_0,
  132796. NULL,
  132797. &_vq_auxt__44c0_s_p2_0,
  132798. NULL,
  132799. 0
  132800. };
  132801. static long _vq_quantlist__44c0_s_p3_0[] = {
  132802. 4,
  132803. 3,
  132804. 5,
  132805. 2,
  132806. 6,
  132807. 1,
  132808. 7,
  132809. 0,
  132810. 8,
  132811. };
  132812. static long _vq_lengthlist__44c0_s_p3_0[] = {
  132813. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  132814. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132815. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132816. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132817. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132818. 0,
  132819. };
  132820. static float _vq_quantthresh__44c0_s_p3_0[] = {
  132821. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132822. };
  132823. static long _vq_quantmap__44c0_s_p3_0[] = {
  132824. 7, 5, 3, 1, 0, 2, 4, 6,
  132825. 8,
  132826. };
  132827. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  132828. _vq_quantthresh__44c0_s_p3_0,
  132829. _vq_quantmap__44c0_s_p3_0,
  132830. 9,
  132831. 9
  132832. };
  132833. static static_codebook _44c0_s_p3_0 = {
  132834. 2, 81,
  132835. _vq_lengthlist__44c0_s_p3_0,
  132836. 1, -531628032, 1611661312, 4, 0,
  132837. _vq_quantlist__44c0_s_p3_0,
  132838. NULL,
  132839. &_vq_auxt__44c0_s_p3_0,
  132840. NULL,
  132841. 0
  132842. };
  132843. static long _vq_quantlist__44c0_s_p4_0[] = {
  132844. 4,
  132845. 3,
  132846. 5,
  132847. 2,
  132848. 6,
  132849. 1,
  132850. 7,
  132851. 0,
  132852. 8,
  132853. };
  132854. static long _vq_lengthlist__44c0_s_p4_0[] = {
  132855. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132856. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132857. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  132858. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  132859. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132860. 10,
  132861. };
  132862. static float _vq_quantthresh__44c0_s_p4_0[] = {
  132863. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132864. };
  132865. static long _vq_quantmap__44c0_s_p4_0[] = {
  132866. 7, 5, 3, 1, 0, 2, 4, 6,
  132867. 8,
  132868. };
  132869. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  132870. _vq_quantthresh__44c0_s_p4_0,
  132871. _vq_quantmap__44c0_s_p4_0,
  132872. 9,
  132873. 9
  132874. };
  132875. static static_codebook _44c0_s_p4_0 = {
  132876. 2, 81,
  132877. _vq_lengthlist__44c0_s_p4_0,
  132878. 1, -531628032, 1611661312, 4, 0,
  132879. _vq_quantlist__44c0_s_p4_0,
  132880. NULL,
  132881. &_vq_auxt__44c0_s_p4_0,
  132882. NULL,
  132883. 0
  132884. };
  132885. static long _vq_quantlist__44c0_s_p5_0[] = {
  132886. 8,
  132887. 7,
  132888. 9,
  132889. 6,
  132890. 10,
  132891. 5,
  132892. 11,
  132893. 4,
  132894. 12,
  132895. 3,
  132896. 13,
  132897. 2,
  132898. 14,
  132899. 1,
  132900. 15,
  132901. 0,
  132902. 16,
  132903. };
  132904. static long _vq_lengthlist__44c0_s_p5_0[] = {
  132905. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132906. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  132907. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132908. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132909. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132910. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  132911. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  132912. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132913. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132914. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  132915. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132916. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132917. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132918. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132919. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  132920. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  132921. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  132922. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132923. 14,
  132924. };
  132925. static float _vq_quantthresh__44c0_s_p5_0[] = {
  132926. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132927. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132928. };
  132929. static long _vq_quantmap__44c0_s_p5_0[] = {
  132930. 15, 13, 11, 9, 7, 5, 3, 1,
  132931. 0, 2, 4, 6, 8, 10, 12, 14,
  132932. 16,
  132933. };
  132934. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  132935. _vq_quantthresh__44c0_s_p5_0,
  132936. _vq_quantmap__44c0_s_p5_0,
  132937. 17,
  132938. 17
  132939. };
  132940. static static_codebook _44c0_s_p5_0 = {
  132941. 2, 289,
  132942. _vq_lengthlist__44c0_s_p5_0,
  132943. 1, -529530880, 1611661312, 5, 0,
  132944. _vq_quantlist__44c0_s_p5_0,
  132945. NULL,
  132946. &_vq_auxt__44c0_s_p5_0,
  132947. NULL,
  132948. 0
  132949. };
  132950. static long _vq_quantlist__44c0_s_p6_0[] = {
  132951. 1,
  132952. 0,
  132953. 2,
  132954. };
  132955. static long _vq_lengthlist__44c0_s_p6_0[] = {
  132956. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  132957. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132958. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  132959. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  132960. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132961. 10,
  132962. };
  132963. static float _vq_quantthresh__44c0_s_p6_0[] = {
  132964. -5.5, 5.5,
  132965. };
  132966. static long _vq_quantmap__44c0_s_p6_0[] = {
  132967. 1, 0, 2,
  132968. };
  132969. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  132970. _vq_quantthresh__44c0_s_p6_0,
  132971. _vq_quantmap__44c0_s_p6_0,
  132972. 3,
  132973. 3
  132974. };
  132975. static static_codebook _44c0_s_p6_0 = {
  132976. 4, 81,
  132977. _vq_lengthlist__44c0_s_p6_0,
  132978. 1, -529137664, 1618345984, 2, 0,
  132979. _vq_quantlist__44c0_s_p6_0,
  132980. NULL,
  132981. &_vq_auxt__44c0_s_p6_0,
  132982. NULL,
  132983. 0
  132984. };
  132985. static long _vq_quantlist__44c0_s_p6_1[] = {
  132986. 5,
  132987. 4,
  132988. 6,
  132989. 3,
  132990. 7,
  132991. 2,
  132992. 8,
  132993. 1,
  132994. 9,
  132995. 0,
  132996. 10,
  132997. };
  132998. static long _vq_lengthlist__44c0_s_p6_1[] = {
  132999. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  133000. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  133001. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133002. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  133003. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133004. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133005. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133006. 10,10,10, 8, 8, 8, 8, 8, 8,
  133007. };
  133008. static float _vq_quantthresh__44c0_s_p6_1[] = {
  133009. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133010. 3.5, 4.5,
  133011. };
  133012. static long _vq_quantmap__44c0_s_p6_1[] = {
  133013. 9, 7, 5, 3, 1, 0, 2, 4,
  133014. 6, 8, 10,
  133015. };
  133016. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  133017. _vq_quantthresh__44c0_s_p6_1,
  133018. _vq_quantmap__44c0_s_p6_1,
  133019. 11,
  133020. 11
  133021. };
  133022. static static_codebook _44c0_s_p6_1 = {
  133023. 2, 121,
  133024. _vq_lengthlist__44c0_s_p6_1,
  133025. 1, -531365888, 1611661312, 4, 0,
  133026. _vq_quantlist__44c0_s_p6_1,
  133027. NULL,
  133028. &_vq_auxt__44c0_s_p6_1,
  133029. NULL,
  133030. 0
  133031. };
  133032. static long _vq_quantlist__44c0_s_p7_0[] = {
  133033. 6,
  133034. 5,
  133035. 7,
  133036. 4,
  133037. 8,
  133038. 3,
  133039. 9,
  133040. 2,
  133041. 10,
  133042. 1,
  133043. 11,
  133044. 0,
  133045. 12,
  133046. };
  133047. static long _vq_lengthlist__44c0_s_p7_0[] = {
  133048. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133049. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133050. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133051. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133052. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133053. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  133054. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133055. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133056. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133057. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  133058. 0,12,12,11,11,12,12,13,13,
  133059. };
  133060. static float _vq_quantthresh__44c0_s_p7_0[] = {
  133061. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133062. 12.5, 17.5, 22.5, 27.5,
  133063. };
  133064. static long _vq_quantmap__44c0_s_p7_0[] = {
  133065. 11, 9, 7, 5, 3, 1, 0, 2,
  133066. 4, 6, 8, 10, 12,
  133067. };
  133068. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  133069. _vq_quantthresh__44c0_s_p7_0,
  133070. _vq_quantmap__44c0_s_p7_0,
  133071. 13,
  133072. 13
  133073. };
  133074. static static_codebook _44c0_s_p7_0 = {
  133075. 2, 169,
  133076. _vq_lengthlist__44c0_s_p7_0,
  133077. 1, -526516224, 1616117760, 4, 0,
  133078. _vq_quantlist__44c0_s_p7_0,
  133079. NULL,
  133080. &_vq_auxt__44c0_s_p7_0,
  133081. NULL,
  133082. 0
  133083. };
  133084. static long _vq_quantlist__44c0_s_p7_1[] = {
  133085. 2,
  133086. 1,
  133087. 3,
  133088. 0,
  133089. 4,
  133090. };
  133091. static long _vq_lengthlist__44c0_s_p7_1[] = {
  133092. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  133093. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133094. };
  133095. static float _vq_quantthresh__44c0_s_p7_1[] = {
  133096. -1.5, -0.5, 0.5, 1.5,
  133097. };
  133098. static long _vq_quantmap__44c0_s_p7_1[] = {
  133099. 3, 1, 0, 2, 4,
  133100. };
  133101. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  133102. _vq_quantthresh__44c0_s_p7_1,
  133103. _vq_quantmap__44c0_s_p7_1,
  133104. 5,
  133105. 5
  133106. };
  133107. static static_codebook _44c0_s_p7_1 = {
  133108. 2, 25,
  133109. _vq_lengthlist__44c0_s_p7_1,
  133110. 1, -533725184, 1611661312, 3, 0,
  133111. _vq_quantlist__44c0_s_p7_1,
  133112. NULL,
  133113. &_vq_auxt__44c0_s_p7_1,
  133114. NULL,
  133115. 0
  133116. };
  133117. static long _vq_quantlist__44c0_s_p8_0[] = {
  133118. 2,
  133119. 1,
  133120. 3,
  133121. 0,
  133122. 4,
  133123. };
  133124. static long _vq_lengthlist__44c0_s_p8_0[] = {
  133125. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  133126. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133130. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133131. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133132. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  133133. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133134. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133135. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133136. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133137. 10,10,10,10,10,10,10,10,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,10,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133164. 11,
  133165. };
  133166. static float _vq_quantthresh__44c0_s_p8_0[] = {
  133167. -331.5, -110.5, 110.5, 331.5,
  133168. };
  133169. static long _vq_quantmap__44c0_s_p8_0[] = {
  133170. 3, 1, 0, 2, 4,
  133171. };
  133172. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  133173. _vq_quantthresh__44c0_s_p8_0,
  133174. _vq_quantmap__44c0_s_p8_0,
  133175. 5,
  133176. 5
  133177. };
  133178. static static_codebook _44c0_s_p8_0 = {
  133179. 4, 625,
  133180. _vq_lengthlist__44c0_s_p8_0,
  133181. 1, -518283264, 1627103232, 3, 0,
  133182. _vq_quantlist__44c0_s_p8_0,
  133183. NULL,
  133184. &_vq_auxt__44c0_s_p8_0,
  133185. NULL,
  133186. 0
  133187. };
  133188. static long _vq_quantlist__44c0_s_p8_1[] = {
  133189. 6,
  133190. 5,
  133191. 7,
  133192. 4,
  133193. 8,
  133194. 3,
  133195. 9,
  133196. 2,
  133197. 10,
  133198. 1,
  133199. 11,
  133200. 0,
  133201. 12,
  133202. };
  133203. static long _vq_lengthlist__44c0_s_p8_1[] = {
  133204. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  133205. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  133206. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  133207. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  133208. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  133209. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  133210. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  133211. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  133212. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  133213. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  133214. 16,13,13,12,12,14,14,15,13,
  133215. };
  133216. static float _vq_quantthresh__44c0_s_p8_1[] = {
  133217. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133218. 42.5, 59.5, 76.5, 93.5,
  133219. };
  133220. static long _vq_quantmap__44c0_s_p8_1[] = {
  133221. 11, 9, 7, 5, 3, 1, 0, 2,
  133222. 4, 6, 8, 10, 12,
  133223. };
  133224. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  133225. _vq_quantthresh__44c0_s_p8_1,
  133226. _vq_quantmap__44c0_s_p8_1,
  133227. 13,
  133228. 13
  133229. };
  133230. static static_codebook _44c0_s_p8_1 = {
  133231. 2, 169,
  133232. _vq_lengthlist__44c0_s_p8_1,
  133233. 1, -522616832, 1620115456, 4, 0,
  133234. _vq_quantlist__44c0_s_p8_1,
  133235. NULL,
  133236. &_vq_auxt__44c0_s_p8_1,
  133237. NULL,
  133238. 0
  133239. };
  133240. static long _vq_quantlist__44c0_s_p8_2[] = {
  133241. 8,
  133242. 7,
  133243. 9,
  133244. 6,
  133245. 10,
  133246. 5,
  133247. 11,
  133248. 4,
  133249. 12,
  133250. 3,
  133251. 13,
  133252. 2,
  133253. 14,
  133254. 1,
  133255. 15,
  133256. 0,
  133257. 16,
  133258. };
  133259. static long _vq_lengthlist__44c0_s_p8_2[] = {
  133260. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133261. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  133262. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133263. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  133264. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133265. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  133266. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  133267. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  133268. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  133269. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  133270. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  133271. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133272. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  133273. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133274. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  133275. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  133276. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  133277. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  133278. 10,
  133279. };
  133280. static float _vq_quantthresh__44c0_s_p8_2[] = {
  133281. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133282. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133283. };
  133284. static long _vq_quantmap__44c0_s_p8_2[] = {
  133285. 15, 13, 11, 9, 7, 5, 3, 1,
  133286. 0, 2, 4, 6, 8, 10, 12, 14,
  133287. 16,
  133288. };
  133289. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  133290. _vq_quantthresh__44c0_s_p8_2,
  133291. _vq_quantmap__44c0_s_p8_2,
  133292. 17,
  133293. 17
  133294. };
  133295. static static_codebook _44c0_s_p8_2 = {
  133296. 2, 289,
  133297. _vq_lengthlist__44c0_s_p8_2,
  133298. 1, -529530880, 1611661312, 5, 0,
  133299. _vq_quantlist__44c0_s_p8_2,
  133300. NULL,
  133301. &_vq_auxt__44c0_s_p8_2,
  133302. NULL,
  133303. 0
  133304. };
  133305. static long _huff_lengthlist__44c0_s_short[] = {
  133306. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  133307. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  133308. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  133309. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  133310. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  133311. 12,
  133312. };
  133313. static static_codebook _huff_book__44c0_s_short = {
  133314. 2, 81,
  133315. _huff_lengthlist__44c0_s_short,
  133316. 0, 0, 0, 0, 0,
  133317. NULL,
  133318. NULL,
  133319. NULL,
  133320. NULL,
  133321. 0
  133322. };
  133323. static long _huff_lengthlist__44c0_sm_long[] = {
  133324. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  133325. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  133326. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  133327. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  133328. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  133329. 13,
  133330. };
  133331. static static_codebook _huff_book__44c0_sm_long = {
  133332. 2, 81,
  133333. _huff_lengthlist__44c0_sm_long,
  133334. 0, 0, 0, 0, 0,
  133335. NULL,
  133336. NULL,
  133337. NULL,
  133338. NULL,
  133339. 0
  133340. };
  133341. static long _vq_quantlist__44c0_sm_p1_0[] = {
  133342. 1,
  133343. 0,
  133344. 2,
  133345. };
  133346. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  133347. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133348. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133353. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  133358. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  133377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  133382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  133393. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  133398. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  133403. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133428. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133439. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133444. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133449. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133757. 0,
  133758. };
  133759. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  133760. -0.5, 0.5,
  133761. };
  133762. static long _vq_quantmap__44c0_sm_p1_0[] = {
  133763. 1, 0, 2,
  133764. };
  133765. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  133766. _vq_quantthresh__44c0_sm_p1_0,
  133767. _vq_quantmap__44c0_sm_p1_0,
  133768. 3,
  133769. 3
  133770. };
  133771. static static_codebook _44c0_sm_p1_0 = {
  133772. 8, 6561,
  133773. _vq_lengthlist__44c0_sm_p1_0,
  133774. 1, -535822336, 1611661312, 2, 0,
  133775. _vq_quantlist__44c0_sm_p1_0,
  133776. NULL,
  133777. &_vq_auxt__44c0_sm_p1_0,
  133778. NULL,
  133779. 0
  133780. };
  133781. static long _vq_quantlist__44c0_sm_p2_0[] = {
  133782. 2,
  133783. 1,
  133784. 3,
  133785. 0,
  133786. 4,
  133787. };
  133788. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  133789. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133795. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133828. 0,
  133829. };
  133830. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  133831. -1.5, -0.5, 0.5, 1.5,
  133832. };
  133833. static long _vq_quantmap__44c0_sm_p2_0[] = {
  133834. 3, 1, 0, 2, 4,
  133835. };
  133836. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  133837. _vq_quantthresh__44c0_sm_p2_0,
  133838. _vq_quantmap__44c0_sm_p2_0,
  133839. 5,
  133840. 5
  133841. };
  133842. static static_codebook _44c0_sm_p2_0 = {
  133843. 4, 625,
  133844. _vq_lengthlist__44c0_sm_p2_0,
  133845. 1, -533725184, 1611661312, 3, 0,
  133846. _vq_quantlist__44c0_sm_p2_0,
  133847. NULL,
  133848. &_vq_auxt__44c0_sm_p2_0,
  133849. NULL,
  133850. 0
  133851. };
  133852. static long _vq_quantlist__44c0_sm_p3_0[] = {
  133853. 4,
  133854. 3,
  133855. 5,
  133856. 2,
  133857. 6,
  133858. 1,
  133859. 7,
  133860. 0,
  133861. 8,
  133862. };
  133863. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  133864. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  133865. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  133866. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133867. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  133868. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133869. 0,
  133870. };
  133871. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  133872. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133873. };
  133874. static long _vq_quantmap__44c0_sm_p3_0[] = {
  133875. 7, 5, 3, 1, 0, 2, 4, 6,
  133876. 8,
  133877. };
  133878. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  133879. _vq_quantthresh__44c0_sm_p3_0,
  133880. _vq_quantmap__44c0_sm_p3_0,
  133881. 9,
  133882. 9
  133883. };
  133884. static static_codebook _44c0_sm_p3_0 = {
  133885. 2, 81,
  133886. _vq_lengthlist__44c0_sm_p3_0,
  133887. 1, -531628032, 1611661312, 4, 0,
  133888. _vq_quantlist__44c0_sm_p3_0,
  133889. NULL,
  133890. &_vq_auxt__44c0_sm_p3_0,
  133891. NULL,
  133892. 0
  133893. };
  133894. static long _vq_quantlist__44c0_sm_p4_0[] = {
  133895. 4,
  133896. 3,
  133897. 5,
  133898. 2,
  133899. 6,
  133900. 1,
  133901. 7,
  133902. 0,
  133903. 8,
  133904. };
  133905. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  133906. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  133907. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133908. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133909. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133910. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133911. 11,
  133912. };
  133913. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  133914. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133915. };
  133916. static long _vq_quantmap__44c0_sm_p4_0[] = {
  133917. 7, 5, 3, 1, 0, 2, 4, 6,
  133918. 8,
  133919. };
  133920. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  133921. _vq_quantthresh__44c0_sm_p4_0,
  133922. _vq_quantmap__44c0_sm_p4_0,
  133923. 9,
  133924. 9
  133925. };
  133926. static static_codebook _44c0_sm_p4_0 = {
  133927. 2, 81,
  133928. _vq_lengthlist__44c0_sm_p4_0,
  133929. 1, -531628032, 1611661312, 4, 0,
  133930. _vq_quantlist__44c0_sm_p4_0,
  133931. NULL,
  133932. &_vq_auxt__44c0_sm_p4_0,
  133933. NULL,
  133934. 0
  133935. };
  133936. static long _vq_quantlist__44c0_sm_p5_0[] = {
  133937. 8,
  133938. 7,
  133939. 9,
  133940. 6,
  133941. 10,
  133942. 5,
  133943. 11,
  133944. 4,
  133945. 12,
  133946. 3,
  133947. 13,
  133948. 2,
  133949. 14,
  133950. 1,
  133951. 15,
  133952. 0,
  133953. 16,
  133954. };
  133955. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  133956. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  133957. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  133958. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133959. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  133960. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  133961. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  133962. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  133963. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133964. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  133965. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133966. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133967. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133968. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  133969. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  133970. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  133971. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  133972. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  133973. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133974. 14,
  133975. };
  133976. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  133977. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133978. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133979. };
  133980. static long _vq_quantmap__44c0_sm_p5_0[] = {
  133981. 15, 13, 11, 9, 7, 5, 3, 1,
  133982. 0, 2, 4, 6, 8, 10, 12, 14,
  133983. 16,
  133984. };
  133985. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  133986. _vq_quantthresh__44c0_sm_p5_0,
  133987. _vq_quantmap__44c0_sm_p5_0,
  133988. 17,
  133989. 17
  133990. };
  133991. static static_codebook _44c0_sm_p5_0 = {
  133992. 2, 289,
  133993. _vq_lengthlist__44c0_sm_p5_0,
  133994. 1, -529530880, 1611661312, 5, 0,
  133995. _vq_quantlist__44c0_sm_p5_0,
  133996. NULL,
  133997. &_vq_auxt__44c0_sm_p5_0,
  133998. NULL,
  133999. 0
  134000. };
  134001. static long _vq_quantlist__44c0_sm_p6_0[] = {
  134002. 1,
  134003. 0,
  134004. 2,
  134005. };
  134006. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  134007. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134008. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  134009. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  134010. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  134011. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  134012. 11,
  134013. };
  134014. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  134015. -5.5, 5.5,
  134016. };
  134017. static long _vq_quantmap__44c0_sm_p6_0[] = {
  134018. 1, 0, 2,
  134019. };
  134020. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  134021. _vq_quantthresh__44c0_sm_p6_0,
  134022. _vq_quantmap__44c0_sm_p6_0,
  134023. 3,
  134024. 3
  134025. };
  134026. static static_codebook _44c0_sm_p6_0 = {
  134027. 4, 81,
  134028. _vq_lengthlist__44c0_sm_p6_0,
  134029. 1, -529137664, 1618345984, 2, 0,
  134030. _vq_quantlist__44c0_sm_p6_0,
  134031. NULL,
  134032. &_vq_auxt__44c0_sm_p6_0,
  134033. NULL,
  134034. 0
  134035. };
  134036. static long _vq_quantlist__44c0_sm_p6_1[] = {
  134037. 5,
  134038. 4,
  134039. 6,
  134040. 3,
  134041. 7,
  134042. 2,
  134043. 8,
  134044. 1,
  134045. 9,
  134046. 0,
  134047. 10,
  134048. };
  134049. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  134050. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  134051. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134052. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134053. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  134054. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  134055. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134056. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134057. 10,10,10, 8, 8, 8, 8, 8, 8,
  134058. };
  134059. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  134060. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134061. 3.5, 4.5,
  134062. };
  134063. static long _vq_quantmap__44c0_sm_p6_1[] = {
  134064. 9, 7, 5, 3, 1, 0, 2, 4,
  134065. 6, 8, 10,
  134066. };
  134067. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  134068. _vq_quantthresh__44c0_sm_p6_1,
  134069. _vq_quantmap__44c0_sm_p6_1,
  134070. 11,
  134071. 11
  134072. };
  134073. static static_codebook _44c0_sm_p6_1 = {
  134074. 2, 121,
  134075. _vq_lengthlist__44c0_sm_p6_1,
  134076. 1, -531365888, 1611661312, 4, 0,
  134077. _vq_quantlist__44c0_sm_p6_1,
  134078. NULL,
  134079. &_vq_auxt__44c0_sm_p6_1,
  134080. NULL,
  134081. 0
  134082. };
  134083. static long _vq_quantlist__44c0_sm_p7_0[] = {
  134084. 6,
  134085. 5,
  134086. 7,
  134087. 4,
  134088. 8,
  134089. 3,
  134090. 9,
  134091. 2,
  134092. 10,
  134093. 1,
  134094. 11,
  134095. 0,
  134096. 12,
  134097. };
  134098. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  134099. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  134100. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  134101. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134102. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134103. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  134104. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  134105. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  134106. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134107. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134108. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  134109. 0,12,12,11,11,13,12,14,14,
  134110. };
  134111. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  134112. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134113. 12.5, 17.5, 22.5, 27.5,
  134114. };
  134115. static long _vq_quantmap__44c0_sm_p7_0[] = {
  134116. 11, 9, 7, 5, 3, 1, 0, 2,
  134117. 4, 6, 8, 10, 12,
  134118. };
  134119. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  134120. _vq_quantthresh__44c0_sm_p7_0,
  134121. _vq_quantmap__44c0_sm_p7_0,
  134122. 13,
  134123. 13
  134124. };
  134125. static static_codebook _44c0_sm_p7_0 = {
  134126. 2, 169,
  134127. _vq_lengthlist__44c0_sm_p7_0,
  134128. 1, -526516224, 1616117760, 4, 0,
  134129. _vq_quantlist__44c0_sm_p7_0,
  134130. NULL,
  134131. &_vq_auxt__44c0_sm_p7_0,
  134132. NULL,
  134133. 0
  134134. };
  134135. static long _vq_quantlist__44c0_sm_p7_1[] = {
  134136. 2,
  134137. 1,
  134138. 3,
  134139. 0,
  134140. 4,
  134141. };
  134142. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  134143. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  134144. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134145. };
  134146. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  134147. -1.5, -0.5, 0.5, 1.5,
  134148. };
  134149. static long _vq_quantmap__44c0_sm_p7_1[] = {
  134150. 3, 1, 0, 2, 4,
  134151. };
  134152. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  134153. _vq_quantthresh__44c0_sm_p7_1,
  134154. _vq_quantmap__44c0_sm_p7_1,
  134155. 5,
  134156. 5
  134157. };
  134158. static static_codebook _44c0_sm_p7_1 = {
  134159. 2, 25,
  134160. _vq_lengthlist__44c0_sm_p7_1,
  134161. 1, -533725184, 1611661312, 3, 0,
  134162. _vq_quantlist__44c0_sm_p7_1,
  134163. NULL,
  134164. &_vq_auxt__44c0_sm_p7_1,
  134165. NULL,
  134166. 0
  134167. };
  134168. static long _vq_quantlist__44c0_sm_p8_0[] = {
  134169. 4,
  134170. 3,
  134171. 5,
  134172. 2,
  134173. 6,
  134174. 1,
  134175. 7,
  134176. 0,
  134177. 8,
  134178. };
  134179. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  134180. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  134181. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  134182. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134183. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134184. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134185. 12,
  134186. };
  134187. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  134188. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  134189. };
  134190. static long _vq_quantmap__44c0_sm_p8_0[] = {
  134191. 7, 5, 3, 1, 0, 2, 4, 6,
  134192. 8,
  134193. };
  134194. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  134195. _vq_quantthresh__44c0_sm_p8_0,
  134196. _vq_quantmap__44c0_sm_p8_0,
  134197. 9,
  134198. 9
  134199. };
  134200. static static_codebook _44c0_sm_p8_0 = {
  134201. 2, 81,
  134202. _vq_lengthlist__44c0_sm_p8_0,
  134203. 1, -516186112, 1627103232, 4, 0,
  134204. _vq_quantlist__44c0_sm_p8_0,
  134205. NULL,
  134206. &_vq_auxt__44c0_sm_p8_0,
  134207. NULL,
  134208. 0
  134209. };
  134210. static long _vq_quantlist__44c0_sm_p8_1[] = {
  134211. 6,
  134212. 5,
  134213. 7,
  134214. 4,
  134215. 8,
  134216. 3,
  134217. 9,
  134218. 2,
  134219. 10,
  134220. 1,
  134221. 11,
  134222. 0,
  134223. 12,
  134224. };
  134225. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  134226. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  134227. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134228. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  134229. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  134230. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  134231. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  134232. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  134233. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  134234. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  134235. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  134236. 20,13,13,12,12,16,13,15,13,
  134237. };
  134238. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  134239. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134240. 42.5, 59.5, 76.5, 93.5,
  134241. };
  134242. static long _vq_quantmap__44c0_sm_p8_1[] = {
  134243. 11, 9, 7, 5, 3, 1, 0, 2,
  134244. 4, 6, 8, 10, 12,
  134245. };
  134246. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  134247. _vq_quantthresh__44c0_sm_p8_1,
  134248. _vq_quantmap__44c0_sm_p8_1,
  134249. 13,
  134250. 13
  134251. };
  134252. static static_codebook _44c0_sm_p8_1 = {
  134253. 2, 169,
  134254. _vq_lengthlist__44c0_sm_p8_1,
  134255. 1, -522616832, 1620115456, 4, 0,
  134256. _vq_quantlist__44c0_sm_p8_1,
  134257. NULL,
  134258. &_vq_auxt__44c0_sm_p8_1,
  134259. NULL,
  134260. 0
  134261. };
  134262. static long _vq_quantlist__44c0_sm_p8_2[] = {
  134263. 8,
  134264. 7,
  134265. 9,
  134266. 6,
  134267. 10,
  134268. 5,
  134269. 11,
  134270. 4,
  134271. 12,
  134272. 3,
  134273. 13,
  134274. 2,
  134275. 14,
  134276. 1,
  134277. 15,
  134278. 0,
  134279. 16,
  134280. };
  134281. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  134282. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134283. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134284. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134285. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134286. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134287. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134288. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134289. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  134290. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  134291. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  134292. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  134293. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  134294. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  134295. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  134296. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134297. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134298. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134299. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  134300. 9,
  134301. };
  134302. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  134303. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134304. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134305. };
  134306. static long _vq_quantmap__44c0_sm_p8_2[] = {
  134307. 15, 13, 11, 9, 7, 5, 3, 1,
  134308. 0, 2, 4, 6, 8, 10, 12, 14,
  134309. 16,
  134310. };
  134311. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  134312. _vq_quantthresh__44c0_sm_p8_2,
  134313. _vq_quantmap__44c0_sm_p8_2,
  134314. 17,
  134315. 17
  134316. };
  134317. static static_codebook _44c0_sm_p8_2 = {
  134318. 2, 289,
  134319. _vq_lengthlist__44c0_sm_p8_2,
  134320. 1, -529530880, 1611661312, 5, 0,
  134321. _vq_quantlist__44c0_sm_p8_2,
  134322. NULL,
  134323. &_vq_auxt__44c0_sm_p8_2,
  134324. NULL,
  134325. 0
  134326. };
  134327. static long _huff_lengthlist__44c0_sm_short[] = {
  134328. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  134329. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  134330. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  134331. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  134332. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  134333. 12,
  134334. };
  134335. static static_codebook _huff_book__44c0_sm_short = {
  134336. 2, 81,
  134337. _huff_lengthlist__44c0_sm_short,
  134338. 0, 0, 0, 0, 0,
  134339. NULL,
  134340. NULL,
  134341. NULL,
  134342. NULL,
  134343. 0
  134344. };
  134345. static long _huff_lengthlist__44c1_s_long[] = {
  134346. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  134347. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  134348. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  134349. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  134350. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  134351. 11,
  134352. };
  134353. static static_codebook _huff_book__44c1_s_long = {
  134354. 2, 81,
  134355. _huff_lengthlist__44c1_s_long,
  134356. 0, 0, 0, 0, 0,
  134357. NULL,
  134358. NULL,
  134359. NULL,
  134360. NULL,
  134361. 0
  134362. };
  134363. static long _vq_quantlist__44c1_s_p1_0[] = {
  134364. 1,
  134365. 0,
  134366. 2,
  134367. };
  134368. static long _vq_lengthlist__44c1_s_p1_0[] = {
  134369. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  134370. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  134375. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134380. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134401. 0, 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, 0, 0, 0, 0, 0, 0,
  134404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  134409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0,
  134415. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  134420. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  134425. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134461. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  134466. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  134471. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134779. 0,
  134780. };
  134781. static float _vq_quantthresh__44c1_s_p1_0[] = {
  134782. -0.5, 0.5,
  134783. };
  134784. static long _vq_quantmap__44c1_s_p1_0[] = {
  134785. 1, 0, 2,
  134786. };
  134787. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  134788. _vq_quantthresh__44c1_s_p1_0,
  134789. _vq_quantmap__44c1_s_p1_0,
  134790. 3,
  134791. 3
  134792. };
  134793. static static_codebook _44c1_s_p1_0 = {
  134794. 8, 6561,
  134795. _vq_lengthlist__44c1_s_p1_0,
  134796. 1, -535822336, 1611661312, 2, 0,
  134797. _vq_quantlist__44c1_s_p1_0,
  134798. NULL,
  134799. &_vq_auxt__44c1_s_p1_0,
  134800. NULL,
  134801. 0
  134802. };
  134803. static long _vq_quantlist__44c1_s_p2_0[] = {
  134804. 2,
  134805. 1,
  134806. 3,
  134807. 0,
  134808. 4,
  134809. };
  134810. static long _vq_lengthlist__44c1_s_p2_0[] = {
  134811. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134850. 0,
  134851. };
  134852. static float _vq_quantthresh__44c1_s_p2_0[] = {
  134853. -1.5, -0.5, 0.5, 1.5,
  134854. };
  134855. static long _vq_quantmap__44c1_s_p2_0[] = {
  134856. 3, 1, 0, 2, 4,
  134857. };
  134858. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  134859. _vq_quantthresh__44c1_s_p2_0,
  134860. _vq_quantmap__44c1_s_p2_0,
  134861. 5,
  134862. 5
  134863. };
  134864. static static_codebook _44c1_s_p2_0 = {
  134865. 4, 625,
  134866. _vq_lengthlist__44c1_s_p2_0,
  134867. 1, -533725184, 1611661312, 3, 0,
  134868. _vq_quantlist__44c1_s_p2_0,
  134869. NULL,
  134870. &_vq_auxt__44c1_s_p2_0,
  134871. NULL,
  134872. 0
  134873. };
  134874. static long _vq_quantlist__44c1_s_p3_0[] = {
  134875. 4,
  134876. 3,
  134877. 5,
  134878. 2,
  134879. 6,
  134880. 1,
  134881. 7,
  134882. 0,
  134883. 8,
  134884. };
  134885. static long _vq_lengthlist__44c1_s_p3_0[] = {
  134886. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  134887. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134888. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134889. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134890. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0,
  134892. };
  134893. static float _vq_quantthresh__44c1_s_p3_0[] = {
  134894. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134895. };
  134896. static long _vq_quantmap__44c1_s_p3_0[] = {
  134897. 7, 5, 3, 1, 0, 2, 4, 6,
  134898. 8,
  134899. };
  134900. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  134901. _vq_quantthresh__44c1_s_p3_0,
  134902. _vq_quantmap__44c1_s_p3_0,
  134903. 9,
  134904. 9
  134905. };
  134906. static static_codebook _44c1_s_p3_0 = {
  134907. 2, 81,
  134908. _vq_lengthlist__44c1_s_p3_0,
  134909. 1, -531628032, 1611661312, 4, 0,
  134910. _vq_quantlist__44c1_s_p3_0,
  134911. NULL,
  134912. &_vq_auxt__44c1_s_p3_0,
  134913. NULL,
  134914. 0
  134915. };
  134916. static long _vq_quantlist__44c1_s_p4_0[] = {
  134917. 4,
  134918. 3,
  134919. 5,
  134920. 2,
  134921. 6,
  134922. 1,
  134923. 7,
  134924. 0,
  134925. 8,
  134926. };
  134927. static long _vq_lengthlist__44c1_s_p4_0[] = {
  134928. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  134929. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134930. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134931. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  134932. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134933. 11,
  134934. };
  134935. static float _vq_quantthresh__44c1_s_p4_0[] = {
  134936. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134937. };
  134938. static long _vq_quantmap__44c1_s_p4_0[] = {
  134939. 7, 5, 3, 1, 0, 2, 4, 6,
  134940. 8,
  134941. };
  134942. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  134943. _vq_quantthresh__44c1_s_p4_0,
  134944. _vq_quantmap__44c1_s_p4_0,
  134945. 9,
  134946. 9
  134947. };
  134948. static static_codebook _44c1_s_p4_0 = {
  134949. 2, 81,
  134950. _vq_lengthlist__44c1_s_p4_0,
  134951. 1, -531628032, 1611661312, 4, 0,
  134952. _vq_quantlist__44c1_s_p4_0,
  134953. NULL,
  134954. &_vq_auxt__44c1_s_p4_0,
  134955. NULL,
  134956. 0
  134957. };
  134958. static long _vq_quantlist__44c1_s_p5_0[] = {
  134959. 8,
  134960. 7,
  134961. 9,
  134962. 6,
  134963. 10,
  134964. 5,
  134965. 11,
  134966. 4,
  134967. 12,
  134968. 3,
  134969. 13,
  134970. 2,
  134971. 14,
  134972. 1,
  134973. 15,
  134974. 0,
  134975. 16,
  134976. };
  134977. static long _vq_lengthlist__44c1_s_p5_0[] = {
  134978. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134979. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134980. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134981. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134982. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134983. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  134984. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  134985. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134986. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134987. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134988. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134989. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134990. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134991. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134992. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  134993. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134994. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134996. 14,
  134997. };
  134998. static float _vq_quantthresh__44c1_s_p5_0[] = {
  134999. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135000. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135001. };
  135002. static long _vq_quantmap__44c1_s_p5_0[] = {
  135003. 15, 13, 11, 9, 7, 5, 3, 1,
  135004. 0, 2, 4, 6, 8, 10, 12, 14,
  135005. 16,
  135006. };
  135007. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  135008. _vq_quantthresh__44c1_s_p5_0,
  135009. _vq_quantmap__44c1_s_p5_0,
  135010. 17,
  135011. 17
  135012. };
  135013. static static_codebook _44c1_s_p5_0 = {
  135014. 2, 289,
  135015. _vq_lengthlist__44c1_s_p5_0,
  135016. 1, -529530880, 1611661312, 5, 0,
  135017. _vq_quantlist__44c1_s_p5_0,
  135018. NULL,
  135019. &_vq_auxt__44c1_s_p5_0,
  135020. NULL,
  135021. 0
  135022. };
  135023. static long _vq_quantlist__44c1_s_p6_0[] = {
  135024. 1,
  135025. 0,
  135026. 2,
  135027. };
  135028. static long _vq_lengthlist__44c1_s_p6_0[] = {
  135029. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135030. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  135031. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135032. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  135033. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  135034. 11,
  135035. };
  135036. static float _vq_quantthresh__44c1_s_p6_0[] = {
  135037. -5.5, 5.5,
  135038. };
  135039. static long _vq_quantmap__44c1_s_p6_0[] = {
  135040. 1, 0, 2,
  135041. };
  135042. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  135043. _vq_quantthresh__44c1_s_p6_0,
  135044. _vq_quantmap__44c1_s_p6_0,
  135045. 3,
  135046. 3
  135047. };
  135048. static static_codebook _44c1_s_p6_0 = {
  135049. 4, 81,
  135050. _vq_lengthlist__44c1_s_p6_0,
  135051. 1, -529137664, 1618345984, 2, 0,
  135052. _vq_quantlist__44c1_s_p6_0,
  135053. NULL,
  135054. &_vq_auxt__44c1_s_p6_0,
  135055. NULL,
  135056. 0
  135057. };
  135058. static long _vq_quantlist__44c1_s_p6_1[] = {
  135059. 5,
  135060. 4,
  135061. 6,
  135062. 3,
  135063. 7,
  135064. 2,
  135065. 8,
  135066. 1,
  135067. 9,
  135068. 0,
  135069. 10,
  135070. };
  135071. static long _vq_lengthlist__44c1_s_p6_1[] = {
  135072. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  135073. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135074. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135075. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135076. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135077. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135078. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135079. 10,10,10, 8, 8, 8, 8, 8, 8,
  135080. };
  135081. static float _vq_quantthresh__44c1_s_p6_1[] = {
  135082. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135083. 3.5, 4.5,
  135084. };
  135085. static long _vq_quantmap__44c1_s_p6_1[] = {
  135086. 9, 7, 5, 3, 1, 0, 2, 4,
  135087. 6, 8, 10,
  135088. };
  135089. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  135090. _vq_quantthresh__44c1_s_p6_1,
  135091. _vq_quantmap__44c1_s_p6_1,
  135092. 11,
  135093. 11
  135094. };
  135095. static static_codebook _44c1_s_p6_1 = {
  135096. 2, 121,
  135097. _vq_lengthlist__44c1_s_p6_1,
  135098. 1, -531365888, 1611661312, 4, 0,
  135099. _vq_quantlist__44c1_s_p6_1,
  135100. NULL,
  135101. &_vq_auxt__44c1_s_p6_1,
  135102. NULL,
  135103. 0
  135104. };
  135105. static long _vq_quantlist__44c1_s_p7_0[] = {
  135106. 6,
  135107. 5,
  135108. 7,
  135109. 4,
  135110. 8,
  135111. 3,
  135112. 9,
  135113. 2,
  135114. 10,
  135115. 1,
  135116. 11,
  135117. 0,
  135118. 12,
  135119. };
  135120. static long _vq_lengthlist__44c1_s_p7_0[] = {
  135121. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  135122. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  135123. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135124. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135125. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  135126. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  135127. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  135128. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135129. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135130. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  135131. 0,12,11,11,11,13,10,14,13,
  135132. };
  135133. static float _vq_quantthresh__44c1_s_p7_0[] = {
  135134. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135135. 12.5, 17.5, 22.5, 27.5,
  135136. };
  135137. static long _vq_quantmap__44c1_s_p7_0[] = {
  135138. 11, 9, 7, 5, 3, 1, 0, 2,
  135139. 4, 6, 8, 10, 12,
  135140. };
  135141. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  135142. _vq_quantthresh__44c1_s_p7_0,
  135143. _vq_quantmap__44c1_s_p7_0,
  135144. 13,
  135145. 13
  135146. };
  135147. static static_codebook _44c1_s_p7_0 = {
  135148. 2, 169,
  135149. _vq_lengthlist__44c1_s_p7_0,
  135150. 1, -526516224, 1616117760, 4, 0,
  135151. _vq_quantlist__44c1_s_p7_0,
  135152. NULL,
  135153. &_vq_auxt__44c1_s_p7_0,
  135154. NULL,
  135155. 0
  135156. };
  135157. static long _vq_quantlist__44c1_s_p7_1[] = {
  135158. 2,
  135159. 1,
  135160. 3,
  135161. 0,
  135162. 4,
  135163. };
  135164. static long _vq_lengthlist__44c1_s_p7_1[] = {
  135165. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135166. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135167. };
  135168. static float _vq_quantthresh__44c1_s_p7_1[] = {
  135169. -1.5, -0.5, 0.5, 1.5,
  135170. };
  135171. static long _vq_quantmap__44c1_s_p7_1[] = {
  135172. 3, 1, 0, 2, 4,
  135173. };
  135174. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  135175. _vq_quantthresh__44c1_s_p7_1,
  135176. _vq_quantmap__44c1_s_p7_1,
  135177. 5,
  135178. 5
  135179. };
  135180. static static_codebook _44c1_s_p7_1 = {
  135181. 2, 25,
  135182. _vq_lengthlist__44c1_s_p7_1,
  135183. 1, -533725184, 1611661312, 3, 0,
  135184. _vq_quantlist__44c1_s_p7_1,
  135185. NULL,
  135186. &_vq_auxt__44c1_s_p7_1,
  135187. NULL,
  135188. 0
  135189. };
  135190. static long _vq_quantlist__44c1_s_p8_0[] = {
  135191. 6,
  135192. 5,
  135193. 7,
  135194. 4,
  135195. 8,
  135196. 3,
  135197. 9,
  135198. 2,
  135199. 10,
  135200. 1,
  135201. 11,
  135202. 0,
  135203. 12,
  135204. };
  135205. static long _vq_lengthlist__44c1_s_p8_0[] = {
  135206. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  135207. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  135208. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135209. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135210. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135211. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135212. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135213. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135214. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135215. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135216. 10,10,10,10,10,10,10,10,10,
  135217. };
  135218. static float _vq_quantthresh__44c1_s_p8_0[] = {
  135219. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135220. 552.5, 773.5, 994.5, 1215.5,
  135221. };
  135222. static long _vq_quantmap__44c1_s_p8_0[] = {
  135223. 11, 9, 7, 5, 3, 1, 0, 2,
  135224. 4, 6, 8, 10, 12,
  135225. };
  135226. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  135227. _vq_quantthresh__44c1_s_p8_0,
  135228. _vq_quantmap__44c1_s_p8_0,
  135229. 13,
  135230. 13
  135231. };
  135232. static static_codebook _44c1_s_p8_0 = {
  135233. 2, 169,
  135234. _vq_lengthlist__44c1_s_p8_0,
  135235. 1, -514541568, 1627103232, 4, 0,
  135236. _vq_quantlist__44c1_s_p8_0,
  135237. NULL,
  135238. &_vq_auxt__44c1_s_p8_0,
  135239. NULL,
  135240. 0
  135241. };
  135242. static long _vq_quantlist__44c1_s_p8_1[] = {
  135243. 6,
  135244. 5,
  135245. 7,
  135246. 4,
  135247. 8,
  135248. 3,
  135249. 9,
  135250. 2,
  135251. 10,
  135252. 1,
  135253. 11,
  135254. 0,
  135255. 12,
  135256. };
  135257. static long _vq_lengthlist__44c1_s_p8_1[] = {
  135258. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  135259. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  135260. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  135261. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  135262. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  135263. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  135264. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  135265. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  135266. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  135267. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  135268. 16,13,12,12,11,14,12,15,13,
  135269. };
  135270. static float _vq_quantthresh__44c1_s_p8_1[] = {
  135271. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135272. 42.5, 59.5, 76.5, 93.5,
  135273. };
  135274. static long _vq_quantmap__44c1_s_p8_1[] = {
  135275. 11, 9, 7, 5, 3, 1, 0, 2,
  135276. 4, 6, 8, 10, 12,
  135277. };
  135278. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  135279. _vq_quantthresh__44c1_s_p8_1,
  135280. _vq_quantmap__44c1_s_p8_1,
  135281. 13,
  135282. 13
  135283. };
  135284. static static_codebook _44c1_s_p8_1 = {
  135285. 2, 169,
  135286. _vq_lengthlist__44c1_s_p8_1,
  135287. 1, -522616832, 1620115456, 4, 0,
  135288. _vq_quantlist__44c1_s_p8_1,
  135289. NULL,
  135290. &_vq_auxt__44c1_s_p8_1,
  135291. NULL,
  135292. 0
  135293. };
  135294. static long _vq_quantlist__44c1_s_p8_2[] = {
  135295. 8,
  135296. 7,
  135297. 9,
  135298. 6,
  135299. 10,
  135300. 5,
  135301. 11,
  135302. 4,
  135303. 12,
  135304. 3,
  135305. 13,
  135306. 2,
  135307. 14,
  135308. 1,
  135309. 15,
  135310. 0,
  135311. 16,
  135312. };
  135313. static long _vq_lengthlist__44c1_s_p8_2[] = {
  135314. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135315. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135316. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  135317. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135318. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135319. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135320. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135321. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  135322. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  135323. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135324. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  135325. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135326. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  135327. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  135328. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135329. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  135330. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135331. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  135332. 9,
  135333. };
  135334. static float _vq_quantthresh__44c1_s_p8_2[] = {
  135335. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135336. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135337. };
  135338. static long _vq_quantmap__44c1_s_p8_2[] = {
  135339. 15, 13, 11, 9, 7, 5, 3, 1,
  135340. 0, 2, 4, 6, 8, 10, 12, 14,
  135341. 16,
  135342. };
  135343. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  135344. _vq_quantthresh__44c1_s_p8_2,
  135345. _vq_quantmap__44c1_s_p8_2,
  135346. 17,
  135347. 17
  135348. };
  135349. static static_codebook _44c1_s_p8_2 = {
  135350. 2, 289,
  135351. _vq_lengthlist__44c1_s_p8_2,
  135352. 1, -529530880, 1611661312, 5, 0,
  135353. _vq_quantlist__44c1_s_p8_2,
  135354. NULL,
  135355. &_vq_auxt__44c1_s_p8_2,
  135356. NULL,
  135357. 0
  135358. };
  135359. static long _huff_lengthlist__44c1_s_short[] = {
  135360. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  135361. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  135362. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  135363. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  135364. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  135365. 11,
  135366. };
  135367. static static_codebook _huff_book__44c1_s_short = {
  135368. 2, 81,
  135369. _huff_lengthlist__44c1_s_short,
  135370. 0, 0, 0, 0, 0,
  135371. NULL,
  135372. NULL,
  135373. NULL,
  135374. NULL,
  135375. 0
  135376. };
  135377. static long _huff_lengthlist__44c1_sm_long[] = {
  135378. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  135379. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  135380. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  135381. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  135382. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  135383. 11,
  135384. };
  135385. static static_codebook _huff_book__44c1_sm_long = {
  135386. 2, 81,
  135387. _huff_lengthlist__44c1_sm_long,
  135388. 0, 0, 0, 0, 0,
  135389. NULL,
  135390. NULL,
  135391. NULL,
  135392. NULL,
  135393. 0
  135394. };
  135395. static long _vq_quantlist__44c1_sm_p1_0[] = {
  135396. 1,
  135397. 0,
  135398. 2,
  135399. };
  135400. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  135401. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135402. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135407. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135412. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  135447. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135452. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  135457. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135493. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135498. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135503. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0,
  135812. };
  135813. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  135814. -0.5, 0.5,
  135815. };
  135816. static long _vq_quantmap__44c1_sm_p1_0[] = {
  135817. 1, 0, 2,
  135818. };
  135819. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  135820. _vq_quantthresh__44c1_sm_p1_0,
  135821. _vq_quantmap__44c1_sm_p1_0,
  135822. 3,
  135823. 3
  135824. };
  135825. static static_codebook _44c1_sm_p1_0 = {
  135826. 8, 6561,
  135827. _vq_lengthlist__44c1_sm_p1_0,
  135828. 1, -535822336, 1611661312, 2, 0,
  135829. _vq_quantlist__44c1_sm_p1_0,
  135830. NULL,
  135831. &_vq_auxt__44c1_sm_p1_0,
  135832. NULL,
  135833. 0
  135834. };
  135835. static long _vq_quantlist__44c1_sm_p2_0[] = {
  135836. 2,
  135837. 1,
  135838. 3,
  135839. 0,
  135840. 4,
  135841. };
  135842. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  135843. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0,
  135883. };
  135884. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  135885. -1.5, -0.5, 0.5, 1.5,
  135886. };
  135887. static long _vq_quantmap__44c1_sm_p2_0[] = {
  135888. 3, 1, 0, 2, 4,
  135889. };
  135890. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  135891. _vq_quantthresh__44c1_sm_p2_0,
  135892. _vq_quantmap__44c1_sm_p2_0,
  135893. 5,
  135894. 5
  135895. };
  135896. static static_codebook _44c1_sm_p2_0 = {
  135897. 4, 625,
  135898. _vq_lengthlist__44c1_sm_p2_0,
  135899. 1, -533725184, 1611661312, 3, 0,
  135900. _vq_quantlist__44c1_sm_p2_0,
  135901. NULL,
  135902. &_vq_auxt__44c1_sm_p2_0,
  135903. NULL,
  135904. 0
  135905. };
  135906. static long _vq_quantlist__44c1_sm_p3_0[] = {
  135907. 4,
  135908. 3,
  135909. 5,
  135910. 2,
  135911. 6,
  135912. 1,
  135913. 7,
  135914. 0,
  135915. 8,
  135916. };
  135917. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  135918. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  135919. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  135920. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135921. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135922. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0,
  135924. };
  135925. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  135926. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135927. };
  135928. static long _vq_quantmap__44c1_sm_p3_0[] = {
  135929. 7, 5, 3, 1, 0, 2, 4, 6,
  135930. 8,
  135931. };
  135932. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  135933. _vq_quantthresh__44c1_sm_p3_0,
  135934. _vq_quantmap__44c1_sm_p3_0,
  135935. 9,
  135936. 9
  135937. };
  135938. static static_codebook _44c1_sm_p3_0 = {
  135939. 2, 81,
  135940. _vq_lengthlist__44c1_sm_p3_0,
  135941. 1, -531628032, 1611661312, 4, 0,
  135942. _vq_quantlist__44c1_sm_p3_0,
  135943. NULL,
  135944. &_vq_auxt__44c1_sm_p3_0,
  135945. NULL,
  135946. 0
  135947. };
  135948. static long _vq_quantlist__44c1_sm_p4_0[] = {
  135949. 4,
  135950. 3,
  135951. 5,
  135952. 2,
  135953. 6,
  135954. 1,
  135955. 7,
  135956. 0,
  135957. 8,
  135958. };
  135959. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  135960. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  135961. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135962. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135963. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  135964. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135965. 11,
  135966. };
  135967. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  135968. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135969. };
  135970. static long _vq_quantmap__44c1_sm_p4_0[] = {
  135971. 7, 5, 3, 1, 0, 2, 4, 6,
  135972. 8,
  135973. };
  135974. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  135975. _vq_quantthresh__44c1_sm_p4_0,
  135976. _vq_quantmap__44c1_sm_p4_0,
  135977. 9,
  135978. 9
  135979. };
  135980. static static_codebook _44c1_sm_p4_0 = {
  135981. 2, 81,
  135982. _vq_lengthlist__44c1_sm_p4_0,
  135983. 1, -531628032, 1611661312, 4, 0,
  135984. _vq_quantlist__44c1_sm_p4_0,
  135985. NULL,
  135986. &_vq_auxt__44c1_sm_p4_0,
  135987. NULL,
  135988. 0
  135989. };
  135990. static long _vq_quantlist__44c1_sm_p5_0[] = {
  135991. 8,
  135992. 7,
  135993. 9,
  135994. 6,
  135995. 10,
  135996. 5,
  135997. 11,
  135998. 4,
  135999. 12,
  136000. 3,
  136001. 13,
  136002. 2,
  136003. 14,
  136004. 1,
  136005. 15,
  136006. 0,
  136007. 16,
  136008. };
  136009. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  136010. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136011. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136012. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  136013. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136014. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136015. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  136016. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  136017. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136018. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136019. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136020. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136021. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136022. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  136023. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136024. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  136025. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  136026. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136028. 14,
  136029. };
  136030. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  136031. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136032. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136033. };
  136034. static long _vq_quantmap__44c1_sm_p5_0[] = {
  136035. 15, 13, 11, 9, 7, 5, 3, 1,
  136036. 0, 2, 4, 6, 8, 10, 12, 14,
  136037. 16,
  136038. };
  136039. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  136040. _vq_quantthresh__44c1_sm_p5_0,
  136041. _vq_quantmap__44c1_sm_p5_0,
  136042. 17,
  136043. 17
  136044. };
  136045. static static_codebook _44c1_sm_p5_0 = {
  136046. 2, 289,
  136047. _vq_lengthlist__44c1_sm_p5_0,
  136048. 1, -529530880, 1611661312, 5, 0,
  136049. _vq_quantlist__44c1_sm_p5_0,
  136050. NULL,
  136051. &_vq_auxt__44c1_sm_p5_0,
  136052. NULL,
  136053. 0
  136054. };
  136055. static long _vq_quantlist__44c1_sm_p6_0[] = {
  136056. 1,
  136057. 0,
  136058. 2,
  136059. };
  136060. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  136061. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136062. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136063. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136064. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  136065. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  136066. 11,
  136067. };
  136068. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  136069. -5.5, 5.5,
  136070. };
  136071. static long _vq_quantmap__44c1_sm_p6_0[] = {
  136072. 1, 0, 2,
  136073. };
  136074. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  136075. _vq_quantthresh__44c1_sm_p6_0,
  136076. _vq_quantmap__44c1_sm_p6_0,
  136077. 3,
  136078. 3
  136079. };
  136080. static static_codebook _44c1_sm_p6_0 = {
  136081. 4, 81,
  136082. _vq_lengthlist__44c1_sm_p6_0,
  136083. 1, -529137664, 1618345984, 2, 0,
  136084. _vq_quantlist__44c1_sm_p6_0,
  136085. NULL,
  136086. &_vq_auxt__44c1_sm_p6_0,
  136087. NULL,
  136088. 0
  136089. };
  136090. static long _vq_quantlist__44c1_sm_p6_1[] = {
  136091. 5,
  136092. 4,
  136093. 6,
  136094. 3,
  136095. 7,
  136096. 2,
  136097. 8,
  136098. 1,
  136099. 9,
  136100. 0,
  136101. 10,
  136102. };
  136103. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  136104. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  136105. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136106. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136107. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  136108. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136109. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  136110. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136111. 10,10,10, 8, 8, 8, 8, 8, 8,
  136112. };
  136113. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  136114. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136115. 3.5, 4.5,
  136116. };
  136117. static long _vq_quantmap__44c1_sm_p6_1[] = {
  136118. 9, 7, 5, 3, 1, 0, 2, 4,
  136119. 6, 8, 10,
  136120. };
  136121. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  136122. _vq_quantthresh__44c1_sm_p6_1,
  136123. _vq_quantmap__44c1_sm_p6_1,
  136124. 11,
  136125. 11
  136126. };
  136127. static static_codebook _44c1_sm_p6_1 = {
  136128. 2, 121,
  136129. _vq_lengthlist__44c1_sm_p6_1,
  136130. 1, -531365888, 1611661312, 4, 0,
  136131. _vq_quantlist__44c1_sm_p6_1,
  136132. NULL,
  136133. &_vq_auxt__44c1_sm_p6_1,
  136134. NULL,
  136135. 0
  136136. };
  136137. static long _vq_quantlist__44c1_sm_p7_0[] = {
  136138. 6,
  136139. 5,
  136140. 7,
  136141. 4,
  136142. 8,
  136143. 3,
  136144. 9,
  136145. 2,
  136146. 10,
  136147. 1,
  136148. 11,
  136149. 0,
  136150. 12,
  136151. };
  136152. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  136153. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136154. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136155. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136156. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136157. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136158. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  136159. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  136160. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136161. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136162. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  136163. 0,12,12,11,11,13,12,14,13,
  136164. };
  136165. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  136166. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136167. 12.5, 17.5, 22.5, 27.5,
  136168. };
  136169. static long _vq_quantmap__44c1_sm_p7_0[] = {
  136170. 11, 9, 7, 5, 3, 1, 0, 2,
  136171. 4, 6, 8, 10, 12,
  136172. };
  136173. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  136174. _vq_quantthresh__44c1_sm_p7_0,
  136175. _vq_quantmap__44c1_sm_p7_0,
  136176. 13,
  136177. 13
  136178. };
  136179. static static_codebook _44c1_sm_p7_0 = {
  136180. 2, 169,
  136181. _vq_lengthlist__44c1_sm_p7_0,
  136182. 1, -526516224, 1616117760, 4, 0,
  136183. _vq_quantlist__44c1_sm_p7_0,
  136184. NULL,
  136185. &_vq_auxt__44c1_sm_p7_0,
  136186. NULL,
  136187. 0
  136188. };
  136189. static long _vq_quantlist__44c1_sm_p7_1[] = {
  136190. 2,
  136191. 1,
  136192. 3,
  136193. 0,
  136194. 4,
  136195. };
  136196. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  136197. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136198. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  136199. };
  136200. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  136201. -1.5, -0.5, 0.5, 1.5,
  136202. };
  136203. static long _vq_quantmap__44c1_sm_p7_1[] = {
  136204. 3, 1, 0, 2, 4,
  136205. };
  136206. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  136207. _vq_quantthresh__44c1_sm_p7_1,
  136208. _vq_quantmap__44c1_sm_p7_1,
  136209. 5,
  136210. 5
  136211. };
  136212. static static_codebook _44c1_sm_p7_1 = {
  136213. 2, 25,
  136214. _vq_lengthlist__44c1_sm_p7_1,
  136215. 1, -533725184, 1611661312, 3, 0,
  136216. _vq_quantlist__44c1_sm_p7_1,
  136217. NULL,
  136218. &_vq_auxt__44c1_sm_p7_1,
  136219. NULL,
  136220. 0
  136221. };
  136222. static long _vq_quantlist__44c1_sm_p8_0[] = {
  136223. 6,
  136224. 5,
  136225. 7,
  136226. 4,
  136227. 8,
  136228. 3,
  136229. 9,
  136230. 2,
  136231. 10,
  136232. 1,
  136233. 11,
  136234. 0,
  136235. 12,
  136236. };
  136237. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  136238. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  136239. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  136240. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136241. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136242. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136243. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136244. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136245. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136246. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136247. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136248. 13,13,13,13,13,13,13,13,13,
  136249. };
  136250. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  136251. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  136252. 552.5, 773.5, 994.5, 1215.5,
  136253. };
  136254. static long _vq_quantmap__44c1_sm_p8_0[] = {
  136255. 11, 9, 7, 5, 3, 1, 0, 2,
  136256. 4, 6, 8, 10, 12,
  136257. };
  136258. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  136259. _vq_quantthresh__44c1_sm_p8_0,
  136260. _vq_quantmap__44c1_sm_p8_0,
  136261. 13,
  136262. 13
  136263. };
  136264. static static_codebook _44c1_sm_p8_0 = {
  136265. 2, 169,
  136266. _vq_lengthlist__44c1_sm_p8_0,
  136267. 1, -514541568, 1627103232, 4, 0,
  136268. _vq_quantlist__44c1_sm_p8_0,
  136269. NULL,
  136270. &_vq_auxt__44c1_sm_p8_0,
  136271. NULL,
  136272. 0
  136273. };
  136274. static long _vq_quantlist__44c1_sm_p8_1[] = {
  136275. 6,
  136276. 5,
  136277. 7,
  136278. 4,
  136279. 8,
  136280. 3,
  136281. 9,
  136282. 2,
  136283. 10,
  136284. 1,
  136285. 11,
  136286. 0,
  136287. 12,
  136288. };
  136289. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  136290. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136291. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  136292. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  136293. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  136294. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  136295. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  136296. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  136297. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  136298. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  136299. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  136300. 20,13,12,12,12,14,12,14,13,
  136301. };
  136302. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  136303. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136304. 42.5, 59.5, 76.5, 93.5,
  136305. };
  136306. static long _vq_quantmap__44c1_sm_p8_1[] = {
  136307. 11, 9, 7, 5, 3, 1, 0, 2,
  136308. 4, 6, 8, 10, 12,
  136309. };
  136310. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  136311. _vq_quantthresh__44c1_sm_p8_1,
  136312. _vq_quantmap__44c1_sm_p8_1,
  136313. 13,
  136314. 13
  136315. };
  136316. static static_codebook _44c1_sm_p8_1 = {
  136317. 2, 169,
  136318. _vq_lengthlist__44c1_sm_p8_1,
  136319. 1, -522616832, 1620115456, 4, 0,
  136320. _vq_quantlist__44c1_sm_p8_1,
  136321. NULL,
  136322. &_vq_auxt__44c1_sm_p8_1,
  136323. NULL,
  136324. 0
  136325. };
  136326. static long _vq_quantlist__44c1_sm_p8_2[] = {
  136327. 8,
  136328. 7,
  136329. 9,
  136330. 6,
  136331. 10,
  136332. 5,
  136333. 11,
  136334. 4,
  136335. 12,
  136336. 3,
  136337. 13,
  136338. 2,
  136339. 14,
  136340. 1,
  136341. 15,
  136342. 0,
  136343. 16,
  136344. };
  136345. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  136346. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136347. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136348. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136349. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136350. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136351. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136352. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136353. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136354. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  136355. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  136356. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  136357. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  136358. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  136359. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  136360. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136361. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  136362. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  136363. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  136364. 9,
  136365. };
  136366. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  136367. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136368. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136369. };
  136370. static long _vq_quantmap__44c1_sm_p8_2[] = {
  136371. 15, 13, 11, 9, 7, 5, 3, 1,
  136372. 0, 2, 4, 6, 8, 10, 12, 14,
  136373. 16,
  136374. };
  136375. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  136376. _vq_quantthresh__44c1_sm_p8_2,
  136377. _vq_quantmap__44c1_sm_p8_2,
  136378. 17,
  136379. 17
  136380. };
  136381. static static_codebook _44c1_sm_p8_2 = {
  136382. 2, 289,
  136383. _vq_lengthlist__44c1_sm_p8_2,
  136384. 1, -529530880, 1611661312, 5, 0,
  136385. _vq_quantlist__44c1_sm_p8_2,
  136386. NULL,
  136387. &_vq_auxt__44c1_sm_p8_2,
  136388. NULL,
  136389. 0
  136390. };
  136391. static long _huff_lengthlist__44c1_sm_short[] = {
  136392. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  136393. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  136394. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  136395. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  136396. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  136397. 11,
  136398. };
  136399. static static_codebook _huff_book__44c1_sm_short = {
  136400. 2, 81,
  136401. _huff_lengthlist__44c1_sm_short,
  136402. 0, 0, 0, 0, 0,
  136403. NULL,
  136404. NULL,
  136405. NULL,
  136406. NULL,
  136407. 0
  136408. };
  136409. static long _huff_lengthlist__44cn1_s_long[] = {
  136410. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  136411. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  136412. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  136413. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  136414. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  136415. 20,
  136416. };
  136417. static static_codebook _huff_book__44cn1_s_long = {
  136418. 2, 81,
  136419. _huff_lengthlist__44cn1_s_long,
  136420. 0, 0, 0, 0, 0,
  136421. NULL,
  136422. NULL,
  136423. NULL,
  136424. NULL,
  136425. 0
  136426. };
  136427. static long _vq_quantlist__44cn1_s_p1_0[] = {
  136428. 1,
  136429. 0,
  136430. 2,
  136431. };
  136432. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  136433. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136434. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136439. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  136444. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  136479. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  136484. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  136489. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  136525. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  136530. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  136535. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0,
  136844. };
  136845. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  136846. -0.5, 0.5,
  136847. };
  136848. static long _vq_quantmap__44cn1_s_p1_0[] = {
  136849. 1, 0, 2,
  136850. };
  136851. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  136852. _vq_quantthresh__44cn1_s_p1_0,
  136853. _vq_quantmap__44cn1_s_p1_0,
  136854. 3,
  136855. 3
  136856. };
  136857. static static_codebook _44cn1_s_p1_0 = {
  136858. 8, 6561,
  136859. _vq_lengthlist__44cn1_s_p1_0,
  136860. 1, -535822336, 1611661312, 2, 0,
  136861. _vq_quantlist__44cn1_s_p1_0,
  136862. NULL,
  136863. &_vq_auxt__44cn1_s_p1_0,
  136864. NULL,
  136865. 0
  136866. };
  136867. static long _vq_quantlist__44cn1_s_p2_0[] = {
  136868. 2,
  136869. 1,
  136870. 3,
  136871. 0,
  136872. 4,
  136873. };
  136874. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  136875. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0,
  136915. };
  136916. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  136917. -1.5, -0.5, 0.5, 1.5,
  136918. };
  136919. static long _vq_quantmap__44cn1_s_p2_0[] = {
  136920. 3, 1, 0, 2, 4,
  136921. };
  136922. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  136923. _vq_quantthresh__44cn1_s_p2_0,
  136924. _vq_quantmap__44cn1_s_p2_0,
  136925. 5,
  136926. 5
  136927. };
  136928. static static_codebook _44cn1_s_p2_0 = {
  136929. 4, 625,
  136930. _vq_lengthlist__44cn1_s_p2_0,
  136931. 1, -533725184, 1611661312, 3, 0,
  136932. _vq_quantlist__44cn1_s_p2_0,
  136933. NULL,
  136934. &_vq_auxt__44cn1_s_p2_0,
  136935. NULL,
  136936. 0
  136937. };
  136938. static long _vq_quantlist__44cn1_s_p3_0[] = {
  136939. 4,
  136940. 3,
  136941. 5,
  136942. 2,
  136943. 6,
  136944. 1,
  136945. 7,
  136946. 0,
  136947. 8,
  136948. };
  136949. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  136950. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136951. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136952. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136953. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136954. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0,
  136956. };
  136957. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  136958. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136959. };
  136960. static long _vq_quantmap__44cn1_s_p3_0[] = {
  136961. 7, 5, 3, 1, 0, 2, 4, 6,
  136962. 8,
  136963. };
  136964. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  136965. _vq_quantthresh__44cn1_s_p3_0,
  136966. _vq_quantmap__44cn1_s_p3_0,
  136967. 9,
  136968. 9
  136969. };
  136970. static static_codebook _44cn1_s_p3_0 = {
  136971. 2, 81,
  136972. _vq_lengthlist__44cn1_s_p3_0,
  136973. 1, -531628032, 1611661312, 4, 0,
  136974. _vq_quantlist__44cn1_s_p3_0,
  136975. NULL,
  136976. &_vq_auxt__44cn1_s_p3_0,
  136977. NULL,
  136978. 0
  136979. };
  136980. static long _vq_quantlist__44cn1_s_p4_0[] = {
  136981. 4,
  136982. 3,
  136983. 5,
  136984. 2,
  136985. 6,
  136986. 1,
  136987. 7,
  136988. 0,
  136989. 8,
  136990. };
  136991. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  136992. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  136993. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136994. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  136995. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136996. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136997. 11,
  136998. };
  136999. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  137000. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137001. };
  137002. static long _vq_quantmap__44cn1_s_p4_0[] = {
  137003. 7, 5, 3, 1, 0, 2, 4, 6,
  137004. 8,
  137005. };
  137006. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  137007. _vq_quantthresh__44cn1_s_p4_0,
  137008. _vq_quantmap__44cn1_s_p4_0,
  137009. 9,
  137010. 9
  137011. };
  137012. static static_codebook _44cn1_s_p4_0 = {
  137013. 2, 81,
  137014. _vq_lengthlist__44cn1_s_p4_0,
  137015. 1, -531628032, 1611661312, 4, 0,
  137016. _vq_quantlist__44cn1_s_p4_0,
  137017. NULL,
  137018. &_vq_auxt__44cn1_s_p4_0,
  137019. NULL,
  137020. 0
  137021. };
  137022. static long _vq_quantlist__44cn1_s_p5_0[] = {
  137023. 8,
  137024. 7,
  137025. 9,
  137026. 6,
  137027. 10,
  137028. 5,
  137029. 11,
  137030. 4,
  137031. 12,
  137032. 3,
  137033. 13,
  137034. 2,
  137035. 14,
  137036. 1,
  137037. 15,
  137038. 0,
  137039. 16,
  137040. };
  137041. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  137042. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  137043. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137044. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137045. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137046. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137047. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  137048. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  137049. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  137050. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137051. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137052. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137053. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137054. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  137055. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137056. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  137057. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  137058. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  137060. 14,
  137061. };
  137062. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  137063. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137064. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137065. };
  137066. static long _vq_quantmap__44cn1_s_p5_0[] = {
  137067. 15, 13, 11, 9, 7, 5, 3, 1,
  137068. 0, 2, 4, 6, 8, 10, 12, 14,
  137069. 16,
  137070. };
  137071. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  137072. _vq_quantthresh__44cn1_s_p5_0,
  137073. _vq_quantmap__44cn1_s_p5_0,
  137074. 17,
  137075. 17
  137076. };
  137077. static static_codebook _44cn1_s_p5_0 = {
  137078. 2, 289,
  137079. _vq_lengthlist__44cn1_s_p5_0,
  137080. 1, -529530880, 1611661312, 5, 0,
  137081. _vq_quantlist__44cn1_s_p5_0,
  137082. NULL,
  137083. &_vq_auxt__44cn1_s_p5_0,
  137084. NULL,
  137085. 0
  137086. };
  137087. static long _vq_quantlist__44cn1_s_p6_0[] = {
  137088. 1,
  137089. 0,
  137090. 2,
  137091. };
  137092. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  137093. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  137094. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  137095. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  137096. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  137097. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  137098. 10,
  137099. };
  137100. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  137101. -5.5, 5.5,
  137102. };
  137103. static long _vq_quantmap__44cn1_s_p6_0[] = {
  137104. 1, 0, 2,
  137105. };
  137106. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  137107. _vq_quantthresh__44cn1_s_p6_0,
  137108. _vq_quantmap__44cn1_s_p6_0,
  137109. 3,
  137110. 3
  137111. };
  137112. static static_codebook _44cn1_s_p6_0 = {
  137113. 4, 81,
  137114. _vq_lengthlist__44cn1_s_p6_0,
  137115. 1, -529137664, 1618345984, 2, 0,
  137116. _vq_quantlist__44cn1_s_p6_0,
  137117. NULL,
  137118. &_vq_auxt__44cn1_s_p6_0,
  137119. NULL,
  137120. 0
  137121. };
  137122. static long _vq_quantlist__44cn1_s_p6_1[] = {
  137123. 5,
  137124. 4,
  137125. 6,
  137126. 3,
  137127. 7,
  137128. 2,
  137129. 8,
  137130. 1,
  137131. 9,
  137132. 0,
  137133. 10,
  137134. };
  137135. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  137136. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  137137. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  137138. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137139. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  137140. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  137141. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  137142. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  137143. 10,10,10, 9, 9, 9, 9, 9, 9,
  137144. };
  137145. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  137146. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137147. 3.5, 4.5,
  137148. };
  137149. static long _vq_quantmap__44cn1_s_p6_1[] = {
  137150. 9, 7, 5, 3, 1, 0, 2, 4,
  137151. 6, 8, 10,
  137152. };
  137153. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  137154. _vq_quantthresh__44cn1_s_p6_1,
  137155. _vq_quantmap__44cn1_s_p6_1,
  137156. 11,
  137157. 11
  137158. };
  137159. static static_codebook _44cn1_s_p6_1 = {
  137160. 2, 121,
  137161. _vq_lengthlist__44cn1_s_p6_1,
  137162. 1, -531365888, 1611661312, 4, 0,
  137163. _vq_quantlist__44cn1_s_p6_1,
  137164. NULL,
  137165. &_vq_auxt__44cn1_s_p6_1,
  137166. NULL,
  137167. 0
  137168. };
  137169. static long _vq_quantlist__44cn1_s_p7_0[] = {
  137170. 6,
  137171. 5,
  137172. 7,
  137173. 4,
  137174. 8,
  137175. 3,
  137176. 9,
  137177. 2,
  137178. 10,
  137179. 1,
  137180. 11,
  137181. 0,
  137182. 12,
  137183. };
  137184. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  137185. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  137186. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  137187. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137188. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137189. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  137190. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  137191. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137192. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  137193. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  137194. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  137195. 0,13,13,12,12,13,13,13,14,
  137196. };
  137197. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  137198. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137199. 12.5, 17.5, 22.5, 27.5,
  137200. };
  137201. static long _vq_quantmap__44cn1_s_p7_0[] = {
  137202. 11, 9, 7, 5, 3, 1, 0, 2,
  137203. 4, 6, 8, 10, 12,
  137204. };
  137205. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  137206. _vq_quantthresh__44cn1_s_p7_0,
  137207. _vq_quantmap__44cn1_s_p7_0,
  137208. 13,
  137209. 13
  137210. };
  137211. static static_codebook _44cn1_s_p7_0 = {
  137212. 2, 169,
  137213. _vq_lengthlist__44cn1_s_p7_0,
  137214. 1, -526516224, 1616117760, 4, 0,
  137215. _vq_quantlist__44cn1_s_p7_0,
  137216. NULL,
  137217. &_vq_auxt__44cn1_s_p7_0,
  137218. NULL,
  137219. 0
  137220. };
  137221. static long _vq_quantlist__44cn1_s_p7_1[] = {
  137222. 2,
  137223. 1,
  137224. 3,
  137225. 0,
  137226. 4,
  137227. };
  137228. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  137229. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137230. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137231. };
  137232. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  137233. -1.5, -0.5, 0.5, 1.5,
  137234. };
  137235. static long _vq_quantmap__44cn1_s_p7_1[] = {
  137236. 3, 1, 0, 2, 4,
  137237. };
  137238. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  137239. _vq_quantthresh__44cn1_s_p7_1,
  137240. _vq_quantmap__44cn1_s_p7_1,
  137241. 5,
  137242. 5
  137243. };
  137244. static static_codebook _44cn1_s_p7_1 = {
  137245. 2, 25,
  137246. _vq_lengthlist__44cn1_s_p7_1,
  137247. 1, -533725184, 1611661312, 3, 0,
  137248. _vq_quantlist__44cn1_s_p7_1,
  137249. NULL,
  137250. &_vq_auxt__44cn1_s_p7_1,
  137251. NULL,
  137252. 0
  137253. };
  137254. static long _vq_quantlist__44cn1_s_p8_0[] = {
  137255. 2,
  137256. 1,
  137257. 3,
  137258. 0,
  137259. 4,
  137260. };
  137261. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  137262. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  137263. 11,11,11,11,11,11,11,11,11,11,11,10,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,10,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, 7,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,10,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,10,
  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, 8,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,11,11,11,11,11,11,11,11,11,
  137280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137295. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  137296. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137297. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137298. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137299. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137300. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137301. 12,
  137302. };
  137303. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  137304. -331.5, -110.5, 110.5, 331.5,
  137305. };
  137306. static long _vq_quantmap__44cn1_s_p8_0[] = {
  137307. 3, 1, 0, 2, 4,
  137308. };
  137309. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  137310. _vq_quantthresh__44cn1_s_p8_0,
  137311. _vq_quantmap__44cn1_s_p8_0,
  137312. 5,
  137313. 5
  137314. };
  137315. static static_codebook _44cn1_s_p8_0 = {
  137316. 4, 625,
  137317. _vq_lengthlist__44cn1_s_p8_0,
  137318. 1, -518283264, 1627103232, 3, 0,
  137319. _vq_quantlist__44cn1_s_p8_0,
  137320. NULL,
  137321. &_vq_auxt__44cn1_s_p8_0,
  137322. NULL,
  137323. 0
  137324. };
  137325. static long _vq_quantlist__44cn1_s_p8_1[] = {
  137326. 6,
  137327. 5,
  137328. 7,
  137329. 4,
  137330. 8,
  137331. 3,
  137332. 9,
  137333. 2,
  137334. 10,
  137335. 1,
  137336. 11,
  137337. 0,
  137338. 12,
  137339. };
  137340. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  137341. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  137342. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  137343. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  137344. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  137345. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  137346. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  137347. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  137348. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  137349. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  137350. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  137351. 15,12,12,11,11,14,12,13,14,
  137352. };
  137353. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  137354. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137355. 42.5, 59.5, 76.5, 93.5,
  137356. };
  137357. static long _vq_quantmap__44cn1_s_p8_1[] = {
  137358. 11, 9, 7, 5, 3, 1, 0, 2,
  137359. 4, 6, 8, 10, 12,
  137360. };
  137361. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  137362. _vq_quantthresh__44cn1_s_p8_1,
  137363. _vq_quantmap__44cn1_s_p8_1,
  137364. 13,
  137365. 13
  137366. };
  137367. static static_codebook _44cn1_s_p8_1 = {
  137368. 2, 169,
  137369. _vq_lengthlist__44cn1_s_p8_1,
  137370. 1, -522616832, 1620115456, 4, 0,
  137371. _vq_quantlist__44cn1_s_p8_1,
  137372. NULL,
  137373. &_vq_auxt__44cn1_s_p8_1,
  137374. NULL,
  137375. 0
  137376. };
  137377. static long _vq_quantlist__44cn1_s_p8_2[] = {
  137378. 8,
  137379. 7,
  137380. 9,
  137381. 6,
  137382. 10,
  137383. 5,
  137384. 11,
  137385. 4,
  137386. 12,
  137387. 3,
  137388. 13,
  137389. 2,
  137390. 14,
  137391. 1,
  137392. 15,
  137393. 0,
  137394. 16,
  137395. };
  137396. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  137397. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  137398. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137399. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137400. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  137401. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  137402. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  137403. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  137404. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  137405. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  137406. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  137407. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  137408. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137409. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  137410. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  137411. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  137412. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137413. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137414. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  137415. 9,
  137416. };
  137417. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  137418. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137419. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137420. };
  137421. static long _vq_quantmap__44cn1_s_p8_2[] = {
  137422. 15, 13, 11, 9, 7, 5, 3, 1,
  137423. 0, 2, 4, 6, 8, 10, 12, 14,
  137424. 16,
  137425. };
  137426. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  137427. _vq_quantthresh__44cn1_s_p8_2,
  137428. _vq_quantmap__44cn1_s_p8_2,
  137429. 17,
  137430. 17
  137431. };
  137432. static static_codebook _44cn1_s_p8_2 = {
  137433. 2, 289,
  137434. _vq_lengthlist__44cn1_s_p8_2,
  137435. 1, -529530880, 1611661312, 5, 0,
  137436. _vq_quantlist__44cn1_s_p8_2,
  137437. NULL,
  137438. &_vq_auxt__44cn1_s_p8_2,
  137439. NULL,
  137440. 0
  137441. };
  137442. static long _huff_lengthlist__44cn1_s_short[] = {
  137443. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  137444. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  137445. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  137446. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  137447. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  137448. 10,
  137449. };
  137450. static static_codebook _huff_book__44cn1_s_short = {
  137451. 2, 81,
  137452. _huff_lengthlist__44cn1_s_short,
  137453. 0, 0, 0, 0, 0,
  137454. NULL,
  137455. NULL,
  137456. NULL,
  137457. NULL,
  137458. 0
  137459. };
  137460. static long _huff_lengthlist__44cn1_sm_long[] = {
  137461. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  137462. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  137463. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  137464. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  137465. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  137466. 17,
  137467. };
  137468. static static_codebook _huff_book__44cn1_sm_long = {
  137469. 2, 81,
  137470. _huff_lengthlist__44cn1_sm_long,
  137471. 0, 0, 0, 0, 0,
  137472. NULL,
  137473. NULL,
  137474. NULL,
  137475. NULL,
  137476. 0
  137477. };
  137478. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  137479. 1,
  137480. 0,
  137481. 2,
  137482. };
  137483. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  137484. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137485. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  137490. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137495. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  137530. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  137535. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137540. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137576. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137581. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  137586. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0,
  137895. };
  137896. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  137897. -0.5, 0.5,
  137898. };
  137899. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  137900. 1, 0, 2,
  137901. };
  137902. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  137903. _vq_quantthresh__44cn1_sm_p1_0,
  137904. _vq_quantmap__44cn1_sm_p1_0,
  137905. 3,
  137906. 3
  137907. };
  137908. static static_codebook _44cn1_sm_p1_0 = {
  137909. 8, 6561,
  137910. _vq_lengthlist__44cn1_sm_p1_0,
  137911. 1, -535822336, 1611661312, 2, 0,
  137912. _vq_quantlist__44cn1_sm_p1_0,
  137913. NULL,
  137914. &_vq_auxt__44cn1_sm_p1_0,
  137915. NULL,
  137916. 0
  137917. };
  137918. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  137919. 2,
  137920. 1,
  137921. 3,
  137922. 0,
  137923. 4,
  137924. };
  137925. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  137926. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0,
  137966. };
  137967. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  137968. -1.5, -0.5, 0.5, 1.5,
  137969. };
  137970. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  137971. 3, 1, 0, 2, 4,
  137972. };
  137973. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  137974. _vq_quantthresh__44cn1_sm_p2_0,
  137975. _vq_quantmap__44cn1_sm_p2_0,
  137976. 5,
  137977. 5
  137978. };
  137979. static static_codebook _44cn1_sm_p2_0 = {
  137980. 4, 625,
  137981. _vq_lengthlist__44cn1_sm_p2_0,
  137982. 1, -533725184, 1611661312, 3, 0,
  137983. _vq_quantlist__44cn1_sm_p2_0,
  137984. NULL,
  137985. &_vq_auxt__44cn1_sm_p2_0,
  137986. NULL,
  137987. 0
  137988. };
  137989. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  137990. 4,
  137991. 3,
  137992. 5,
  137993. 2,
  137994. 6,
  137995. 1,
  137996. 7,
  137997. 0,
  137998. 8,
  137999. };
  138000. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  138001. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  138002. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  138003. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138004. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  138005. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0,
  138007. };
  138008. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  138009. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138010. };
  138011. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  138012. 7, 5, 3, 1, 0, 2, 4, 6,
  138013. 8,
  138014. };
  138015. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  138016. _vq_quantthresh__44cn1_sm_p3_0,
  138017. _vq_quantmap__44cn1_sm_p3_0,
  138018. 9,
  138019. 9
  138020. };
  138021. static static_codebook _44cn1_sm_p3_0 = {
  138022. 2, 81,
  138023. _vq_lengthlist__44cn1_sm_p3_0,
  138024. 1, -531628032, 1611661312, 4, 0,
  138025. _vq_quantlist__44cn1_sm_p3_0,
  138026. NULL,
  138027. &_vq_auxt__44cn1_sm_p3_0,
  138028. NULL,
  138029. 0
  138030. };
  138031. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  138032. 4,
  138033. 3,
  138034. 5,
  138035. 2,
  138036. 6,
  138037. 1,
  138038. 7,
  138039. 0,
  138040. 8,
  138041. };
  138042. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  138043. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  138044. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138045. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138046. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  138047. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  138048. 11,
  138049. };
  138050. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  138051. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138052. };
  138053. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  138054. 7, 5, 3, 1, 0, 2, 4, 6,
  138055. 8,
  138056. };
  138057. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  138058. _vq_quantthresh__44cn1_sm_p4_0,
  138059. _vq_quantmap__44cn1_sm_p4_0,
  138060. 9,
  138061. 9
  138062. };
  138063. static static_codebook _44cn1_sm_p4_0 = {
  138064. 2, 81,
  138065. _vq_lengthlist__44cn1_sm_p4_0,
  138066. 1, -531628032, 1611661312, 4, 0,
  138067. _vq_quantlist__44cn1_sm_p4_0,
  138068. NULL,
  138069. &_vq_auxt__44cn1_sm_p4_0,
  138070. NULL,
  138071. 0
  138072. };
  138073. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  138074. 8,
  138075. 7,
  138076. 9,
  138077. 6,
  138078. 10,
  138079. 5,
  138080. 11,
  138081. 4,
  138082. 12,
  138083. 3,
  138084. 13,
  138085. 2,
  138086. 14,
  138087. 1,
  138088. 15,
  138089. 0,
  138090. 16,
  138091. };
  138092. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  138093. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  138094. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138095. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138096. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138097. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  138098. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  138099. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  138100. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138101. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  138102. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138103. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  138104. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  138105. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  138106. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  138107. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  138108. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  138109. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  138111. 14,
  138112. };
  138113. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  138114. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138115. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138116. };
  138117. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  138118. 15, 13, 11, 9, 7, 5, 3, 1,
  138119. 0, 2, 4, 6, 8, 10, 12, 14,
  138120. 16,
  138121. };
  138122. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  138123. _vq_quantthresh__44cn1_sm_p5_0,
  138124. _vq_quantmap__44cn1_sm_p5_0,
  138125. 17,
  138126. 17
  138127. };
  138128. static static_codebook _44cn1_sm_p5_0 = {
  138129. 2, 289,
  138130. _vq_lengthlist__44cn1_sm_p5_0,
  138131. 1, -529530880, 1611661312, 5, 0,
  138132. _vq_quantlist__44cn1_sm_p5_0,
  138133. NULL,
  138134. &_vq_auxt__44cn1_sm_p5_0,
  138135. NULL,
  138136. 0
  138137. };
  138138. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  138139. 1,
  138140. 0,
  138141. 2,
  138142. };
  138143. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  138144. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  138145. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138146. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138147. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  138148. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  138149. 10,
  138150. };
  138151. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  138152. -5.5, 5.5,
  138153. };
  138154. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  138155. 1, 0, 2,
  138156. };
  138157. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  138158. _vq_quantthresh__44cn1_sm_p6_0,
  138159. _vq_quantmap__44cn1_sm_p6_0,
  138160. 3,
  138161. 3
  138162. };
  138163. static static_codebook _44cn1_sm_p6_0 = {
  138164. 4, 81,
  138165. _vq_lengthlist__44cn1_sm_p6_0,
  138166. 1, -529137664, 1618345984, 2, 0,
  138167. _vq_quantlist__44cn1_sm_p6_0,
  138168. NULL,
  138169. &_vq_auxt__44cn1_sm_p6_0,
  138170. NULL,
  138171. 0
  138172. };
  138173. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  138174. 5,
  138175. 4,
  138176. 6,
  138177. 3,
  138178. 7,
  138179. 2,
  138180. 8,
  138181. 1,
  138182. 9,
  138183. 0,
  138184. 10,
  138185. };
  138186. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  138187. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138188. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138189. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138190. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  138191. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  138192. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  138193. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  138194. 10,10,10, 8, 9, 8, 8, 9, 8,
  138195. };
  138196. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  138197. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138198. 3.5, 4.5,
  138199. };
  138200. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  138201. 9, 7, 5, 3, 1, 0, 2, 4,
  138202. 6, 8, 10,
  138203. };
  138204. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  138205. _vq_quantthresh__44cn1_sm_p6_1,
  138206. _vq_quantmap__44cn1_sm_p6_1,
  138207. 11,
  138208. 11
  138209. };
  138210. static static_codebook _44cn1_sm_p6_1 = {
  138211. 2, 121,
  138212. _vq_lengthlist__44cn1_sm_p6_1,
  138213. 1, -531365888, 1611661312, 4, 0,
  138214. _vq_quantlist__44cn1_sm_p6_1,
  138215. NULL,
  138216. &_vq_auxt__44cn1_sm_p6_1,
  138217. NULL,
  138218. 0
  138219. };
  138220. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  138221. 6,
  138222. 5,
  138223. 7,
  138224. 4,
  138225. 8,
  138226. 3,
  138227. 9,
  138228. 2,
  138229. 10,
  138230. 1,
  138231. 11,
  138232. 0,
  138233. 12,
  138234. };
  138235. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  138236. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  138237. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  138238. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138239. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138240. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  138241. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  138242. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  138243. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  138244. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  138245. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  138246. 0,13,12,12,12,13,13,13,14,
  138247. };
  138248. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  138249. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138250. 12.5, 17.5, 22.5, 27.5,
  138251. };
  138252. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  138253. 11, 9, 7, 5, 3, 1, 0, 2,
  138254. 4, 6, 8, 10, 12,
  138255. };
  138256. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  138257. _vq_quantthresh__44cn1_sm_p7_0,
  138258. _vq_quantmap__44cn1_sm_p7_0,
  138259. 13,
  138260. 13
  138261. };
  138262. static static_codebook _44cn1_sm_p7_0 = {
  138263. 2, 169,
  138264. _vq_lengthlist__44cn1_sm_p7_0,
  138265. 1, -526516224, 1616117760, 4, 0,
  138266. _vq_quantlist__44cn1_sm_p7_0,
  138267. NULL,
  138268. &_vq_auxt__44cn1_sm_p7_0,
  138269. NULL,
  138270. 0
  138271. };
  138272. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  138273. 2,
  138274. 1,
  138275. 3,
  138276. 0,
  138277. 4,
  138278. };
  138279. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  138280. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138281. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138282. };
  138283. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  138284. -1.5, -0.5, 0.5, 1.5,
  138285. };
  138286. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  138287. 3, 1, 0, 2, 4,
  138288. };
  138289. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  138290. _vq_quantthresh__44cn1_sm_p7_1,
  138291. _vq_quantmap__44cn1_sm_p7_1,
  138292. 5,
  138293. 5
  138294. };
  138295. static static_codebook _44cn1_sm_p7_1 = {
  138296. 2, 25,
  138297. _vq_lengthlist__44cn1_sm_p7_1,
  138298. 1, -533725184, 1611661312, 3, 0,
  138299. _vq_quantlist__44cn1_sm_p7_1,
  138300. NULL,
  138301. &_vq_auxt__44cn1_sm_p7_1,
  138302. NULL,
  138303. 0
  138304. };
  138305. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  138306. 4,
  138307. 3,
  138308. 5,
  138309. 2,
  138310. 6,
  138311. 1,
  138312. 7,
  138313. 0,
  138314. 8,
  138315. };
  138316. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  138317. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  138318. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  138319. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  138320. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  138321. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  138322. 14,
  138323. };
  138324. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  138325. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  138326. };
  138327. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  138328. 7, 5, 3, 1, 0, 2, 4, 6,
  138329. 8,
  138330. };
  138331. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  138332. _vq_quantthresh__44cn1_sm_p8_0,
  138333. _vq_quantmap__44cn1_sm_p8_0,
  138334. 9,
  138335. 9
  138336. };
  138337. static static_codebook _44cn1_sm_p8_0 = {
  138338. 2, 81,
  138339. _vq_lengthlist__44cn1_sm_p8_0,
  138340. 1, -516186112, 1627103232, 4, 0,
  138341. _vq_quantlist__44cn1_sm_p8_0,
  138342. NULL,
  138343. &_vq_auxt__44cn1_sm_p8_0,
  138344. NULL,
  138345. 0
  138346. };
  138347. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  138348. 6,
  138349. 5,
  138350. 7,
  138351. 4,
  138352. 8,
  138353. 3,
  138354. 9,
  138355. 2,
  138356. 10,
  138357. 1,
  138358. 11,
  138359. 0,
  138360. 12,
  138361. };
  138362. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  138363. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  138364. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  138365. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  138366. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  138367. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  138368. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  138369. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  138370. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  138371. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  138372. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  138373. 17,12,12,11,10,13,11,13,13,
  138374. };
  138375. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  138376. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138377. 42.5, 59.5, 76.5, 93.5,
  138378. };
  138379. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  138380. 11, 9, 7, 5, 3, 1, 0, 2,
  138381. 4, 6, 8, 10, 12,
  138382. };
  138383. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  138384. _vq_quantthresh__44cn1_sm_p8_1,
  138385. _vq_quantmap__44cn1_sm_p8_1,
  138386. 13,
  138387. 13
  138388. };
  138389. static static_codebook _44cn1_sm_p8_1 = {
  138390. 2, 169,
  138391. _vq_lengthlist__44cn1_sm_p8_1,
  138392. 1, -522616832, 1620115456, 4, 0,
  138393. _vq_quantlist__44cn1_sm_p8_1,
  138394. NULL,
  138395. &_vq_auxt__44cn1_sm_p8_1,
  138396. NULL,
  138397. 0
  138398. };
  138399. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  138400. 8,
  138401. 7,
  138402. 9,
  138403. 6,
  138404. 10,
  138405. 5,
  138406. 11,
  138407. 4,
  138408. 12,
  138409. 3,
  138410. 13,
  138411. 2,
  138412. 14,
  138413. 1,
  138414. 15,
  138415. 0,
  138416. 16,
  138417. };
  138418. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  138419. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138420. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138421. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  138422. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  138423. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  138424. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  138425. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  138426. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  138427. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  138428. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  138429. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  138430. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  138431. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  138432. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  138433. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  138434. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138435. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138436. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138437. 9,
  138438. };
  138439. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  138440. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138441. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138442. };
  138443. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  138444. 15, 13, 11, 9, 7, 5, 3, 1,
  138445. 0, 2, 4, 6, 8, 10, 12, 14,
  138446. 16,
  138447. };
  138448. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  138449. _vq_quantthresh__44cn1_sm_p8_2,
  138450. _vq_quantmap__44cn1_sm_p8_2,
  138451. 17,
  138452. 17
  138453. };
  138454. static static_codebook _44cn1_sm_p8_2 = {
  138455. 2, 289,
  138456. _vq_lengthlist__44cn1_sm_p8_2,
  138457. 1, -529530880, 1611661312, 5, 0,
  138458. _vq_quantlist__44cn1_sm_p8_2,
  138459. NULL,
  138460. &_vq_auxt__44cn1_sm_p8_2,
  138461. NULL,
  138462. 0
  138463. };
  138464. static long _huff_lengthlist__44cn1_sm_short[] = {
  138465. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  138466. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  138467. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  138468. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  138469. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  138470. 9,
  138471. };
  138472. static static_codebook _huff_book__44cn1_sm_short = {
  138473. 2, 81,
  138474. _huff_lengthlist__44cn1_sm_short,
  138475. 0, 0, 0, 0, 0,
  138476. NULL,
  138477. NULL,
  138478. NULL,
  138479. NULL,
  138480. 0
  138481. };
  138482. /*** End of inlined file: res_books_stereo.h ***/
  138483. /***** residue backends *********************************************/
  138484. static vorbis_info_residue0 _residue_44_low={
  138485. 0,-1, -1, 9,-1,
  138486. /* 0 1 2 3 4 5 6 7 */
  138487. {0},
  138488. {-1},
  138489. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  138490. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  138491. };
  138492. static vorbis_info_residue0 _residue_44_mid={
  138493. 0,-1, -1, 10,-1,
  138494. /* 0 1 2 3 4 5 6 7 8 */
  138495. {0},
  138496. {-1},
  138497. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  138498. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  138499. };
  138500. static vorbis_info_residue0 _residue_44_high={
  138501. 0,-1, -1, 10,-1,
  138502. /* 0 1 2 3 4 5 6 7 8 */
  138503. {0},
  138504. {-1},
  138505. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  138506. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  138507. };
  138508. static static_bookblock _resbook_44s_n1={
  138509. {
  138510. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  138511. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  138512. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  138513. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  138514. }
  138515. };
  138516. static static_bookblock _resbook_44sm_n1={
  138517. {
  138518. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  138519. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  138520. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  138521. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  138522. }
  138523. };
  138524. static static_bookblock _resbook_44s_0={
  138525. {
  138526. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  138527. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  138528. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  138529. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  138530. }
  138531. };
  138532. static static_bookblock _resbook_44sm_0={
  138533. {
  138534. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  138535. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  138536. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  138537. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  138538. }
  138539. };
  138540. static static_bookblock _resbook_44s_1={
  138541. {
  138542. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  138543. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  138544. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  138545. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  138546. }
  138547. };
  138548. static static_bookblock _resbook_44sm_1={
  138549. {
  138550. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  138551. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  138552. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  138553. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  138554. }
  138555. };
  138556. static static_bookblock _resbook_44s_2={
  138557. {
  138558. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  138559. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  138560. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  138561. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  138562. }
  138563. };
  138564. static static_bookblock _resbook_44s_3={
  138565. {
  138566. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  138567. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  138568. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  138569. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  138570. }
  138571. };
  138572. static static_bookblock _resbook_44s_4={
  138573. {
  138574. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  138575. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  138576. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  138577. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  138578. }
  138579. };
  138580. static static_bookblock _resbook_44s_5={
  138581. {
  138582. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  138583. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  138584. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  138585. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  138586. }
  138587. };
  138588. static static_bookblock _resbook_44s_6={
  138589. {
  138590. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  138591. {0,0,&_44c6_s_p4_0},
  138592. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  138593. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  138594. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  138595. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  138596. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  138597. }
  138598. };
  138599. static static_bookblock _resbook_44s_7={
  138600. {
  138601. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  138602. {0,0,&_44c7_s_p4_0},
  138603. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  138604. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  138605. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  138606. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  138607. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  138608. }
  138609. };
  138610. static static_bookblock _resbook_44s_8={
  138611. {
  138612. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  138613. {0,0,&_44c8_s_p4_0},
  138614. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  138615. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  138616. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  138617. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  138618. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  138619. }
  138620. };
  138621. static static_bookblock _resbook_44s_9={
  138622. {
  138623. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  138624. {0,0,&_44c9_s_p4_0},
  138625. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  138626. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  138627. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  138628. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  138629. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  138630. }
  138631. };
  138632. static vorbis_residue_template _res_44s_n1[]={
  138633. {2,0, &_residue_44_low,
  138634. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  138635. &_resbook_44s_n1,&_resbook_44sm_n1},
  138636. {2,0, &_residue_44_low,
  138637. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  138638. &_resbook_44s_n1,&_resbook_44sm_n1}
  138639. };
  138640. static vorbis_residue_template _res_44s_0[]={
  138641. {2,0, &_residue_44_low,
  138642. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  138643. &_resbook_44s_0,&_resbook_44sm_0},
  138644. {2,0, &_residue_44_low,
  138645. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  138646. &_resbook_44s_0,&_resbook_44sm_0}
  138647. };
  138648. static vorbis_residue_template _res_44s_1[]={
  138649. {2,0, &_residue_44_low,
  138650. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  138651. &_resbook_44s_1,&_resbook_44sm_1},
  138652. {2,0, &_residue_44_low,
  138653. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  138654. &_resbook_44s_1,&_resbook_44sm_1}
  138655. };
  138656. static vorbis_residue_template _res_44s_2[]={
  138657. {2,0, &_residue_44_mid,
  138658. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  138659. &_resbook_44s_2,&_resbook_44s_2},
  138660. {2,0, &_residue_44_mid,
  138661. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  138662. &_resbook_44s_2,&_resbook_44s_2}
  138663. };
  138664. static vorbis_residue_template _res_44s_3[]={
  138665. {2,0, &_residue_44_mid,
  138666. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  138667. &_resbook_44s_3,&_resbook_44s_3},
  138668. {2,0, &_residue_44_mid,
  138669. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  138670. &_resbook_44s_3,&_resbook_44s_3}
  138671. };
  138672. static vorbis_residue_template _res_44s_4[]={
  138673. {2,0, &_residue_44_mid,
  138674. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  138675. &_resbook_44s_4,&_resbook_44s_4},
  138676. {2,0, &_residue_44_mid,
  138677. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  138678. &_resbook_44s_4,&_resbook_44s_4}
  138679. };
  138680. static vorbis_residue_template _res_44s_5[]={
  138681. {2,0, &_residue_44_mid,
  138682. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  138683. &_resbook_44s_5,&_resbook_44s_5},
  138684. {2,0, &_residue_44_mid,
  138685. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  138686. &_resbook_44s_5,&_resbook_44s_5}
  138687. };
  138688. static vorbis_residue_template _res_44s_6[]={
  138689. {2,0, &_residue_44_high,
  138690. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  138691. &_resbook_44s_6,&_resbook_44s_6},
  138692. {2,0, &_residue_44_high,
  138693. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  138694. &_resbook_44s_6,&_resbook_44s_6}
  138695. };
  138696. static vorbis_residue_template _res_44s_7[]={
  138697. {2,0, &_residue_44_high,
  138698. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  138699. &_resbook_44s_7,&_resbook_44s_7},
  138700. {2,0, &_residue_44_high,
  138701. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  138702. &_resbook_44s_7,&_resbook_44s_7}
  138703. };
  138704. static vorbis_residue_template _res_44s_8[]={
  138705. {2,0, &_residue_44_high,
  138706. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  138707. &_resbook_44s_8,&_resbook_44s_8},
  138708. {2,0, &_residue_44_high,
  138709. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  138710. &_resbook_44s_8,&_resbook_44s_8}
  138711. };
  138712. static vorbis_residue_template _res_44s_9[]={
  138713. {2,0, &_residue_44_high,
  138714. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  138715. &_resbook_44s_9,&_resbook_44s_9},
  138716. {2,0, &_residue_44_high,
  138717. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  138718. &_resbook_44s_9,&_resbook_44s_9}
  138719. };
  138720. static vorbis_mapping_template _mapres_template_44_stereo[]={
  138721. { _map_nominal, _res_44s_n1 }, /* -1 */
  138722. { _map_nominal, _res_44s_0 }, /* 0 */
  138723. { _map_nominal, _res_44s_1 }, /* 1 */
  138724. { _map_nominal, _res_44s_2 }, /* 2 */
  138725. { _map_nominal, _res_44s_3 }, /* 3 */
  138726. { _map_nominal, _res_44s_4 }, /* 4 */
  138727. { _map_nominal, _res_44s_5 }, /* 5 */
  138728. { _map_nominal, _res_44s_6 }, /* 6 */
  138729. { _map_nominal, _res_44s_7 }, /* 7 */
  138730. { _map_nominal, _res_44s_8 }, /* 8 */
  138731. { _map_nominal, _res_44s_9 }, /* 9 */
  138732. };
  138733. /*** End of inlined file: residue_44.h ***/
  138734. /*** Start of inlined file: psych_44.h ***/
  138735. /* preecho trigger settings *****************************************/
  138736. static vorbis_info_psy_global _psy_global_44[5]={
  138737. {8, /* lines per eighth octave */
  138738. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  138739. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  138740. -6.f,
  138741. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138742. },
  138743. {8, /* lines per eighth octave */
  138744. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  138745. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  138746. -6.f,
  138747. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138748. },
  138749. {8, /* lines per eighth octave */
  138750. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  138751. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  138752. -6.f,
  138753. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138754. },
  138755. {8, /* lines per eighth octave */
  138756. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  138757. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  138758. -6.f,
  138759. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138760. },
  138761. {8, /* lines per eighth octave */
  138762. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  138763. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  138764. -6.f,
  138765. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138766. },
  138767. };
  138768. /* noise compander lookups * low, mid, high quality ****************/
  138769. static compandblock _psy_compand_44[6]={
  138770. /* sub-mode Z short */
  138771. {{
  138772. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138773. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138774. 16,17,18,19,20,21,22, 23, /* 23dB */
  138775. 24,25,26,27,28,29,30, 31, /* 31dB */
  138776. 32,33,34,35,36,37,38, 39, /* 39dB */
  138777. }},
  138778. /* mode_Z nominal short */
  138779. {{
  138780. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  138781. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  138782. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  138783. 15,16,17,17,17,18,18, 19, /* 31dB */
  138784. 19,19,20,21,22,23,24, 25, /* 39dB */
  138785. }},
  138786. /* mode A short */
  138787. {{
  138788. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  138789. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  138790. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138791. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138792. 11,12,13,14,15,16,17, 18, /* 39dB */
  138793. }},
  138794. /* sub-mode Z long */
  138795. {{
  138796. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138797. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138798. 16,17,18,19,20,21,22, 23, /* 23dB */
  138799. 24,25,26,27,28,29,30, 31, /* 31dB */
  138800. 32,33,34,35,36,37,38, 39, /* 39dB */
  138801. }},
  138802. /* mode_Z nominal long */
  138803. {{
  138804. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138805. 8, 9,10,11,12,12,13, 13, /* 15dB */
  138806. 13,14,14,14,15,15,15, 15, /* 23dB */
  138807. 16,16,17,17,17,18,18, 19, /* 31dB */
  138808. 19,19,20,21,22,23,24, 25, /* 39dB */
  138809. }},
  138810. /* mode A long */
  138811. {{
  138812. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138813. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  138814. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138815. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138816. 11,12,13,14,15,16,17, 18, /* 39dB */
  138817. }}
  138818. };
  138819. /* tonal masking curve level adjustments *************************/
  138820. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  138821. /* 63 125 250 500 1 2 4 8 16 */
  138822. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  138823. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138824. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  138825. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138826. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  138827. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138828. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  138829. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138830. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  138831. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  138832. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138833. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138834. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138835. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138836. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138837. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138838. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138839. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138840. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138841. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138842. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138843. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138844. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138845. };
  138846. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  138847. /* 63 125 250 500 1 2 4 8 16 */
  138848. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  138849. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138850. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  138851. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138852. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  138853. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138854. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  138855. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138856. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  138857. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  138858. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138859. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138860. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138861. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138862. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138863. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138864. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138865. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138866. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138867. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138868. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138869. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138870. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138871. };
  138872. /* noise bias (transition block) */
  138873. static noise3 _psy_noisebias_trans[12]={
  138874. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138875. /* -1 */
  138876. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138877. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138878. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138879. /* 0
  138880. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138881. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  138882. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138883. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138884. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  138885. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138886. /* 1
  138887. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138888. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138889. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138890. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138891. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138892. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138893. /* 2
  138894. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138895. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138896. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  138897. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138898. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138899. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  138900. /* 3
  138901. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138902. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138903. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138904. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138905. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138906. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138907. /* 4
  138908. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138909. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138910. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138911. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138912. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138913. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138914. /* 5
  138915. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138916. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138917. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  138918. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138919. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138920. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  138921. /* 6
  138922. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138923. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138924. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138925. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138926. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138927. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138928. /* 7
  138929. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138930. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  138931. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  138932. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138933. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138934. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138935. /* 8
  138936. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138937. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138938. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138939. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138940. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138941. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138942. /* 9
  138943. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138944. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138945. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138946. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138947. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  138948. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  138949. /* 10 */
  138950. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  138951. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  138952. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138953. };
  138954. /* noise bias (long block) */
  138955. static noise3 _psy_noisebias_long[12]={
  138956. /*63 125 250 500 1k 2k 4k 8k 16k*/
  138957. /* -1 */
  138958. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  138959. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  138960. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138961. /* 0 */
  138962. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138963. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  138964. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138965. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138966. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  138967. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138968. /* 1 */
  138969. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138970. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138971. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138972. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138973. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138974. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138975. /* 2 */
  138976. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138977. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138978. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138979. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138980. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138981. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138982. /* 3 */
  138983. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138984. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138985. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138986. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138987. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138988. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  138989. /* 4 */
  138990. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138991. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138992. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138993. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138994. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138995. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  138996. /* 5 */
  138997. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138998. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138999. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  139000. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139001. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  139002. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  139003. /* 6 */
  139004. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139005. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  139006. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  139007. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139008. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  139009. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  139010. /* 7 */
  139011. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139012. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  139013. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  139014. /* 8 */
  139015. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  139016. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  139017. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  139018. /* 9 */
  139019. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139020. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  139021. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139022. /* 10 */
  139023. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  139024. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  139025. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139026. };
  139027. /* noise bias (impulse block) */
  139028. static noise3 _psy_noisebias_impulse[12]={
  139029. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139030. /* -1 */
  139031. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139032. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139033. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139034. /* 0 */
  139035. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139036. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  139037. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  139038. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139039. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  139040. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139041. /* 1 */
  139042. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139043. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  139044. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  139045. /* 2 */
  139046. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139047. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139048. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139049. /* 3 */
  139050. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139051. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139052. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139053. /* 4 */
  139054. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139055. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139056. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139057. /* 5 */
  139058. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139059. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  139060. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  139061. /* 6
  139062. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139063. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  139064. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  139065. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139066. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  139067. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  139068. /* 7 */
  139069. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139070. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  139071. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  139072. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139073. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  139074. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139075. /* 8 */
  139076. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139077. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  139078. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  139079. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139080. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  139081. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139082. /* 9 */
  139083. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139084. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  139085. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  139086. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139087. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  139088. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139089. /* 10 */
  139090. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  139091. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  139092. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139093. };
  139094. /* noise bias (padding block) */
  139095. static noise3 _psy_noisebias_padding[12]={
  139096. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139097. /* -1 */
  139098. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139099. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139100. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139101. /* 0 */
  139102. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139103. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  139104. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  139105. /* 1 */
  139106. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139107. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139108. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  139109. /* 2 */
  139110. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139111. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139112. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  139113. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139114. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139115. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139116. /* 3 */
  139117. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139118. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139119. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139120. /* 4 */
  139121. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139122. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  139123. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139124. /* 5 */
  139125. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139126. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  139127. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  139128. /* 6 */
  139129. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139130. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  139131. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  139132. /* 7 */
  139133. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139134. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  139135. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  139136. /* 8 */
  139137. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  139138. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  139139. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  139140. /* 9 */
  139141. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  139142. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  139143. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  139144. /* 10 */
  139145. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  139146. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  139147. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139148. };
  139149. static noiseguard _psy_noiseguards_44[4]={
  139150. {3,3,15},
  139151. {3,3,15},
  139152. {10,10,100},
  139153. {10,10,100},
  139154. };
  139155. static int _psy_tone_suppress[12]={
  139156. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  139157. };
  139158. static int _psy_tone_0dB[12]={
  139159. 90,90,95,95,95,95,105,105,105,105,105,105,
  139160. };
  139161. static int _psy_noise_suppress[12]={
  139162. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  139163. };
  139164. static vorbis_info_psy _psy_info_template={
  139165. /* blockflag */
  139166. -1,
  139167. /* ath_adjatt, ath_maxatt */
  139168. -140.,-140.,
  139169. /* tonemask att boost/decay,suppr,curves */
  139170. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  139171. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  139172. 1, -0.f, .5f, .5f, 0,0,0,
  139173. /* noiseoffset*3, noisecompand, max_curve_dB */
  139174. {{-1},{-1},{-1}},{-1},105.f,
  139175. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  139176. 0,0,-1,-1,0.,
  139177. };
  139178. /* ath ****************/
  139179. static int _psy_ath_floater[12]={
  139180. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  139181. };
  139182. static int _psy_ath_abs[12]={
  139183. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  139184. };
  139185. /* stereo setup. These don't map directly to quality level, there's
  139186. an additional indirection as several of the below may be used in a
  139187. single bitmanaged stream
  139188. ****************/
  139189. /* various stereo possibilities */
  139190. /* stereo mode by base quality level */
  139191. static adj_stereo _psy_stereo_modes_44[12]={
  139192. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  139193. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139194. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139195. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  139196. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139197. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  139198. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139199. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139200. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  139201. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139202. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  139203. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139204. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139205. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139206. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  139207. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  139208. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139209. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139210. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139211. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  139212. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  139213. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  139214. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139215. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139216. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  139217. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139218. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139219. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139220. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  139221. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  139222. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139223. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  139224. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139225. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  139226. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139227. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  139228. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  139229. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139230. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  139231. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139232. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139233. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139234. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139235. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139236. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139237. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  139238. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139239. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  139240. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139241. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139242. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139243. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139244. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139245. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139246. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139247. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139248. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  139249. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139250. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139251. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139252. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139253. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139254. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139255. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139256. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139257. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  139258. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139259. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139260. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139261. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139262. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139263. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139264. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139265. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139266. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  139267. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139268. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139269. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139270. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139271. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  139272. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139273. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139274. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139275. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139276. };
  139277. /* tone master attenuation by base quality mode and bitrate tweak */
  139278. static att3 _psy_tone_masteratt_44[12]={
  139279. {{ 35, 21, 9}, 0, 0}, /* -1 */
  139280. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  139281. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  139282. {{ 25, 12, 2}, 0, 0}, /* 1 */
  139283. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  139284. {{ 20, 9, -3}, 0, 0}, /* 2 */
  139285. {{ 20, 9, -4}, 0, 0}, /* 3 */
  139286. {{ 20, 9, -4}, 0, 0}, /* 4 */
  139287. {{ 20, 6, -6}, 0, 0}, /* 5 */
  139288. {{ 20, 3, -10}, 0, 0}, /* 6 */
  139289. {{ 18, 1, -14}, 0, 0}, /* 7 */
  139290. {{ 18, 0, -16}, 0, 0}, /* 8 */
  139291. {{ 18, -2, -16}, 0, 0}, /* 9 */
  139292. {{ 12, -2, -20}, 0, 0}, /* 10 */
  139293. };
  139294. /* lowpass by mode **************/
  139295. static double _psy_lowpass_44[12]={
  139296. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  139297. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  139298. };
  139299. /* noise normalization **********/
  139300. static int _noise_start_short_44[11]={
  139301. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  139302. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  139303. };
  139304. static int _noise_start_long_44[11]={
  139305. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  139306. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  139307. };
  139308. static int _noise_part_short_44[11]={
  139309. 8,8,8,8,8,8,8,8,8,8,8
  139310. };
  139311. static int _noise_part_long_44[11]={
  139312. 32,32,32,32,32,32,32,32,32,32,32
  139313. };
  139314. static double _noise_thresh_44[11]={
  139315. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  139316. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  139317. };
  139318. static double _noise_thresh_5only[2]={
  139319. .5,.5,
  139320. };
  139321. /*** End of inlined file: psych_44.h ***/
  139322. static double rate_mapping_44_stereo[12]={
  139323. 22500.,32000.,40000.,48000.,56000.,64000.,
  139324. 80000.,96000.,112000.,128000.,160000.,250001.
  139325. };
  139326. static double quality_mapping_44[12]={
  139327. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  139328. };
  139329. static int blocksize_short_44[11]={
  139330. 512,256,256,256,256,256,256,256,256,256,256
  139331. };
  139332. static int blocksize_long_44[11]={
  139333. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  139334. };
  139335. static double _psy_compand_short_mapping[12]={
  139336. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  139337. };
  139338. static double _psy_compand_long_mapping[12]={
  139339. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  139340. };
  139341. static double _global_mapping_44[12]={
  139342. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  139343. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  139344. };
  139345. static int _floor_short_mapping_44[11]={
  139346. 1,0,0,2,2,4,5,5,5,5,5
  139347. };
  139348. static int _floor_long_mapping_44[11]={
  139349. 8,7,7,7,7,7,7,7,7,7,7
  139350. };
  139351. ve_setup_data_template ve_setup_44_stereo={
  139352. 11,
  139353. rate_mapping_44_stereo,
  139354. quality_mapping_44,
  139355. 2,
  139356. 40000,
  139357. 50000,
  139358. blocksize_short_44,
  139359. blocksize_long_44,
  139360. _psy_tone_masteratt_44,
  139361. _psy_tone_0dB,
  139362. _psy_tone_suppress,
  139363. _vp_tonemask_adj_otherblock,
  139364. _vp_tonemask_adj_longblock,
  139365. _vp_tonemask_adj_otherblock,
  139366. _psy_noiseguards_44,
  139367. _psy_noisebias_impulse,
  139368. _psy_noisebias_padding,
  139369. _psy_noisebias_trans,
  139370. _psy_noisebias_long,
  139371. _psy_noise_suppress,
  139372. _psy_compand_44,
  139373. _psy_compand_short_mapping,
  139374. _psy_compand_long_mapping,
  139375. {_noise_start_short_44,_noise_start_long_44},
  139376. {_noise_part_short_44,_noise_part_long_44},
  139377. _noise_thresh_44,
  139378. _psy_ath_floater,
  139379. _psy_ath_abs,
  139380. _psy_lowpass_44,
  139381. _psy_global_44,
  139382. _global_mapping_44,
  139383. _psy_stereo_modes_44,
  139384. _floor_books,
  139385. _floor,
  139386. _floor_short_mapping_44,
  139387. _floor_long_mapping_44,
  139388. _mapres_template_44_stereo
  139389. };
  139390. /*** End of inlined file: setup_44.h ***/
  139391. /*** Start of inlined file: setup_44u.h ***/
  139392. /*** Start of inlined file: residue_44u.h ***/
  139393. /*** Start of inlined file: res_books_uncoupled.h ***/
  139394. static long _vq_quantlist__16u0__p1_0[] = {
  139395. 1,
  139396. 0,
  139397. 2,
  139398. };
  139399. static long _vq_lengthlist__16u0__p1_0[] = {
  139400. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  139401. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  139402. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  139403. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  139404. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  139405. 12,
  139406. };
  139407. static float _vq_quantthresh__16u0__p1_0[] = {
  139408. -0.5, 0.5,
  139409. };
  139410. static long _vq_quantmap__16u0__p1_0[] = {
  139411. 1, 0, 2,
  139412. };
  139413. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  139414. _vq_quantthresh__16u0__p1_0,
  139415. _vq_quantmap__16u0__p1_0,
  139416. 3,
  139417. 3
  139418. };
  139419. static static_codebook _16u0__p1_0 = {
  139420. 4, 81,
  139421. _vq_lengthlist__16u0__p1_0,
  139422. 1, -535822336, 1611661312, 2, 0,
  139423. _vq_quantlist__16u0__p1_0,
  139424. NULL,
  139425. &_vq_auxt__16u0__p1_0,
  139426. NULL,
  139427. 0
  139428. };
  139429. static long _vq_quantlist__16u0__p2_0[] = {
  139430. 1,
  139431. 0,
  139432. 2,
  139433. };
  139434. static long _vq_lengthlist__16u0__p2_0[] = {
  139435. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  139436. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  139437. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  139438. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  139439. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  139440. 8,
  139441. };
  139442. static float _vq_quantthresh__16u0__p2_0[] = {
  139443. -0.5, 0.5,
  139444. };
  139445. static long _vq_quantmap__16u0__p2_0[] = {
  139446. 1, 0, 2,
  139447. };
  139448. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  139449. _vq_quantthresh__16u0__p2_0,
  139450. _vq_quantmap__16u0__p2_0,
  139451. 3,
  139452. 3
  139453. };
  139454. static static_codebook _16u0__p2_0 = {
  139455. 4, 81,
  139456. _vq_lengthlist__16u0__p2_0,
  139457. 1, -535822336, 1611661312, 2, 0,
  139458. _vq_quantlist__16u0__p2_0,
  139459. NULL,
  139460. &_vq_auxt__16u0__p2_0,
  139461. NULL,
  139462. 0
  139463. };
  139464. static long _vq_quantlist__16u0__p3_0[] = {
  139465. 2,
  139466. 1,
  139467. 3,
  139468. 0,
  139469. 4,
  139470. };
  139471. static long _vq_lengthlist__16u0__p3_0[] = {
  139472. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  139473. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  139474. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  139475. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  139476. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  139477. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  139478. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  139479. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  139480. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  139481. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  139482. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  139483. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  139484. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  139485. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  139486. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  139487. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  139488. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  139489. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  139490. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  139491. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  139492. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  139493. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  139494. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  139495. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  139496. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  139497. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  139498. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  139499. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  139500. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  139501. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  139502. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  139503. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  139504. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  139505. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  139506. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  139507. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  139508. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  139509. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  139510. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  139511. 18,
  139512. };
  139513. static float _vq_quantthresh__16u0__p3_0[] = {
  139514. -1.5, -0.5, 0.5, 1.5,
  139515. };
  139516. static long _vq_quantmap__16u0__p3_0[] = {
  139517. 3, 1, 0, 2, 4,
  139518. };
  139519. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  139520. _vq_quantthresh__16u0__p3_0,
  139521. _vq_quantmap__16u0__p3_0,
  139522. 5,
  139523. 5
  139524. };
  139525. static static_codebook _16u0__p3_0 = {
  139526. 4, 625,
  139527. _vq_lengthlist__16u0__p3_0,
  139528. 1, -533725184, 1611661312, 3, 0,
  139529. _vq_quantlist__16u0__p3_0,
  139530. NULL,
  139531. &_vq_auxt__16u0__p3_0,
  139532. NULL,
  139533. 0
  139534. };
  139535. static long _vq_quantlist__16u0__p4_0[] = {
  139536. 2,
  139537. 1,
  139538. 3,
  139539. 0,
  139540. 4,
  139541. };
  139542. static long _vq_lengthlist__16u0__p4_0[] = {
  139543. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  139544. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  139545. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  139546. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  139547. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  139548. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  139549. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  139550. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  139551. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139552. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  139553. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  139554. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  139555. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  139556. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  139557. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  139558. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  139559. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  139560. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  139561. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  139562. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  139563. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  139564. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  139565. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  139566. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  139567. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  139568. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  139569. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  139570. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  139571. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  139572. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  139573. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  139574. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  139575. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  139576. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  139577. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  139578. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  139579. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  139580. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  139581. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  139582. 11,
  139583. };
  139584. static float _vq_quantthresh__16u0__p4_0[] = {
  139585. -1.5, -0.5, 0.5, 1.5,
  139586. };
  139587. static long _vq_quantmap__16u0__p4_0[] = {
  139588. 3, 1, 0, 2, 4,
  139589. };
  139590. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  139591. _vq_quantthresh__16u0__p4_0,
  139592. _vq_quantmap__16u0__p4_0,
  139593. 5,
  139594. 5
  139595. };
  139596. static static_codebook _16u0__p4_0 = {
  139597. 4, 625,
  139598. _vq_lengthlist__16u0__p4_0,
  139599. 1, -533725184, 1611661312, 3, 0,
  139600. _vq_quantlist__16u0__p4_0,
  139601. NULL,
  139602. &_vq_auxt__16u0__p4_0,
  139603. NULL,
  139604. 0
  139605. };
  139606. static long _vq_quantlist__16u0__p5_0[] = {
  139607. 4,
  139608. 3,
  139609. 5,
  139610. 2,
  139611. 6,
  139612. 1,
  139613. 7,
  139614. 0,
  139615. 8,
  139616. };
  139617. static long _vq_lengthlist__16u0__p5_0[] = {
  139618. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139619. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  139620. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  139621. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139622. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  139623. 12,
  139624. };
  139625. static float _vq_quantthresh__16u0__p5_0[] = {
  139626. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139627. };
  139628. static long _vq_quantmap__16u0__p5_0[] = {
  139629. 7, 5, 3, 1, 0, 2, 4, 6,
  139630. 8,
  139631. };
  139632. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  139633. _vq_quantthresh__16u0__p5_0,
  139634. _vq_quantmap__16u0__p5_0,
  139635. 9,
  139636. 9
  139637. };
  139638. static static_codebook _16u0__p5_0 = {
  139639. 2, 81,
  139640. _vq_lengthlist__16u0__p5_0,
  139641. 1, -531628032, 1611661312, 4, 0,
  139642. _vq_quantlist__16u0__p5_0,
  139643. NULL,
  139644. &_vq_auxt__16u0__p5_0,
  139645. NULL,
  139646. 0
  139647. };
  139648. static long _vq_quantlist__16u0__p6_0[] = {
  139649. 6,
  139650. 5,
  139651. 7,
  139652. 4,
  139653. 8,
  139654. 3,
  139655. 9,
  139656. 2,
  139657. 10,
  139658. 1,
  139659. 11,
  139660. 0,
  139661. 12,
  139662. };
  139663. static long _vq_lengthlist__16u0__p6_0[] = {
  139664. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  139665. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  139666. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  139667. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  139668. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  139669. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  139670. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  139671. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  139672. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  139673. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  139674. 18, 0,19, 0, 0, 0, 0, 0, 0,
  139675. };
  139676. static float _vq_quantthresh__16u0__p6_0[] = {
  139677. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139678. 12.5, 17.5, 22.5, 27.5,
  139679. };
  139680. static long _vq_quantmap__16u0__p6_0[] = {
  139681. 11, 9, 7, 5, 3, 1, 0, 2,
  139682. 4, 6, 8, 10, 12,
  139683. };
  139684. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  139685. _vq_quantthresh__16u0__p6_0,
  139686. _vq_quantmap__16u0__p6_0,
  139687. 13,
  139688. 13
  139689. };
  139690. static static_codebook _16u0__p6_0 = {
  139691. 2, 169,
  139692. _vq_lengthlist__16u0__p6_0,
  139693. 1, -526516224, 1616117760, 4, 0,
  139694. _vq_quantlist__16u0__p6_0,
  139695. NULL,
  139696. &_vq_auxt__16u0__p6_0,
  139697. NULL,
  139698. 0
  139699. };
  139700. static long _vq_quantlist__16u0__p6_1[] = {
  139701. 2,
  139702. 1,
  139703. 3,
  139704. 0,
  139705. 4,
  139706. };
  139707. static long _vq_lengthlist__16u0__p6_1[] = {
  139708. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  139709. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  139710. };
  139711. static float _vq_quantthresh__16u0__p6_1[] = {
  139712. -1.5, -0.5, 0.5, 1.5,
  139713. };
  139714. static long _vq_quantmap__16u0__p6_1[] = {
  139715. 3, 1, 0, 2, 4,
  139716. };
  139717. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  139718. _vq_quantthresh__16u0__p6_1,
  139719. _vq_quantmap__16u0__p6_1,
  139720. 5,
  139721. 5
  139722. };
  139723. static static_codebook _16u0__p6_1 = {
  139724. 2, 25,
  139725. _vq_lengthlist__16u0__p6_1,
  139726. 1, -533725184, 1611661312, 3, 0,
  139727. _vq_quantlist__16u0__p6_1,
  139728. NULL,
  139729. &_vq_auxt__16u0__p6_1,
  139730. NULL,
  139731. 0
  139732. };
  139733. static long _vq_quantlist__16u0__p7_0[] = {
  139734. 1,
  139735. 0,
  139736. 2,
  139737. };
  139738. static long _vq_lengthlist__16u0__p7_0[] = {
  139739. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139740. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139741. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139742. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139743. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139744. 7,
  139745. };
  139746. static float _vq_quantthresh__16u0__p7_0[] = {
  139747. -157.5, 157.5,
  139748. };
  139749. static long _vq_quantmap__16u0__p7_0[] = {
  139750. 1, 0, 2,
  139751. };
  139752. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  139753. _vq_quantthresh__16u0__p7_0,
  139754. _vq_quantmap__16u0__p7_0,
  139755. 3,
  139756. 3
  139757. };
  139758. static static_codebook _16u0__p7_0 = {
  139759. 4, 81,
  139760. _vq_lengthlist__16u0__p7_0,
  139761. 1, -518803456, 1628680192, 2, 0,
  139762. _vq_quantlist__16u0__p7_0,
  139763. NULL,
  139764. &_vq_auxt__16u0__p7_0,
  139765. NULL,
  139766. 0
  139767. };
  139768. static long _vq_quantlist__16u0__p7_1[] = {
  139769. 7,
  139770. 6,
  139771. 8,
  139772. 5,
  139773. 9,
  139774. 4,
  139775. 10,
  139776. 3,
  139777. 11,
  139778. 2,
  139779. 12,
  139780. 1,
  139781. 13,
  139782. 0,
  139783. 14,
  139784. };
  139785. static long _vq_lengthlist__16u0__p7_1[] = {
  139786. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  139787. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  139788. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  139789. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  139790. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  139791. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  139792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139795. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139796. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139797. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139798. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139800. 10,
  139801. };
  139802. static float _vq_quantthresh__16u0__p7_1[] = {
  139803. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139804. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139805. };
  139806. static long _vq_quantmap__16u0__p7_1[] = {
  139807. 13, 11, 9, 7, 5, 3, 1, 0,
  139808. 2, 4, 6, 8, 10, 12, 14,
  139809. };
  139810. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  139811. _vq_quantthresh__16u0__p7_1,
  139812. _vq_quantmap__16u0__p7_1,
  139813. 15,
  139814. 15
  139815. };
  139816. static static_codebook _16u0__p7_1 = {
  139817. 2, 225,
  139818. _vq_lengthlist__16u0__p7_1,
  139819. 1, -520986624, 1620377600, 4, 0,
  139820. _vq_quantlist__16u0__p7_1,
  139821. NULL,
  139822. &_vq_auxt__16u0__p7_1,
  139823. NULL,
  139824. 0
  139825. };
  139826. static long _vq_quantlist__16u0__p7_2[] = {
  139827. 10,
  139828. 9,
  139829. 11,
  139830. 8,
  139831. 12,
  139832. 7,
  139833. 13,
  139834. 6,
  139835. 14,
  139836. 5,
  139837. 15,
  139838. 4,
  139839. 16,
  139840. 3,
  139841. 17,
  139842. 2,
  139843. 18,
  139844. 1,
  139845. 19,
  139846. 0,
  139847. 20,
  139848. };
  139849. static long _vq_lengthlist__16u0__p7_2[] = {
  139850. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  139851. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  139852. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  139853. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  139854. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  139855. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  139856. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  139857. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  139858. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  139859. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  139860. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  139861. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  139862. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  139863. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  139864. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  139865. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  139866. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  139867. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  139868. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  139869. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  139870. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  139871. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  139872. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  139873. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  139874. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  139875. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  139876. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  139877. 10,10,12,11,10,11,11,11,10,
  139878. };
  139879. static float _vq_quantthresh__16u0__p7_2[] = {
  139880. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139881. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139882. 6.5, 7.5, 8.5, 9.5,
  139883. };
  139884. static long _vq_quantmap__16u0__p7_2[] = {
  139885. 19, 17, 15, 13, 11, 9, 7, 5,
  139886. 3, 1, 0, 2, 4, 6, 8, 10,
  139887. 12, 14, 16, 18, 20,
  139888. };
  139889. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  139890. _vq_quantthresh__16u0__p7_2,
  139891. _vq_quantmap__16u0__p7_2,
  139892. 21,
  139893. 21
  139894. };
  139895. static static_codebook _16u0__p7_2 = {
  139896. 2, 441,
  139897. _vq_lengthlist__16u0__p7_2,
  139898. 1, -529268736, 1611661312, 5, 0,
  139899. _vq_quantlist__16u0__p7_2,
  139900. NULL,
  139901. &_vq_auxt__16u0__p7_2,
  139902. NULL,
  139903. 0
  139904. };
  139905. static long _huff_lengthlist__16u0__single[] = {
  139906. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  139907. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  139908. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  139909. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  139910. };
  139911. static static_codebook _huff_book__16u0__single = {
  139912. 2, 64,
  139913. _huff_lengthlist__16u0__single,
  139914. 0, 0, 0, 0, 0,
  139915. NULL,
  139916. NULL,
  139917. NULL,
  139918. NULL,
  139919. 0
  139920. };
  139921. static long _huff_lengthlist__16u1__long[] = {
  139922. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  139923. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  139924. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  139925. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  139926. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  139927. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  139928. 16,13,16,18,
  139929. };
  139930. static static_codebook _huff_book__16u1__long = {
  139931. 2, 100,
  139932. _huff_lengthlist__16u1__long,
  139933. 0, 0, 0, 0, 0,
  139934. NULL,
  139935. NULL,
  139936. NULL,
  139937. NULL,
  139938. 0
  139939. };
  139940. static long _vq_quantlist__16u1__p1_0[] = {
  139941. 1,
  139942. 0,
  139943. 2,
  139944. };
  139945. static long _vq_lengthlist__16u1__p1_0[] = {
  139946. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  139947. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  139948. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  139949. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139950. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  139951. 11,
  139952. };
  139953. static float _vq_quantthresh__16u1__p1_0[] = {
  139954. -0.5, 0.5,
  139955. };
  139956. static long _vq_quantmap__16u1__p1_0[] = {
  139957. 1, 0, 2,
  139958. };
  139959. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  139960. _vq_quantthresh__16u1__p1_0,
  139961. _vq_quantmap__16u1__p1_0,
  139962. 3,
  139963. 3
  139964. };
  139965. static static_codebook _16u1__p1_0 = {
  139966. 4, 81,
  139967. _vq_lengthlist__16u1__p1_0,
  139968. 1, -535822336, 1611661312, 2, 0,
  139969. _vq_quantlist__16u1__p1_0,
  139970. NULL,
  139971. &_vq_auxt__16u1__p1_0,
  139972. NULL,
  139973. 0
  139974. };
  139975. static long _vq_quantlist__16u1__p2_0[] = {
  139976. 1,
  139977. 0,
  139978. 2,
  139979. };
  139980. static long _vq_lengthlist__16u1__p2_0[] = {
  139981. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  139982. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  139983. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  139984. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  139985. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  139986. 8,
  139987. };
  139988. static float _vq_quantthresh__16u1__p2_0[] = {
  139989. -0.5, 0.5,
  139990. };
  139991. static long _vq_quantmap__16u1__p2_0[] = {
  139992. 1, 0, 2,
  139993. };
  139994. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  139995. _vq_quantthresh__16u1__p2_0,
  139996. _vq_quantmap__16u1__p2_0,
  139997. 3,
  139998. 3
  139999. };
  140000. static static_codebook _16u1__p2_0 = {
  140001. 4, 81,
  140002. _vq_lengthlist__16u1__p2_0,
  140003. 1, -535822336, 1611661312, 2, 0,
  140004. _vq_quantlist__16u1__p2_0,
  140005. NULL,
  140006. &_vq_auxt__16u1__p2_0,
  140007. NULL,
  140008. 0
  140009. };
  140010. static long _vq_quantlist__16u1__p3_0[] = {
  140011. 2,
  140012. 1,
  140013. 3,
  140014. 0,
  140015. 4,
  140016. };
  140017. static long _vq_lengthlist__16u1__p3_0[] = {
  140018. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  140019. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  140020. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  140021. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  140022. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  140023. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  140024. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  140025. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  140026. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  140027. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  140028. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  140029. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  140030. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  140031. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  140032. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  140033. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  140034. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  140035. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  140036. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  140037. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  140038. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  140039. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  140040. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  140041. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  140042. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  140043. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  140044. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  140045. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  140046. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  140047. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  140048. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  140049. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  140050. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  140051. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  140052. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  140053. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  140054. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  140055. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  140056. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  140057. 16,
  140058. };
  140059. static float _vq_quantthresh__16u1__p3_0[] = {
  140060. -1.5, -0.5, 0.5, 1.5,
  140061. };
  140062. static long _vq_quantmap__16u1__p3_0[] = {
  140063. 3, 1, 0, 2, 4,
  140064. };
  140065. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  140066. _vq_quantthresh__16u1__p3_0,
  140067. _vq_quantmap__16u1__p3_0,
  140068. 5,
  140069. 5
  140070. };
  140071. static static_codebook _16u1__p3_0 = {
  140072. 4, 625,
  140073. _vq_lengthlist__16u1__p3_0,
  140074. 1, -533725184, 1611661312, 3, 0,
  140075. _vq_quantlist__16u1__p3_0,
  140076. NULL,
  140077. &_vq_auxt__16u1__p3_0,
  140078. NULL,
  140079. 0
  140080. };
  140081. static long _vq_quantlist__16u1__p4_0[] = {
  140082. 2,
  140083. 1,
  140084. 3,
  140085. 0,
  140086. 4,
  140087. };
  140088. static long _vq_lengthlist__16u1__p4_0[] = {
  140089. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  140090. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  140091. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  140092. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  140093. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  140094. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  140095. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  140096. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  140097. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  140098. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  140099. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  140100. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  140101. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  140102. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  140103. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  140104. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  140105. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  140106. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  140107. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  140108. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  140109. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  140110. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  140111. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  140112. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  140113. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  140114. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  140115. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  140116. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  140117. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  140118. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  140119. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  140120. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  140121. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  140122. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  140123. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  140124. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  140125. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  140126. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  140127. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  140128. 11,
  140129. };
  140130. static float _vq_quantthresh__16u1__p4_0[] = {
  140131. -1.5, -0.5, 0.5, 1.5,
  140132. };
  140133. static long _vq_quantmap__16u1__p4_0[] = {
  140134. 3, 1, 0, 2, 4,
  140135. };
  140136. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  140137. _vq_quantthresh__16u1__p4_0,
  140138. _vq_quantmap__16u1__p4_0,
  140139. 5,
  140140. 5
  140141. };
  140142. static static_codebook _16u1__p4_0 = {
  140143. 4, 625,
  140144. _vq_lengthlist__16u1__p4_0,
  140145. 1, -533725184, 1611661312, 3, 0,
  140146. _vq_quantlist__16u1__p4_0,
  140147. NULL,
  140148. &_vq_auxt__16u1__p4_0,
  140149. NULL,
  140150. 0
  140151. };
  140152. static long _vq_quantlist__16u1__p5_0[] = {
  140153. 4,
  140154. 3,
  140155. 5,
  140156. 2,
  140157. 6,
  140158. 1,
  140159. 7,
  140160. 0,
  140161. 8,
  140162. };
  140163. static long _vq_lengthlist__16u1__p5_0[] = {
  140164. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140165. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140166. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140167. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  140168. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  140169. 13,
  140170. };
  140171. static float _vq_quantthresh__16u1__p5_0[] = {
  140172. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140173. };
  140174. static long _vq_quantmap__16u1__p5_0[] = {
  140175. 7, 5, 3, 1, 0, 2, 4, 6,
  140176. 8,
  140177. };
  140178. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  140179. _vq_quantthresh__16u1__p5_0,
  140180. _vq_quantmap__16u1__p5_0,
  140181. 9,
  140182. 9
  140183. };
  140184. static static_codebook _16u1__p5_0 = {
  140185. 2, 81,
  140186. _vq_lengthlist__16u1__p5_0,
  140187. 1, -531628032, 1611661312, 4, 0,
  140188. _vq_quantlist__16u1__p5_0,
  140189. NULL,
  140190. &_vq_auxt__16u1__p5_0,
  140191. NULL,
  140192. 0
  140193. };
  140194. static long _vq_quantlist__16u1__p6_0[] = {
  140195. 4,
  140196. 3,
  140197. 5,
  140198. 2,
  140199. 6,
  140200. 1,
  140201. 7,
  140202. 0,
  140203. 8,
  140204. };
  140205. static long _vq_lengthlist__16u1__p6_0[] = {
  140206. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  140207. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  140208. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140209. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140210. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140211. 11,
  140212. };
  140213. static float _vq_quantthresh__16u1__p6_0[] = {
  140214. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140215. };
  140216. static long _vq_quantmap__16u1__p6_0[] = {
  140217. 7, 5, 3, 1, 0, 2, 4, 6,
  140218. 8,
  140219. };
  140220. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  140221. _vq_quantthresh__16u1__p6_0,
  140222. _vq_quantmap__16u1__p6_0,
  140223. 9,
  140224. 9
  140225. };
  140226. static static_codebook _16u1__p6_0 = {
  140227. 2, 81,
  140228. _vq_lengthlist__16u1__p6_0,
  140229. 1, -531628032, 1611661312, 4, 0,
  140230. _vq_quantlist__16u1__p6_0,
  140231. NULL,
  140232. &_vq_auxt__16u1__p6_0,
  140233. NULL,
  140234. 0
  140235. };
  140236. static long _vq_quantlist__16u1__p7_0[] = {
  140237. 1,
  140238. 0,
  140239. 2,
  140240. };
  140241. static long _vq_lengthlist__16u1__p7_0[] = {
  140242. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  140243. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  140244. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  140245. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  140246. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  140247. 13,
  140248. };
  140249. static float _vq_quantthresh__16u1__p7_0[] = {
  140250. -5.5, 5.5,
  140251. };
  140252. static long _vq_quantmap__16u1__p7_0[] = {
  140253. 1, 0, 2,
  140254. };
  140255. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  140256. _vq_quantthresh__16u1__p7_0,
  140257. _vq_quantmap__16u1__p7_0,
  140258. 3,
  140259. 3
  140260. };
  140261. static static_codebook _16u1__p7_0 = {
  140262. 4, 81,
  140263. _vq_lengthlist__16u1__p7_0,
  140264. 1, -529137664, 1618345984, 2, 0,
  140265. _vq_quantlist__16u1__p7_0,
  140266. NULL,
  140267. &_vq_auxt__16u1__p7_0,
  140268. NULL,
  140269. 0
  140270. };
  140271. static long _vq_quantlist__16u1__p7_1[] = {
  140272. 5,
  140273. 4,
  140274. 6,
  140275. 3,
  140276. 7,
  140277. 2,
  140278. 8,
  140279. 1,
  140280. 9,
  140281. 0,
  140282. 10,
  140283. };
  140284. static long _vq_lengthlist__16u1__p7_1[] = {
  140285. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  140286. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  140287. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140288. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  140289. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  140290. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  140291. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  140292. 8, 9, 9,10,10,10,10,10,10,
  140293. };
  140294. static float _vq_quantthresh__16u1__p7_1[] = {
  140295. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140296. 3.5, 4.5,
  140297. };
  140298. static long _vq_quantmap__16u1__p7_1[] = {
  140299. 9, 7, 5, 3, 1, 0, 2, 4,
  140300. 6, 8, 10,
  140301. };
  140302. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  140303. _vq_quantthresh__16u1__p7_1,
  140304. _vq_quantmap__16u1__p7_1,
  140305. 11,
  140306. 11
  140307. };
  140308. static static_codebook _16u1__p7_1 = {
  140309. 2, 121,
  140310. _vq_lengthlist__16u1__p7_1,
  140311. 1, -531365888, 1611661312, 4, 0,
  140312. _vq_quantlist__16u1__p7_1,
  140313. NULL,
  140314. &_vq_auxt__16u1__p7_1,
  140315. NULL,
  140316. 0
  140317. };
  140318. static long _vq_quantlist__16u1__p8_0[] = {
  140319. 5,
  140320. 4,
  140321. 6,
  140322. 3,
  140323. 7,
  140324. 2,
  140325. 8,
  140326. 1,
  140327. 9,
  140328. 0,
  140329. 10,
  140330. };
  140331. static long _vq_lengthlist__16u1__p8_0[] = {
  140332. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  140333. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  140334. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  140335. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  140336. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  140337. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  140338. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  140339. 13,14,14,15,15,16,16,15,16,
  140340. };
  140341. static float _vq_quantthresh__16u1__p8_0[] = {
  140342. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140343. 38.5, 49.5,
  140344. };
  140345. static long _vq_quantmap__16u1__p8_0[] = {
  140346. 9, 7, 5, 3, 1, 0, 2, 4,
  140347. 6, 8, 10,
  140348. };
  140349. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  140350. _vq_quantthresh__16u1__p8_0,
  140351. _vq_quantmap__16u1__p8_0,
  140352. 11,
  140353. 11
  140354. };
  140355. static static_codebook _16u1__p8_0 = {
  140356. 2, 121,
  140357. _vq_lengthlist__16u1__p8_0,
  140358. 1, -524582912, 1618345984, 4, 0,
  140359. _vq_quantlist__16u1__p8_0,
  140360. NULL,
  140361. &_vq_auxt__16u1__p8_0,
  140362. NULL,
  140363. 0
  140364. };
  140365. static long _vq_quantlist__16u1__p8_1[] = {
  140366. 5,
  140367. 4,
  140368. 6,
  140369. 3,
  140370. 7,
  140371. 2,
  140372. 8,
  140373. 1,
  140374. 9,
  140375. 0,
  140376. 10,
  140377. };
  140378. static long _vq_lengthlist__16u1__p8_1[] = {
  140379. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  140380. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140381. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  140382. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140383. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140384. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140385. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140386. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  140387. };
  140388. static float _vq_quantthresh__16u1__p8_1[] = {
  140389. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140390. 3.5, 4.5,
  140391. };
  140392. static long _vq_quantmap__16u1__p8_1[] = {
  140393. 9, 7, 5, 3, 1, 0, 2, 4,
  140394. 6, 8, 10,
  140395. };
  140396. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  140397. _vq_quantthresh__16u1__p8_1,
  140398. _vq_quantmap__16u1__p8_1,
  140399. 11,
  140400. 11
  140401. };
  140402. static static_codebook _16u1__p8_1 = {
  140403. 2, 121,
  140404. _vq_lengthlist__16u1__p8_1,
  140405. 1, -531365888, 1611661312, 4, 0,
  140406. _vq_quantlist__16u1__p8_1,
  140407. NULL,
  140408. &_vq_auxt__16u1__p8_1,
  140409. NULL,
  140410. 0
  140411. };
  140412. static long _vq_quantlist__16u1__p9_0[] = {
  140413. 7,
  140414. 6,
  140415. 8,
  140416. 5,
  140417. 9,
  140418. 4,
  140419. 10,
  140420. 3,
  140421. 11,
  140422. 2,
  140423. 12,
  140424. 1,
  140425. 13,
  140426. 0,
  140427. 14,
  140428. };
  140429. static long _vq_lengthlist__16u1__p9_0[] = {
  140430. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140431. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140432. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140433. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140434. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140435. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140436. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140437. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140438. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140439. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140440. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140441. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140442. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140443. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140444. 8,
  140445. };
  140446. static float _vq_quantthresh__16u1__p9_0[] = {
  140447. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140448. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140449. };
  140450. static long _vq_quantmap__16u1__p9_0[] = {
  140451. 13, 11, 9, 7, 5, 3, 1, 0,
  140452. 2, 4, 6, 8, 10, 12, 14,
  140453. };
  140454. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  140455. _vq_quantthresh__16u1__p9_0,
  140456. _vq_quantmap__16u1__p9_0,
  140457. 15,
  140458. 15
  140459. };
  140460. static static_codebook _16u1__p9_0 = {
  140461. 2, 225,
  140462. _vq_lengthlist__16u1__p9_0,
  140463. 1, -514071552, 1627381760, 4, 0,
  140464. _vq_quantlist__16u1__p9_0,
  140465. NULL,
  140466. &_vq_auxt__16u1__p9_0,
  140467. NULL,
  140468. 0
  140469. };
  140470. static long _vq_quantlist__16u1__p9_1[] = {
  140471. 7,
  140472. 6,
  140473. 8,
  140474. 5,
  140475. 9,
  140476. 4,
  140477. 10,
  140478. 3,
  140479. 11,
  140480. 2,
  140481. 12,
  140482. 1,
  140483. 13,
  140484. 0,
  140485. 14,
  140486. };
  140487. static long _vq_lengthlist__16u1__p9_1[] = {
  140488. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  140489. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  140490. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  140491. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  140492. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  140493. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  140494. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  140495. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  140496. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  140497. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140498. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140499. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140500. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140501. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140502. 9,
  140503. };
  140504. static float _vq_quantthresh__16u1__p9_1[] = {
  140505. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  140506. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  140507. };
  140508. static long _vq_quantmap__16u1__p9_1[] = {
  140509. 13, 11, 9, 7, 5, 3, 1, 0,
  140510. 2, 4, 6, 8, 10, 12, 14,
  140511. };
  140512. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  140513. _vq_quantthresh__16u1__p9_1,
  140514. _vq_quantmap__16u1__p9_1,
  140515. 15,
  140516. 15
  140517. };
  140518. static static_codebook _16u1__p9_1 = {
  140519. 2, 225,
  140520. _vq_lengthlist__16u1__p9_1,
  140521. 1, -522338304, 1620115456, 4, 0,
  140522. _vq_quantlist__16u1__p9_1,
  140523. NULL,
  140524. &_vq_auxt__16u1__p9_1,
  140525. NULL,
  140526. 0
  140527. };
  140528. static long _vq_quantlist__16u1__p9_2[] = {
  140529. 8,
  140530. 7,
  140531. 9,
  140532. 6,
  140533. 10,
  140534. 5,
  140535. 11,
  140536. 4,
  140537. 12,
  140538. 3,
  140539. 13,
  140540. 2,
  140541. 14,
  140542. 1,
  140543. 15,
  140544. 0,
  140545. 16,
  140546. };
  140547. static long _vq_lengthlist__16u1__p9_2[] = {
  140548. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  140549. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  140550. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  140551. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  140552. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  140553. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  140554. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  140555. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  140556. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  140557. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  140558. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  140559. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  140560. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  140561. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  140562. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  140563. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  140564. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  140565. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  140566. 10,
  140567. };
  140568. static float _vq_quantthresh__16u1__p9_2[] = {
  140569. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140570. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140571. };
  140572. static long _vq_quantmap__16u1__p9_2[] = {
  140573. 15, 13, 11, 9, 7, 5, 3, 1,
  140574. 0, 2, 4, 6, 8, 10, 12, 14,
  140575. 16,
  140576. };
  140577. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  140578. _vq_quantthresh__16u1__p9_2,
  140579. _vq_quantmap__16u1__p9_2,
  140580. 17,
  140581. 17
  140582. };
  140583. static static_codebook _16u1__p9_2 = {
  140584. 2, 289,
  140585. _vq_lengthlist__16u1__p9_2,
  140586. 1, -529530880, 1611661312, 5, 0,
  140587. _vq_quantlist__16u1__p9_2,
  140588. NULL,
  140589. &_vq_auxt__16u1__p9_2,
  140590. NULL,
  140591. 0
  140592. };
  140593. static long _huff_lengthlist__16u1__short[] = {
  140594. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  140595. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  140596. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  140597. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  140598. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  140599. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  140600. 16,16,16,16,
  140601. };
  140602. static static_codebook _huff_book__16u1__short = {
  140603. 2, 100,
  140604. _huff_lengthlist__16u1__short,
  140605. 0, 0, 0, 0, 0,
  140606. NULL,
  140607. NULL,
  140608. NULL,
  140609. NULL,
  140610. 0
  140611. };
  140612. static long _huff_lengthlist__16u2__long[] = {
  140613. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  140614. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  140615. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  140616. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  140617. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  140618. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  140619. 13,14,18,18,
  140620. };
  140621. static static_codebook _huff_book__16u2__long = {
  140622. 2, 100,
  140623. _huff_lengthlist__16u2__long,
  140624. 0, 0, 0, 0, 0,
  140625. NULL,
  140626. NULL,
  140627. NULL,
  140628. NULL,
  140629. 0
  140630. };
  140631. static long _huff_lengthlist__16u2__short[] = {
  140632. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  140633. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  140634. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  140635. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  140636. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  140637. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  140638. 16,16,16,16,
  140639. };
  140640. static static_codebook _huff_book__16u2__short = {
  140641. 2, 100,
  140642. _huff_lengthlist__16u2__short,
  140643. 0, 0, 0, 0, 0,
  140644. NULL,
  140645. NULL,
  140646. NULL,
  140647. NULL,
  140648. 0
  140649. };
  140650. static long _vq_quantlist__16u2_p1_0[] = {
  140651. 1,
  140652. 0,
  140653. 2,
  140654. };
  140655. static long _vq_lengthlist__16u2_p1_0[] = {
  140656. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  140657. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  140658. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  140659. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  140660. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  140661. 10,
  140662. };
  140663. static float _vq_quantthresh__16u2_p1_0[] = {
  140664. -0.5, 0.5,
  140665. };
  140666. static long _vq_quantmap__16u2_p1_0[] = {
  140667. 1, 0, 2,
  140668. };
  140669. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  140670. _vq_quantthresh__16u2_p1_0,
  140671. _vq_quantmap__16u2_p1_0,
  140672. 3,
  140673. 3
  140674. };
  140675. static static_codebook _16u2_p1_0 = {
  140676. 4, 81,
  140677. _vq_lengthlist__16u2_p1_0,
  140678. 1, -535822336, 1611661312, 2, 0,
  140679. _vq_quantlist__16u2_p1_0,
  140680. NULL,
  140681. &_vq_auxt__16u2_p1_0,
  140682. NULL,
  140683. 0
  140684. };
  140685. static long _vq_quantlist__16u2_p2_0[] = {
  140686. 2,
  140687. 1,
  140688. 3,
  140689. 0,
  140690. 4,
  140691. };
  140692. static long _vq_lengthlist__16u2_p2_0[] = {
  140693. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  140694. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  140695. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  140696. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  140697. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  140698. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  140699. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  140700. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  140701. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  140702. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  140703. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  140704. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140705. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  140706. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  140707. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  140708. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  140709. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  140710. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  140711. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  140712. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  140713. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  140714. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  140715. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  140716. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  140717. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  140718. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  140719. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  140720. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  140721. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  140722. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  140723. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  140724. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  140725. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  140726. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  140727. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  140728. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  140729. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  140730. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  140731. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  140732. 13,
  140733. };
  140734. static float _vq_quantthresh__16u2_p2_0[] = {
  140735. -1.5, -0.5, 0.5, 1.5,
  140736. };
  140737. static long _vq_quantmap__16u2_p2_0[] = {
  140738. 3, 1, 0, 2, 4,
  140739. };
  140740. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  140741. _vq_quantthresh__16u2_p2_0,
  140742. _vq_quantmap__16u2_p2_0,
  140743. 5,
  140744. 5
  140745. };
  140746. static static_codebook _16u2_p2_0 = {
  140747. 4, 625,
  140748. _vq_lengthlist__16u2_p2_0,
  140749. 1, -533725184, 1611661312, 3, 0,
  140750. _vq_quantlist__16u2_p2_0,
  140751. NULL,
  140752. &_vq_auxt__16u2_p2_0,
  140753. NULL,
  140754. 0
  140755. };
  140756. static long _vq_quantlist__16u2_p3_0[] = {
  140757. 4,
  140758. 3,
  140759. 5,
  140760. 2,
  140761. 6,
  140762. 1,
  140763. 7,
  140764. 0,
  140765. 8,
  140766. };
  140767. static long _vq_lengthlist__16u2_p3_0[] = {
  140768. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  140769. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  140770. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140771. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140772. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140773. 11,
  140774. };
  140775. static float _vq_quantthresh__16u2_p3_0[] = {
  140776. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140777. };
  140778. static long _vq_quantmap__16u2_p3_0[] = {
  140779. 7, 5, 3, 1, 0, 2, 4, 6,
  140780. 8,
  140781. };
  140782. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  140783. _vq_quantthresh__16u2_p3_0,
  140784. _vq_quantmap__16u2_p3_0,
  140785. 9,
  140786. 9
  140787. };
  140788. static static_codebook _16u2_p3_0 = {
  140789. 2, 81,
  140790. _vq_lengthlist__16u2_p3_0,
  140791. 1, -531628032, 1611661312, 4, 0,
  140792. _vq_quantlist__16u2_p3_0,
  140793. NULL,
  140794. &_vq_auxt__16u2_p3_0,
  140795. NULL,
  140796. 0
  140797. };
  140798. static long _vq_quantlist__16u2_p4_0[] = {
  140799. 8,
  140800. 7,
  140801. 9,
  140802. 6,
  140803. 10,
  140804. 5,
  140805. 11,
  140806. 4,
  140807. 12,
  140808. 3,
  140809. 13,
  140810. 2,
  140811. 14,
  140812. 1,
  140813. 15,
  140814. 0,
  140815. 16,
  140816. };
  140817. static long _vq_lengthlist__16u2_p4_0[] = {
  140818. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  140819. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140820. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140821. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140822. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140823. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  140824. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  140825. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  140826. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  140827. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  140828. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  140829. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  140830. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  140831. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  140832. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  140833. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  140834. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  140835. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  140836. 14,
  140837. };
  140838. static float _vq_quantthresh__16u2_p4_0[] = {
  140839. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140840. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140841. };
  140842. static long _vq_quantmap__16u2_p4_0[] = {
  140843. 15, 13, 11, 9, 7, 5, 3, 1,
  140844. 0, 2, 4, 6, 8, 10, 12, 14,
  140845. 16,
  140846. };
  140847. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  140848. _vq_quantthresh__16u2_p4_0,
  140849. _vq_quantmap__16u2_p4_0,
  140850. 17,
  140851. 17
  140852. };
  140853. static static_codebook _16u2_p4_0 = {
  140854. 2, 289,
  140855. _vq_lengthlist__16u2_p4_0,
  140856. 1, -529530880, 1611661312, 5, 0,
  140857. _vq_quantlist__16u2_p4_0,
  140858. NULL,
  140859. &_vq_auxt__16u2_p4_0,
  140860. NULL,
  140861. 0
  140862. };
  140863. static long _vq_quantlist__16u2_p5_0[] = {
  140864. 1,
  140865. 0,
  140866. 2,
  140867. };
  140868. static long _vq_lengthlist__16u2_p5_0[] = {
  140869. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  140870. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  140871. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  140872. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  140873. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  140874. 10,
  140875. };
  140876. static float _vq_quantthresh__16u2_p5_0[] = {
  140877. -5.5, 5.5,
  140878. };
  140879. static long _vq_quantmap__16u2_p5_0[] = {
  140880. 1, 0, 2,
  140881. };
  140882. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  140883. _vq_quantthresh__16u2_p5_0,
  140884. _vq_quantmap__16u2_p5_0,
  140885. 3,
  140886. 3
  140887. };
  140888. static static_codebook _16u2_p5_0 = {
  140889. 4, 81,
  140890. _vq_lengthlist__16u2_p5_0,
  140891. 1, -529137664, 1618345984, 2, 0,
  140892. _vq_quantlist__16u2_p5_0,
  140893. NULL,
  140894. &_vq_auxt__16u2_p5_0,
  140895. NULL,
  140896. 0
  140897. };
  140898. static long _vq_quantlist__16u2_p5_1[] = {
  140899. 5,
  140900. 4,
  140901. 6,
  140902. 3,
  140903. 7,
  140904. 2,
  140905. 8,
  140906. 1,
  140907. 9,
  140908. 0,
  140909. 10,
  140910. };
  140911. static long _vq_lengthlist__16u2_p5_1[] = {
  140912. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  140913. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  140914. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140915. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140916. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140917. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140918. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140919. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140920. };
  140921. static float _vq_quantthresh__16u2_p5_1[] = {
  140922. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140923. 3.5, 4.5,
  140924. };
  140925. static long _vq_quantmap__16u2_p5_1[] = {
  140926. 9, 7, 5, 3, 1, 0, 2, 4,
  140927. 6, 8, 10,
  140928. };
  140929. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  140930. _vq_quantthresh__16u2_p5_1,
  140931. _vq_quantmap__16u2_p5_1,
  140932. 11,
  140933. 11
  140934. };
  140935. static static_codebook _16u2_p5_1 = {
  140936. 2, 121,
  140937. _vq_lengthlist__16u2_p5_1,
  140938. 1, -531365888, 1611661312, 4, 0,
  140939. _vq_quantlist__16u2_p5_1,
  140940. NULL,
  140941. &_vq_auxt__16u2_p5_1,
  140942. NULL,
  140943. 0
  140944. };
  140945. static long _vq_quantlist__16u2_p6_0[] = {
  140946. 6,
  140947. 5,
  140948. 7,
  140949. 4,
  140950. 8,
  140951. 3,
  140952. 9,
  140953. 2,
  140954. 10,
  140955. 1,
  140956. 11,
  140957. 0,
  140958. 12,
  140959. };
  140960. static long _vq_lengthlist__16u2_p6_0[] = {
  140961. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  140962. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  140963. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  140964. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  140965. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  140966. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  140967. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  140968. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  140969. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  140970. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  140971. 12,13,13,14,14,14,14,15,15,
  140972. };
  140973. static float _vq_quantthresh__16u2_p6_0[] = {
  140974. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140975. 12.5, 17.5, 22.5, 27.5,
  140976. };
  140977. static long _vq_quantmap__16u2_p6_0[] = {
  140978. 11, 9, 7, 5, 3, 1, 0, 2,
  140979. 4, 6, 8, 10, 12,
  140980. };
  140981. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  140982. _vq_quantthresh__16u2_p6_0,
  140983. _vq_quantmap__16u2_p6_0,
  140984. 13,
  140985. 13
  140986. };
  140987. static static_codebook _16u2_p6_0 = {
  140988. 2, 169,
  140989. _vq_lengthlist__16u2_p6_0,
  140990. 1, -526516224, 1616117760, 4, 0,
  140991. _vq_quantlist__16u2_p6_0,
  140992. NULL,
  140993. &_vq_auxt__16u2_p6_0,
  140994. NULL,
  140995. 0
  140996. };
  140997. static long _vq_quantlist__16u2_p6_1[] = {
  140998. 2,
  140999. 1,
  141000. 3,
  141001. 0,
  141002. 4,
  141003. };
  141004. static long _vq_lengthlist__16u2_p6_1[] = {
  141005. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  141006. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  141007. };
  141008. static float _vq_quantthresh__16u2_p6_1[] = {
  141009. -1.5, -0.5, 0.5, 1.5,
  141010. };
  141011. static long _vq_quantmap__16u2_p6_1[] = {
  141012. 3, 1, 0, 2, 4,
  141013. };
  141014. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  141015. _vq_quantthresh__16u2_p6_1,
  141016. _vq_quantmap__16u2_p6_1,
  141017. 5,
  141018. 5
  141019. };
  141020. static static_codebook _16u2_p6_1 = {
  141021. 2, 25,
  141022. _vq_lengthlist__16u2_p6_1,
  141023. 1, -533725184, 1611661312, 3, 0,
  141024. _vq_quantlist__16u2_p6_1,
  141025. NULL,
  141026. &_vq_auxt__16u2_p6_1,
  141027. NULL,
  141028. 0
  141029. };
  141030. static long _vq_quantlist__16u2_p7_0[] = {
  141031. 6,
  141032. 5,
  141033. 7,
  141034. 4,
  141035. 8,
  141036. 3,
  141037. 9,
  141038. 2,
  141039. 10,
  141040. 1,
  141041. 11,
  141042. 0,
  141043. 12,
  141044. };
  141045. static long _vq_lengthlist__16u2_p7_0[] = {
  141046. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  141047. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  141048. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  141049. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  141050. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  141051. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  141052. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  141053. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  141054. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  141055. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  141056. 12,13,13,13,14,14,14,15,14,
  141057. };
  141058. static float _vq_quantthresh__16u2_p7_0[] = {
  141059. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  141060. 27.5, 38.5, 49.5, 60.5,
  141061. };
  141062. static long _vq_quantmap__16u2_p7_0[] = {
  141063. 11, 9, 7, 5, 3, 1, 0, 2,
  141064. 4, 6, 8, 10, 12,
  141065. };
  141066. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  141067. _vq_quantthresh__16u2_p7_0,
  141068. _vq_quantmap__16u2_p7_0,
  141069. 13,
  141070. 13
  141071. };
  141072. static static_codebook _16u2_p7_0 = {
  141073. 2, 169,
  141074. _vq_lengthlist__16u2_p7_0,
  141075. 1, -523206656, 1618345984, 4, 0,
  141076. _vq_quantlist__16u2_p7_0,
  141077. NULL,
  141078. &_vq_auxt__16u2_p7_0,
  141079. NULL,
  141080. 0
  141081. };
  141082. static long _vq_quantlist__16u2_p7_1[] = {
  141083. 5,
  141084. 4,
  141085. 6,
  141086. 3,
  141087. 7,
  141088. 2,
  141089. 8,
  141090. 1,
  141091. 9,
  141092. 0,
  141093. 10,
  141094. };
  141095. static long _vq_lengthlist__16u2_p7_1[] = {
  141096. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  141097. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  141098. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  141099. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  141100. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  141101. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  141102. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  141103. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141104. };
  141105. static float _vq_quantthresh__16u2_p7_1[] = {
  141106. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141107. 3.5, 4.5,
  141108. };
  141109. static long _vq_quantmap__16u2_p7_1[] = {
  141110. 9, 7, 5, 3, 1, 0, 2, 4,
  141111. 6, 8, 10,
  141112. };
  141113. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  141114. _vq_quantthresh__16u2_p7_1,
  141115. _vq_quantmap__16u2_p7_1,
  141116. 11,
  141117. 11
  141118. };
  141119. static static_codebook _16u2_p7_1 = {
  141120. 2, 121,
  141121. _vq_lengthlist__16u2_p7_1,
  141122. 1, -531365888, 1611661312, 4, 0,
  141123. _vq_quantlist__16u2_p7_1,
  141124. NULL,
  141125. &_vq_auxt__16u2_p7_1,
  141126. NULL,
  141127. 0
  141128. };
  141129. static long _vq_quantlist__16u2_p8_0[] = {
  141130. 7,
  141131. 6,
  141132. 8,
  141133. 5,
  141134. 9,
  141135. 4,
  141136. 10,
  141137. 3,
  141138. 11,
  141139. 2,
  141140. 12,
  141141. 1,
  141142. 13,
  141143. 0,
  141144. 14,
  141145. };
  141146. static long _vq_lengthlist__16u2_p8_0[] = {
  141147. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  141148. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  141149. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  141150. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  141151. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  141152. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  141153. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  141154. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  141155. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  141156. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  141157. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  141158. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  141159. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  141160. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  141161. 14,
  141162. };
  141163. static float _vq_quantthresh__16u2_p8_0[] = {
  141164. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141165. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141166. };
  141167. static long _vq_quantmap__16u2_p8_0[] = {
  141168. 13, 11, 9, 7, 5, 3, 1, 0,
  141169. 2, 4, 6, 8, 10, 12, 14,
  141170. };
  141171. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  141172. _vq_quantthresh__16u2_p8_0,
  141173. _vq_quantmap__16u2_p8_0,
  141174. 15,
  141175. 15
  141176. };
  141177. static static_codebook _16u2_p8_0 = {
  141178. 2, 225,
  141179. _vq_lengthlist__16u2_p8_0,
  141180. 1, -520986624, 1620377600, 4, 0,
  141181. _vq_quantlist__16u2_p8_0,
  141182. NULL,
  141183. &_vq_auxt__16u2_p8_0,
  141184. NULL,
  141185. 0
  141186. };
  141187. static long _vq_quantlist__16u2_p8_1[] = {
  141188. 10,
  141189. 9,
  141190. 11,
  141191. 8,
  141192. 12,
  141193. 7,
  141194. 13,
  141195. 6,
  141196. 14,
  141197. 5,
  141198. 15,
  141199. 4,
  141200. 16,
  141201. 3,
  141202. 17,
  141203. 2,
  141204. 18,
  141205. 1,
  141206. 19,
  141207. 0,
  141208. 20,
  141209. };
  141210. static long _vq_lengthlist__16u2_p8_1[] = {
  141211. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  141212. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  141213. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  141214. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  141215. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  141216. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  141217. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  141218. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  141219. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  141220. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  141221. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  141222. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  141223. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  141224. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  141225. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  141226. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  141227. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  141228. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  141229. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  141230. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  141231. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  141232. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  141233. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  141234. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  141235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141236. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  141237. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  141238. 11,11,10,11,11,11,10,11,11,
  141239. };
  141240. static float _vq_quantthresh__16u2_p8_1[] = {
  141241. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141242. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141243. 6.5, 7.5, 8.5, 9.5,
  141244. };
  141245. static long _vq_quantmap__16u2_p8_1[] = {
  141246. 19, 17, 15, 13, 11, 9, 7, 5,
  141247. 3, 1, 0, 2, 4, 6, 8, 10,
  141248. 12, 14, 16, 18, 20,
  141249. };
  141250. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  141251. _vq_quantthresh__16u2_p8_1,
  141252. _vq_quantmap__16u2_p8_1,
  141253. 21,
  141254. 21
  141255. };
  141256. static static_codebook _16u2_p8_1 = {
  141257. 2, 441,
  141258. _vq_lengthlist__16u2_p8_1,
  141259. 1, -529268736, 1611661312, 5, 0,
  141260. _vq_quantlist__16u2_p8_1,
  141261. NULL,
  141262. &_vq_auxt__16u2_p8_1,
  141263. NULL,
  141264. 0
  141265. };
  141266. static long _vq_quantlist__16u2_p9_0[] = {
  141267. 5586,
  141268. 4655,
  141269. 6517,
  141270. 3724,
  141271. 7448,
  141272. 2793,
  141273. 8379,
  141274. 1862,
  141275. 9310,
  141276. 931,
  141277. 10241,
  141278. 0,
  141279. 11172,
  141280. 5521,
  141281. 5651,
  141282. };
  141283. static long _vq_lengthlist__16u2_p9_0[] = {
  141284. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  141285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141286. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141287. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141288. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141289. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141291. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141292. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141293. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141294. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141295. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141296. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  141297. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  141298. 5,
  141299. };
  141300. static float _vq_quantthresh__16u2_p9_0[] = {
  141301. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  141302. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  141303. };
  141304. static long _vq_quantmap__16u2_p9_0[] = {
  141305. 11, 9, 7, 5, 3, 1, 13, 0,
  141306. 14, 2, 4, 6, 8, 10, 12,
  141307. };
  141308. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  141309. _vq_quantthresh__16u2_p9_0,
  141310. _vq_quantmap__16u2_p9_0,
  141311. 15,
  141312. 15
  141313. };
  141314. static static_codebook _16u2_p9_0 = {
  141315. 2, 225,
  141316. _vq_lengthlist__16u2_p9_0,
  141317. 1, -510275072, 1611661312, 14, 0,
  141318. _vq_quantlist__16u2_p9_0,
  141319. NULL,
  141320. &_vq_auxt__16u2_p9_0,
  141321. NULL,
  141322. 0
  141323. };
  141324. static long _vq_quantlist__16u2_p9_1[] = {
  141325. 392,
  141326. 343,
  141327. 441,
  141328. 294,
  141329. 490,
  141330. 245,
  141331. 539,
  141332. 196,
  141333. 588,
  141334. 147,
  141335. 637,
  141336. 98,
  141337. 686,
  141338. 49,
  141339. 735,
  141340. 0,
  141341. 784,
  141342. 388,
  141343. 396,
  141344. };
  141345. static long _vq_lengthlist__16u2_p9_1[] = {
  141346. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  141347. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  141348. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  141349. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  141350. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  141351. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  141352. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141353. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  141354. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  141355. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141356. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141357. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141358. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141359. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141360. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  141361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141366. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  141367. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  141368. 11,11,11,11,11,11,11, 5, 4,
  141369. };
  141370. static float _vq_quantthresh__16u2_p9_1[] = {
  141371. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  141372. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  141373. 318.5, 367.5,
  141374. };
  141375. static long _vq_quantmap__16u2_p9_1[] = {
  141376. 15, 13, 11, 9, 7, 5, 3, 1,
  141377. 17, 0, 18, 2, 4, 6, 8, 10,
  141378. 12, 14, 16,
  141379. };
  141380. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  141381. _vq_quantthresh__16u2_p9_1,
  141382. _vq_quantmap__16u2_p9_1,
  141383. 19,
  141384. 19
  141385. };
  141386. static static_codebook _16u2_p9_1 = {
  141387. 2, 361,
  141388. _vq_lengthlist__16u2_p9_1,
  141389. 1, -518488064, 1611661312, 10, 0,
  141390. _vq_quantlist__16u2_p9_1,
  141391. NULL,
  141392. &_vq_auxt__16u2_p9_1,
  141393. NULL,
  141394. 0
  141395. };
  141396. static long _vq_quantlist__16u2_p9_2[] = {
  141397. 24,
  141398. 23,
  141399. 25,
  141400. 22,
  141401. 26,
  141402. 21,
  141403. 27,
  141404. 20,
  141405. 28,
  141406. 19,
  141407. 29,
  141408. 18,
  141409. 30,
  141410. 17,
  141411. 31,
  141412. 16,
  141413. 32,
  141414. 15,
  141415. 33,
  141416. 14,
  141417. 34,
  141418. 13,
  141419. 35,
  141420. 12,
  141421. 36,
  141422. 11,
  141423. 37,
  141424. 10,
  141425. 38,
  141426. 9,
  141427. 39,
  141428. 8,
  141429. 40,
  141430. 7,
  141431. 41,
  141432. 6,
  141433. 42,
  141434. 5,
  141435. 43,
  141436. 4,
  141437. 44,
  141438. 3,
  141439. 45,
  141440. 2,
  141441. 46,
  141442. 1,
  141443. 47,
  141444. 0,
  141445. 48,
  141446. };
  141447. static long _vq_lengthlist__16u2_p9_2[] = {
  141448. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  141449. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  141450. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  141451. 11,
  141452. };
  141453. static float _vq_quantthresh__16u2_p9_2[] = {
  141454. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  141455. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  141456. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141457. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141458. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  141459. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  141460. };
  141461. static long _vq_quantmap__16u2_p9_2[] = {
  141462. 47, 45, 43, 41, 39, 37, 35, 33,
  141463. 31, 29, 27, 25, 23, 21, 19, 17,
  141464. 15, 13, 11, 9, 7, 5, 3, 1,
  141465. 0, 2, 4, 6, 8, 10, 12, 14,
  141466. 16, 18, 20, 22, 24, 26, 28, 30,
  141467. 32, 34, 36, 38, 40, 42, 44, 46,
  141468. 48,
  141469. };
  141470. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  141471. _vq_quantthresh__16u2_p9_2,
  141472. _vq_quantmap__16u2_p9_2,
  141473. 49,
  141474. 49
  141475. };
  141476. static static_codebook _16u2_p9_2 = {
  141477. 1, 49,
  141478. _vq_lengthlist__16u2_p9_2,
  141479. 1, -526909440, 1611661312, 6, 0,
  141480. _vq_quantlist__16u2_p9_2,
  141481. NULL,
  141482. &_vq_auxt__16u2_p9_2,
  141483. NULL,
  141484. 0
  141485. };
  141486. static long _vq_quantlist__8u0__p1_0[] = {
  141487. 1,
  141488. 0,
  141489. 2,
  141490. };
  141491. static long _vq_lengthlist__8u0__p1_0[] = {
  141492. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  141493. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  141494. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  141495. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  141496. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  141497. 11,
  141498. };
  141499. static float _vq_quantthresh__8u0__p1_0[] = {
  141500. -0.5, 0.5,
  141501. };
  141502. static long _vq_quantmap__8u0__p1_0[] = {
  141503. 1, 0, 2,
  141504. };
  141505. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  141506. _vq_quantthresh__8u0__p1_0,
  141507. _vq_quantmap__8u0__p1_0,
  141508. 3,
  141509. 3
  141510. };
  141511. static static_codebook _8u0__p1_0 = {
  141512. 4, 81,
  141513. _vq_lengthlist__8u0__p1_0,
  141514. 1, -535822336, 1611661312, 2, 0,
  141515. _vq_quantlist__8u0__p1_0,
  141516. NULL,
  141517. &_vq_auxt__8u0__p1_0,
  141518. NULL,
  141519. 0
  141520. };
  141521. static long _vq_quantlist__8u0__p2_0[] = {
  141522. 1,
  141523. 0,
  141524. 2,
  141525. };
  141526. static long _vq_lengthlist__8u0__p2_0[] = {
  141527. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  141528. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  141529. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  141530. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  141531. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  141532. 8,
  141533. };
  141534. static float _vq_quantthresh__8u0__p2_0[] = {
  141535. -0.5, 0.5,
  141536. };
  141537. static long _vq_quantmap__8u0__p2_0[] = {
  141538. 1, 0, 2,
  141539. };
  141540. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  141541. _vq_quantthresh__8u0__p2_0,
  141542. _vq_quantmap__8u0__p2_0,
  141543. 3,
  141544. 3
  141545. };
  141546. static static_codebook _8u0__p2_0 = {
  141547. 4, 81,
  141548. _vq_lengthlist__8u0__p2_0,
  141549. 1, -535822336, 1611661312, 2, 0,
  141550. _vq_quantlist__8u0__p2_0,
  141551. NULL,
  141552. &_vq_auxt__8u0__p2_0,
  141553. NULL,
  141554. 0
  141555. };
  141556. static long _vq_quantlist__8u0__p3_0[] = {
  141557. 2,
  141558. 1,
  141559. 3,
  141560. 0,
  141561. 4,
  141562. };
  141563. static long _vq_lengthlist__8u0__p3_0[] = {
  141564. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  141565. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  141566. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  141567. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141568. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  141569. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  141570. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  141571. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  141572. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  141573. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  141574. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  141575. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  141576. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  141577. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  141578. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  141579. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  141580. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  141581. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  141582. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  141583. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  141584. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  141585. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  141586. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  141587. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  141588. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  141589. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  141590. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  141591. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  141592. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  141593. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  141594. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  141595. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  141596. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  141597. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  141598. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  141599. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  141600. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  141601. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  141602. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  141603. 16,
  141604. };
  141605. static float _vq_quantthresh__8u0__p3_0[] = {
  141606. -1.5, -0.5, 0.5, 1.5,
  141607. };
  141608. static long _vq_quantmap__8u0__p3_0[] = {
  141609. 3, 1, 0, 2, 4,
  141610. };
  141611. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  141612. _vq_quantthresh__8u0__p3_0,
  141613. _vq_quantmap__8u0__p3_0,
  141614. 5,
  141615. 5
  141616. };
  141617. static static_codebook _8u0__p3_0 = {
  141618. 4, 625,
  141619. _vq_lengthlist__8u0__p3_0,
  141620. 1, -533725184, 1611661312, 3, 0,
  141621. _vq_quantlist__8u0__p3_0,
  141622. NULL,
  141623. &_vq_auxt__8u0__p3_0,
  141624. NULL,
  141625. 0
  141626. };
  141627. static long _vq_quantlist__8u0__p4_0[] = {
  141628. 2,
  141629. 1,
  141630. 3,
  141631. 0,
  141632. 4,
  141633. };
  141634. static long _vq_lengthlist__8u0__p4_0[] = {
  141635. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  141636. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  141637. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  141638. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  141639. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  141640. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  141641. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  141642. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  141643. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  141644. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  141645. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  141646. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  141647. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  141648. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  141649. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  141650. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  141651. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  141652. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  141653. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  141654. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  141655. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  141656. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  141657. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  141658. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  141659. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  141660. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  141661. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  141662. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  141663. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  141664. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  141665. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  141666. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  141667. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  141668. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  141669. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  141670. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  141671. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  141672. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  141673. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  141674. 12,
  141675. };
  141676. static float _vq_quantthresh__8u0__p4_0[] = {
  141677. -1.5, -0.5, 0.5, 1.5,
  141678. };
  141679. static long _vq_quantmap__8u0__p4_0[] = {
  141680. 3, 1, 0, 2, 4,
  141681. };
  141682. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  141683. _vq_quantthresh__8u0__p4_0,
  141684. _vq_quantmap__8u0__p4_0,
  141685. 5,
  141686. 5
  141687. };
  141688. static static_codebook _8u0__p4_0 = {
  141689. 4, 625,
  141690. _vq_lengthlist__8u0__p4_0,
  141691. 1, -533725184, 1611661312, 3, 0,
  141692. _vq_quantlist__8u0__p4_0,
  141693. NULL,
  141694. &_vq_auxt__8u0__p4_0,
  141695. NULL,
  141696. 0
  141697. };
  141698. static long _vq_quantlist__8u0__p5_0[] = {
  141699. 4,
  141700. 3,
  141701. 5,
  141702. 2,
  141703. 6,
  141704. 1,
  141705. 7,
  141706. 0,
  141707. 8,
  141708. };
  141709. static long _vq_lengthlist__8u0__p5_0[] = {
  141710. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  141711. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  141712. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  141713. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141714. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  141715. 12,
  141716. };
  141717. static float _vq_quantthresh__8u0__p5_0[] = {
  141718. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141719. };
  141720. static long _vq_quantmap__8u0__p5_0[] = {
  141721. 7, 5, 3, 1, 0, 2, 4, 6,
  141722. 8,
  141723. };
  141724. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  141725. _vq_quantthresh__8u0__p5_0,
  141726. _vq_quantmap__8u0__p5_0,
  141727. 9,
  141728. 9
  141729. };
  141730. static static_codebook _8u0__p5_0 = {
  141731. 2, 81,
  141732. _vq_lengthlist__8u0__p5_0,
  141733. 1, -531628032, 1611661312, 4, 0,
  141734. _vq_quantlist__8u0__p5_0,
  141735. NULL,
  141736. &_vq_auxt__8u0__p5_0,
  141737. NULL,
  141738. 0
  141739. };
  141740. static long _vq_quantlist__8u0__p6_0[] = {
  141741. 6,
  141742. 5,
  141743. 7,
  141744. 4,
  141745. 8,
  141746. 3,
  141747. 9,
  141748. 2,
  141749. 10,
  141750. 1,
  141751. 11,
  141752. 0,
  141753. 12,
  141754. };
  141755. static long _vq_lengthlist__8u0__p6_0[] = {
  141756. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  141757. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  141758. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  141759. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  141760. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  141761. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  141762. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  141763. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  141764. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  141765. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  141766. 16, 0,15, 0,17, 0, 0, 0, 0,
  141767. };
  141768. static float _vq_quantthresh__8u0__p6_0[] = {
  141769. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141770. 12.5, 17.5, 22.5, 27.5,
  141771. };
  141772. static long _vq_quantmap__8u0__p6_0[] = {
  141773. 11, 9, 7, 5, 3, 1, 0, 2,
  141774. 4, 6, 8, 10, 12,
  141775. };
  141776. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  141777. _vq_quantthresh__8u0__p6_0,
  141778. _vq_quantmap__8u0__p6_0,
  141779. 13,
  141780. 13
  141781. };
  141782. static static_codebook _8u0__p6_0 = {
  141783. 2, 169,
  141784. _vq_lengthlist__8u0__p6_0,
  141785. 1, -526516224, 1616117760, 4, 0,
  141786. _vq_quantlist__8u0__p6_0,
  141787. NULL,
  141788. &_vq_auxt__8u0__p6_0,
  141789. NULL,
  141790. 0
  141791. };
  141792. static long _vq_quantlist__8u0__p6_1[] = {
  141793. 2,
  141794. 1,
  141795. 3,
  141796. 0,
  141797. 4,
  141798. };
  141799. static long _vq_lengthlist__8u0__p6_1[] = {
  141800. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  141801. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  141802. };
  141803. static float _vq_quantthresh__8u0__p6_1[] = {
  141804. -1.5, -0.5, 0.5, 1.5,
  141805. };
  141806. static long _vq_quantmap__8u0__p6_1[] = {
  141807. 3, 1, 0, 2, 4,
  141808. };
  141809. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  141810. _vq_quantthresh__8u0__p6_1,
  141811. _vq_quantmap__8u0__p6_1,
  141812. 5,
  141813. 5
  141814. };
  141815. static static_codebook _8u0__p6_1 = {
  141816. 2, 25,
  141817. _vq_lengthlist__8u0__p6_1,
  141818. 1, -533725184, 1611661312, 3, 0,
  141819. _vq_quantlist__8u0__p6_1,
  141820. NULL,
  141821. &_vq_auxt__8u0__p6_1,
  141822. NULL,
  141823. 0
  141824. };
  141825. static long _vq_quantlist__8u0__p7_0[] = {
  141826. 1,
  141827. 0,
  141828. 2,
  141829. };
  141830. static long _vq_lengthlist__8u0__p7_0[] = {
  141831. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141832. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141833. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141834. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141835. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141836. 7,
  141837. };
  141838. static float _vq_quantthresh__8u0__p7_0[] = {
  141839. -157.5, 157.5,
  141840. };
  141841. static long _vq_quantmap__8u0__p7_0[] = {
  141842. 1, 0, 2,
  141843. };
  141844. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  141845. _vq_quantthresh__8u0__p7_0,
  141846. _vq_quantmap__8u0__p7_0,
  141847. 3,
  141848. 3
  141849. };
  141850. static static_codebook _8u0__p7_0 = {
  141851. 4, 81,
  141852. _vq_lengthlist__8u0__p7_0,
  141853. 1, -518803456, 1628680192, 2, 0,
  141854. _vq_quantlist__8u0__p7_0,
  141855. NULL,
  141856. &_vq_auxt__8u0__p7_0,
  141857. NULL,
  141858. 0
  141859. };
  141860. static long _vq_quantlist__8u0__p7_1[] = {
  141861. 7,
  141862. 6,
  141863. 8,
  141864. 5,
  141865. 9,
  141866. 4,
  141867. 10,
  141868. 3,
  141869. 11,
  141870. 2,
  141871. 12,
  141872. 1,
  141873. 13,
  141874. 0,
  141875. 14,
  141876. };
  141877. static long _vq_lengthlist__8u0__p7_1[] = {
  141878. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  141879. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  141880. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  141881. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  141882. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  141883. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  141884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141890. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  141891. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141892. 10,
  141893. };
  141894. static float _vq_quantthresh__8u0__p7_1[] = {
  141895. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141896. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141897. };
  141898. static long _vq_quantmap__8u0__p7_1[] = {
  141899. 13, 11, 9, 7, 5, 3, 1, 0,
  141900. 2, 4, 6, 8, 10, 12, 14,
  141901. };
  141902. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  141903. _vq_quantthresh__8u0__p7_1,
  141904. _vq_quantmap__8u0__p7_1,
  141905. 15,
  141906. 15
  141907. };
  141908. static static_codebook _8u0__p7_1 = {
  141909. 2, 225,
  141910. _vq_lengthlist__8u0__p7_1,
  141911. 1, -520986624, 1620377600, 4, 0,
  141912. _vq_quantlist__8u0__p7_1,
  141913. NULL,
  141914. &_vq_auxt__8u0__p7_1,
  141915. NULL,
  141916. 0
  141917. };
  141918. static long _vq_quantlist__8u0__p7_2[] = {
  141919. 10,
  141920. 9,
  141921. 11,
  141922. 8,
  141923. 12,
  141924. 7,
  141925. 13,
  141926. 6,
  141927. 14,
  141928. 5,
  141929. 15,
  141930. 4,
  141931. 16,
  141932. 3,
  141933. 17,
  141934. 2,
  141935. 18,
  141936. 1,
  141937. 19,
  141938. 0,
  141939. 20,
  141940. };
  141941. static long _vq_lengthlist__8u0__p7_2[] = {
  141942. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  141943. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  141944. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  141945. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  141946. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  141947. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  141948. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  141949. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  141950. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  141951. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  141952. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  141953. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  141954. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  141955. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  141956. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  141957. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  141958. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  141959. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  141960. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  141961. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  141962. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  141963. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  141964. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  141965. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  141966. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  141967. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  141968. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  141969. 11,12,11,11,11,10,10,11,11,
  141970. };
  141971. static float _vq_quantthresh__8u0__p7_2[] = {
  141972. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141973. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141974. 6.5, 7.5, 8.5, 9.5,
  141975. };
  141976. static long _vq_quantmap__8u0__p7_2[] = {
  141977. 19, 17, 15, 13, 11, 9, 7, 5,
  141978. 3, 1, 0, 2, 4, 6, 8, 10,
  141979. 12, 14, 16, 18, 20,
  141980. };
  141981. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  141982. _vq_quantthresh__8u0__p7_2,
  141983. _vq_quantmap__8u0__p7_2,
  141984. 21,
  141985. 21
  141986. };
  141987. static static_codebook _8u0__p7_2 = {
  141988. 2, 441,
  141989. _vq_lengthlist__8u0__p7_2,
  141990. 1, -529268736, 1611661312, 5, 0,
  141991. _vq_quantlist__8u0__p7_2,
  141992. NULL,
  141993. &_vq_auxt__8u0__p7_2,
  141994. NULL,
  141995. 0
  141996. };
  141997. static long _huff_lengthlist__8u0__single[] = {
  141998. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  141999. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  142000. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  142001. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  142002. };
  142003. static static_codebook _huff_book__8u0__single = {
  142004. 2, 64,
  142005. _huff_lengthlist__8u0__single,
  142006. 0, 0, 0, 0, 0,
  142007. NULL,
  142008. NULL,
  142009. NULL,
  142010. NULL,
  142011. 0
  142012. };
  142013. static long _vq_quantlist__8u1__p1_0[] = {
  142014. 1,
  142015. 0,
  142016. 2,
  142017. };
  142018. static long _vq_lengthlist__8u1__p1_0[] = {
  142019. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  142020. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  142021. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  142022. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142023. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  142024. 10,
  142025. };
  142026. static float _vq_quantthresh__8u1__p1_0[] = {
  142027. -0.5, 0.5,
  142028. };
  142029. static long _vq_quantmap__8u1__p1_0[] = {
  142030. 1, 0, 2,
  142031. };
  142032. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  142033. _vq_quantthresh__8u1__p1_0,
  142034. _vq_quantmap__8u1__p1_0,
  142035. 3,
  142036. 3
  142037. };
  142038. static static_codebook _8u1__p1_0 = {
  142039. 4, 81,
  142040. _vq_lengthlist__8u1__p1_0,
  142041. 1, -535822336, 1611661312, 2, 0,
  142042. _vq_quantlist__8u1__p1_0,
  142043. NULL,
  142044. &_vq_auxt__8u1__p1_0,
  142045. NULL,
  142046. 0
  142047. };
  142048. static long _vq_quantlist__8u1__p2_0[] = {
  142049. 1,
  142050. 0,
  142051. 2,
  142052. };
  142053. static long _vq_lengthlist__8u1__p2_0[] = {
  142054. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  142055. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  142056. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  142057. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  142058. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  142059. 7,
  142060. };
  142061. static float _vq_quantthresh__8u1__p2_0[] = {
  142062. -0.5, 0.5,
  142063. };
  142064. static long _vq_quantmap__8u1__p2_0[] = {
  142065. 1, 0, 2,
  142066. };
  142067. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  142068. _vq_quantthresh__8u1__p2_0,
  142069. _vq_quantmap__8u1__p2_0,
  142070. 3,
  142071. 3
  142072. };
  142073. static static_codebook _8u1__p2_0 = {
  142074. 4, 81,
  142075. _vq_lengthlist__8u1__p2_0,
  142076. 1, -535822336, 1611661312, 2, 0,
  142077. _vq_quantlist__8u1__p2_0,
  142078. NULL,
  142079. &_vq_auxt__8u1__p2_0,
  142080. NULL,
  142081. 0
  142082. };
  142083. static long _vq_quantlist__8u1__p3_0[] = {
  142084. 2,
  142085. 1,
  142086. 3,
  142087. 0,
  142088. 4,
  142089. };
  142090. static long _vq_lengthlist__8u1__p3_0[] = {
  142091. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  142092. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  142093. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  142094. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142095. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  142096. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  142097. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  142098. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  142099. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142100. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  142101. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  142102. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  142103. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  142104. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  142105. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  142106. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  142107. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142108. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  142109. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  142110. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  142111. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  142112. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  142113. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  142114. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  142115. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  142116. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  142117. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  142118. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  142119. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  142120. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  142121. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  142122. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  142123. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  142124. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  142125. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  142126. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  142127. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  142128. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  142129. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  142130. 16,
  142131. };
  142132. static float _vq_quantthresh__8u1__p3_0[] = {
  142133. -1.5, -0.5, 0.5, 1.5,
  142134. };
  142135. static long _vq_quantmap__8u1__p3_0[] = {
  142136. 3, 1, 0, 2, 4,
  142137. };
  142138. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  142139. _vq_quantthresh__8u1__p3_0,
  142140. _vq_quantmap__8u1__p3_0,
  142141. 5,
  142142. 5
  142143. };
  142144. static static_codebook _8u1__p3_0 = {
  142145. 4, 625,
  142146. _vq_lengthlist__8u1__p3_0,
  142147. 1, -533725184, 1611661312, 3, 0,
  142148. _vq_quantlist__8u1__p3_0,
  142149. NULL,
  142150. &_vq_auxt__8u1__p3_0,
  142151. NULL,
  142152. 0
  142153. };
  142154. static long _vq_quantlist__8u1__p4_0[] = {
  142155. 2,
  142156. 1,
  142157. 3,
  142158. 0,
  142159. 4,
  142160. };
  142161. static long _vq_lengthlist__8u1__p4_0[] = {
  142162. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  142163. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  142164. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  142165. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  142166. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142167. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  142168. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  142169. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  142170. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  142171. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  142172. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  142173. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  142174. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  142175. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  142176. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  142177. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  142178. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  142179. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142180. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  142181. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  142182. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  142183. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  142184. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  142185. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  142186. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  142187. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  142188. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  142189. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  142190. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  142191. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  142192. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  142193. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  142194. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  142195. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  142196. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  142197. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  142198. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  142199. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  142200. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  142201. 10,
  142202. };
  142203. static float _vq_quantthresh__8u1__p4_0[] = {
  142204. -1.5, -0.5, 0.5, 1.5,
  142205. };
  142206. static long _vq_quantmap__8u1__p4_0[] = {
  142207. 3, 1, 0, 2, 4,
  142208. };
  142209. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  142210. _vq_quantthresh__8u1__p4_0,
  142211. _vq_quantmap__8u1__p4_0,
  142212. 5,
  142213. 5
  142214. };
  142215. static static_codebook _8u1__p4_0 = {
  142216. 4, 625,
  142217. _vq_lengthlist__8u1__p4_0,
  142218. 1, -533725184, 1611661312, 3, 0,
  142219. _vq_quantlist__8u1__p4_0,
  142220. NULL,
  142221. &_vq_auxt__8u1__p4_0,
  142222. NULL,
  142223. 0
  142224. };
  142225. static long _vq_quantlist__8u1__p5_0[] = {
  142226. 4,
  142227. 3,
  142228. 5,
  142229. 2,
  142230. 6,
  142231. 1,
  142232. 7,
  142233. 0,
  142234. 8,
  142235. };
  142236. static long _vq_lengthlist__8u1__p5_0[] = {
  142237. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  142238. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142239. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  142240. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  142241. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  142242. 13,
  142243. };
  142244. static float _vq_quantthresh__8u1__p5_0[] = {
  142245. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142246. };
  142247. static long _vq_quantmap__8u1__p5_0[] = {
  142248. 7, 5, 3, 1, 0, 2, 4, 6,
  142249. 8,
  142250. };
  142251. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  142252. _vq_quantthresh__8u1__p5_0,
  142253. _vq_quantmap__8u1__p5_0,
  142254. 9,
  142255. 9
  142256. };
  142257. static static_codebook _8u1__p5_0 = {
  142258. 2, 81,
  142259. _vq_lengthlist__8u1__p5_0,
  142260. 1, -531628032, 1611661312, 4, 0,
  142261. _vq_quantlist__8u1__p5_0,
  142262. NULL,
  142263. &_vq_auxt__8u1__p5_0,
  142264. NULL,
  142265. 0
  142266. };
  142267. static long _vq_quantlist__8u1__p6_0[] = {
  142268. 4,
  142269. 3,
  142270. 5,
  142271. 2,
  142272. 6,
  142273. 1,
  142274. 7,
  142275. 0,
  142276. 8,
  142277. };
  142278. static long _vq_lengthlist__8u1__p6_0[] = {
  142279. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  142280. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142281. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  142282. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  142283. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  142284. 10,
  142285. };
  142286. static float _vq_quantthresh__8u1__p6_0[] = {
  142287. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142288. };
  142289. static long _vq_quantmap__8u1__p6_0[] = {
  142290. 7, 5, 3, 1, 0, 2, 4, 6,
  142291. 8,
  142292. };
  142293. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  142294. _vq_quantthresh__8u1__p6_0,
  142295. _vq_quantmap__8u1__p6_0,
  142296. 9,
  142297. 9
  142298. };
  142299. static static_codebook _8u1__p6_0 = {
  142300. 2, 81,
  142301. _vq_lengthlist__8u1__p6_0,
  142302. 1, -531628032, 1611661312, 4, 0,
  142303. _vq_quantlist__8u1__p6_0,
  142304. NULL,
  142305. &_vq_auxt__8u1__p6_0,
  142306. NULL,
  142307. 0
  142308. };
  142309. static long _vq_quantlist__8u1__p7_0[] = {
  142310. 1,
  142311. 0,
  142312. 2,
  142313. };
  142314. static long _vq_lengthlist__8u1__p7_0[] = {
  142315. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  142316. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  142317. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  142318. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  142319. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  142320. 11,
  142321. };
  142322. static float _vq_quantthresh__8u1__p7_0[] = {
  142323. -5.5, 5.5,
  142324. };
  142325. static long _vq_quantmap__8u1__p7_0[] = {
  142326. 1, 0, 2,
  142327. };
  142328. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  142329. _vq_quantthresh__8u1__p7_0,
  142330. _vq_quantmap__8u1__p7_0,
  142331. 3,
  142332. 3
  142333. };
  142334. static static_codebook _8u1__p7_0 = {
  142335. 4, 81,
  142336. _vq_lengthlist__8u1__p7_0,
  142337. 1, -529137664, 1618345984, 2, 0,
  142338. _vq_quantlist__8u1__p7_0,
  142339. NULL,
  142340. &_vq_auxt__8u1__p7_0,
  142341. NULL,
  142342. 0
  142343. };
  142344. static long _vq_quantlist__8u1__p7_1[] = {
  142345. 5,
  142346. 4,
  142347. 6,
  142348. 3,
  142349. 7,
  142350. 2,
  142351. 8,
  142352. 1,
  142353. 9,
  142354. 0,
  142355. 10,
  142356. };
  142357. static long _vq_lengthlist__8u1__p7_1[] = {
  142358. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  142359. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  142360. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142361. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  142362. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  142363. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142364. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  142365. 9, 9, 9, 9, 9,10,10,10,10,
  142366. };
  142367. static float _vq_quantthresh__8u1__p7_1[] = {
  142368. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142369. 3.5, 4.5,
  142370. };
  142371. static long _vq_quantmap__8u1__p7_1[] = {
  142372. 9, 7, 5, 3, 1, 0, 2, 4,
  142373. 6, 8, 10,
  142374. };
  142375. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  142376. _vq_quantthresh__8u1__p7_1,
  142377. _vq_quantmap__8u1__p7_1,
  142378. 11,
  142379. 11
  142380. };
  142381. static static_codebook _8u1__p7_1 = {
  142382. 2, 121,
  142383. _vq_lengthlist__8u1__p7_1,
  142384. 1, -531365888, 1611661312, 4, 0,
  142385. _vq_quantlist__8u1__p7_1,
  142386. NULL,
  142387. &_vq_auxt__8u1__p7_1,
  142388. NULL,
  142389. 0
  142390. };
  142391. static long _vq_quantlist__8u1__p8_0[] = {
  142392. 5,
  142393. 4,
  142394. 6,
  142395. 3,
  142396. 7,
  142397. 2,
  142398. 8,
  142399. 1,
  142400. 9,
  142401. 0,
  142402. 10,
  142403. };
  142404. static long _vq_lengthlist__8u1__p8_0[] = {
  142405. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  142406. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  142407. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  142408. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  142409. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  142410. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  142411. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  142412. 12,13,13,14,14,15,15,15,15,
  142413. };
  142414. static float _vq_quantthresh__8u1__p8_0[] = {
  142415. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142416. 38.5, 49.5,
  142417. };
  142418. static long _vq_quantmap__8u1__p8_0[] = {
  142419. 9, 7, 5, 3, 1, 0, 2, 4,
  142420. 6, 8, 10,
  142421. };
  142422. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  142423. _vq_quantthresh__8u1__p8_0,
  142424. _vq_quantmap__8u1__p8_0,
  142425. 11,
  142426. 11
  142427. };
  142428. static static_codebook _8u1__p8_0 = {
  142429. 2, 121,
  142430. _vq_lengthlist__8u1__p8_0,
  142431. 1, -524582912, 1618345984, 4, 0,
  142432. _vq_quantlist__8u1__p8_0,
  142433. NULL,
  142434. &_vq_auxt__8u1__p8_0,
  142435. NULL,
  142436. 0
  142437. };
  142438. static long _vq_quantlist__8u1__p8_1[] = {
  142439. 5,
  142440. 4,
  142441. 6,
  142442. 3,
  142443. 7,
  142444. 2,
  142445. 8,
  142446. 1,
  142447. 9,
  142448. 0,
  142449. 10,
  142450. };
  142451. static long _vq_lengthlist__8u1__p8_1[] = {
  142452. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  142453. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  142454. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  142455. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  142456. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142457. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  142458. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  142459. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  142460. };
  142461. static float _vq_quantthresh__8u1__p8_1[] = {
  142462. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142463. 3.5, 4.5,
  142464. };
  142465. static long _vq_quantmap__8u1__p8_1[] = {
  142466. 9, 7, 5, 3, 1, 0, 2, 4,
  142467. 6, 8, 10,
  142468. };
  142469. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  142470. _vq_quantthresh__8u1__p8_1,
  142471. _vq_quantmap__8u1__p8_1,
  142472. 11,
  142473. 11
  142474. };
  142475. static static_codebook _8u1__p8_1 = {
  142476. 2, 121,
  142477. _vq_lengthlist__8u1__p8_1,
  142478. 1, -531365888, 1611661312, 4, 0,
  142479. _vq_quantlist__8u1__p8_1,
  142480. NULL,
  142481. &_vq_auxt__8u1__p8_1,
  142482. NULL,
  142483. 0
  142484. };
  142485. static long _vq_quantlist__8u1__p9_0[] = {
  142486. 7,
  142487. 6,
  142488. 8,
  142489. 5,
  142490. 9,
  142491. 4,
  142492. 10,
  142493. 3,
  142494. 11,
  142495. 2,
  142496. 12,
  142497. 1,
  142498. 13,
  142499. 0,
  142500. 14,
  142501. };
  142502. static long _vq_lengthlist__8u1__p9_0[] = {
  142503. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  142504. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  142505. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142515. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  142516. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142517. 10,
  142518. };
  142519. static float _vq_quantthresh__8u1__p9_0[] = {
  142520. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  142521. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  142522. };
  142523. static long _vq_quantmap__8u1__p9_0[] = {
  142524. 13, 11, 9, 7, 5, 3, 1, 0,
  142525. 2, 4, 6, 8, 10, 12, 14,
  142526. };
  142527. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  142528. _vq_quantthresh__8u1__p9_0,
  142529. _vq_quantmap__8u1__p9_0,
  142530. 15,
  142531. 15
  142532. };
  142533. static static_codebook _8u1__p9_0 = {
  142534. 2, 225,
  142535. _vq_lengthlist__8u1__p9_0,
  142536. 1, -514071552, 1627381760, 4, 0,
  142537. _vq_quantlist__8u1__p9_0,
  142538. NULL,
  142539. &_vq_auxt__8u1__p9_0,
  142540. NULL,
  142541. 0
  142542. };
  142543. static long _vq_quantlist__8u1__p9_1[] = {
  142544. 7,
  142545. 6,
  142546. 8,
  142547. 5,
  142548. 9,
  142549. 4,
  142550. 10,
  142551. 3,
  142552. 11,
  142553. 2,
  142554. 12,
  142555. 1,
  142556. 13,
  142557. 0,
  142558. 14,
  142559. };
  142560. static long _vq_lengthlist__8u1__p9_1[] = {
  142561. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  142562. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  142563. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  142564. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  142565. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  142566. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  142567. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  142568. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  142569. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  142570. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  142571. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  142572. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  142573. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  142574. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  142575. 13,
  142576. };
  142577. static float _vq_quantthresh__8u1__p9_1[] = {
  142578. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142579. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142580. };
  142581. static long _vq_quantmap__8u1__p9_1[] = {
  142582. 13, 11, 9, 7, 5, 3, 1, 0,
  142583. 2, 4, 6, 8, 10, 12, 14,
  142584. };
  142585. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  142586. _vq_quantthresh__8u1__p9_1,
  142587. _vq_quantmap__8u1__p9_1,
  142588. 15,
  142589. 15
  142590. };
  142591. static static_codebook _8u1__p9_1 = {
  142592. 2, 225,
  142593. _vq_lengthlist__8u1__p9_1,
  142594. 1, -522338304, 1620115456, 4, 0,
  142595. _vq_quantlist__8u1__p9_1,
  142596. NULL,
  142597. &_vq_auxt__8u1__p9_1,
  142598. NULL,
  142599. 0
  142600. };
  142601. static long _vq_quantlist__8u1__p9_2[] = {
  142602. 8,
  142603. 7,
  142604. 9,
  142605. 6,
  142606. 10,
  142607. 5,
  142608. 11,
  142609. 4,
  142610. 12,
  142611. 3,
  142612. 13,
  142613. 2,
  142614. 14,
  142615. 1,
  142616. 15,
  142617. 0,
  142618. 16,
  142619. };
  142620. static long _vq_lengthlist__8u1__p9_2[] = {
  142621. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142622. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142623. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142624. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  142625. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  142626. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  142627. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  142628. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  142629. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  142630. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  142631. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142632. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142633. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142634. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142635. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  142636. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142637. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142638. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142639. 10,
  142640. };
  142641. static float _vq_quantthresh__8u1__p9_2[] = {
  142642. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142643. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142644. };
  142645. static long _vq_quantmap__8u1__p9_2[] = {
  142646. 15, 13, 11, 9, 7, 5, 3, 1,
  142647. 0, 2, 4, 6, 8, 10, 12, 14,
  142648. 16,
  142649. };
  142650. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  142651. _vq_quantthresh__8u1__p9_2,
  142652. _vq_quantmap__8u1__p9_2,
  142653. 17,
  142654. 17
  142655. };
  142656. static static_codebook _8u1__p9_2 = {
  142657. 2, 289,
  142658. _vq_lengthlist__8u1__p9_2,
  142659. 1, -529530880, 1611661312, 5, 0,
  142660. _vq_quantlist__8u1__p9_2,
  142661. NULL,
  142662. &_vq_auxt__8u1__p9_2,
  142663. NULL,
  142664. 0
  142665. };
  142666. static long _huff_lengthlist__8u1__single[] = {
  142667. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  142668. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  142669. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  142670. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  142671. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  142672. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  142673. 13, 8, 8,15,
  142674. };
  142675. static static_codebook _huff_book__8u1__single = {
  142676. 2, 100,
  142677. _huff_lengthlist__8u1__single,
  142678. 0, 0, 0, 0, 0,
  142679. NULL,
  142680. NULL,
  142681. NULL,
  142682. NULL,
  142683. 0
  142684. };
  142685. static long _huff_lengthlist__44u0__long[] = {
  142686. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  142687. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  142688. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  142689. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  142690. };
  142691. static static_codebook _huff_book__44u0__long = {
  142692. 2, 64,
  142693. _huff_lengthlist__44u0__long,
  142694. 0, 0, 0, 0, 0,
  142695. NULL,
  142696. NULL,
  142697. NULL,
  142698. NULL,
  142699. 0
  142700. };
  142701. static long _vq_quantlist__44u0__p1_0[] = {
  142702. 1,
  142703. 0,
  142704. 2,
  142705. };
  142706. static long _vq_lengthlist__44u0__p1_0[] = {
  142707. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142708. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142709. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  142710. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  142711. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  142712. 13,
  142713. };
  142714. static float _vq_quantthresh__44u0__p1_0[] = {
  142715. -0.5, 0.5,
  142716. };
  142717. static long _vq_quantmap__44u0__p1_0[] = {
  142718. 1, 0, 2,
  142719. };
  142720. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  142721. _vq_quantthresh__44u0__p1_0,
  142722. _vq_quantmap__44u0__p1_0,
  142723. 3,
  142724. 3
  142725. };
  142726. static static_codebook _44u0__p1_0 = {
  142727. 4, 81,
  142728. _vq_lengthlist__44u0__p1_0,
  142729. 1, -535822336, 1611661312, 2, 0,
  142730. _vq_quantlist__44u0__p1_0,
  142731. NULL,
  142732. &_vq_auxt__44u0__p1_0,
  142733. NULL,
  142734. 0
  142735. };
  142736. static long _vq_quantlist__44u0__p2_0[] = {
  142737. 1,
  142738. 0,
  142739. 2,
  142740. };
  142741. static long _vq_lengthlist__44u0__p2_0[] = {
  142742. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142743. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142744. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142745. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142746. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142747. 9,
  142748. };
  142749. static float _vq_quantthresh__44u0__p2_0[] = {
  142750. -0.5, 0.5,
  142751. };
  142752. static long _vq_quantmap__44u0__p2_0[] = {
  142753. 1, 0, 2,
  142754. };
  142755. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  142756. _vq_quantthresh__44u0__p2_0,
  142757. _vq_quantmap__44u0__p2_0,
  142758. 3,
  142759. 3
  142760. };
  142761. static static_codebook _44u0__p2_0 = {
  142762. 4, 81,
  142763. _vq_lengthlist__44u0__p2_0,
  142764. 1, -535822336, 1611661312, 2, 0,
  142765. _vq_quantlist__44u0__p2_0,
  142766. NULL,
  142767. &_vq_auxt__44u0__p2_0,
  142768. NULL,
  142769. 0
  142770. };
  142771. static long _vq_quantlist__44u0__p3_0[] = {
  142772. 2,
  142773. 1,
  142774. 3,
  142775. 0,
  142776. 4,
  142777. };
  142778. static long _vq_lengthlist__44u0__p3_0[] = {
  142779. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142780. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142781. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142782. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142783. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142784. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142785. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142786. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142787. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142788. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142789. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142790. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142791. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142792. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142793. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142794. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142795. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142796. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142797. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142798. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142799. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142800. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142801. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142802. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142803. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142804. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142805. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142806. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142807. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142808. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142809. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142810. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142811. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142812. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142813. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142814. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142815. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142816. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142817. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142818. 19,
  142819. };
  142820. static float _vq_quantthresh__44u0__p3_0[] = {
  142821. -1.5, -0.5, 0.5, 1.5,
  142822. };
  142823. static long _vq_quantmap__44u0__p3_0[] = {
  142824. 3, 1, 0, 2, 4,
  142825. };
  142826. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  142827. _vq_quantthresh__44u0__p3_0,
  142828. _vq_quantmap__44u0__p3_0,
  142829. 5,
  142830. 5
  142831. };
  142832. static static_codebook _44u0__p3_0 = {
  142833. 4, 625,
  142834. _vq_lengthlist__44u0__p3_0,
  142835. 1, -533725184, 1611661312, 3, 0,
  142836. _vq_quantlist__44u0__p3_0,
  142837. NULL,
  142838. &_vq_auxt__44u0__p3_0,
  142839. NULL,
  142840. 0
  142841. };
  142842. static long _vq_quantlist__44u0__p4_0[] = {
  142843. 2,
  142844. 1,
  142845. 3,
  142846. 0,
  142847. 4,
  142848. };
  142849. static long _vq_lengthlist__44u0__p4_0[] = {
  142850. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142851. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142852. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142853. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142854. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142855. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142856. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142857. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142858. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142859. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142860. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142861. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142862. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142863. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142864. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142865. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142866. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142867. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142868. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142869. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142870. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142871. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142872. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142873. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142874. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142875. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142876. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142877. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142878. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142879. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142880. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142881. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142882. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142883. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142884. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142885. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142886. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142887. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142888. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142889. 12,
  142890. };
  142891. static float _vq_quantthresh__44u0__p4_0[] = {
  142892. -1.5, -0.5, 0.5, 1.5,
  142893. };
  142894. static long _vq_quantmap__44u0__p4_0[] = {
  142895. 3, 1, 0, 2, 4,
  142896. };
  142897. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  142898. _vq_quantthresh__44u0__p4_0,
  142899. _vq_quantmap__44u0__p4_0,
  142900. 5,
  142901. 5
  142902. };
  142903. static static_codebook _44u0__p4_0 = {
  142904. 4, 625,
  142905. _vq_lengthlist__44u0__p4_0,
  142906. 1, -533725184, 1611661312, 3, 0,
  142907. _vq_quantlist__44u0__p4_0,
  142908. NULL,
  142909. &_vq_auxt__44u0__p4_0,
  142910. NULL,
  142911. 0
  142912. };
  142913. static long _vq_quantlist__44u0__p5_0[] = {
  142914. 4,
  142915. 3,
  142916. 5,
  142917. 2,
  142918. 6,
  142919. 1,
  142920. 7,
  142921. 0,
  142922. 8,
  142923. };
  142924. static long _vq_lengthlist__44u0__p5_0[] = {
  142925. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142926. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142927. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142928. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142929. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142930. 12,
  142931. };
  142932. static float _vq_quantthresh__44u0__p5_0[] = {
  142933. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142934. };
  142935. static long _vq_quantmap__44u0__p5_0[] = {
  142936. 7, 5, 3, 1, 0, 2, 4, 6,
  142937. 8,
  142938. };
  142939. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  142940. _vq_quantthresh__44u0__p5_0,
  142941. _vq_quantmap__44u0__p5_0,
  142942. 9,
  142943. 9
  142944. };
  142945. static static_codebook _44u0__p5_0 = {
  142946. 2, 81,
  142947. _vq_lengthlist__44u0__p5_0,
  142948. 1, -531628032, 1611661312, 4, 0,
  142949. _vq_quantlist__44u0__p5_0,
  142950. NULL,
  142951. &_vq_auxt__44u0__p5_0,
  142952. NULL,
  142953. 0
  142954. };
  142955. static long _vq_quantlist__44u0__p6_0[] = {
  142956. 6,
  142957. 5,
  142958. 7,
  142959. 4,
  142960. 8,
  142961. 3,
  142962. 9,
  142963. 2,
  142964. 10,
  142965. 1,
  142966. 11,
  142967. 0,
  142968. 12,
  142969. };
  142970. static long _vq_lengthlist__44u0__p6_0[] = {
  142971. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142972. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142973. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142974. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142975. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142976. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142977. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142978. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142979. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142980. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142981. 15,17,16,17,18,17,17,18, 0,
  142982. };
  142983. static float _vq_quantthresh__44u0__p6_0[] = {
  142984. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142985. 12.5, 17.5, 22.5, 27.5,
  142986. };
  142987. static long _vq_quantmap__44u0__p6_0[] = {
  142988. 11, 9, 7, 5, 3, 1, 0, 2,
  142989. 4, 6, 8, 10, 12,
  142990. };
  142991. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  142992. _vq_quantthresh__44u0__p6_0,
  142993. _vq_quantmap__44u0__p6_0,
  142994. 13,
  142995. 13
  142996. };
  142997. static static_codebook _44u0__p6_0 = {
  142998. 2, 169,
  142999. _vq_lengthlist__44u0__p6_0,
  143000. 1, -526516224, 1616117760, 4, 0,
  143001. _vq_quantlist__44u0__p6_0,
  143002. NULL,
  143003. &_vq_auxt__44u0__p6_0,
  143004. NULL,
  143005. 0
  143006. };
  143007. static long _vq_quantlist__44u0__p6_1[] = {
  143008. 2,
  143009. 1,
  143010. 3,
  143011. 0,
  143012. 4,
  143013. };
  143014. static long _vq_lengthlist__44u0__p6_1[] = {
  143015. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  143016. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  143017. };
  143018. static float _vq_quantthresh__44u0__p6_1[] = {
  143019. -1.5, -0.5, 0.5, 1.5,
  143020. };
  143021. static long _vq_quantmap__44u0__p6_1[] = {
  143022. 3, 1, 0, 2, 4,
  143023. };
  143024. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  143025. _vq_quantthresh__44u0__p6_1,
  143026. _vq_quantmap__44u0__p6_1,
  143027. 5,
  143028. 5
  143029. };
  143030. static static_codebook _44u0__p6_1 = {
  143031. 2, 25,
  143032. _vq_lengthlist__44u0__p6_1,
  143033. 1, -533725184, 1611661312, 3, 0,
  143034. _vq_quantlist__44u0__p6_1,
  143035. NULL,
  143036. &_vq_auxt__44u0__p6_1,
  143037. NULL,
  143038. 0
  143039. };
  143040. static long _vq_quantlist__44u0__p7_0[] = {
  143041. 2,
  143042. 1,
  143043. 3,
  143044. 0,
  143045. 4,
  143046. };
  143047. static long _vq_lengthlist__44u0__p7_0[] = {
  143048. 1, 4, 4,11,11, 9,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, 9,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,10,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,11,11,11,11,11,11,11,11,11,11,
  143063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143065. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143066. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143068. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143069. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143073. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143078. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  143079. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143080. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143082. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143083. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143084. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143085. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143086. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143087. 10,
  143088. };
  143089. static float _vq_quantthresh__44u0__p7_0[] = {
  143090. -253.5, -84.5, 84.5, 253.5,
  143091. };
  143092. static long _vq_quantmap__44u0__p7_0[] = {
  143093. 3, 1, 0, 2, 4,
  143094. };
  143095. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  143096. _vq_quantthresh__44u0__p7_0,
  143097. _vq_quantmap__44u0__p7_0,
  143098. 5,
  143099. 5
  143100. };
  143101. static static_codebook _44u0__p7_0 = {
  143102. 4, 625,
  143103. _vq_lengthlist__44u0__p7_0,
  143104. 1, -518709248, 1626677248, 3, 0,
  143105. _vq_quantlist__44u0__p7_0,
  143106. NULL,
  143107. &_vq_auxt__44u0__p7_0,
  143108. NULL,
  143109. 0
  143110. };
  143111. static long _vq_quantlist__44u0__p7_1[] = {
  143112. 6,
  143113. 5,
  143114. 7,
  143115. 4,
  143116. 8,
  143117. 3,
  143118. 9,
  143119. 2,
  143120. 10,
  143121. 1,
  143122. 11,
  143123. 0,
  143124. 12,
  143125. };
  143126. static long _vq_lengthlist__44u0__p7_1[] = {
  143127. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  143128. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  143129. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  143130. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  143131. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  143132. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  143133. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  143134. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  143135. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  143136. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  143137. 15,15,15,15,15,15,15,15,15,
  143138. };
  143139. static float _vq_quantthresh__44u0__p7_1[] = {
  143140. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143141. 32.5, 45.5, 58.5, 71.5,
  143142. };
  143143. static long _vq_quantmap__44u0__p7_1[] = {
  143144. 11, 9, 7, 5, 3, 1, 0, 2,
  143145. 4, 6, 8, 10, 12,
  143146. };
  143147. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  143148. _vq_quantthresh__44u0__p7_1,
  143149. _vq_quantmap__44u0__p7_1,
  143150. 13,
  143151. 13
  143152. };
  143153. static static_codebook _44u0__p7_1 = {
  143154. 2, 169,
  143155. _vq_lengthlist__44u0__p7_1,
  143156. 1, -523010048, 1618608128, 4, 0,
  143157. _vq_quantlist__44u0__p7_1,
  143158. NULL,
  143159. &_vq_auxt__44u0__p7_1,
  143160. NULL,
  143161. 0
  143162. };
  143163. static long _vq_quantlist__44u0__p7_2[] = {
  143164. 6,
  143165. 5,
  143166. 7,
  143167. 4,
  143168. 8,
  143169. 3,
  143170. 9,
  143171. 2,
  143172. 10,
  143173. 1,
  143174. 11,
  143175. 0,
  143176. 12,
  143177. };
  143178. static long _vq_lengthlist__44u0__p7_2[] = {
  143179. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  143180. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  143181. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  143182. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143183. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  143184. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  143185. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  143186. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143187. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143188. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  143189. 9, 9, 9,10, 9, 9,10,10, 9,
  143190. };
  143191. static float _vq_quantthresh__44u0__p7_2[] = {
  143192. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143193. 2.5, 3.5, 4.5, 5.5,
  143194. };
  143195. static long _vq_quantmap__44u0__p7_2[] = {
  143196. 11, 9, 7, 5, 3, 1, 0, 2,
  143197. 4, 6, 8, 10, 12,
  143198. };
  143199. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  143200. _vq_quantthresh__44u0__p7_2,
  143201. _vq_quantmap__44u0__p7_2,
  143202. 13,
  143203. 13
  143204. };
  143205. static static_codebook _44u0__p7_2 = {
  143206. 2, 169,
  143207. _vq_lengthlist__44u0__p7_2,
  143208. 1, -531103744, 1611661312, 4, 0,
  143209. _vq_quantlist__44u0__p7_2,
  143210. NULL,
  143211. &_vq_auxt__44u0__p7_2,
  143212. NULL,
  143213. 0
  143214. };
  143215. static long _huff_lengthlist__44u0__short[] = {
  143216. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143217. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143218. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143219. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143220. };
  143221. static static_codebook _huff_book__44u0__short = {
  143222. 2, 64,
  143223. _huff_lengthlist__44u0__short,
  143224. 0, 0, 0, 0, 0,
  143225. NULL,
  143226. NULL,
  143227. NULL,
  143228. NULL,
  143229. 0
  143230. };
  143231. static long _huff_lengthlist__44u1__long[] = {
  143232. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  143233. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  143234. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  143235. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  143236. };
  143237. static static_codebook _huff_book__44u1__long = {
  143238. 2, 64,
  143239. _huff_lengthlist__44u1__long,
  143240. 0, 0, 0, 0, 0,
  143241. NULL,
  143242. NULL,
  143243. NULL,
  143244. NULL,
  143245. 0
  143246. };
  143247. static long _vq_quantlist__44u1__p1_0[] = {
  143248. 1,
  143249. 0,
  143250. 2,
  143251. };
  143252. static long _vq_lengthlist__44u1__p1_0[] = {
  143253. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143254. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143255. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  143256. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  143257. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  143258. 13,
  143259. };
  143260. static float _vq_quantthresh__44u1__p1_0[] = {
  143261. -0.5, 0.5,
  143262. };
  143263. static long _vq_quantmap__44u1__p1_0[] = {
  143264. 1, 0, 2,
  143265. };
  143266. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  143267. _vq_quantthresh__44u1__p1_0,
  143268. _vq_quantmap__44u1__p1_0,
  143269. 3,
  143270. 3
  143271. };
  143272. static static_codebook _44u1__p1_0 = {
  143273. 4, 81,
  143274. _vq_lengthlist__44u1__p1_0,
  143275. 1, -535822336, 1611661312, 2, 0,
  143276. _vq_quantlist__44u1__p1_0,
  143277. NULL,
  143278. &_vq_auxt__44u1__p1_0,
  143279. NULL,
  143280. 0
  143281. };
  143282. static long _vq_quantlist__44u1__p2_0[] = {
  143283. 1,
  143284. 0,
  143285. 2,
  143286. };
  143287. static long _vq_lengthlist__44u1__p2_0[] = {
  143288. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  143289. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  143290. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143291. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  143292. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143293. 9,
  143294. };
  143295. static float _vq_quantthresh__44u1__p2_0[] = {
  143296. -0.5, 0.5,
  143297. };
  143298. static long _vq_quantmap__44u1__p2_0[] = {
  143299. 1, 0, 2,
  143300. };
  143301. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  143302. _vq_quantthresh__44u1__p2_0,
  143303. _vq_quantmap__44u1__p2_0,
  143304. 3,
  143305. 3
  143306. };
  143307. static static_codebook _44u1__p2_0 = {
  143308. 4, 81,
  143309. _vq_lengthlist__44u1__p2_0,
  143310. 1, -535822336, 1611661312, 2, 0,
  143311. _vq_quantlist__44u1__p2_0,
  143312. NULL,
  143313. &_vq_auxt__44u1__p2_0,
  143314. NULL,
  143315. 0
  143316. };
  143317. static long _vq_quantlist__44u1__p3_0[] = {
  143318. 2,
  143319. 1,
  143320. 3,
  143321. 0,
  143322. 4,
  143323. };
  143324. static long _vq_lengthlist__44u1__p3_0[] = {
  143325. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  143326. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  143327. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  143328. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143329. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  143330. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  143331. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  143332. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  143333. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  143334. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  143335. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  143336. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  143337. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  143338. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  143339. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  143340. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  143341. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  143342. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  143343. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  143344. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  143345. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  143346. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  143347. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  143348. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  143349. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  143350. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  143351. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  143352. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  143353. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  143354. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  143355. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  143356. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  143357. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  143358. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  143359. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  143360. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  143361. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  143362. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  143363. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  143364. 19,
  143365. };
  143366. static float _vq_quantthresh__44u1__p3_0[] = {
  143367. -1.5, -0.5, 0.5, 1.5,
  143368. };
  143369. static long _vq_quantmap__44u1__p3_0[] = {
  143370. 3, 1, 0, 2, 4,
  143371. };
  143372. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  143373. _vq_quantthresh__44u1__p3_0,
  143374. _vq_quantmap__44u1__p3_0,
  143375. 5,
  143376. 5
  143377. };
  143378. static static_codebook _44u1__p3_0 = {
  143379. 4, 625,
  143380. _vq_lengthlist__44u1__p3_0,
  143381. 1, -533725184, 1611661312, 3, 0,
  143382. _vq_quantlist__44u1__p3_0,
  143383. NULL,
  143384. &_vq_auxt__44u1__p3_0,
  143385. NULL,
  143386. 0
  143387. };
  143388. static long _vq_quantlist__44u1__p4_0[] = {
  143389. 2,
  143390. 1,
  143391. 3,
  143392. 0,
  143393. 4,
  143394. };
  143395. static long _vq_lengthlist__44u1__p4_0[] = {
  143396. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  143397. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  143398. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  143399. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  143400. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  143401. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  143402. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  143403. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  143404. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  143405. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  143406. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  143407. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143408. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  143409. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  143410. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  143411. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  143412. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  143413. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143414. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  143415. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  143416. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  143417. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  143418. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  143419. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  143420. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  143421. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  143422. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  143423. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  143424. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  143425. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  143426. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  143427. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  143428. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  143429. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  143430. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  143431. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  143432. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  143433. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  143434. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  143435. 12,
  143436. };
  143437. static float _vq_quantthresh__44u1__p4_0[] = {
  143438. -1.5, -0.5, 0.5, 1.5,
  143439. };
  143440. static long _vq_quantmap__44u1__p4_0[] = {
  143441. 3, 1, 0, 2, 4,
  143442. };
  143443. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  143444. _vq_quantthresh__44u1__p4_0,
  143445. _vq_quantmap__44u1__p4_0,
  143446. 5,
  143447. 5
  143448. };
  143449. static static_codebook _44u1__p4_0 = {
  143450. 4, 625,
  143451. _vq_lengthlist__44u1__p4_0,
  143452. 1, -533725184, 1611661312, 3, 0,
  143453. _vq_quantlist__44u1__p4_0,
  143454. NULL,
  143455. &_vq_auxt__44u1__p4_0,
  143456. NULL,
  143457. 0
  143458. };
  143459. static long _vq_quantlist__44u1__p5_0[] = {
  143460. 4,
  143461. 3,
  143462. 5,
  143463. 2,
  143464. 6,
  143465. 1,
  143466. 7,
  143467. 0,
  143468. 8,
  143469. };
  143470. static long _vq_lengthlist__44u1__p5_0[] = {
  143471. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143472. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143473. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  143474. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143475. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  143476. 12,
  143477. };
  143478. static float _vq_quantthresh__44u1__p5_0[] = {
  143479. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143480. };
  143481. static long _vq_quantmap__44u1__p5_0[] = {
  143482. 7, 5, 3, 1, 0, 2, 4, 6,
  143483. 8,
  143484. };
  143485. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  143486. _vq_quantthresh__44u1__p5_0,
  143487. _vq_quantmap__44u1__p5_0,
  143488. 9,
  143489. 9
  143490. };
  143491. static static_codebook _44u1__p5_0 = {
  143492. 2, 81,
  143493. _vq_lengthlist__44u1__p5_0,
  143494. 1, -531628032, 1611661312, 4, 0,
  143495. _vq_quantlist__44u1__p5_0,
  143496. NULL,
  143497. &_vq_auxt__44u1__p5_0,
  143498. NULL,
  143499. 0
  143500. };
  143501. static long _vq_quantlist__44u1__p6_0[] = {
  143502. 6,
  143503. 5,
  143504. 7,
  143505. 4,
  143506. 8,
  143507. 3,
  143508. 9,
  143509. 2,
  143510. 10,
  143511. 1,
  143512. 11,
  143513. 0,
  143514. 12,
  143515. };
  143516. static long _vq_lengthlist__44u1__p6_0[] = {
  143517. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  143518. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  143519. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143520. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  143521. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  143522. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  143523. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  143524. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  143525. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  143526. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  143527. 15,17,16,17,18,17,17,18, 0,
  143528. };
  143529. static float _vq_quantthresh__44u1__p6_0[] = {
  143530. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143531. 12.5, 17.5, 22.5, 27.5,
  143532. };
  143533. static long _vq_quantmap__44u1__p6_0[] = {
  143534. 11, 9, 7, 5, 3, 1, 0, 2,
  143535. 4, 6, 8, 10, 12,
  143536. };
  143537. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  143538. _vq_quantthresh__44u1__p6_0,
  143539. _vq_quantmap__44u1__p6_0,
  143540. 13,
  143541. 13
  143542. };
  143543. static static_codebook _44u1__p6_0 = {
  143544. 2, 169,
  143545. _vq_lengthlist__44u1__p6_0,
  143546. 1, -526516224, 1616117760, 4, 0,
  143547. _vq_quantlist__44u1__p6_0,
  143548. NULL,
  143549. &_vq_auxt__44u1__p6_0,
  143550. NULL,
  143551. 0
  143552. };
  143553. static long _vq_quantlist__44u1__p6_1[] = {
  143554. 2,
  143555. 1,
  143556. 3,
  143557. 0,
  143558. 4,
  143559. };
  143560. static long _vq_lengthlist__44u1__p6_1[] = {
  143561. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  143562. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  143563. };
  143564. static float _vq_quantthresh__44u1__p6_1[] = {
  143565. -1.5, -0.5, 0.5, 1.5,
  143566. };
  143567. static long _vq_quantmap__44u1__p6_1[] = {
  143568. 3, 1, 0, 2, 4,
  143569. };
  143570. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  143571. _vq_quantthresh__44u1__p6_1,
  143572. _vq_quantmap__44u1__p6_1,
  143573. 5,
  143574. 5
  143575. };
  143576. static static_codebook _44u1__p6_1 = {
  143577. 2, 25,
  143578. _vq_lengthlist__44u1__p6_1,
  143579. 1, -533725184, 1611661312, 3, 0,
  143580. _vq_quantlist__44u1__p6_1,
  143581. NULL,
  143582. &_vq_auxt__44u1__p6_1,
  143583. NULL,
  143584. 0
  143585. };
  143586. static long _vq_quantlist__44u1__p7_0[] = {
  143587. 3,
  143588. 2,
  143589. 4,
  143590. 1,
  143591. 5,
  143592. 0,
  143593. 6,
  143594. };
  143595. static long _vq_lengthlist__44u1__p7_0[] = {
  143596. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143598. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143599. 8,
  143600. };
  143601. static float _vq_quantthresh__44u1__p7_0[] = {
  143602. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  143603. };
  143604. static long _vq_quantmap__44u1__p7_0[] = {
  143605. 5, 3, 1, 0, 2, 4, 6,
  143606. };
  143607. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  143608. _vq_quantthresh__44u1__p7_0,
  143609. _vq_quantmap__44u1__p7_0,
  143610. 7,
  143611. 7
  143612. };
  143613. static static_codebook _44u1__p7_0 = {
  143614. 2, 49,
  143615. _vq_lengthlist__44u1__p7_0,
  143616. 1, -518017024, 1626677248, 3, 0,
  143617. _vq_quantlist__44u1__p7_0,
  143618. NULL,
  143619. &_vq_auxt__44u1__p7_0,
  143620. NULL,
  143621. 0
  143622. };
  143623. static long _vq_quantlist__44u1__p7_1[] = {
  143624. 6,
  143625. 5,
  143626. 7,
  143627. 4,
  143628. 8,
  143629. 3,
  143630. 9,
  143631. 2,
  143632. 10,
  143633. 1,
  143634. 11,
  143635. 0,
  143636. 12,
  143637. };
  143638. static long _vq_lengthlist__44u1__p7_1[] = {
  143639. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  143640. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  143641. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  143642. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  143643. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  143644. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  143645. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  143646. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  143647. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  143648. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  143649. 15,15,15,15,15,15,15,15,15,
  143650. };
  143651. static float _vq_quantthresh__44u1__p7_1[] = {
  143652. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143653. 32.5, 45.5, 58.5, 71.5,
  143654. };
  143655. static long _vq_quantmap__44u1__p7_1[] = {
  143656. 11, 9, 7, 5, 3, 1, 0, 2,
  143657. 4, 6, 8, 10, 12,
  143658. };
  143659. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  143660. _vq_quantthresh__44u1__p7_1,
  143661. _vq_quantmap__44u1__p7_1,
  143662. 13,
  143663. 13
  143664. };
  143665. static static_codebook _44u1__p7_1 = {
  143666. 2, 169,
  143667. _vq_lengthlist__44u1__p7_1,
  143668. 1, -523010048, 1618608128, 4, 0,
  143669. _vq_quantlist__44u1__p7_1,
  143670. NULL,
  143671. &_vq_auxt__44u1__p7_1,
  143672. NULL,
  143673. 0
  143674. };
  143675. static long _vq_quantlist__44u1__p7_2[] = {
  143676. 6,
  143677. 5,
  143678. 7,
  143679. 4,
  143680. 8,
  143681. 3,
  143682. 9,
  143683. 2,
  143684. 10,
  143685. 1,
  143686. 11,
  143687. 0,
  143688. 12,
  143689. };
  143690. static long _vq_lengthlist__44u1__p7_2[] = {
  143691. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  143692. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  143693. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  143694. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143695. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  143696. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  143697. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  143698. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143699. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143700. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  143701. 9, 9, 9,10, 9, 9,10,10, 9,
  143702. };
  143703. static float _vq_quantthresh__44u1__p7_2[] = {
  143704. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143705. 2.5, 3.5, 4.5, 5.5,
  143706. };
  143707. static long _vq_quantmap__44u1__p7_2[] = {
  143708. 11, 9, 7, 5, 3, 1, 0, 2,
  143709. 4, 6, 8, 10, 12,
  143710. };
  143711. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  143712. _vq_quantthresh__44u1__p7_2,
  143713. _vq_quantmap__44u1__p7_2,
  143714. 13,
  143715. 13
  143716. };
  143717. static static_codebook _44u1__p7_2 = {
  143718. 2, 169,
  143719. _vq_lengthlist__44u1__p7_2,
  143720. 1, -531103744, 1611661312, 4, 0,
  143721. _vq_quantlist__44u1__p7_2,
  143722. NULL,
  143723. &_vq_auxt__44u1__p7_2,
  143724. NULL,
  143725. 0
  143726. };
  143727. static long _huff_lengthlist__44u1__short[] = {
  143728. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143729. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143730. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143731. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143732. };
  143733. static static_codebook _huff_book__44u1__short = {
  143734. 2, 64,
  143735. _huff_lengthlist__44u1__short,
  143736. 0, 0, 0, 0, 0,
  143737. NULL,
  143738. NULL,
  143739. NULL,
  143740. NULL,
  143741. 0
  143742. };
  143743. static long _huff_lengthlist__44u2__long[] = {
  143744. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  143745. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  143746. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  143747. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  143748. };
  143749. static static_codebook _huff_book__44u2__long = {
  143750. 2, 64,
  143751. _huff_lengthlist__44u2__long,
  143752. 0, 0, 0, 0, 0,
  143753. NULL,
  143754. NULL,
  143755. NULL,
  143756. NULL,
  143757. 0
  143758. };
  143759. static long _vq_quantlist__44u2__p1_0[] = {
  143760. 1,
  143761. 0,
  143762. 2,
  143763. };
  143764. static long _vq_lengthlist__44u2__p1_0[] = {
  143765. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143766. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143767. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  143768. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  143769. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  143770. 13,
  143771. };
  143772. static float _vq_quantthresh__44u2__p1_0[] = {
  143773. -0.5, 0.5,
  143774. };
  143775. static long _vq_quantmap__44u2__p1_0[] = {
  143776. 1, 0, 2,
  143777. };
  143778. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  143779. _vq_quantthresh__44u2__p1_0,
  143780. _vq_quantmap__44u2__p1_0,
  143781. 3,
  143782. 3
  143783. };
  143784. static static_codebook _44u2__p1_0 = {
  143785. 4, 81,
  143786. _vq_lengthlist__44u2__p1_0,
  143787. 1, -535822336, 1611661312, 2, 0,
  143788. _vq_quantlist__44u2__p1_0,
  143789. NULL,
  143790. &_vq_auxt__44u2__p1_0,
  143791. NULL,
  143792. 0
  143793. };
  143794. static long _vq_quantlist__44u2__p2_0[] = {
  143795. 1,
  143796. 0,
  143797. 2,
  143798. };
  143799. static long _vq_lengthlist__44u2__p2_0[] = {
  143800. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143801. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  143802. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143803. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143804. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143805. 9,
  143806. };
  143807. static float _vq_quantthresh__44u2__p2_0[] = {
  143808. -0.5, 0.5,
  143809. };
  143810. static long _vq_quantmap__44u2__p2_0[] = {
  143811. 1, 0, 2,
  143812. };
  143813. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  143814. _vq_quantthresh__44u2__p2_0,
  143815. _vq_quantmap__44u2__p2_0,
  143816. 3,
  143817. 3
  143818. };
  143819. static static_codebook _44u2__p2_0 = {
  143820. 4, 81,
  143821. _vq_lengthlist__44u2__p2_0,
  143822. 1, -535822336, 1611661312, 2, 0,
  143823. _vq_quantlist__44u2__p2_0,
  143824. NULL,
  143825. &_vq_auxt__44u2__p2_0,
  143826. NULL,
  143827. 0
  143828. };
  143829. static long _vq_quantlist__44u2__p3_0[] = {
  143830. 2,
  143831. 1,
  143832. 3,
  143833. 0,
  143834. 4,
  143835. };
  143836. static long _vq_lengthlist__44u2__p3_0[] = {
  143837. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143838. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143839. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143840. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143841. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  143842. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  143843. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143844. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  143845. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143846. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143847. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  143848. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143849. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  143850. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  143851. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  143852. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  143853. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143854. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  143855. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  143856. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  143857. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  143858. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  143859. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  143860. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  143861. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  143862. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  143863. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  143864. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  143865. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  143866. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  143867. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  143868. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  143869. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  143870. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  143871. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  143872. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  143873. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  143874. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  143875. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  143876. 0,
  143877. };
  143878. static float _vq_quantthresh__44u2__p3_0[] = {
  143879. -1.5, -0.5, 0.5, 1.5,
  143880. };
  143881. static long _vq_quantmap__44u2__p3_0[] = {
  143882. 3, 1, 0, 2, 4,
  143883. };
  143884. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  143885. _vq_quantthresh__44u2__p3_0,
  143886. _vq_quantmap__44u2__p3_0,
  143887. 5,
  143888. 5
  143889. };
  143890. static static_codebook _44u2__p3_0 = {
  143891. 4, 625,
  143892. _vq_lengthlist__44u2__p3_0,
  143893. 1, -533725184, 1611661312, 3, 0,
  143894. _vq_quantlist__44u2__p3_0,
  143895. NULL,
  143896. &_vq_auxt__44u2__p3_0,
  143897. NULL,
  143898. 0
  143899. };
  143900. static long _vq_quantlist__44u2__p4_0[] = {
  143901. 2,
  143902. 1,
  143903. 3,
  143904. 0,
  143905. 4,
  143906. };
  143907. static long _vq_lengthlist__44u2__p4_0[] = {
  143908. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143909. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143910. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143911. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  143912. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  143913. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143914. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  143915. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  143916. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143917. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143918. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  143919. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143920. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  143921. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  143922. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  143923. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  143924. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143925. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143926. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143927. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143928. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143929. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  143930. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143931. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143932. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143933. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  143934. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  143935. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  143936. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143937. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  143938. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  143939. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  143940. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  143941. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143942. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143943. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  143944. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143945. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  143946. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  143947. 13,
  143948. };
  143949. static float _vq_quantthresh__44u2__p4_0[] = {
  143950. -1.5, -0.5, 0.5, 1.5,
  143951. };
  143952. static long _vq_quantmap__44u2__p4_0[] = {
  143953. 3, 1, 0, 2, 4,
  143954. };
  143955. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  143956. _vq_quantthresh__44u2__p4_0,
  143957. _vq_quantmap__44u2__p4_0,
  143958. 5,
  143959. 5
  143960. };
  143961. static static_codebook _44u2__p4_0 = {
  143962. 4, 625,
  143963. _vq_lengthlist__44u2__p4_0,
  143964. 1, -533725184, 1611661312, 3, 0,
  143965. _vq_quantlist__44u2__p4_0,
  143966. NULL,
  143967. &_vq_auxt__44u2__p4_0,
  143968. NULL,
  143969. 0
  143970. };
  143971. static long _vq_quantlist__44u2__p5_0[] = {
  143972. 4,
  143973. 3,
  143974. 5,
  143975. 2,
  143976. 6,
  143977. 1,
  143978. 7,
  143979. 0,
  143980. 8,
  143981. };
  143982. static long _vq_lengthlist__44u2__p5_0[] = {
  143983. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  143984. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143985. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  143986. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  143987. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  143988. 13,
  143989. };
  143990. static float _vq_quantthresh__44u2__p5_0[] = {
  143991. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143992. };
  143993. static long _vq_quantmap__44u2__p5_0[] = {
  143994. 7, 5, 3, 1, 0, 2, 4, 6,
  143995. 8,
  143996. };
  143997. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  143998. _vq_quantthresh__44u2__p5_0,
  143999. _vq_quantmap__44u2__p5_0,
  144000. 9,
  144001. 9
  144002. };
  144003. static static_codebook _44u2__p5_0 = {
  144004. 2, 81,
  144005. _vq_lengthlist__44u2__p5_0,
  144006. 1, -531628032, 1611661312, 4, 0,
  144007. _vq_quantlist__44u2__p5_0,
  144008. NULL,
  144009. &_vq_auxt__44u2__p5_0,
  144010. NULL,
  144011. 0
  144012. };
  144013. static long _vq_quantlist__44u2__p6_0[] = {
  144014. 6,
  144015. 5,
  144016. 7,
  144017. 4,
  144018. 8,
  144019. 3,
  144020. 9,
  144021. 2,
  144022. 10,
  144023. 1,
  144024. 11,
  144025. 0,
  144026. 12,
  144027. };
  144028. static long _vq_lengthlist__44u2__p6_0[] = {
  144029. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  144030. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  144031. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  144032. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  144033. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  144034. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  144035. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  144036. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  144037. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  144038. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  144039. 15,17,17,16,18,17,18, 0, 0,
  144040. };
  144041. static float _vq_quantthresh__44u2__p6_0[] = {
  144042. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144043. 12.5, 17.5, 22.5, 27.5,
  144044. };
  144045. static long _vq_quantmap__44u2__p6_0[] = {
  144046. 11, 9, 7, 5, 3, 1, 0, 2,
  144047. 4, 6, 8, 10, 12,
  144048. };
  144049. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  144050. _vq_quantthresh__44u2__p6_0,
  144051. _vq_quantmap__44u2__p6_0,
  144052. 13,
  144053. 13
  144054. };
  144055. static static_codebook _44u2__p6_0 = {
  144056. 2, 169,
  144057. _vq_lengthlist__44u2__p6_0,
  144058. 1, -526516224, 1616117760, 4, 0,
  144059. _vq_quantlist__44u2__p6_0,
  144060. NULL,
  144061. &_vq_auxt__44u2__p6_0,
  144062. NULL,
  144063. 0
  144064. };
  144065. static long _vq_quantlist__44u2__p6_1[] = {
  144066. 2,
  144067. 1,
  144068. 3,
  144069. 0,
  144070. 4,
  144071. };
  144072. static long _vq_lengthlist__44u2__p6_1[] = {
  144073. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144074. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144075. };
  144076. static float _vq_quantthresh__44u2__p6_1[] = {
  144077. -1.5, -0.5, 0.5, 1.5,
  144078. };
  144079. static long _vq_quantmap__44u2__p6_1[] = {
  144080. 3, 1, 0, 2, 4,
  144081. };
  144082. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  144083. _vq_quantthresh__44u2__p6_1,
  144084. _vq_quantmap__44u2__p6_1,
  144085. 5,
  144086. 5
  144087. };
  144088. static static_codebook _44u2__p6_1 = {
  144089. 2, 25,
  144090. _vq_lengthlist__44u2__p6_1,
  144091. 1, -533725184, 1611661312, 3, 0,
  144092. _vq_quantlist__44u2__p6_1,
  144093. NULL,
  144094. &_vq_auxt__44u2__p6_1,
  144095. NULL,
  144096. 0
  144097. };
  144098. static long _vq_quantlist__44u2__p7_0[] = {
  144099. 4,
  144100. 3,
  144101. 5,
  144102. 2,
  144103. 6,
  144104. 1,
  144105. 7,
  144106. 0,
  144107. 8,
  144108. };
  144109. static long _vq_lengthlist__44u2__p7_0[] = {
  144110. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  144111. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  144112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144115. 11,
  144116. };
  144117. static float _vq_quantthresh__44u2__p7_0[] = {
  144118. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  144119. };
  144120. static long _vq_quantmap__44u2__p7_0[] = {
  144121. 7, 5, 3, 1, 0, 2, 4, 6,
  144122. 8,
  144123. };
  144124. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  144125. _vq_quantthresh__44u2__p7_0,
  144126. _vq_quantmap__44u2__p7_0,
  144127. 9,
  144128. 9
  144129. };
  144130. static static_codebook _44u2__p7_0 = {
  144131. 2, 81,
  144132. _vq_lengthlist__44u2__p7_0,
  144133. 1, -516612096, 1626677248, 4, 0,
  144134. _vq_quantlist__44u2__p7_0,
  144135. NULL,
  144136. &_vq_auxt__44u2__p7_0,
  144137. NULL,
  144138. 0
  144139. };
  144140. static long _vq_quantlist__44u2__p7_1[] = {
  144141. 6,
  144142. 5,
  144143. 7,
  144144. 4,
  144145. 8,
  144146. 3,
  144147. 9,
  144148. 2,
  144149. 10,
  144150. 1,
  144151. 11,
  144152. 0,
  144153. 12,
  144154. };
  144155. static long _vq_lengthlist__44u2__p7_1[] = {
  144156. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  144157. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  144158. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  144159. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  144160. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  144161. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  144162. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  144163. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  144164. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  144165. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  144166. 14,14,14,17,15,17,17,17,17,
  144167. };
  144168. static float _vq_quantthresh__44u2__p7_1[] = {
  144169. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  144170. 32.5, 45.5, 58.5, 71.5,
  144171. };
  144172. static long _vq_quantmap__44u2__p7_1[] = {
  144173. 11, 9, 7, 5, 3, 1, 0, 2,
  144174. 4, 6, 8, 10, 12,
  144175. };
  144176. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  144177. _vq_quantthresh__44u2__p7_1,
  144178. _vq_quantmap__44u2__p7_1,
  144179. 13,
  144180. 13
  144181. };
  144182. static static_codebook _44u2__p7_1 = {
  144183. 2, 169,
  144184. _vq_lengthlist__44u2__p7_1,
  144185. 1, -523010048, 1618608128, 4, 0,
  144186. _vq_quantlist__44u2__p7_1,
  144187. NULL,
  144188. &_vq_auxt__44u2__p7_1,
  144189. NULL,
  144190. 0
  144191. };
  144192. static long _vq_quantlist__44u2__p7_2[] = {
  144193. 6,
  144194. 5,
  144195. 7,
  144196. 4,
  144197. 8,
  144198. 3,
  144199. 9,
  144200. 2,
  144201. 10,
  144202. 1,
  144203. 11,
  144204. 0,
  144205. 12,
  144206. };
  144207. static long _vq_lengthlist__44u2__p7_2[] = {
  144208. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  144209. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  144210. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  144211. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  144212. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  144213. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  144214. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144215. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144216. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  144217. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  144218. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144219. };
  144220. static float _vq_quantthresh__44u2__p7_2[] = {
  144221. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  144222. 2.5, 3.5, 4.5, 5.5,
  144223. };
  144224. static long _vq_quantmap__44u2__p7_2[] = {
  144225. 11, 9, 7, 5, 3, 1, 0, 2,
  144226. 4, 6, 8, 10, 12,
  144227. };
  144228. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  144229. _vq_quantthresh__44u2__p7_2,
  144230. _vq_quantmap__44u2__p7_2,
  144231. 13,
  144232. 13
  144233. };
  144234. static static_codebook _44u2__p7_2 = {
  144235. 2, 169,
  144236. _vq_lengthlist__44u2__p7_2,
  144237. 1, -531103744, 1611661312, 4, 0,
  144238. _vq_quantlist__44u2__p7_2,
  144239. NULL,
  144240. &_vq_auxt__44u2__p7_2,
  144241. NULL,
  144242. 0
  144243. };
  144244. static long _huff_lengthlist__44u2__short[] = {
  144245. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  144246. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  144247. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  144248. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  144249. };
  144250. static static_codebook _huff_book__44u2__short = {
  144251. 2, 64,
  144252. _huff_lengthlist__44u2__short,
  144253. 0, 0, 0, 0, 0,
  144254. NULL,
  144255. NULL,
  144256. NULL,
  144257. NULL,
  144258. 0
  144259. };
  144260. static long _huff_lengthlist__44u3__long[] = {
  144261. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  144262. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  144263. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  144264. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  144265. };
  144266. static static_codebook _huff_book__44u3__long = {
  144267. 2, 64,
  144268. _huff_lengthlist__44u3__long,
  144269. 0, 0, 0, 0, 0,
  144270. NULL,
  144271. NULL,
  144272. NULL,
  144273. NULL,
  144274. 0
  144275. };
  144276. static long _vq_quantlist__44u3__p1_0[] = {
  144277. 1,
  144278. 0,
  144279. 2,
  144280. };
  144281. static long _vq_lengthlist__44u3__p1_0[] = {
  144282. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144283. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144284. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  144285. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144286. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  144287. 13,
  144288. };
  144289. static float _vq_quantthresh__44u3__p1_0[] = {
  144290. -0.5, 0.5,
  144291. };
  144292. static long _vq_quantmap__44u3__p1_0[] = {
  144293. 1, 0, 2,
  144294. };
  144295. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  144296. _vq_quantthresh__44u3__p1_0,
  144297. _vq_quantmap__44u3__p1_0,
  144298. 3,
  144299. 3
  144300. };
  144301. static static_codebook _44u3__p1_0 = {
  144302. 4, 81,
  144303. _vq_lengthlist__44u3__p1_0,
  144304. 1, -535822336, 1611661312, 2, 0,
  144305. _vq_quantlist__44u3__p1_0,
  144306. NULL,
  144307. &_vq_auxt__44u3__p1_0,
  144308. NULL,
  144309. 0
  144310. };
  144311. static long _vq_quantlist__44u3__p2_0[] = {
  144312. 1,
  144313. 0,
  144314. 2,
  144315. };
  144316. static long _vq_lengthlist__44u3__p2_0[] = {
  144317. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144318. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  144319. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144320. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144321. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  144322. 9,
  144323. };
  144324. static float _vq_quantthresh__44u3__p2_0[] = {
  144325. -0.5, 0.5,
  144326. };
  144327. static long _vq_quantmap__44u3__p2_0[] = {
  144328. 1, 0, 2,
  144329. };
  144330. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  144331. _vq_quantthresh__44u3__p2_0,
  144332. _vq_quantmap__44u3__p2_0,
  144333. 3,
  144334. 3
  144335. };
  144336. static static_codebook _44u3__p2_0 = {
  144337. 4, 81,
  144338. _vq_lengthlist__44u3__p2_0,
  144339. 1, -535822336, 1611661312, 2, 0,
  144340. _vq_quantlist__44u3__p2_0,
  144341. NULL,
  144342. &_vq_auxt__44u3__p2_0,
  144343. NULL,
  144344. 0
  144345. };
  144346. static long _vq_quantlist__44u3__p3_0[] = {
  144347. 2,
  144348. 1,
  144349. 3,
  144350. 0,
  144351. 4,
  144352. };
  144353. static long _vq_lengthlist__44u3__p3_0[] = {
  144354. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144355. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  144356. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  144357. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  144358. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  144359. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  144360. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  144361. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  144362. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  144363. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144364. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  144365. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144366. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  144367. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  144368. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  144369. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  144370. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  144371. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  144372. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  144373. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  144374. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  144375. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  144376. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  144377. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  144378. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  144379. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  144380. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  144381. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  144382. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  144383. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  144384. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  144385. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  144386. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  144387. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  144388. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  144389. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  144390. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  144391. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  144392. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  144393. 0,
  144394. };
  144395. static float _vq_quantthresh__44u3__p3_0[] = {
  144396. -1.5, -0.5, 0.5, 1.5,
  144397. };
  144398. static long _vq_quantmap__44u3__p3_0[] = {
  144399. 3, 1, 0, 2, 4,
  144400. };
  144401. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  144402. _vq_quantthresh__44u3__p3_0,
  144403. _vq_quantmap__44u3__p3_0,
  144404. 5,
  144405. 5
  144406. };
  144407. static static_codebook _44u3__p3_0 = {
  144408. 4, 625,
  144409. _vq_lengthlist__44u3__p3_0,
  144410. 1, -533725184, 1611661312, 3, 0,
  144411. _vq_quantlist__44u3__p3_0,
  144412. NULL,
  144413. &_vq_auxt__44u3__p3_0,
  144414. NULL,
  144415. 0
  144416. };
  144417. static long _vq_quantlist__44u3__p4_0[] = {
  144418. 2,
  144419. 1,
  144420. 3,
  144421. 0,
  144422. 4,
  144423. };
  144424. static long _vq_lengthlist__44u3__p4_0[] = {
  144425. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144426. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144427. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144428. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144429. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144430. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  144431. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  144432. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  144433. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144434. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144435. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144436. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144437. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144438. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  144439. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144440. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144441. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144442. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144443. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144444. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  144445. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144446. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144447. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144448. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144449. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  144450. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  144451. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  144452. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  144453. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  144454. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  144455. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  144456. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144457. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144458. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  144459. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  144460. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  144461. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  144462. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  144463. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  144464. 13,
  144465. };
  144466. static float _vq_quantthresh__44u3__p4_0[] = {
  144467. -1.5, -0.5, 0.5, 1.5,
  144468. };
  144469. static long _vq_quantmap__44u3__p4_0[] = {
  144470. 3, 1, 0, 2, 4,
  144471. };
  144472. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  144473. _vq_quantthresh__44u3__p4_0,
  144474. _vq_quantmap__44u3__p4_0,
  144475. 5,
  144476. 5
  144477. };
  144478. static static_codebook _44u3__p4_0 = {
  144479. 4, 625,
  144480. _vq_lengthlist__44u3__p4_0,
  144481. 1, -533725184, 1611661312, 3, 0,
  144482. _vq_quantlist__44u3__p4_0,
  144483. NULL,
  144484. &_vq_auxt__44u3__p4_0,
  144485. NULL,
  144486. 0
  144487. };
  144488. static long _vq_quantlist__44u3__p5_0[] = {
  144489. 4,
  144490. 3,
  144491. 5,
  144492. 2,
  144493. 6,
  144494. 1,
  144495. 7,
  144496. 0,
  144497. 8,
  144498. };
  144499. static long _vq_lengthlist__44u3__p5_0[] = {
  144500. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  144501. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  144502. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  144503. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144504. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  144505. 12,
  144506. };
  144507. static float _vq_quantthresh__44u3__p5_0[] = {
  144508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144509. };
  144510. static long _vq_quantmap__44u3__p5_0[] = {
  144511. 7, 5, 3, 1, 0, 2, 4, 6,
  144512. 8,
  144513. };
  144514. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  144515. _vq_quantthresh__44u3__p5_0,
  144516. _vq_quantmap__44u3__p5_0,
  144517. 9,
  144518. 9
  144519. };
  144520. static static_codebook _44u3__p5_0 = {
  144521. 2, 81,
  144522. _vq_lengthlist__44u3__p5_0,
  144523. 1, -531628032, 1611661312, 4, 0,
  144524. _vq_quantlist__44u3__p5_0,
  144525. NULL,
  144526. &_vq_auxt__44u3__p5_0,
  144527. NULL,
  144528. 0
  144529. };
  144530. static long _vq_quantlist__44u3__p6_0[] = {
  144531. 6,
  144532. 5,
  144533. 7,
  144534. 4,
  144535. 8,
  144536. 3,
  144537. 9,
  144538. 2,
  144539. 10,
  144540. 1,
  144541. 11,
  144542. 0,
  144543. 12,
  144544. };
  144545. static long _vq_lengthlist__44u3__p6_0[] = {
  144546. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  144547. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  144548. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144549. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  144550. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  144551. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  144552. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  144553. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  144554. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  144555. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  144556. 15,16,16,16,17,18,16,20,18,
  144557. };
  144558. static float _vq_quantthresh__44u3__p6_0[] = {
  144559. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144560. 12.5, 17.5, 22.5, 27.5,
  144561. };
  144562. static long _vq_quantmap__44u3__p6_0[] = {
  144563. 11, 9, 7, 5, 3, 1, 0, 2,
  144564. 4, 6, 8, 10, 12,
  144565. };
  144566. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  144567. _vq_quantthresh__44u3__p6_0,
  144568. _vq_quantmap__44u3__p6_0,
  144569. 13,
  144570. 13
  144571. };
  144572. static static_codebook _44u3__p6_0 = {
  144573. 2, 169,
  144574. _vq_lengthlist__44u3__p6_0,
  144575. 1, -526516224, 1616117760, 4, 0,
  144576. _vq_quantlist__44u3__p6_0,
  144577. NULL,
  144578. &_vq_auxt__44u3__p6_0,
  144579. NULL,
  144580. 0
  144581. };
  144582. static long _vq_quantlist__44u3__p6_1[] = {
  144583. 2,
  144584. 1,
  144585. 3,
  144586. 0,
  144587. 4,
  144588. };
  144589. static long _vq_lengthlist__44u3__p6_1[] = {
  144590. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144591. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144592. };
  144593. static float _vq_quantthresh__44u3__p6_1[] = {
  144594. -1.5, -0.5, 0.5, 1.5,
  144595. };
  144596. static long _vq_quantmap__44u3__p6_1[] = {
  144597. 3, 1, 0, 2, 4,
  144598. };
  144599. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  144600. _vq_quantthresh__44u3__p6_1,
  144601. _vq_quantmap__44u3__p6_1,
  144602. 5,
  144603. 5
  144604. };
  144605. static static_codebook _44u3__p6_1 = {
  144606. 2, 25,
  144607. _vq_lengthlist__44u3__p6_1,
  144608. 1, -533725184, 1611661312, 3, 0,
  144609. _vq_quantlist__44u3__p6_1,
  144610. NULL,
  144611. &_vq_auxt__44u3__p6_1,
  144612. NULL,
  144613. 0
  144614. };
  144615. static long _vq_quantlist__44u3__p7_0[] = {
  144616. 4,
  144617. 3,
  144618. 5,
  144619. 2,
  144620. 6,
  144621. 1,
  144622. 7,
  144623. 0,
  144624. 8,
  144625. };
  144626. static long _vq_lengthlist__44u3__p7_0[] = {
  144627. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  144628. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144629. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144630. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144631. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144632. 9,
  144633. };
  144634. static float _vq_quantthresh__44u3__p7_0[] = {
  144635. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  144636. };
  144637. static long _vq_quantmap__44u3__p7_0[] = {
  144638. 7, 5, 3, 1, 0, 2, 4, 6,
  144639. 8,
  144640. };
  144641. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  144642. _vq_quantthresh__44u3__p7_0,
  144643. _vq_quantmap__44u3__p7_0,
  144644. 9,
  144645. 9
  144646. };
  144647. static static_codebook _44u3__p7_0 = {
  144648. 2, 81,
  144649. _vq_lengthlist__44u3__p7_0,
  144650. 1, -515907584, 1627381760, 4, 0,
  144651. _vq_quantlist__44u3__p7_0,
  144652. NULL,
  144653. &_vq_auxt__44u3__p7_0,
  144654. NULL,
  144655. 0
  144656. };
  144657. static long _vq_quantlist__44u3__p7_1[] = {
  144658. 7,
  144659. 6,
  144660. 8,
  144661. 5,
  144662. 9,
  144663. 4,
  144664. 10,
  144665. 3,
  144666. 11,
  144667. 2,
  144668. 12,
  144669. 1,
  144670. 13,
  144671. 0,
  144672. 14,
  144673. };
  144674. static long _vq_lengthlist__44u3__p7_1[] = {
  144675. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  144676. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  144677. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  144678. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  144679. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  144680. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  144681. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  144682. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  144683. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  144684. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  144685. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  144686. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  144687. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  144688. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  144689. 17,
  144690. };
  144691. static float _vq_quantthresh__44u3__p7_1[] = {
  144692. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144693. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144694. };
  144695. static long _vq_quantmap__44u3__p7_1[] = {
  144696. 13, 11, 9, 7, 5, 3, 1, 0,
  144697. 2, 4, 6, 8, 10, 12, 14,
  144698. };
  144699. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  144700. _vq_quantthresh__44u3__p7_1,
  144701. _vq_quantmap__44u3__p7_1,
  144702. 15,
  144703. 15
  144704. };
  144705. static static_codebook _44u3__p7_1 = {
  144706. 2, 225,
  144707. _vq_lengthlist__44u3__p7_1,
  144708. 1, -522338304, 1620115456, 4, 0,
  144709. _vq_quantlist__44u3__p7_1,
  144710. NULL,
  144711. &_vq_auxt__44u3__p7_1,
  144712. NULL,
  144713. 0
  144714. };
  144715. static long _vq_quantlist__44u3__p7_2[] = {
  144716. 8,
  144717. 7,
  144718. 9,
  144719. 6,
  144720. 10,
  144721. 5,
  144722. 11,
  144723. 4,
  144724. 12,
  144725. 3,
  144726. 13,
  144727. 2,
  144728. 14,
  144729. 1,
  144730. 15,
  144731. 0,
  144732. 16,
  144733. };
  144734. static long _vq_lengthlist__44u3__p7_2[] = {
  144735. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144736. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144737. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  144738. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144739. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144740. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144741. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  144742. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144743. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  144744. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  144745. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144746. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  144747. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  144748. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144749. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  144750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  144751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144752. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  144753. 11,
  144754. };
  144755. static float _vq_quantthresh__44u3__p7_2[] = {
  144756. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144757. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144758. };
  144759. static long _vq_quantmap__44u3__p7_2[] = {
  144760. 15, 13, 11, 9, 7, 5, 3, 1,
  144761. 0, 2, 4, 6, 8, 10, 12, 14,
  144762. 16,
  144763. };
  144764. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  144765. _vq_quantthresh__44u3__p7_2,
  144766. _vq_quantmap__44u3__p7_2,
  144767. 17,
  144768. 17
  144769. };
  144770. static static_codebook _44u3__p7_2 = {
  144771. 2, 289,
  144772. _vq_lengthlist__44u3__p7_2,
  144773. 1, -529530880, 1611661312, 5, 0,
  144774. _vq_quantlist__44u3__p7_2,
  144775. NULL,
  144776. &_vq_auxt__44u3__p7_2,
  144777. NULL,
  144778. 0
  144779. };
  144780. static long _huff_lengthlist__44u3__short[] = {
  144781. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  144782. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  144783. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  144784. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  144785. };
  144786. static static_codebook _huff_book__44u3__short = {
  144787. 2, 64,
  144788. _huff_lengthlist__44u3__short,
  144789. 0, 0, 0, 0, 0,
  144790. NULL,
  144791. NULL,
  144792. NULL,
  144793. NULL,
  144794. 0
  144795. };
  144796. static long _huff_lengthlist__44u4__long[] = {
  144797. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  144798. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  144799. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  144800. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  144801. };
  144802. static static_codebook _huff_book__44u4__long = {
  144803. 2, 64,
  144804. _huff_lengthlist__44u4__long,
  144805. 0, 0, 0, 0, 0,
  144806. NULL,
  144807. NULL,
  144808. NULL,
  144809. NULL,
  144810. 0
  144811. };
  144812. static long _vq_quantlist__44u4__p1_0[] = {
  144813. 1,
  144814. 0,
  144815. 2,
  144816. };
  144817. static long _vq_lengthlist__44u4__p1_0[] = {
  144818. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144819. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144820. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  144821. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144822. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  144823. 13,
  144824. };
  144825. static float _vq_quantthresh__44u4__p1_0[] = {
  144826. -0.5, 0.5,
  144827. };
  144828. static long _vq_quantmap__44u4__p1_0[] = {
  144829. 1, 0, 2,
  144830. };
  144831. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  144832. _vq_quantthresh__44u4__p1_0,
  144833. _vq_quantmap__44u4__p1_0,
  144834. 3,
  144835. 3
  144836. };
  144837. static static_codebook _44u4__p1_0 = {
  144838. 4, 81,
  144839. _vq_lengthlist__44u4__p1_0,
  144840. 1, -535822336, 1611661312, 2, 0,
  144841. _vq_quantlist__44u4__p1_0,
  144842. NULL,
  144843. &_vq_auxt__44u4__p1_0,
  144844. NULL,
  144845. 0
  144846. };
  144847. static long _vq_quantlist__44u4__p2_0[] = {
  144848. 1,
  144849. 0,
  144850. 2,
  144851. };
  144852. static long _vq_lengthlist__44u4__p2_0[] = {
  144853. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144854. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  144855. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144856. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  144857. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  144858. 9,
  144859. };
  144860. static float _vq_quantthresh__44u4__p2_0[] = {
  144861. -0.5, 0.5,
  144862. };
  144863. static long _vq_quantmap__44u4__p2_0[] = {
  144864. 1, 0, 2,
  144865. };
  144866. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  144867. _vq_quantthresh__44u4__p2_0,
  144868. _vq_quantmap__44u4__p2_0,
  144869. 3,
  144870. 3
  144871. };
  144872. static static_codebook _44u4__p2_0 = {
  144873. 4, 81,
  144874. _vq_lengthlist__44u4__p2_0,
  144875. 1, -535822336, 1611661312, 2, 0,
  144876. _vq_quantlist__44u4__p2_0,
  144877. NULL,
  144878. &_vq_auxt__44u4__p2_0,
  144879. NULL,
  144880. 0
  144881. };
  144882. static long _vq_quantlist__44u4__p3_0[] = {
  144883. 2,
  144884. 1,
  144885. 3,
  144886. 0,
  144887. 4,
  144888. };
  144889. static long _vq_lengthlist__44u4__p3_0[] = {
  144890. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144891. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144892. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  144893. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  144894. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144895. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  144896. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  144897. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  144898. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  144899. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  144900. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  144901. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  144902. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  144903. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  144904. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  144905. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  144906. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  144907. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  144908. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  144909. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  144910. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  144911. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  144912. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  144913. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  144914. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  144915. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  144916. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  144917. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  144918. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  144919. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  144920. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  144921. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  144922. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  144923. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  144924. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  144925. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  144926. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  144927. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  144928. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  144929. 0,
  144930. };
  144931. static float _vq_quantthresh__44u4__p3_0[] = {
  144932. -1.5, -0.5, 0.5, 1.5,
  144933. };
  144934. static long _vq_quantmap__44u4__p3_0[] = {
  144935. 3, 1, 0, 2, 4,
  144936. };
  144937. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  144938. _vq_quantthresh__44u4__p3_0,
  144939. _vq_quantmap__44u4__p3_0,
  144940. 5,
  144941. 5
  144942. };
  144943. static static_codebook _44u4__p3_0 = {
  144944. 4, 625,
  144945. _vq_lengthlist__44u4__p3_0,
  144946. 1, -533725184, 1611661312, 3, 0,
  144947. _vq_quantlist__44u4__p3_0,
  144948. NULL,
  144949. &_vq_auxt__44u4__p3_0,
  144950. NULL,
  144951. 0
  144952. };
  144953. static long _vq_quantlist__44u4__p4_0[] = {
  144954. 2,
  144955. 1,
  144956. 3,
  144957. 0,
  144958. 4,
  144959. };
  144960. static long _vq_lengthlist__44u4__p4_0[] = {
  144961. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144962. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144963. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144964. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144965. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144966. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144967. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  144968. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  144969. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144970. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144971. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144972. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144973. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144974. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  144975. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144976. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144977. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144978. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144979. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144980. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144981. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144982. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144983. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144984. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144985. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144986. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  144987. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  144988. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  144989. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  144990. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  144991. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  144992. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144993. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144994. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  144995. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144996. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  144997. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144998. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  144999. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  145000. 13,
  145001. };
  145002. static float _vq_quantthresh__44u4__p4_0[] = {
  145003. -1.5, -0.5, 0.5, 1.5,
  145004. };
  145005. static long _vq_quantmap__44u4__p4_0[] = {
  145006. 3, 1, 0, 2, 4,
  145007. };
  145008. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  145009. _vq_quantthresh__44u4__p4_0,
  145010. _vq_quantmap__44u4__p4_0,
  145011. 5,
  145012. 5
  145013. };
  145014. static static_codebook _44u4__p4_0 = {
  145015. 4, 625,
  145016. _vq_lengthlist__44u4__p4_0,
  145017. 1, -533725184, 1611661312, 3, 0,
  145018. _vq_quantlist__44u4__p4_0,
  145019. NULL,
  145020. &_vq_auxt__44u4__p4_0,
  145021. NULL,
  145022. 0
  145023. };
  145024. static long _vq_quantlist__44u4__p5_0[] = {
  145025. 4,
  145026. 3,
  145027. 5,
  145028. 2,
  145029. 6,
  145030. 1,
  145031. 7,
  145032. 0,
  145033. 8,
  145034. };
  145035. static long _vq_lengthlist__44u4__p5_0[] = {
  145036. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  145037. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  145038. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  145039. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145040. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  145041. 12,
  145042. };
  145043. static float _vq_quantthresh__44u4__p5_0[] = {
  145044. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145045. };
  145046. static long _vq_quantmap__44u4__p5_0[] = {
  145047. 7, 5, 3, 1, 0, 2, 4, 6,
  145048. 8,
  145049. };
  145050. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  145051. _vq_quantthresh__44u4__p5_0,
  145052. _vq_quantmap__44u4__p5_0,
  145053. 9,
  145054. 9
  145055. };
  145056. static static_codebook _44u4__p5_0 = {
  145057. 2, 81,
  145058. _vq_lengthlist__44u4__p5_0,
  145059. 1, -531628032, 1611661312, 4, 0,
  145060. _vq_quantlist__44u4__p5_0,
  145061. NULL,
  145062. &_vq_auxt__44u4__p5_0,
  145063. NULL,
  145064. 0
  145065. };
  145066. static long _vq_quantlist__44u4__p6_0[] = {
  145067. 6,
  145068. 5,
  145069. 7,
  145070. 4,
  145071. 8,
  145072. 3,
  145073. 9,
  145074. 2,
  145075. 10,
  145076. 1,
  145077. 11,
  145078. 0,
  145079. 12,
  145080. };
  145081. static long _vq_lengthlist__44u4__p6_0[] = {
  145082. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  145083. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  145084. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145085. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  145086. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  145087. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  145088. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  145089. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  145090. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  145091. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  145092. 16,16,16,17,17,18,17,20,21,
  145093. };
  145094. static float _vq_quantthresh__44u4__p6_0[] = {
  145095. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145096. 12.5, 17.5, 22.5, 27.5,
  145097. };
  145098. static long _vq_quantmap__44u4__p6_0[] = {
  145099. 11, 9, 7, 5, 3, 1, 0, 2,
  145100. 4, 6, 8, 10, 12,
  145101. };
  145102. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  145103. _vq_quantthresh__44u4__p6_0,
  145104. _vq_quantmap__44u4__p6_0,
  145105. 13,
  145106. 13
  145107. };
  145108. static static_codebook _44u4__p6_0 = {
  145109. 2, 169,
  145110. _vq_lengthlist__44u4__p6_0,
  145111. 1, -526516224, 1616117760, 4, 0,
  145112. _vq_quantlist__44u4__p6_0,
  145113. NULL,
  145114. &_vq_auxt__44u4__p6_0,
  145115. NULL,
  145116. 0
  145117. };
  145118. static long _vq_quantlist__44u4__p6_1[] = {
  145119. 2,
  145120. 1,
  145121. 3,
  145122. 0,
  145123. 4,
  145124. };
  145125. static long _vq_lengthlist__44u4__p6_1[] = {
  145126. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  145127. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  145128. };
  145129. static float _vq_quantthresh__44u4__p6_1[] = {
  145130. -1.5, -0.5, 0.5, 1.5,
  145131. };
  145132. static long _vq_quantmap__44u4__p6_1[] = {
  145133. 3, 1, 0, 2, 4,
  145134. };
  145135. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  145136. _vq_quantthresh__44u4__p6_1,
  145137. _vq_quantmap__44u4__p6_1,
  145138. 5,
  145139. 5
  145140. };
  145141. static static_codebook _44u4__p6_1 = {
  145142. 2, 25,
  145143. _vq_lengthlist__44u4__p6_1,
  145144. 1, -533725184, 1611661312, 3, 0,
  145145. _vq_quantlist__44u4__p6_1,
  145146. NULL,
  145147. &_vq_auxt__44u4__p6_1,
  145148. NULL,
  145149. 0
  145150. };
  145151. static long _vq_quantlist__44u4__p7_0[] = {
  145152. 6,
  145153. 5,
  145154. 7,
  145155. 4,
  145156. 8,
  145157. 3,
  145158. 9,
  145159. 2,
  145160. 10,
  145161. 1,
  145162. 11,
  145163. 0,
  145164. 12,
  145165. };
  145166. static long _vq_lengthlist__44u4__p7_0[] = {
  145167. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  145168. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  145169. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145170. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145171. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145172. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145173. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145177. 11,11,11,11,11,11,11,11,11,
  145178. };
  145179. static float _vq_quantthresh__44u4__p7_0[] = {
  145180. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145181. 637.5, 892.5, 1147.5, 1402.5,
  145182. };
  145183. static long _vq_quantmap__44u4__p7_0[] = {
  145184. 11, 9, 7, 5, 3, 1, 0, 2,
  145185. 4, 6, 8, 10, 12,
  145186. };
  145187. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  145188. _vq_quantthresh__44u4__p7_0,
  145189. _vq_quantmap__44u4__p7_0,
  145190. 13,
  145191. 13
  145192. };
  145193. static static_codebook _44u4__p7_0 = {
  145194. 2, 169,
  145195. _vq_lengthlist__44u4__p7_0,
  145196. 1, -514332672, 1627381760, 4, 0,
  145197. _vq_quantlist__44u4__p7_0,
  145198. NULL,
  145199. &_vq_auxt__44u4__p7_0,
  145200. NULL,
  145201. 0
  145202. };
  145203. static long _vq_quantlist__44u4__p7_1[] = {
  145204. 7,
  145205. 6,
  145206. 8,
  145207. 5,
  145208. 9,
  145209. 4,
  145210. 10,
  145211. 3,
  145212. 11,
  145213. 2,
  145214. 12,
  145215. 1,
  145216. 13,
  145217. 0,
  145218. 14,
  145219. };
  145220. static long _vq_lengthlist__44u4__p7_1[] = {
  145221. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  145222. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  145223. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  145224. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  145225. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  145226. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  145227. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  145228. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  145229. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  145230. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  145231. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  145232. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  145233. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  145234. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  145235. 16,
  145236. };
  145237. static float _vq_quantthresh__44u4__p7_1[] = {
  145238. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145239. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145240. };
  145241. static long _vq_quantmap__44u4__p7_1[] = {
  145242. 13, 11, 9, 7, 5, 3, 1, 0,
  145243. 2, 4, 6, 8, 10, 12, 14,
  145244. };
  145245. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  145246. _vq_quantthresh__44u4__p7_1,
  145247. _vq_quantmap__44u4__p7_1,
  145248. 15,
  145249. 15
  145250. };
  145251. static static_codebook _44u4__p7_1 = {
  145252. 2, 225,
  145253. _vq_lengthlist__44u4__p7_1,
  145254. 1, -522338304, 1620115456, 4, 0,
  145255. _vq_quantlist__44u4__p7_1,
  145256. NULL,
  145257. &_vq_auxt__44u4__p7_1,
  145258. NULL,
  145259. 0
  145260. };
  145261. static long _vq_quantlist__44u4__p7_2[] = {
  145262. 8,
  145263. 7,
  145264. 9,
  145265. 6,
  145266. 10,
  145267. 5,
  145268. 11,
  145269. 4,
  145270. 12,
  145271. 3,
  145272. 13,
  145273. 2,
  145274. 14,
  145275. 1,
  145276. 15,
  145277. 0,
  145278. 16,
  145279. };
  145280. static long _vq_lengthlist__44u4__p7_2[] = {
  145281. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145282. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145283. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145284. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145285. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145286. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145287. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145288. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145289. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  145290. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  145291. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145292. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145293. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145294. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  145295. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145296. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145297. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145298. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  145299. 10,
  145300. };
  145301. static float _vq_quantthresh__44u4__p7_2[] = {
  145302. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145303. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145304. };
  145305. static long _vq_quantmap__44u4__p7_2[] = {
  145306. 15, 13, 11, 9, 7, 5, 3, 1,
  145307. 0, 2, 4, 6, 8, 10, 12, 14,
  145308. 16,
  145309. };
  145310. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  145311. _vq_quantthresh__44u4__p7_2,
  145312. _vq_quantmap__44u4__p7_2,
  145313. 17,
  145314. 17
  145315. };
  145316. static static_codebook _44u4__p7_2 = {
  145317. 2, 289,
  145318. _vq_lengthlist__44u4__p7_2,
  145319. 1, -529530880, 1611661312, 5, 0,
  145320. _vq_quantlist__44u4__p7_2,
  145321. NULL,
  145322. &_vq_auxt__44u4__p7_2,
  145323. NULL,
  145324. 0
  145325. };
  145326. static long _huff_lengthlist__44u4__short[] = {
  145327. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  145328. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  145329. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  145330. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  145331. };
  145332. static static_codebook _huff_book__44u4__short = {
  145333. 2, 64,
  145334. _huff_lengthlist__44u4__short,
  145335. 0, 0, 0, 0, 0,
  145336. NULL,
  145337. NULL,
  145338. NULL,
  145339. NULL,
  145340. 0
  145341. };
  145342. static long _huff_lengthlist__44u5__long[] = {
  145343. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  145344. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  145345. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  145346. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  145347. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  145348. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  145349. 14, 8, 7, 8,
  145350. };
  145351. static static_codebook _huff_book__44u5__long = {
  145352. 2, 100,
  145353. _huff_lengthlist__44u5__long,
  145354. 0, 0, 0, 0, 0,
  145355. NULL,
  145356. NULL,
  145357. NULL,
  145358. NULL,
  145359. 0
  145360. };
  145361. static long _vq_quantlist__44u5__p1_0[] = {
  145362. 1,
  145363. 0,
  145364. 2,
  145365. };
  145366. static long _vq_lengthlist__44u5__p1_0[] = {
  145367. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145368. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145369. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145370. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  145371. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145372. 12,
  145373. };
  145374. static float _vq_quantthresh__44u5__p1_0[] = {
  145375. -0.5, 0.5,
  145376. };
  145377. static long _vq_quantmap__44u5__p1_0[] = {
  145378. 1, 0, 2,
  145379. };
  145380. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  145381. _vq_quantthresh__44u5__p1_0,
  145382. _vq_quantmap__44u5__p1_0,
  145383. 3,
  145384. 3
  145385. };
  145386. static static_codebook _44u5__p1_0 = {
  145387. 4, 81,
  145388. _vq_lengthlist__44u5__p1_0,
  145389. 1, -535822336, 1611661312, 2, 0,
  145390. _vq_quantlist__44u5__p1_0,
  145391. NULL,
  145392. &_vq_auxt__44u5__p1_0,
  145393. NULL,
  145394. 0
  145395. };
  145396. static long _vq_quantlist__44u5__p2_0[] = {
  145397. 1,
  145398. 0,
  145399. 2,
  145400. };
  145401. static long _vq_lengthlist__44u5__p2_0[] = {
  145402. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145403. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145404. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145405. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145406. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145407. 9,
  145408. };
  145409. static float _vq_quantthresh__44u5__p2_0[] = {
  145410. -0.5, 0.5,
  145411. };
  145412. static long _vq_quantmap__44u5__p2_0[] = {
  145413. 1, 0, 2,
  145414. };
  145415. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  145416. _vq_quantthresh__44u5__p2_0,
  145417. _vq_quantmap__44u5__p2_0,
  145418. 3,
  145419. 3
  145420. };
  145421. static static_codebook _44u5__p2_0 = {
  145422. 4, 81,
  145423. _vq_lengthlist__44u5__p2_0,
  145424. 1, -535822336, 1611661312, 2, 0,
  145425. _vq_quantlist__44u5__p2_0,
  145426. NULL,
  145427. &_vq_auxt__44u5__p2_0,
  145428. NULL,
  145429. 0
  145430. };
  145431. static long _vq_quantlist__44u5__p3_0[] = {
  145432. 2,
  145433. 1,
  145434. 3,
  145435. 0,
  145436. 4,
  145437. };
  145438. static long _vq_lengthlist__44u5__p3_0[] = {
  145439. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145440. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  145441. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145442. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  145443. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  145444. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  145445. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145446. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  145447. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  145448. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145449. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  145450. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145451. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  145452. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  145453. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  145454. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  145455. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145456. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  145457. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  145458. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  145459. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  145460. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  145461. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  145462. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  145463. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  145464. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  145465. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  145466. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  145467. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  145468. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  145469. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  145470. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  145471. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  145472. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  145473. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  145474. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  145475. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  145476. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  145477. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  145478. 0,
  145479. };
  145480. static float _vq_quantthresh__44u5__p3_0[] = {
  145481. -1.5, -0.5, 0.5, 1.5,
  145482. };
  145483. static long _vq_quantmap__44u5__p3_0[] = {
  145484. 3, 1, 0, 2, 4,
  145485. };
  145486. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  145487. _vq_quantthresh__44u5__p3_0,
  145488. _vq_quantmap__44u5__p3_0,
  145489. 5,
  145490. 5
  145491. };
  145492. static static_codebook _44u5__p3_0 = {
  145493. 4, 625,
  145494. _vq_lengthlist__44u5__p3_0,
  145495. 1, -533725184, 1611661312, 3, 0,
  145496. _vq_quantlist__44u5__p3_0,
  145497. NULL,
  145498. &_vq_auxt__44u5__p3_0,
  145499. NULL,
  145500. 0
  145501. };
  145502. static long _vq_quantlist__44u5__p4_0[] = {
  145503. 2,
  145504. 1,
  145505. 3,
  145506. 0,
  145507. 4,
  145508. };
  145509. static long _vq_lengthlist__44u5__p4_0[] = {
  145510. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145511. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145512. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  145513. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  145514. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  145515. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  145516. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  145517. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  145518. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145519. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  145520. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  145521. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145522. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145523. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  145524. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  145525. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  145526. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  145527. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  145528. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  145529. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  145530. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  145531. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  145532. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  145533. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  145534. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  145535. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  145536. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  145537. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  145538. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  145539. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  145540. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  145541. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  145542. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  145543. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  145544. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  145545. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  145546. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  145547. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  145548. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  145549. 12,
  145550. };
  145551. static float _vq_quantthresh__44u5__p4_0[] = {
  145552. -1.5, -0.5, 0.5, 1.5,
  145553. };
  145554. static long _vq_quantmap__44u5__p4_0[] = {
  145555. 3, 1, 0, 2, 4,
  145556. };
  145557. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  145558. _vq_quantthresh__44u5__p4_0,
  145559. _vq_quantmap__44u5__p4_0,
  145560. 5,
  145561. 5
  145562. };
  145563. static static_codebook _44u5__p4_0 = {
  145564. 4, 625,
  145565. _vq_lengthlist__44u5__p4_0,
  145566. 1, -533725184, 1611661312, 3, 0,
  145567. _vq_quantlist__44u5__p4_0,
  145568. NULL,
  145569. &_vq_auxt__44u5__p4_0,
  145570. NULL,
  145571. 0
  145572. };
  145573. static long _vq_quantlist__44u5__p5_0[] = {
  145574. 4,
  145575. 3,
  145576. 5,
  145577. 2,
  145578. 6,
  145579. 1,
  145580. 7,
  145581. 0,
  145582. 8,
  145583. };
  145584. static long _vq_lengthlist__44u5__p5_0[] = {
  145585. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145586. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  145587. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  145588. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  145589. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  145590. 14,
  145591. };
  145592. static float _vq_quantthresh__44u5__p5_0[] = {
  145593. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145594. };
  145595. static long _vq_quantmap__44u5__p5_0[] = {
  145596. 7, 5, 3, 1, 0, 2, 4, 6,
  145597. 8,
  145598. };
  145599. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  145600. _vq_quantthresh__44u5__p5_0,
  145601. _vq_quantmap__44u5__p5_0,
  145602. 9,
  145603. 9
  145604. };
  145605. static static_codebook _44u5__p5_0 = {
  145606. 2, 81,
  145607. _vq_lengthlist__44u5__p5_0,
  145608. 1, -531628032, 1611661312, 4, 0,
  145609. _vq_quantlist__44u5__p5_0,
  145610. NULL,
  145611. &_vq_auxt__44u5__p5_0,
  145612. NULL,
  145613. 0
  145614. };
  145615. static long _vq_quantlist__44u5__p6_0[] = {
  145616. 4,
  145617. 3,
  145618. 5,
  145619. 2,
  145620. 6,
  145621. 1,
  145622. 7,
  145623. 0,
  145624. 8,
  145625. };
  145626. static long _vq_lengthlist__44u5__p6_0[] = {
  145627. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145628. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145629. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  145630. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  145631. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  145632. 11,
  145633. };
  145634. static float _vq_quantthresh__44u5__p6_0[] = {
  145635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145636. };
  145637. static long _vq_quantmap__44u5__p6_0[] = {
  145638. 7, 5, 3, 1, 0, 2, 4, 6,
  145639. 8,
  145640. };
  145641. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  145642. _vq_quantthresh__44u5__p6_0,
  145643. _vq_quantmap__44u5__p6_0,
  145644. 9,
  145645. 9
  145646. };
  145647. static static_codebook _44u5__p6_0 = {
  145648. 2, 81,
  145649. _vq_lengthlist__44u5__p6_0,
  145650. 1, -531628032, 1611661312, 4, 0,
  145651. _vq_quantlist__44u5__p6_0,
  145652. NULL,
  145653. &_vq_auxt__44u5__p6_0,
  145654. NULL,
  145655. 0
  145656. };
  145657. static long _vq_quantlist__44u5__p7_0[] = {
  145658. 1,
  145659. 0,
  145660. 2,
  145661. };
  145662. static long _vq_lengthlist__44u5__p7_0[] = {
  145663. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  145664. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  145665. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  145666. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  145667. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  145668. 12,
  145669. };
  145670. static float _vq_quantthresh__44u5__p7_0[] = {
  145671. -5.5, 5.5,
  145672. };
  145673. static long _vq_quantmap__44u5__p7_0[] = {
  145674. 1, 0, 2,
  145675. };
  145676. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  145677. _vq_quantthresh__44u5__p7_0,
  145678. _vq_quantmap__44u5__p7_0,
  145679. 3,
  145680. 3
  145681. };
  145682. static static_codebook _44u5__p7_0 = {
  145683. 4, 81,
  145684. _vq_lengthlist__44u5__p7_0,
  145685. 1, -529137664, 1618345984, 2, 0,
  145686. _vq_quantlist__44u5__p7_0,
  145687. NULL,
  145688. &_vq_auxt__44u5__p7_0,
  145689. NULL,
  145690. 0
  145691. };
  145692. static long _vq_quantlist__44u5__p7_1[] = {
  145693. 5,
  145694. 4,
  145695. 6,
  145696. 3,
  145697. 7,
  145698. 2,
  145699. 8,
  145700. 1,
  145701. 9,
  145702. 0,
  145703. 10,
  145704. };
  145705. static long _vq_lengthlist__44u5__p7_1[] = {
  145706. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145707. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  145708. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145709. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  145710. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145711. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145712. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145713. 9, 9, 9, 9, 9,10,10,10,10,
  145714. };
  145715. static float _vq_quantthresh__44u5__p7_1[] = {
  145716. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145717. 3.5, 4.5,
  145718. };
  145719. static long _vq_quantmap__44u5__p7_1[] = {
  145720. 9, 7, 5, 3, 1, 0, 2, 4,
  145721. 6, 8, 10,
  145722. };
  145723. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  145724. _vq_quantthresh__44u5__p7_1,
  145725. _vq_quantmap__44u5__p7_1,
  145726. 11,
  145727. 11
  145728. };
  145729. static static_codebook _44u5__p7_1 = {
  145730. 2, 121,
  145731. _vq_lengthlist__44u5__p7_1,
  145732. 1, -531365888, 1611661312, 4, 0,
  145733. _vq_quantlist__44u5__p7_1,
  145734. NULL,
  145735. &_vq_auxt__44u5__p7_1,
  145736. NULL,
  145737. 0
  145738. };
  145739. static long _vq_quantlist__44u5__p8_0[] = {
  145740. 5,
  145741. 4,
  145742. 6,
  145743. 3,
  145744. 7,
  145745. 2,
  145746. 8,
  145747. 1,
  145748. 9,
  145749. 0,
  145750. 10,
  145751. };
  145752. static long _vq_lengthlist__44u5__p8_0[] = {
  145753. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145754. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145755. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  145756. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  145757. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  145758. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  145759. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  145760. 12,13,13,14,14,14,14,15,15,
  145761. };
  145762. static float _vq_quantthresh__44u5__p8_0[] = {
  145763. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145764. 38.5, 49.5,
  145765. };
  145766. static long _vq_quantmap__44u5__p8_0[] = {
  145767. 9, 7, 5, 3, 1, 0, 2, 4,
  145768. 6, 8, 10,
  145769. };
  145770. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  145771. _vq_quantthresh__44u5__p8_0,
  145772. _vq_quantmap__44u5__p8_0,
  145773. 11,
  145774. 11
  145775. };
  145776. static static_codebook _44u5__p8_0 = {
  145777. 2, 121,
  145778. _vq_lengthlist__44u5__p8_0,
  145779. 1, -524582912, 1618345984, 4, 0,
  145780. _vq_quantlist__44u5__p8_0,
  145781. NULL,
  145782. &_vq_auxt__44u5__p8_0,
  145783. NULL,
  145784. 0
  145785. };
  145786. static long _vq_quantlist__44u5__p8_1[] = {
  145787. 5,
  145788. 4,
  145789. 6,
  145790. 3,
  145791. 7,
  145792. 2,
  145793. 8,
  145794. 1,
  145795. 9,
  145796. 0,
  145797. 10,
  145798. };
  145799. static long _vq_lengthlist__44u5__p8_1[] = {
  145800. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  145801. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  145802. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  145803. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145804. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  145805. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145806. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145807. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145808. };
  145809. static float _vq_quantthresh__44u5__p8_1[] = {
  145810. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145811. 3.5, 4.5,
  145812. };
  145813. static long _vq_quantmap__44u5__p8_1[] = {
  145814. 9, 7, 5, 3, 1, 0, 2, 4,
  145815. 6, 8, 10,
  145816. };
  145817. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  145818. _vq_quantthresh__44u5__p8_1,
  145819. _vq_quantmap__44u5__p8_1,
  145820. 11,
  145821. 11
  145822. };
  145823. static static_codebook _44u5__p8_1 = {
  145824. 2, 121,
  145825. _vq_lengthlist__44u5__p8_1,
  145826. 1, -531365888, 1611661312, 4, 0,
  145827. _vq_quantlist__44u5__p8_1,
  145828. NULL,
  145829. &_vq_auxt__44u5__p8_1,
  145830. NULL,
  145831. 0
  145832. };
  145833. static long _vq_quantlist__44u5__p9_0[] = {
  145834. 6,
  145835. 5,
  145836. 7,
  145837. 4,
  145838. 8,
  145839. 3,
  145840. 9,
  145841. 2,
  145842. 10,
  145843. 1,
  145844. 11,
  145845. 0,
  145846. 12,
  145847. };
  145848. static long _vq_lengthlist__44u5__p9_0[] = {
  145849. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  145850. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  145851. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  145852. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  145853. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145854. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145855. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145856. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145857. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  145858. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145859. 12,12,12,12,12,12,12,12,12,
  145860. };
  145861. static float _vq_quantthresh__44u5__p9_0[] = {
  145862. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145863. 637.5, 892.5, 1147.5, 1402.5,
  145864. };
  145865. static long _vq_quantmap__44u5__p9_0[] = {
  145866. 11, 9, 7, 5, 3, 1, 0, 2,
  145867. 4, 6, 8, 10, 12,
  145868. };
  145869. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  145870. _vq_quantthresh__44u5__p9_0,
  145871. _vq_quantmap__44u5__p9_0,
  145872. 13,
  145873. 13
  145874. };
  145875. static static_codebook _44u5__p9_0 = {
  145876. 2, 169,
  145877. _vq_lengthlist__44u5__p9_0,
  145878. 1, -514332672, 1627381760, 4, 0,
  145879. _vq_quantlist__44u5__p9_0,
  145880. NULL,
  145881. &_vq_auxt__44u5__p9_0,
  145882. NULL,
  145883. 0
  145884. };
  145885. static long _vq_quantlist__44u5__p9_1[] = {
  145886. 7,
  145887. 6,
  145888. 8,
  145889. 5,
  145890. 9,
  145891. 4,
  145892. 10,
  145893. 3,
  145894. 11,
  145895. 2,
  145896. 12,
  145897. 1,
  145898. 13,
  145899. 0,
  145900. 14,
  145901. };
  145902. static long _vq_lengthlist__44u5__p9_1[] = {
  145903. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  145904. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  145905. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  145906. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  145907. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  145908. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  145909. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  145910. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  145911. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  145912. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  145913. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  145914. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  145915. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  145916. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  145917. 14,
  145918. };
  145919. static float _vq_quantthresh__44u5__p9_1[] = {
  145920. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145921. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145922. };
  145923. static long _vq_quantmap__44u5__p9_1[] = {
  145924. 13, 11, 9, 7, 5, 3, 1, 0,
  145925. 2, 4, 6, 8, 10, 12, 14,
  145926. };
  145927. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  145928. _vq_quantthresh__44u5__p9_1,
  145929. _vq_quantmap__44u5__p9_1,
  145930. 15,
  145931. 15
  145932. };
  145933. static static_codebook _44u5__p9_1 = {
  145934. 2, 225,
  145935. _vq_lengthlist__44u5__p9_1,
  145936. 1, -522338304, 1620115456, 4, 0,
  145937. _vq_quantlist__44u5__p9_1,
  145938. NULL,
  145939. &_vq_auxt__44u5__p9_1,
  145940. NULL,
  145941. 0
  145942. };
  145943. static long _vq_quantlist__44u5__p9_2[] = {
  145944. 8,
  145945. 7,
  145946. 9,
  145947. 6,
  145948. 10,
  145949. 5,
  145950. 11,
  145951. 4,
  145952. 12,
  145953. 3,
  145954. 13,
  145955. 2,
  145956. 14,
  145957. 1,
  145958. 15,
  145959. 0,
  145960. 16,
  145961. };
  145962. static long _vq_lengthlist__44u5__p9_2[] = {
  145963. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145964. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145965. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145966. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145967. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145968. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145969. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145970. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145971. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145972. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  145973. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  145974. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145975. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145976. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145977. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145978. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145979. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145980. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  145981. 10,
  145982. };
  145983. static float _vq_quantthresh__44u5__p9_2[] = {
  145984. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145985. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145986. };
  145987. static long _vq_quantmap__44u5__p9_2[] = {
  145988. 15, 13, 11, 9, 7, 5, 3, 1,
  145989. 0, 2, 4, 6, 8, 10, 12, 14,
  145990. 16,
  145991. };
  145992. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  145993. _vq_quantthresh__44u5__p9_2,
  145994. _vq_quantmap__44u5__p9_2,
  145995. 17,
  145996. 17
  145997. };
  145998. static static_codebook _44u5__p9_2 = {
  145999. 2, 289,
  146000. _vq_lengthlist__44u5__p9_2,
  146001. 1, -529530880, 1611661312, 5, 0,
  146002. _vq_quantlist__44u5__p9_2,
  146003. NULL,
  146004. &_vq_auxt__44u5__p9_2,
  146005. NULL,
  146006. 0
  146007. };
  146008. static long _huff_lengthlist__44u5__short[] = {
  146009. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  146010. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  146011. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  146012. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  146013. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  146014. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  146015. 6, 8,15,17,
  146016. };
  146017. static static_codebook _huff_book__44u5__short = {
  146018. 2, 100,
  146019. _huff_lengthlist__44u5__short,
  146020. 0, 0, 0, 0, 0,
  146021. NULL,
  146022. NULL,
  146023. NULL,
  146024. NULL,
  146025. 0
  146026. };
  146027. static long _huff_lengthlist__44u6__long[] = {
  146028. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  146029. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  146030. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  146031. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  146032. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  146033. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  146034. 13, 8, 7, 7,
  146035. };
  146036. static static_codebook _huff_book__44u6__long = {
  146037. 2, 100,
  146038. _huff_lengthlist__44u6__long,
  146039. 0, 0, 0, 0, 0,
  146040. NULL,
  146041. NULL,
  146042. NULL,
  146043. NULL,
  146044. 0
  146045. };
  146046. static long _vq_quantlist__44u6__p1_0[] = {
  146047. 1,
  146048. 0,
  146049. 2,
  146050. };
  146051. static long _vq_lengthlist__44u6__p1_0[] = {
  146052. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146053. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  146054. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146055. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  146056. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  146057. 12,
  146058. };
  146059. static float _vq_quantthresh__44u6__p1_0[] = {
  146060. -0.5, 0.5,
  146061. };
  146062. static long _vq_quantmap__44u6__p1_0[] = {
  146063. 1, 0, 2,
  146064. };
  146065. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  146066. _vq_quantthresh__44u6__p1_0,
  146067. _vq_quantmap__44u6__p1_0,
  146068. 3,
  146069. 3
  146070. };
  146071. static static_codebook _44u6__p1_0 = {
  146072. 4, 81,
  146073. _vq_lengthlist__44u6__p1_0,
  146074. 1, -535822336, 1611661312, 2, 0,
  146075. _vq_quantlist__44u6__p1_0,
  146076. NULL,
  146077. &_vq_auxt__44u6__p1_0,
  146078. NULL,
  146079. 0
  146080. };
  146081. static long _vq_quantlist__44u6__p2_0[] = {
  146082. 1,
  146083. 0,
  146084. 2,
  146085. };
  146086. static long _vq_lengthlist__44u6__p2_0[] = {
  146087. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146088. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146089. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  146090. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146091. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146092. 9,
  146093. };
  146094. static float _vq_quantthresh__44u6__p2_0[] = {
  146095. -0.5, 0.5,
  146096. };
  146097. static long _vq_quantmap__44u6__p2_0[] = {
  146098. 1, 0, 2,
  146099. };
  146100. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  146101. _vq_quantthresh__44u6__p2_0,
  146102. _vq_quantmap__44u6__p2_0,
  146103. 3,
  146104. 3
  146105. };
  146106. static static_codebook _44u6__p2_0 = {
  146107. 4, 81,
  146108. _vq_lengthlist__44u6__p2_0,
  146109. 1, -535822336, 1611661312, 2, 0,
  146110. _vq_quantlist__44u6__p2_0,
  146111. NULL,
  146112. &_vq_auxt__44u6__p2_0,
  146113. NULL,
  146114. 0
  146115. };
  146116. static long _vq_quantlist__44u6__p3_0[] = {
  146117. 2,
  146118. 1,
  146119. 3,
  146120. 0,
  146121. 4,
  146122. };
  146123. static long _vq_lengthlist__44u6__p3_0[] = {
  146124. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146125. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146126. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146127. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  146128. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  146129. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  146130. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146131. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  146132. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  146133. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  146134. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  146135. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  146136. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  146137. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  146138. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  146139. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  146140. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146141. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146142. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  146143. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  146144. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  146145. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  146146. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  146147. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  146148. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  146149. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  146150. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  146151. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  146152. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  146153. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  146154. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  146155. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  146156. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  146157. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  146158. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  146159. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  146160. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  146161. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  146162. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  146163. 19,
  146164. };
  146165. static float _vq_quantthresh__44u6__p3_0[] = {
  146166. -1.5, -0.5, 0.5, 1.5,
  146167. };
  146168. static long _vq_quantmap__44u6__p3_0[] = {
  146169. 3, 1, 0, 2, 4,
  146170. };
  146171. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  146172. _vq_quantthresh__44u6__p3_0,
  146173. _vq_quantmap__44u6__p3_0,
  146174. 5,
  146175. 5
  146176. };
  146177. static static_codebook _44u6__p3_0 = {
  146178. 4, 625,
  146179. _vq_lengthlist__44u6__p3_0,
  146180. 1, -533725184, 1611661312, 3, 0,
  146181. _vq_quantlist__44u6__p3_0,
  146182. NULL,
  146183. &_vq_auxt__44u6__p3_0,
  146184. NULL,
  146185. 0
  146186. };
  146187. static long _vq_quantlist__44u6__p4_0[] = {
  146188. 2,
  146189. 1,
  146190. 3,
  146191. 0,
  146192. 4,
  146193. };
  146194. static long _vq_lengthlist__44u6__p4_0[] = {
  146195. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146196. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146197. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146198. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  146199. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146200. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  146201. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146202. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  146203. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146204. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146205. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  146206. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146207. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146208. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  146209. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  146210. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146211. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  146212. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146213. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  146214. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  146215. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146216. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146217. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  146218. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146219. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  146220. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146221. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146222. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  146223. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  146224. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  146225. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  146226. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146227. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  146228. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146229. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146230. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146231. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  146232. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  146233. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  146234. 13,
  146235. };
  146236. static float _vq_quantthresh__44u6__p4_0[] = {
  146237. -1.5, -0.5, 0.5, 1.5,
  146238. };
  146239. static long _vq_quantmap__44u6__p4_0[] = {
  146240. 3, 1, 0, 2, 4,
  146241. };
  146242. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  146243. _vq_quantthresh__44u6__p4_0,
  146244. _vq_quantmap__44u6__p4_0,
  146245. 5,
  146246. 5
  146247. };
  146248. static static_codebook _44u6__p4_0 = {
  146249. 4, 625,
  146250. _vq_lengthlist__44u6__p4_0,
  146251. 1, -533725184, 1611661312, 3, 0,
  146252. _vq_quantlist__44u6__p4_0,
  146253. NULL,
  146254. &_vq_auxt__44u6__p4_0,
  146255. NULL,
  146256. 0
  146257. };
  146258. static long _vq_quantlist__44u6__p5_0[] = {
  146259. 4,
  146260. 3,
  146261. 5,
  146262. 2,
  146263. 6,
  146264. 1,
  146265. 7,
  146266. 0,
  146267. 8,
  146268. };
  146269. static long _vq_lengthlist__44u6__p5_0[] = {
  146270. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146271. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  146272. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  146273. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  146274. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  146275. 14,
  146276. };
  146277. static float _vq_quantthresh__44u6__p5_0[] = {
  146278. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146279. };
  146280. static long _vq_quantmap__44u6__p5_0[] = {
  146281. 7, 5, 3, 1, 0, 2, 4, 6,
  146282. 8,
  146283. };
  146284. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  146285. _vq_quantthresh__44u6__p5_0,
  146286. _vq_quantmap__44u6__p5_0,
  146287. 9,
  146288. 9
  146289. };
  146290. static static_codebook _44u6__p5_0 = {
  146291. 2, 81,
  146292. _vq_lengthlist__44u6__p5_0,
  146293. 1, -531628032, 1611661312, 4, 0,
  146294. _vq_quantlist__44u6__p5_0,
  146295. NULL,
  146296. &_vq_auxt__44u6__p5_0,
  146297. NULL,
  146298. 0
  146299. };
  146300. static long _vq_quantlist__44u6__p6_0[] = {
  146301. 4,
  146302. 3,
  146303. 5,
  146304. 2,
  146305. 6,
  146306. 1,
  146307. 7,
  146308. 0,
  146309. 8,
  146310. };
  146311. static long _vq_lengthlist__44u6__p6_0[] = {
  146312. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146313. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  146314. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146315. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  146316. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  146317. 12,
  146318. };
  146319. static float _vq_quantthresh__44u6__p6_0[] = {
  146320. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146321. };
  146322. static long _vq_quantmap__44u6__p6_0[] = {
  146323. 7, 5, 3, 1, 0, 2, 4, 6,
  146324. 8,
  146325. };
  146326. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  146327. _vq_quantthresh__44u6__p6_0,
  146328. _vq_quantmap__44u6__p6_0,
  146329. 9,
  146330. 9
  146331. };
  146332. static static_codebook _44u6__p6_0 = {
  146333. 2, 81,
  146334. _vq_lengthlist__44u6__p6_0,
  146335. 1, -531628032, 1611661312, 4, 0,
  146336. _vq_quantlist__44u6__p6_0,
  146337. NULL,
  146338. &_vq_auxt__44u6__p6_0,
  146339. NULL,
  146340. 0
  146341. };
  146342. static long _vq_quantlist__44u6__p7_0[] = {
  146343. 1,
  146344. 0,
  146345. 2,
  146346. };
  146347. static long _vq_lengthlist__44u6__p7_0[] = {
  146348. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  146349. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  146350. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  146351. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  146352. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  146353. 10,
  146354. };
  146355. static float _vq_quantthresh__44u6__p7_0[] = {
  146356. -5.5, 5.5,
  146357. };
  146358. static long _vq_quantmap__44u6__p7_0[] = {
  146359. 1, 0, 2,
  146360. };
  146361. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  146362. _vq_quantthresh__44u6__p7_0,
  146363. _vq_quantmap__44u6__p7_0,
  146364. 3,
  146365. 3
  146366. };
  146367. static static_codebook _44u6__p7_0 = {
  146368. 4, 81,
  146369. _vq_lengthlist__44u6__p7_0,
  146370. 1, -529137664, 1618345984, 2, 0,
  146371. _vq_quantlist__44u6__p7_0,
  146372. NULL,
  146373. &_vq_auxt__44u6__p7_0,
  146374. NULL,
  146375. 0
  146376. };
  146377. static long _vq_quantlist__44u6__p7_1[] = {
  146378. 5,
  146379. 4,
  146380. 6,
  146381. 3,
  146382. 7,
  146383. 2,
  146384. 8,
  146385. 1,
  146386. 9,
  146387. 0,
  146388. 10,
  146389. };
  146390. static long _vq_lengthlist__44u6__p7_1[] = {
  146391. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  146392. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  146393. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146394. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  146395. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  146396. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  146397. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  146398. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146399. };
  146400. static float _vq_quantthresh__44u6__p7_1[] = {
  146401. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146402. 3.5, 4.5,
  146403. };
  146404. static long _vq_quantmap__44u6__p7_1[] = {
  146405. 9, 7, 5, 3, 1, 0, 2, 4,
  146406. 6, 8, 10,
  146407. };
  146408. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  146409. _vq_quantthresh__44u6__p7_1,
  146410. _vq_quantmap__44u6__p7_1,
  146411. 11,
  146412. 11
  146413. };
  146414. static static_codebook _44u6__p7_1 = {
  146415. 2, 121,
  146416. _vq_lengthlist__44u6__p7_1,
  146417. 1, -531365888, 1611661312, 4, 0,
  146418. _vq_quantlist__44u6__p7_1,
  146419. NULL,
  146420. &_vq_auxt__44u6__p7_1,
  146421. NULL,
  146422. 0
  146423. };
  146424. static long _vq_quantlist__44u6__p8_0[] = {
  146425. 5,
  146426. 4,
  146427. 6,
  146428. 3,
  146429. 7,
  146430. 2,
  146431. 8,
  146432. 1,
  146433. 9,
  146434. 0,
  146435. 10,
  146436. };
  146437. static long _vq_lengthlist__44u6__p8_0[] = {
  146438. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  146439. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  146440. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  146441. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  146442. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  146443. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  146444. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  146445. 12,13,13,14,14,14,15,15,15,
  146446. };
  146447. static float _vq_quantthresh__44u6__p8_0[] = {
  146448. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146449. 38.5, 49.5,
  146450. };
  146451. static long _vq_quantmap__44u6__p8_0[] = {
  146452. 9, 7, 5, 3, 1, 0, 2, 4,
  146453. 6, 8, 10,
  146454. };
  146455. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  146456. _vq_quantthresh__44u6__p8_0,
  146457. _vq_quantmap__44u6__p8_0,
  146458. 11,
  146459. 11
  146460. };
  146461. static static_codebook _44u6__p8_0 = {
  146462. 2, 121,
  146463. _vq_lengthlist__44u6__p8_0,
  146464. 1, -524582912, 1618345984, 4, 0,
  146465. _vq_quantlist__44u6__p8_0,
  146466. NULL,
  146467. &_vq_auxt__44u6__p8_0,
  146468. NULL,
  146469. 0
  146470. };
  146471. static long _vq_quantlist__44u6__p8_1[] = {
  146472. 5,
  146473. 4,
  146474. 6,
  146475. 3,
  146476. 7,
  146477. 2,
  146478. 8,
  146479. 1,
  146480. 9,
  146481. 0,
  146482. 10,
  146483. };
  146484. static long _vq_lengthlist__44u6__p8_1[] = {
  146485. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  146486. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  146487. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  146488. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146489. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  146490. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146491. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146492. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146493. };
  146494. static float _vq_quantthresh__44u6__p8_1[] = {
  146495. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146496. 3.5, 4.5,
  146497. };
  146498. static long _vq_quantmap__44u6__p8_1[] = {
  146499. 9, 7, 5, 3, 1, 0, 2, 4,
  146500. 6, 8, 10,
  146501. };
  146502. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  146503. _vq_quantthresh__44u6__p8_1,
  146504. _vq_quantmap__44u6__p8_1,
  146505. 11,
  146506. 11
  146507. };
  146508. static static_codebook _44u6__p8_1 = {
  146509. 2, 121,
  146510. _vq_lengthlist__44u6__p8_1,
  146511. 1, -531365888, 1611661312, 4, 0,
  146512. _vq_quantlist__44u6__p8_1,
  146513. NULL,
  146514. &_vq_auxt__44u6__p8_1,
  146515. NULL,
  146516. 0
  146517. };
  146518. static long _vq_quantlist__44u6__p9_0[] = {
  146519. 7,
  146520. 6,
  146521. 8,
  146522. 5,
  146523. 9,
  146524. 4,
  146525. 10,
  146526. 3,
  146527. 11,
  146528. 2,
  146529. 12,
  146530. 1,
  146531. 13,
  146532. 0,
  146533. 14,
  146534. };
  146535. static long _vq_lengthlist__44u6__p9_0[] = {
  146536. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  146537. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  146538. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  146539. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  146540. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146541. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146542. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146543. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146544. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146545. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146546. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146547. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146548. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146549. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146550. 14,
  146551. };
  146552. static float _vq_quantthresh__44u6__p9_0[] = {
  146553. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146554. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146555. };
  146556. static long _vq_quantmap__44u6__p9_0[] = {
  146557. 13, 11, 9, 7, 5, 3, 1, 0,
  146558. 2, 4, 6, 8, 10, 12, 14,
  146559. };
  146560. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  146561. _vq_quantthresh__44u6__p9_0,
  146562. _vq_quantmap__44u6__p9_0,
  146563. 15,
  146564. 15
  146565. };
  146566. static static_codebook _44u6__p9_0 = {
  146567. 2, 225,
  146568. _vq_lengthlist__44u6__p9_0,
  146569. 1, -514071552, 1627381760, 4, 0,
  146570. _vq_quantlist__44u6__p9_0,
  146571. NULL,
  146572. &_vq_auxt__44u6__p9_0,
  146573. NULL,
  146574. 0
  146575. };
  146576. static long _vq_quantlist__44u6__p9_1[] = {
  146577. 7,
  146578. 6,
  146579. 8,
  146580. 5,
  146581. 9,
  146582. 4,
  146583. 10,
  146584. 3,
  146585. 11,
  146586. 2,
  146587. 12,
  146588. 1,
  146589. 13,
  146590. 0,
  146591. 14,
  146592. };
  146593. static long _vq_lengthlist__44u6__p9_1[] = {
  146594. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  146595. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  146596. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  146597. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  146598. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  146599. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  146600. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  146601. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  146602. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  146603. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  146604. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  146605. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  146606. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  146607. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  146608. 13,
  146609. };
  146610. static float _vq_quantthresh__44u6__p9_1[] = {
  146611. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146612. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146613. };
  146614. static long _vq_quantmap__44u6__p9_1[] = {
  146615. 13, 11, 9, 7, 5, 3, 1, 0,
  146616. 2, 4, 6, 8, 10, 12, 14,
  146617. };
  146618. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  146619. _vq_quantthresh__44u6__p9_1,
  146620. _vq_quantmap__44u6__p9_1,
  146621. 15,
  146622. 15
  146623. };
  146624. static static_codebook _44u6__p9_1 = {
  146625. 2, 225,
  146626. _vq_lengthlist__44u6__p9_1,
  146627. 1, -522338304, 1620115456, 4, 0,
  146628. _vq_quantlist__44u6__p9_1,
  146629. NULL,
  146630. &_vq_auxt__44u6__p9_1,
  146631. NULL,
  146632. 0
  146633. };
  146634. static long _vq_quantlist__44u6__p9_2[] = {
  146635. 8,
  146636. 7,
  146637. 9,
  146638. 6,
  146639. 10,
  146640. 5,
  146641. 11,
  146642. 4,
  146643. 12,
  146644. 3,
  146645. 13,
  146646. 2,
  146647. 14,
  146648. 1,
  146649. 15,
  146650. 0,
  146651. 16,
  146652. };
  146653. static long _vq_lengthlist__44u6__p9_2[] = {
  146654. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  146655. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146656. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  146657. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146658. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146659. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146660. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146661. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146662. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146663. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  146664. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  146665. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146666. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  146667. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  146668. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  146669. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  146670. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  146671. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  146672. 10,
  146673. };
  146674. static float _vq_quantthresh__44u6__p9_2[] = {
  146675. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146676. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146677. };
  146678. static long _vq_quantmap__44u6__p9_2[] = {
  146679. 15, 13, 11, 9, 7, 5, 3, 1,
  146680. 0, 2, 4, 6, 8, 10, 12, 14,
  146681. 16,
  146682. };
  146683. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  146684. _vq_quantthresh__44u6__p9_2,
  146685. _vq_quantmap__44u6__p9_2,
  146686. 17,
  146687. 17
  146688. };
  146689. static static_codebook _44u6__p9_2 = {
  146690. 2, 289,
  146691. _vq_lengthlist__44u6__p9_2,
  146692. 1, -529530880, 1611661312, 5, 0,
  146693. _vq_quantlist__44u6__p9_2,
  146694. NULL,
  146695. &_vq_auxt__44u6__p9_2,
  146696. NULL,
  146697. 0
  146698. };
  146699. static long _huff_lengthlist__44u6__short[] = {
  146700. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  146701. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  146702. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  146703. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  146704. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  146705. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  146706. 7, 6, 9,16,
  146707. };
  146708. static static_codebook _huff_book__44u6__short = {
  146709. 2, 100,
  146710. _huff_lengthlist__44u6__short,
  146711. 0, 0, 0, 0, 0,
  146712. NULL,
  146713. NULL,
  146714. NULL,
  146715. NULL,
  146716. 0
  146717. };
  146718. static long _huff_lengthlist__44u7__long[] = {
  146719. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  146720. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  146721. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  146722. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  146723. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  146724. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  146725. 12, 8, 6, 7,
  146726. };
  146727. static static_codebook _huff_book__44u7__long = {
  146728. 2, 100,
  146729. _huff_lengthlist__44u7__long,
  146730. 0, 0, 0, 0, 0,
  146731. NULL,
  146732. NULL,
  146733. NULL,
  146734. NULL,
  146735. 0
  146736. };
  146737. static long _vq_quantlist__44u7__p1_0[] = {
  146738. 1,
  146739. 0,
  146740. 2,
  146741. };
  146742. static long _vq_lengthlist__44u7__p1_0[] = {
  146743. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146744. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  146745. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146746. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  146747. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  146748. 12,
  146749. };
  146750. static float _vq_quantthresh__44u7__p1_0[] = {
  146751. -0.5, 0.5,
  146752. };
  146753. static long _vq_quantmap__44u7__p1_0[] = {
  146754. 1, 0, 2,
  146755. };
  146756. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  146757. _vq_quantthresh__44u7__p1_0,
  146758. _vq_quantmap__44u7__p1_0,
  146759. 3,
  146760. 3
  146761. };
  146762. static static_codebook _44u7__p1_0 = {
  146763. 4, 81,
  146764. _vq_lengthlist__44u7__p1_0,
  146765. 1, -535822336, 1611661312, 2, 0,
  146766. _vq_quantlist__44u7__p1_0,
  146767. NULL,
  146768. &_vq_auxt__44u7__p1_0,
  146769. NULL,
  146770. 0
  146771. };
  146772. static long _vq_quantlist__44u7__p2_0[] = {
  146773. 1,
  146774. 0,
  146775. 2,
  146776. };
  146777. static long _vq_lengthlist__44u7__p2_0[] = {
  146778. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146779. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146780. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  146781. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146782. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146783. 9,
  146784. };
  146785. static float _vq_quantthresh__44u7__p2_0[] = {
  146786. -0.5, 0.5,
  146787. };
  146788. static long _vq_quantmap__44u7__p2_0[] = {
  146789. 1, 0, 2,
  146790. };
  146791. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  146792. _vq_quantthresh__44u7__p2_0,
  146793. _vq_quantmap__44u7__p2_0,
  146794. 3,
  146795. 3
  146796. };
  146797. static static_codebook _44u7__p2_0 = {
  146798. 4, 81,
  146799. _vq_lengthlist__44u7__p2_0,
  146800. 1, -535822336, 1611661312, 2, 0,
  146801. _vq_quantlist__44u7__p2_0,
  146802. NULL,
  146803. &_vq_auxt__44u7__p2_0,
  146804. NULL,
  146805. 0
  146806. };
  146807. static long _vq_quantlist__44u7__p3_0[] = {
  146808. 2,
  146809. 1,
  146810. 3,
  146811. 0,
  146812. 4,
  146813. };
  146814. static long _vq_lengthlist__44u7__p3_0[] = {
  146815. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146816. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146817. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146818. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  146819. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  146820. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  146821. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  146822. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  146823. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  146824. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146825. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  146826. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146827. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  146828. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  146829. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  146830. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  146831. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  146832. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146833. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  146834. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  146835. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  146836. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  146837. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  146838. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  146839. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  146840. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  146841. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  146842. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  146843. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  146844. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  146845. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  146846. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  146847. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  146848. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  146849. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  146850. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  146851. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  146852. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  146853. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  146854. 0,
  146855. };
  146856. static float _vq_quantthresh__44u7__p3_0[] = {
  146857. -1.5, -0.5, 0.5, 1.5,
  146858. };
  146859. static long _vq_quantmap__44u7__p3_0[] = {
  146860. 3, 1, 0, 2, 4,
  146861. };
  146862. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  146863. _vq_quantthresh__44u7__p3_0,
  146864. _vq_quantmap__44u7__p3_0,
  146865. 5,
  146866. 5
  146867. };
  146868. static static_codebook _44u7__p3_0 = {
  146869. 4, 625,
  146870. _vq_lengthlist__44u7__p3_0,
  146871. 1, -533725184, 1611661312, 3, 0,
  146872. _vq_quantlist__44u7__p3_0,
  146873. NULL,
  146874. &_vq_auxt__44u7__p3_0,
  146875. NULL,
  146876. 0
  146877. };
  146878. static long _vq_quantlist__44u7__p4_0[] = {
  146879. 2,
  146880. 1,
  146881. 3,
  146882. 0,
  146883. 4,
  146884. };
  146885. static long _vq_lengthlist__44u7__p4_0[] = {
  146886. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146887. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  146888. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  146889. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  146890. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146891. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  146892. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  146893. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  146894. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146895. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146896. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  146897. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146898. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146899. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  146900. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  146901. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146902. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  146903. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146904. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  146905. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  146906. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146907. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146908. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  146909. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146910. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  146911. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146912. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146913. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  146914. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  146915. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  146916. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  146917. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146918. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  146919. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146920. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  146921. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146922. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  146923. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  146924. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  146925. 14,
  146926. };
  146927. static float _vq_quantthresh__44u7__p4_0[] = {
  146928. -1.5, -0.5, 0.5, 1.5,
  146929. };
  146930. static long _vq_quantmap__44u7__p4_0[] = {
  146931. 3, 1, 0, 2, 4,
  146932. };
  146933. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  146934. _vq_quantthresh__44u7__p4_0,
  146935. _vq_quantmap__44u7__p4_0,
  146936. 5,
  146937. 5
  146938. };
  146939. static static_codebook _44u7__p4_0 = {
  146940. 4, 625,
  146941. _vq_lengthlist__44u7__p4_0,
  146942. 1, -533725184, 1611661312, 3, 0,
  146943. _vq_quantlist__44u7__p4_0,
  146944. NULL,
  146945. &_vq_auxt__44u7__p4_0,
  146946. NULL,
  146947. 0
  146948. };
  146949. static long _vq_quantlist__44u7__p5_0[] = {
  146950. 4,
  146951. 3,
  146952. 5,
  146953. 2,
  146954. 6,
  146955. 1,
  146956. 7,
  146957. 0,
  146958. 8,
  146959. };
  146960. static long _vq_lengthlist__44u7__p5_0[] = {
  146961. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146962. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  146963. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  146964. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  146965. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  146966. 14,
  146967. };
  146968. static float _vq_quantthresh__44u7__p5_0[] = {
  146969. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146970. };
  146971. static long _vq_quantmap__44u7__p5_0[] = {
  146972. 7, 5, 3, 1, 0, 2, 4, 6,
  146973. 8,
  146974. };
  146975. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  146976. _vq_quantthresh__44u7__p5_0,
  146977. _vq_quantmap__44u7__p5_0,
  146978. 9,
  146979. 9
  146980. };
  146981. static static_codebook _44u7__p5_0 = {
  146982. 2, 81,
  146983. _vq_lengthlist__44u7__p5_0,
  146984. 1, -531628032, 1611661312, 4, 0,
  146985. _vq_quantlist__44u7__p5_0,
  146986. NULL,
  146987. &_vq_auxt__44u7__p5_0,
  146988. NULL,
  146989. 0
  146990. };
  146991. static long _vq_quantlist__44u7__p6_0[] = {
  146992. 4,
  146993. 3,
  146994. 5,
  146995. 2,
  146996. 6,
  146997. 1,
  146998. 7,
  146999. 0,
  147000. 8,
  147001. };
  147002. static long _vq_lengthlist__44u7__p6_0[] = {
  147003. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  147004. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147005. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  147006. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  147007. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  147008. 12,
  147009. };
  147010. static float _vq_quantthresh__44u7__p6_0[] = {
  147011. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147012. };
  147013. static long _vq_quantmap__44u7__p6_0[] = {
  147014. 7, 5, 3, 1, 0, 2, 4, 6,
  147015. 8,
  147016. };
  147017. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  147018. _vq_quantthresh__44u7__p6_0,
  147019. _vq_quantmap__44u7__p6_0,
  147020. 9,
  147021. 9
  147022. };
  147023. static static_codebook _44u7__p6_0 = {
  147024. 2, 81,
  147025. _vq_lengthlist__44u7__p6_0,
  147026. 1, -531628032, 1611661312, 4, 0,
  147027. _vq_quantlist__44u7__p6_0,
  147028. NULL,
  147029. &_vq_auxt__44u7__p6_0,
  147030. NULL,
  147031. 0
  147032. };
  147033. static long _vq_quantlist__44u7__p7_0[] = {
  147034. 1,
  147035. 0,
  147036. 2,
  147037. };
  147038. static long _vq_lengthlist__44u7__p7_0[] = {
  147039. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  147040. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  147041. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  147042. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  147043. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  147044. 10,
  147045. };
  147046. static float _vq_quantthresh__44u7__p7_0[] = {
  147047. -5.5, 5.5,
  147048. };
  147049. static long _vq_quantmap__44u7__p7_0[] = {
  147050. 1, 0, 2,
  147051. };
  147052. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  147053. _vq_quantthresh__44u7__p7_0,
  147054. _vq_quantmap__44u7__p7_0,
  147055. 3,
  147056. 3
  147057. };
  147058. static static_codebook _44u7__p7_0 = {
  147059. 4, 81,
  147060. _vq_lengthlist__44u7__p7_0,
  147061. 1, -529137664, 1618345984, 2, 0,
  147062. _vq_quantlist__44u7__p7_0,
  147063. NULL,
  147064. &_vq_auxt__44u7__p7_0,
  147065. NULL,
  147066. 0
  147067. };
  147068. static long _vq_quantlist__44u7__p7_1[] = {
  147069. 5,
  147070. 4,
  147071. 6,
  147072. 3,
  147073. 7,
  147074. 2,
  147075. 8,
  147076. 1,
  147077. 9,
  147078. 0,
  147079. 10,
  147080. };
  147081. static long _vq_lengthlist__44u7__p7_1[] = {
  147082. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  147083. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  147084. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  147085. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  147086. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147087. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147088. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  147089. 8, 9, 9, 9, 9, 9,10,10,10,
  147090. };
  147091. static float _vq_quantthresh__44u7__p7_1[] = {
  147092. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147093. 3.5, 4.5,
  147094. };
  147095. static long _vq_quantmap__44u7__p7_1[] = {
  147096. 9, 7, 5, 3, 1, 0, 2, 4,
  147097. 6, 8, 10,
  147098. };
  147099. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  147100. _vq_quantthresh__44u7__p7_1,
  147101. _vq_quantmap__44u7__p7_1,
  147102. 11,
  147103. 11
  147104. };
  147105. static static_codebook _44u7__p7_1 = {
  147106. 2, 121,
  147107. _vq_lengthlist__44u7__p7_1,
  147108. 1, -531365888, 1611661312, 4, 0,
  147109. _vq_quantlist__44u7__p7_1,
  147110. NULL,
  147111. &_vq_auxt__44u7__p7_1,
  147112. NULL,
  147113. 0
  147114. };
  147115. static long _vq_quantlist__44u7__p8_0[] = {
  147116. 5,
  147117. 4,
  147118. 6,
  147119. 3,
  147120. 7,
  147121. 2,
  147122. 8,
  147123. 1,
  147124. 9,
  147125. 0,
  147126. 10,
  147127. };
  147128. static long _vq_lengthlist__44u7__p8_0[] = {
  147129. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  147130. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  147131. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  147132. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  147133. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  147134. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  147135. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  147136. 12,13,13,14,14,15,15,15,16,
  147137. };
  147138. static float _vq_quantthresh__44u7__p8_0[] = {
  147139. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  147140. 38.5, 49.5,
  147141. };
  147142. static long _vq_quantmap__44u7__p8_0[] = {
  147143. 9, 7, 5, 3, 1, 0, 2, 4,
  147144. 6, 8, 10,
  147145. };
  147146. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  147147. _vq_quantthresh__44u7__p8_0,
  147148. _vq_quantmap__44u7__p8_0,
  147149. 11,
  147150. 11
  147151. };
  147152. static static_codebook _44u7__p8_0 = {
  147153. 2, 121,
  147154. _vq_lengthlist__44u7__p8_0,
  147155. 1, -524582912, 1618345984, 4, 0,
  147156. _vq_quantlist__44u7__p8_0,
  147157. NULL,
  147158. &_vq_auxt__44u7__p8_0,
  147159. NULL,
  147160. 0
  147161. };
  147162. static long _vq_quantlist__44u7__p8_1[] = {
  147163. 5,
  147164. 4,
  147165. 6,
  147166. 3,
  147167. 7,
  147168. 2,
  147169. 8,
  147170. 1,
  147171. 9,
  147172. 0,
  147173. 10,
  147174. };
  147175. static long _vq_lengthlist__44u7__p8_1[] = {
  147176. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147177. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  147178. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147179. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147180. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147181. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147182. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147183. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147184. };
  147185. static float _vq_quantthresh__44u7__p8_1[] = {
  147186. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147187. 3.5, 4.5,
  147188. };
  147189. static long _vq_quantmap__44u7__p8_1[] = {
  147190. 9, 7, 5, 3, 1, 0, 2, 4,
  147191. 6, 8, 10,
  147192. };
  147193. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  147194. _vq_quantthresh__44u7__p8_1,
  147195. _vq_quantmap__44u7__p8_1,
  147196. 11,
  147197. 11
  147198. };
  147199. static static_codebook _44u7__p8_1 = {
  147200. 2, 121,
  147201. _vq_lengthlist__44u7__p8_1,
  147202. 1, -531365888, 1611661312, 4, 0,
  147203. _vq_quantlist__44u7__p8_1,
  147204. NULL,
  147205. &_vq_auxt__44u7__p8_1,
  147206. NULL,
  147207. 0
  147208. };
  147209. static long _vq_quantlist__44u7__p9_0[] = {
  147210. 5,
  147211. 4,
  147212. 6,
  147213. 3,
  147214. 7,
  147215. 2,
  147216. 8,
  147217. 1,
  147218. 9,
  147219. 0,
  147220. 10,
  147221. };
  147222. static long _vq_lengthlist__44u7__p9_0[] = {
  147223. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  147224. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  147225. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147226. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147227. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147228. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147229. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147230. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147231. };
  147232. static float _vq_quantthresh__44u7__p9_0[] = {
  147233. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  147234. 2229.5, 2866.5,
  147235. };
  147236. static long _vq_quantmap__44u7__p9_0[] = {
  147237. 9, 7, 5, 3, 1, 0, 2, 4,
  147238. 6, 8, 10,
  147239. };
  147240. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  147241. _vq_quantthresh__44u7__p9_0,
  147242. _vq_quantmap__44u7__p9_0,
  147243. 11,
  147244. 11
  147245. };
  147246. static static_codebook _44u7__p9_0 = {
  147247. 2, 121,
  147248. _vq_lengthlist__44u7__p9_0,
  147249. 1, -512171520, 1630791680, 4, 0,
  147250. _vq_quantlist__44u7__p9_0,
  147251. NULL,
  147252. &_vq_auxt__44u7__p9_0,
  147253. NULL,
  147254. 0
  147255. };
  147256. static long _vq_quantlist__44u7__p9_1[] = {
  147257. 6,
  147258. 5,
  147259. 7,
  147260. 4,
  147261. 8,
  147262. 3,
  147263. 9,
  147264. 2,
  147265. 10,
  147266. 1,
  147267. 11,
  147268. 0,
  147269. 12,
  147270. };
  147271. static long _vq_lengthlist__44u7__p9_1[] = {
  147272. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  147273. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  147274. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  147275. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  147276. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  147277. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  147278. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  147279. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  147280. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  147281. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  147282. 15,15,15,15,17,17,16,17,16,
  147283. };
  147284. static float _vq_quantthresh__44u7__p9_1[] = {
  147285. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  147286. 122.5, 171.5, 220.5, 269.5,
  147287. };
  147288. static long _vq_quantmap__44u7__p9_1[] = {
  147289. 11, 9, 7, 5, 3, 1, 0, 2,
  147290. 4, 6, 8, 10, 12,
  147291. };
  147292. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  147293. _vq_quantthresh__44u7__p9_1,
  147294. _vq_quantmap__44u7__p9_1,
  147295. 13,
  147296. 13
  147297. };
  147298. static static_codebook _44u7__p9_1 = {
  147299. 2, 169,
  147300. _vq_lengthlist__44u7__p9_1,
  147301. 1, -518889472, 1622704128, 4, 0,
  147302. _vq_quantlist__44u7__p9_1,
  147303. NULL,
  147304. &_vq_auxt__44u7__p9_1,
  147305. NULL,
  147306. 0
  147307. };
  147308. static long _vq_quantlist__44u7__p9_2[] = {
  147309. 24,
  147310. 23,
  147311. 25,
  147312. 22,
  147313. 26,
  147314. 21,
  147315. 27,
  147316. 20,
  147317. 28,
  147318. 19,
  147319. 29,
  147320. 18,
  147321. 30,
  147322. 17,
  147323. 31,
  147324. 16,
  147325. 32,
  147326. 15,
  147327. 33,
  147328. 14,
  147329. 34,
  147330. 13,
  147331. 35,
  147332. 12,
  147333. 36,
  147334. 11,
  147335. 37,
  147336. 10,
  147337. 38,
  147338. 9,
  147339. 39,
  147340. 8,
  147341. 40,
  147342. 7,
  147343. 41,
  147344. 6,
  147345. 42,
  147346. 5,
  147347. 43,
  147348. 4,
  147349. 44,
  147350. 3,
  147351. 45,
  147352. 2,
  147353. 46,
  147354. 1,
  147355. 47,
  147356. 0,
  147357. 48,
  147358. };
  147359. static long _vq_lengthlist__44u7__p9_2[] = {
  147360. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  147361. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147362. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  147363. 8,
  147364. };
  147365. static float _vq_quantthresh__44u7__p9_2[] = {
  147366. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147367. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147368. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147369. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147370. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147371. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147372. };
  147373. static long _vq_quantmap__44u7__p9_2[] = {
  147374. 47, 45, 43, 41, 39, 37, 35, 33,
  147375. 31, 29, 27, 25, 23, 21, 19, 17,
  147376. 15, 13, 11, 9, 7, 5, 3, 1,
  147377. 0, 2, 4, 6, 8, 10, 12, 14,
  147378. 16, 18, 20, 22, 24, 26, 28, 30,
  147379. 32, 34, 36, 38, 40, 42, 44, 46,
  147380. 48,
  147381. };
  147382. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  147383. _vq_quantthresh__44u7__p9_2,
  147384. _vq_quantmap__44u7__p9_2,
  147385. 49,
  147386. 49
  147387. };
  147388. static static_codebook _44u7__p9_2 = {
  147389. 1, 49,
  147390. _vq_lengthlist__44u7__p9_2,
  147391. 1, -526909440, 1611661312, 6, 0,
  147392. _vq_quantlist__44u7__p9_2,
  147393. NULL,
  147394. &_vq_auxt__44u7__p9_2,
  147395. NULL,
  147396. 0
  147397. };
  147398. static long _huff_lengthlist__44u7__short[] = {
  147399. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  147400. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  147401. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  147402. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  147403. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  147404. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  147405. 6, 8, 5, 9,
  147406. };
  147407. static static_codebook _huff_book__44u7__short = {
  147408. 2, 100,
  147409. _huff_lengthlist__44u7__short,
  147410. 0, 0, 0, 0, 0,
  147411. NULL,
  147412. NULL,
  147413. NULL,
  147414. NULL,
  147415. 0
  147416. };
  147417. static long _huff_lengthlist__44u8__long[] = {
  147418. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  147419. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  147420. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  147421. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  147422. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  147423. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  147424. 10, 8, 8, 9,
  147425. };
  147426. static static_codebook _huff_book__44u8__long = {
  147427. 2, 100,
  147428. _huff_lengthlist__44u8__long,
  147429. 0, 0, 0, 0, 0,
  147430. NULL,
  147431. NULL,
  147432. NULL,
  147433. NULL,
  147434. 0
  147435. };
  147436. static long _huff_lengthlist__44u8__short[] = {
  147437. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  147438. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  147439. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  147440. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  147441. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  147442. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  147443. 10,10,15,17,
  147444. };
  147445. static static_codebook _huff_book__44u8__short = {
  147446. 2, 100,
  147447. _huff_lengthlist__44u8__short,
  147448. 0, 0, 0, 0, 0,
  147449. NULL,
  147450. NULL,
  147451. NULL,
  147452. NULL,
  147453. 0
  147454. };
  147455. static long _vq_quantlist__44u8_p1_0[] = {
  147456. 1,
  147457. 0,
  147458. 2,
  147459. };
  147460. static long _vq_lengthlist__44u8_p1_0[] = {
  147461. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  147462. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  147463. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  147464. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  147465. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  147466. 10,
  147467. };
  147468. static float _vq_quantthresh__44u8_p1_0[] = {
  147469. -0.5, 0.5,
  147470. };
  147471. static long _vq_quantmap__44u8_p1_0[] = {
  147472. 1, 0, 2,
  147473. };
  147474. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  147475. _vq_quantthresh__44u8_p1_0,
  147476. _vq_quantmap__44u8_p1_0,
  147477. 3,
  147478. 3
  147479. };
  147480. static static_codebook _44u8_p1_0 = {
  147481. 4, 81,
  147482. _vq_lengthlist__44u8_p1_0,
  147483. 1, -535822336, 1611661312, 2, 0,
  147484. _vq_quantlist__44u8_p1_0,
  147485. NULL,
  147486. &_vq_auxt__44u8_p1_0,
  147487. NULL,
  147488. 0
  147489. };
  147490. static long _vq_quantlist__44u8_p2_0[] = {
  147491. 2,
  147492. 1,
  147493. 3,
  147494. 0,
  147495. 4,
  147496. };
  147497. static long _vq_lengthlist__44u8_p2_0[] = {
  147498. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  147499. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147500. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  147501. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147502. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  147503. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  147504. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  147505. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  147506. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147507. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  147508. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  147509. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147510. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  147511. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  147512. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  147513. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  147514. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  147515. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  147516. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  147517. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147518. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  147519. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  147520. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147521. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  147522. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  147523. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  147524. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  147525. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  147526. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  147527. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  147528. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  147529. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  147530. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  147531. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  147532. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  147533. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  147534. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  147535. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  147536. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  147537. 14,
  147538. };
  147539. static float _vq_quantthresh__44u8_p2_0[] = {
  147540. -1.5, -0.5, 0.5, 1.5,
  147541. };
  147542. static long _vq_quantmap__44u8_p2_0[] = {
  147543. 3, 1, 0, 2, 4,
  147544. };
  147545. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  147546. _vq_quantthresh__44u8_p2_0,
  147547. _vq_quantmap__44u8_p2_0,
  147548. 5,
  147549. 5
  147550. };
  147551. static static_codebook _44u8_p2_0 = {
  147552. 4, 625,
  147553. _vq_lengthlist__44u8_p2_0,
  147554. 1, -533725184, 1611661312, 3, 0,
  147555. _vq_quantlist__44u8_p2_0,
  147556. NULL,
  147557. &_vq_auxt__44u8_p2_0,
  147558. NULL,
  147559. 0
  147560. };
  147561. static long _vq_quantlist__44u8_p3_0[] = {
  147562. 4,
  147563. 3,
  147564. 5,
  147565. 2,
  147566. 6,
  147567. 1,
  147568. 7,
  147569. 0,
  147570. 8,
  147571. };
  147572. static long _vq_lengthlist__44u8_p3_0[] = {
  147573. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  147574. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147575. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  147576. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  147577. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  147578. 12,
  147579. };
  147580. static float _vq_quantthresh__44u8_p3_0[] = {
  147581. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147582. };
  147583. static long _vq_quantmap__44u8_p3_0[] = {
  147584. 7, 5, 3, 1, 0, 2, 4, 6,
  147585. 8,
  147586. };
  147587. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  147588. _vq_quantthresh__44u8_p3_0,
  147589. _vq_quantmap__44u8_p3_0,
  147590. 9,
  147591. 9
  147592. };
  147593. static static_codebook _44u8_p3_0 = {
  147594. 2, 81,
  147595. _vq_lengthlist__44u8_p3_0,
  147596. 1, -531628032, 1611661312, 4, 0,
  147597. _vq_quantlist__44u8_p3_0,
  147598. NULL,
  147599. &_vq_auxt__44u8_p3_0,
  147600. NULL,
  147601. 0
  147602. };
  147603. static long _vq_quantlist__44u8_p4_0[] = {
  147604. 8,
  147605. 7,
  147606. 9,
  147607. 6,
  147608. 10,
  147609. 5,
  147610. 11,
  147611. 4,
  147612. 12,
  147613. 3,
  147614. 13,
  147615. 2,
  147616. 14,
  147617. 1,
  147618. 15,
  147619. 0,
  147620. 16,
  147621. };
  147622. static long _vq_lengthlist__44u8_p4_0[] = {
  147623. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  147624. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  147625. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  147626. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  147627. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  147628. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  147629. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  147630. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  147631. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  147632. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  147633. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  147634. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  147635. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  147636. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  147637. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  147638. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  147639. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  147640. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  147641. 14,
  147642. };
  147643. static float _vq_quantthresh__44u8_p4_0[] = {
  147644. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147645. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147646. };
  147647. static long _vq_quantmap__44u8_p4_0[] = {
  147648. 15, 13, 11, 9, 7, 5, 3, 1,
  147649. 0, 2, 4, 6, 8, 10, 12, 14,
  147650. 16,
  147651. };
  147652. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  147653. _vq_quantthresh__44u8_p4_0,
  147654. _vq_quantmap__44u8_p4_0,
  147655. 17,
  147656. 17
  147657. };
  147658. static static_codebook _44u8_p4_0 = {
  147659. 2, 289,
  147660. _vq_lengthlist__44u8_p4_0,
  147661. 1, -529530880, 1611661312, 5, 0,
  147662. _vq_quantlist__44u8_p4_0,
  147663. NULL,
  147664. &_vq_auxt__44u8_p4_0,
  147665. NULL,
  147666. 0
  147667. };
  147668. static long _vq_quantlist__44u8_p5_0[] = {
  147669. 1,
  147670. 0,
  147671. 2,
  147672. };
  147673. static long _vq_lengthlist__44u8_p5_0[] = {
  147674. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147675. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147676. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  147677. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147678. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147679. 10,
  147680. };
  147681. static float _vq_quantthresh__44u8_p5_0[] = {
  147682. -5.5, 5.5,
  147683. };
  147684. static long _vq_quantmap__44u8_p5_0[] = {
  147685. 1, 0, 2,
  147686. };
  147687. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  147688. _vq_quantthresh__44u8_p5_0,
  147689. _vq_quantmap__44u8_p5_0,
  147690. 3,
  147691. 3
  147692. };
  147693. static static_codebook _44u8_p5_0 = {
  147694. 4, 81,
  147695. _vq_lengthlist__44u8_p5_0,
  147696. 1, -529137664, 1618345984, 2, 0,
  147697. _vq_quantlist__44u8_p5_0,
  147698. NULL,
  147699. &_vq_auxt__44u8_p5_0,
  147700. NULL,
  147701. 0
  147702. };
  147703. static long _vq_quantlist__44u8_p5_1[] = {
  147704. 5,
  147705. 4,
  147706. 6,
  147707. 3,
  147708. 7,
  147709. 2,
  147710. 8,
  147711. 1,
  147712. 9,
  147713. 0,
  147714. 10,
  147715. };
  147716. static long _vq_lengthlist__44u8_p5_1[] = {
  147717. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  147718. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  147719. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  147720. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147721. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  147722. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  147723. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  147724. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  147725. };
  147726. static float _vq_quantthresh__44u8_p5_1[] = {
  147727. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147728. 3.5, 4.5,
  147729. };
  147730. static long _vq_quantmap__44u8_p5_1[] = {
  147731. 9, 7, 5, 3, 1, 0, 2, 4,
  147732. 6, 8, 10,
  147733. };
  147734. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  147735. _vq_quantthresh__44u8_p5_1,
  147736. _vq_quantmap__44u8_p5_1,
  147737. 11,
  147738. 11
  147739. };
  147740. static static_codebook _44u8_p5_1 = {
  147741. 2, 121,
  147742. _vq_lengthlist__44u8_p5_1,
  147743. 1, -531365888, 1611661312, 4, 0,
  147744. _vq_quantlist__44u8_p5_1,
  147745. NULL,
  147746. &_vq_auxt__44u8_p5_1,
  147747. NULL,
  147748. 0
  147749. };
  147750. static long _vq_quantlist__44u8_p6_0[] = {
  147751. 6,
  147752. 5,
  147753. 7,
  147754. 4,
  147755. 8,
  147756. 3,
  147757. 9,
  147758. 2,
  147759. 10,
  147760. 1,
  147761. 11,
  147762. 0,
  147763. 12,
  147764. };
  147765. static long _vq_lengthlist__44u8_p6_0[] = {
  147766. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147767. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  147768. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  147769. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  147770. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  147771. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147772. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147773. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  147774. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  147775. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147776. 11,11,11,11,11,12,11,12,12,
  147777. };
  147778. static float _vq_quantthresh__44u8_p6_0[] = {
  147779. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147780. 12.5, 17.5, 22.5, 27.5,
  147781. };
  147782. static long _vq_quantmap__44u8_p6_0[] = {
  147783. 11, 9, 7, 5, 3, 1, 0, 2,
  147784. 4, 6, 8, 10, 12,
  147785. };
  147786. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  147787. _vq_quantthresh__44u8_p6_0,
  147788. _vq_quantmap__44u8_p6_0,
  147789. 13,
  147790. 13
  147791. };
  147792. static static_codebook _44u8_p6_0 = {
  147793. 2, 169,
  147794. _vq_lengthlist__44u8_p6_0,
  147795. 1, -526516224, 1616117760, 4, 0,
  147796. _vq_quantlist__44u8_p6_0,
  147797. NULL,
  147798. &_vq_auxt__44u8_p6_0,
  147799. NULL,
  147800. 0
  147801. };
  147802. static long _vq_quantlist__44u8_p6_1[] = {
  147803. 2,
  147804. 1,
  147805. 3,
  147806. 0,
  147807. 4,
  147808. };
  147809. static long _vq_lengthlist__44u8_p6_1[] = {
  147810. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147811. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147812. };
  147813. static float _vq_quantthresh__44u8_p6_1[] = {
  147814. -1.5, -0.5, 0.5, 1.5,
  147815. };
  147816. static long _vq_quantmap__44u8_p6_1[] = {
  147817. 3, 1, 0, 2, 4,
  147818. };
  147819. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  147820. _vq_quantthresh__44u8_p6_1,
  147821. _vq_quantmap__44u8_p6_1,
  147822. 5,
  147823. 5
  147824. };
  147825. static static_codebook _44u8_p6_1 = {
  147826. 2, 25,
  147827. _vq_lengthlist__44u8_p6_1,
  147828. 1, -533725184, 1611661312, 3, 0,
  147829. _vq_quantlist__44u8_p6_1,
  147830. NULL,
  147831. &_vq_auxt__44u8_p6_1,
  147832. NULL,
  147833. 0
  147834. };
  147835. static long _vq_quantlist__44u8_p7_0[] = {
  147836. 6,
  147837. 5,
  147838. 7,
  147839. 4,
  147840. 8,
  147841. 3,
  147842. 9,
  147843. 2,
  147844. 10,
  147845. 1,
  147846. 11,
  147847. 0,
  147848. 12,
  147849. };
  147850. static long _vq_lengthlist__44u8_p7_0[] = {
  147851. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  147852. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  147853. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  147854. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  147855. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147856. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147857. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  147858. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  147859. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  147860. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  147861. 13,13,14,14,14,15,15,15,16,
  147862. };
  147863. static float _vq_quantthresh__44u8_p7_0[] = {
  147864. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147865. 27.5, 38.5, 49.5, 60.5,
  147866. };
  147867. static long _vq_quantmap__44u8_p7_0[] = {
  147868. 11, 9, 7, 5, 3, 1, 0, 2,
  147869. 4, 6, 8, 10, 12,
  147870. };
  147871. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  147872. _vq_quantthresh__44u8_p7_0,
  147873. _vq_quantmap__44u8_p7_0,
  147874. 13,
  147875. 13
  147876. };
  147877. static static_codebook _44u8_p7_0 = {
  147878. 2, 169,
  147879. _vq_lengthlist__44u8_p7_0,
  147880. 1, -523206656, 1618345984, 4, 0,
  147881. _vq_quantlist__44u8_p7_0,
  147882. NULL,
  147883. &_vq_auxt__44u8_p7_0,
  147884. NULL,
  147885. 0
  147886. };
  147887. static long _vq_quantlist__44u8_p7_1[] = {
  147888. 5,
  147889. 4,
  147890. 6,
  147891. 3,
  147892. 7,
  147893. 2,
  147894. 8,
  147895. 1,
  147896. 9,
  147897. 0,
  147898. 10,
  147899. };
  147900. static long _vq_lengthlist__44u8_p7_1[] = {
  147901. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147902. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147903. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147904. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  147905. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  147906. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147907. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147908. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147909. };
  147910. static float _vq_quantthresh__44u8_p7_1[] = {
  147911. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147912. 3.5, 4.5,
  147913. };
  147914. static long _vq_quantmap__44u8_p7_1[] = {
  147915. 9, 7, 5, 3, 1, 0, 2, 4,
  147916. 6, 8, 10,
  147917. };
  147918. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  147919. _vq_quantthresh__44u8_p7_1,
  147920. _vq_quantmap__44u8_p7_1,
  147921. 11,
  147922. 11
  147923. };
  147924. static static_codebook _44u8_p7_1 = {
  147925. 2, 121,
  147926. _vq_lengthlist__44u8_p7_1,
  147927. 1, -531365888, 1611661312, 4, 0,
  147928. _vq_quantlist__44u8_p7_1,
  147929. NULL,
  147930. &_vq_auxt__44u8_p7_1,
  147931. NULL,
  147932. 0
  147933. };
  147934. static long _vq_quantlist__44u8_p8_0[] = {
  147935. 7,
  147936. 6,
  147937. 8,
  147938. 5,
  147939. 9,
  147940. 4,
  147941. 10,
  147942. 3,
  147943. 11,
  147944. 2,
  147945. 12,
  147946. 1,
  147947. 13,
  147948. 0,
  147949. 14,
  147950. };
  147951. static long _vq_lengthlist__44u8_p8_0[] = {
  147952. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  147953. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147954. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  147955. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  147956. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  147957. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  147958. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  147959. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  147960. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  147961. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  147962. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  147963. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  147964. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  147965. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  147966. 17,
  147967. };
  147968. static float _vq_quantthresh__44u8_p8_0[] = {
  147969. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147970. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147971. };
  147972. static long _vq_quantmap__44u8_p8_0[] = {
  147973. 13, 11, 9, 7, 5, 3, 1, 0,
  147974. 2, 4, 6, 8, 10, 12, 14,
  147975. };
  147976. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  147977. _vq_quantthresh__44u8_p8_0,
  147978. _vq_quantmap__44u8_p8_0,
  147979. 15,
  147980. 15
  147981. };
  147982. static static_codebook _44u8_p8_0 = {
  147983. 2, 225,
  147984. _vq_lengthlist__44u8_p8_0,
  147985. 1, -520986624, 1620377600, 4, 0,
  147986. _vq_quantlist__44u8_p8_0,
  147987. NULL,
  147988. &_vq_auxt__44u8_p8_0,
  147989. NULL,
  147990. 0
  147991. };
  147992. static long _vq_quantlist__44u8_p8_1[] = {
  147993. 10,
  147994. 9,
  147995. 11,
  147996. 8,
  147997. 12,
  147998. 7,
  147999. 13,
  148000. 6,
  148001. 14,
  148002. 5,
  148003. 15,
  148004. 4,
  148005. 16,
  148006. 3,
  148007. 17,
  148008. 2,
  148009. 18,
  148010. 1,
  148011. 19,
  148012. 0,
  148013. 20,
  148014. };
  148015. static long _vq_lengthlist__44u8_p8_1[] = {
  148016. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148017. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148018. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  148019. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148020. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148021. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148022. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148023. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  148024. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148025. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148026. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  148027. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  148028. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148029. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148030. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148031. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148032. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  148033. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148034. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148035. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148036. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148037. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148038. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148039. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148040. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148041. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148042. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  148043. 10,10,10,10,10,10,10,10,10,
  148044. };
  148045. static float _vq_quantthresh__44u8_p8_1[] = {
  148046. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148047. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148048. 6.5, 7.5, 8.5, 9.5,
  148049. };
  148050. static long _vq_quantmap__44u8_p8_1[] = {
  148051. 19, 17, 15, 13, 11, 9, 7, 5,
  148052. 3, 1, 0, 2, 4, 6, 8, 10,
  148053. 12, 14, 16, 18, 20,
  148054. };
  148055. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  148056. _vq_quantthresh__44u8_p8_1,
  148057. _vq_quantmap__44u8_p8_1,
  148058. 21,
  148059. 21
  148060. };
  148061. static static_codebook _44u8_p8_1 = {
  148062. 2, 441,
  148063. _vq_lengthlist__44u8_p8_1,
  148064. 1, -529268736, 1611661312, 5, 0,
  148065. _vq_quantlist__44u8_p8_1,
  148066. NULL,
  148067. &_vq_auxt__44u8_p8_1,
  148068. NULL,
  148069. 0
  148070. };
  148071. static long _vq_quantlist__44u8_p9_0[] = {
  148072. 4,
  148073. 3,
  148074. 5,
  148075. 2,
  148076. 6,
  148077. 1,
  148078. 7,
  148079. 0,
  148080. 8,
  148081. };
  148082. static long _vq_lengthlist__44u8_p9_0[] = {
  148083. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  148084. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148085. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148086. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148087. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  148088. 8,
  148089. };
  148090. static float _vq_quantthresh__44u8_p9_0[] = {
  148091. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  148092. };
  148093. static long _vq_quantmap__44u8_p9_0[] = {
  148094. 7, 5, 3, 1, 0, 2, 4, 6,
  148095. 8,
  148096. };
  148097. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  148098. _vq_quantthresh__44u8_p9_0,
  148099. _vq_quantmap__44u8_p9_0,
  148100. 9,
  148101. 9
  148102. };
  148103. static static_codebook _44u8_p9_0 = {
  148104. 2, 81,
  148105. _vq_lengthlist__44u8_p9_0,
  148106. 1, -511895552, 1631393792, 4, 0,
  148107. _vq_quantlist__44u8_p9_0,
  148108. NULL,
  148109. &_vq_auxt__44u8_p9_0,
  148110. NULL,
  148111. 0
  148112. };
  148113. static long _vq_quantlist__44u8_p9_1[] = {
  148114. 9,
  148115. 8,
  148116. 10,
  148117. 7,
  148118. 11,
  148119. 6,
  148120. 12,
  148121. 5,
  148122. 13,
  148123. 4,
  148124. 14,
  148125. 3,
  148126. 15,
  148127. 2,
  148128. 16,
  148129. 1,
  148130. 17,
  148131. 0,
  148132. 18,
  148133. };
  148134. static long _vq_lengthlist__44u8_p9_1[] = {
  148135. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  148136. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  148137. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  148138. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  148139. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  148140. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  148141. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  148142. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  148143. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  148144. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  148145. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  148146. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  148147. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  148148. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  148149. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  148150. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  148151. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  148152. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  148153. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  148154. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  148155. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  148156. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  148157. 16,15,16,16,16,16,16,16,16,
  148158. };
  148159. static float _vq_quantthresh__44u8_p9_1[] = {
  148160. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148161. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148162. 367.5, 416.5,
  148163. };
  148164. static long _vq_quantmap__44u8_p9_1[] = {
  148165. 17, 15, 13, 11, 9, 7, 5, 3,
  148166. 1, 0, 2, 4, 6, 8, 10, 12,
  148167. 14, 16, 18,
  148168. };
  148169. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  148170. _vq_quantthresh__44u8_p9_1,
  148171. _vq_quantmap__44u8_p9_1,
  148172. 19,
  148173. 19
  148174. };
  148175. static static_codebook _44u8_p9_1 = {
  148176. 2, 361,
  148177. _vq_lengthlist__44u8_p9_1,
  148178. 1, -518287360, 1622704128, 5, 0,
  148179. _vq_quantlist__44u8_p9_1,
  148180. NULL,
  148181. &_vq_auxt__44u8_p9_1,
  148182. NULL,
  148183. 0
  148184. };
  148185. static long _vq_quantlist__44u8_p9_2[] = {
  148186. 24,
  148187. 23,
  148188. 25,
  148189. 22,
  148190. 26,
  148191. 21,
  148192. 27,
  148193. 20,
  148194. 28,
  148195. 19,
  148196. 29,
  148197. 18,
  148198. 30,
  148199. 17,
  148200. 31,
  148201. 16,
  148202. 32,
  148203. 15,
  148204. 33,
  148205. 14,
  148206. 34,
  148207. 13,
  148208. 35,
  148209. 12,
  148210. 36,
  148211. 11,
  148212. 37,
  148213. 10,
  148214. 38,
  148215. 9,
  148216. 39,
  148217. 8,
  148218. 40,
  148219. 7,
  148220. 41,
  148221. 6,
  148222. 42,
  148223. 5,
  148224. 43,
  148225. 4,
  148226. 44,
  148227. 3,
  148228. 45,
  148229. 2,
  148230. 46,
  148231. 1,
  148232. 47,
  148233. 0,
  148234. 48,
  148235. };
  148236. static long _vq_lengthlist__44u8_p9_2[] = {
  148237. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  148238. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148239. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148240. 7,
  148241. };
  148242. static float _vq_quantthresh__44u8_p9_2[] = {
  148243. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148244. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148245. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148246. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148247. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148248. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148249. };
  148250. static long _vq_quantmap__44u8_p9_2[] = {
  148251. 47, 45, 43, 41, 39, 37, 35, 33,
  148252. 31, 29, 27, 25, 23, 21, 19, 17,
  148253. 15, 13, 11, 9, 7, 5, 3, 1,
  148254. 0, 2, 4, 6, 8, 10, 12, 14,
  148255. 16, 18, 20, 22, 24, 26, 28, 30,
  148256. 32, 34, 36, 38, 40, 42, 44, 46,
  148257. 48,
  148258. };
  148259. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  148260. _vq_quantthresh__44u8_p9_2,
  148261. _vq_quantmap__44u8_p9_2,
  148262. 49,
  148263. 49
  148264. };
  148265. static static_codebook _44u8_p9_2 = {
  148266. 1, 49,
  148267. _vq_lengthlist__44u8_p9_2,
  148268. 1, -526909440, 1611661312, 6, 0,
  148269. _vq_quantlist__44u8_p9_2,
  148270. NULL,
  148271. &_vq_auxt__44u8_p9_2,
  148272. NULL,
  148273. 0
  148274. };
  148275. static long _huff_lengthlist__44u9__long[] = {
  148276. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  148277. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  148278. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  148279. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  148280. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  148281. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  148282. 10, 8, 8, 9,
  148283. };
  148284. static static_codebook _huff_book__44u9__long = {
  148285. 2, 100,
  148286. _huff_lengthlist__44u9__long,
  148287. 0, 0, 0, 0, 0,
  148288. NULL,
  148289. NULL,
  148290. NULL,
  148291. NULL,
  148292. 0
  148293. };
  148294. static long _huff_lengthlist__44u9__short[] = {
  148295. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  148296. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  148297. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  148298. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  148299. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  148300. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  148301. 9, 9,12,15,
  148302. };
  148303. static static_codebook _huff_book__44u9__short = {
  148304. 2, 100,
  148305. _huff_lengthlist__44u9__short,
  148306. 0, 0, 0, 0, 0,
  148307. NULL,
  148308. NULL,
  148309. NULL,
  148310. NULL,
  148311. 0
  148312. };
  148313. static long _vq_quantlist__44u9_p1_0[] = {
  148314. 1,
  148315. 0,
  148316. 2,
  148317. };
  148318. static long _vq_lengthlist__44u9_p1_0[] = {
  148319. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  148320. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  148321. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  148322. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  148323. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  148324. 10,
  148325. };
  148326. static float _vq_quantthresh__44u9_p1_0[] = {
  148327. -0.5, 0.5,
  148328. };
  148329. static long _vq_quantmap__44u9_p1_0[] = {
  148330. 1, 0, 2,
  148331. };
  148332. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  148333. _vq_quantthresh__44u9_p1_0,
  148334. _vq_quantmap__44u9_p1_0,
  148335. 3,
  148336. 3
  148337. };
  148338. static static_codebook _44u9_p1_0 = {
  148339. 4, 81,
  148340. _vq_lengthlist__44u9_p1_0,
  148341. 1, -535822336, 1611661312, 2, 0,
  148342. _vq_quantlist__44u9_p1_0,
  148343. NULL,
  148344. &_vq_auxt__44u9_p1_0,
  148345. NULL,
  148346. 0
  148347. };
  148348. static long _vq_quantlist__44u9_p2_0[] = {
  148349. 2,
  148350. 1,
  148351. 3,
  148352. 0,
  148353. 4,
  148354. };
  148355. static long _vq_lengthlist__44u9_p2_0[] = {
  148356. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  148357. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148358. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148359. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  148360. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  148361. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  148362. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  148363. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  148364. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148365. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  148366. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  148367. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  148368. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  148369. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  148370. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  148371. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  148372. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  148373. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  148374. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  148375. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  148376. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  148377. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  148378. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  148379. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  148380. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  148381. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  148382. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  148383. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  148384. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  148385. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  148386. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  148387. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  148388. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  148389. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  148390. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  148391. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  148392. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  148393. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  148394. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  148395. 14,
  148396. };
  148397. static float _vq_quantthresh__44u9_p2_0[] = {
  148398. -1.5, -0.5, 0.5, 1.5,
  148399. };
  148400. static long _vq_quantmap__44u9_p2_0[] = {
  148401. 3, 1, 0, 2, 4,
  148402. };
  148403. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  148404. _vq_quantthresh__44u9_p2_0,
  148405. _vq_quantmap__44u9_p2_0,
  148406. 5,
  148407. 5
  148408. };
  148409. static static_codebook _44u9_p2_0 = {
  148410. 4, 625,
  148411. _vq_lengthlist__44u9_p2_0,
  148412. 1, -533725184, 1611661312, 3, 0,
  148413. _vq_quantlist__44u9_p2_0,
  148414. NULL,
  148415. &_vq_auxt__44u9_p2_0,
  148416. NULL,
  148417. 0
  148418. };
  148419. static long _vq_quantlist__44u9_p3_0[] = {
  148420. 4,
  148421. 3,
  148422. 5,
  148423. 2,
  148424. 6,
  148425. 1,
  148426. 7,
  148427. 0,
  148428. 8,
  148429. };
  148430. static long _vq_lengthlist__44u9_p3_0[] = {
  148431. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  148432. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148433. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  148434. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  148435. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  148436. 11,
  148437. };
  148438. static float _vq_quantthresh__44u9_p3_0[] = {
  148439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148440. };
  148441. static long _vq_quantmap__44u9_p3_0[] = {
  148442. 7, 5, 3, 1, 0, 2, 4, 6,
  148443. 8,
  148444. };
  148445. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  148446. _vq_quantthresh__44u9_p3_0,
  148447. _vq_quantmap__44u9_p3_0,
  148448. 9,
  148449. 9
  148450. };
  148451. static static_codebook _44u9_p3_0 = {
  148452. 2, 81,
  148453. _vq_lengthlist__44u9_p3_0,
  148454. 1, -531628032, 1611661312, 4, 0,
  148455. _vq_quantlist__44u9_p3_0,
  148456. NULL,
  148457. &_vq_auxt__44u9_p3_0,
  148458. NULL,
  148459. 0
  148460. };
  148461. static long _vq_quantlist__44u9_p4_0[] = {
  148462. 8,
  148463. 7,
  148464. 9,
  148465. 6,
  148466. 10,
  148467. 5,
  148468. 11,
  148469. 4,
  148470. 12,
  148471. 3,
  148472. 13,
  148473. 2,
  148474. 14,
  148475. 1,
  148476. 15,
  148477. 0,
  148478. 16,
  148479. };
  148480. static long _vq_lengthlist__44u9_p4_0[] = {
  148481. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  148482. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  148483. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  148484. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  148485. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  148486. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  148487. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  148488. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  148489. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  148490. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  148491. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  148492. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  148493. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  148494. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  148495. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  148496. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  148497. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  148498. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  148499. 14,
  148500. };
  148501. static float _vq_quantthresh__44u9_p4_0[] = {
  148502. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148503. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148504. };
  148505. static long _vq_quantmap__44u9_p4_0[] = {
  148506. 15, 13, 11, 9, 7, 5, 3, 1,
  148507. 0, 2, 4, 6, 8, 10, 12, 14,
  148508. 16,
  148509. };
  148510. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  148511. _vq_quantthresh__44u9_p4_0,
  148512. _vq_quantmap__44u9_p4_0,
  148513. 17,
  148514. 17
  148515. };
  148516. static static_codebook _44u9_p4_0 = {
  148517. 2, 289,
  148518. _vq_lengthlist__44u9_p4_0,
  148519. 1, -529530880, 1611661312, 5, 0,
  148520. _vq_quantlist__44u9_p4_0,
  148521. NULL,
  148522. &_vq_auxt__44u9_p4_0,
  148523. NULL,
  148524. 0
  148525. };
  148526. static long _vq_quantlist__44u9_p5_0[] = {
  148527. 1,
  148528. 0,
  148529. 2,
  148530. };
  148531. static long _vq_lengthlist__44u9_p5_0[] = {
  148532. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  148533. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  148534. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  148535. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  148536. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  148537. 10,
  148538. };
  148539. static float _vq_quantthresh__44u9_p5_0[] = {
  148540. -5.5, 5.5,
  148541. };
  148542. static long _vq_quantmap__44u9_p5_0[] = {
  148543. 1, 0, 2,
  148544. };
  148545. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  148546. _vq_quantthresh__44u9_p5_0,
  148547. _vq_quantmap__44u9_p5_0,
  148548. 3,
  148549. 3
  148550. };
  148551. static static_codebook _44u9_p5_0 = {
  148552. 4, 81,
  148553. _vq_lengthlist__44u9_p5_0,
  148554. 1, -529137664, 1618345984, 2, 0,
  148555. _vq_quantlist__44u9_p5_0,
  148556. NULL,
  148557. &_vq_auxt__44u9_p5_0,
  148558. NULL,
  148559. 0
  148560. };
  148561. static long _vq_quantlist__44u9_p5_1[] = {
  148562. 5,
  148563. 4,
  148564. 6,
  148565. 3,
  148566. 7,
  148567. 2,
  148568. 8,
  148569. 1,
  148570. 9,
  148571. 0,
  148572. 10,
  148573. };
  148574. static long _vq_lengthlist__44u9_p5_1[] = {
  148575. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  148576. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  148577. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  148578. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  148579. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  148580. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  148581. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  148582. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148583. };
  148584. static float _vq_quantthresh__44u9_p5_1[] = {
  148585. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148586. 3.5, 4.5,
  148587. };
  148588. static long _vq_quantmap__44u9_p5_1[] = {
  148589. 9, 7, 5, 3, 1, 0, 2, 4,
  148590. 6, 8, 10,
  148591. };
  148592. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  148593. _vq_quantthresh__44u9_p5_1,
  148594. _vq_quantmap__44u9_p5_1,
  148595. 11,
  148596. 11
  148597. };
  148598. static static_codebook _44u9_p5_1 = {
  148599. 2, 121,
  148600. _vq_lengthlist__44u9_p5_1,
  148601. 1, -531365888, 1611661312, 4, 0,
  148602. _vq_quantlist__44u9_p5_1,
  148603. NULL,
  148604. &_vq_auxt__44u9_p5_1,
  148605. NULL,
  148606. 0
  148607. };
  148608. static long _vq_quantlist__44u9_p6_0[] = {
  148609. 6,
  148610. 5,
  148611. 7,
  148612. 4,
  148613. 8,
  148614. 3,
  148615. 9,
  148616. 2,
  148617. 10,
  148618. 1,
  148619. 11,
  148620. 0,
  148621. 12,
  148622. };
  148623. static long _vq_lengthlist__44u9_p6_0[] = {
  148624. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  148625. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  148626. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148627. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  148628. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  148629. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  148630. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  148631. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  148632. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  148633. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  148634. 10,11,11,11,11,12,11,12,12,
  148635. };
  148636. static float _vq_quantthresh__44u9_p6_0[] = {
  148637. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148638. 12.5, 17.5, 22.5, 27.5,
  148639. };
  148640. static long _vq_quantmap__44u9_p6_0[] = {
  148641. 11, 9, 7, 5, 3, 1, 0, 2,
  148642. 4, 6, 8, 10, 12,
  148643. };
  148644. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  148645. _vq_quantthresh__44u9_p6_0,
  148646. _vq_quantmap__44u9_p6_0,
  148647. 13,
  148648. 13
  148649. };
  148650. static static_codebook _44u9_p6_0 = {
  148651. 2, 169,
  148652. _vq_lengthlist__44u9_p6_0,
  148653. 1, -526516224, 1616117760, 4, 0,
  148654. _vq_quantlist__44u9_p6_0,
  148655. NULL,
  148656. &_vq_auxt__44u9_p6_0,
  148657. NULL,
  148658. 0
  148659. };
  148660. static long _vq_quantlist__44u9_p6_1[] = {
  148661. 2,
  148662. 1,
  148663. 3,
  148664. 0,
  148665. 4,
  148666. };
  148667. static long _vq_lengthlist__44u9_p6_1[] = {
  148668. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  148669. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  148670. };
  148671. static float _vq_quantthresh__44u9_p6_1[] = {
  148672. -1.5, -0.5, 0.5, 1.5,
  148673. };
  148674. static long _vq_quantmap__44u9_p6_1[] = {
  148675. 3, 1, 0, 2, 4,
  148676. };
  148677. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  148678. _vq_quantthresh__44u9_p6_1,
  148679. _vq_quantmap__44u9_p6_1,
  148680. 5,
  148681. 5
  148682. };
  148683. static static_codebook _44u9_p6_1 = {
  148684. 2, 25,
  148685. _vq_lengthlist__44u9_p6_1,
  148686. 1, -533725184, 1611661312, 3, 0,
  148687. _vq_quantlist__44u9_p6_1,
  148688. NULL,
  148689. &_vq_auxt__44u9_p6_1,
  148690. NULL,
  148691. 0
  148692. };
  148693. static long _vq_quantlist__44u9_p7_0[] = {
  148694. 6,
  148695. 5,
  148696. 7,
  148697. 4,
  148698. 8,
  148699. 3,
  148700. 9,
  148701. 2,
  148702. 10,
  148703. 1,
  148704. 11,
  148705. 0,
  148706. 12,
  148707. };
  148708. static long _vq_lengthlist__44u9_p7_0[] = {
  148709. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  148710. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  148711. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  148712. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  148713. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  148714. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  148715. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  148716. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  148717. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  148718. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  148719. 12,13,13,14,14,14,15,15,15,
  148720. };
  148721. static float _vq_quantthresh__44u9_p7_0[] = {
  148722. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  148723. 27.5, 38.5, 49.5, 60.5,
  148724. };
  148725. static long _vq_quantmap__44u9_p7_0[] = {
  148726. 11, 9, 7, 5, 3, 1, 0, 2,
  148727. 4, 6, 8, 10, 12,
  148728. };
  148729. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  148730. _vq_quantthresh__44u9_p7_0,
  148731. _vq_quantmap__44u9_p7_0,
  148732. 13,
  148733. 13
  148734. };
  148735. static static_codebook _44u9_p7_0 = {
  148736. 2, 169,
  148737. _vq_lengthlist__44u9_p7_0,
  148738. 1, -523206656, 1618345984, 4, 0,
  148739. _vq_quantlist__44u9_p7_0,
  148740. NULL,
  148741. &_vq_auxt__44u9_p7_0,
  148742. NULL,
  148743. 0
  148744. };
  148745. static long _vq_quantlist__44u9_p7_1[] = {
  148746. 5,
  148747. 4,
  148748. 6,
  148749. 3,
  148750. 7,
  148751. 2,
  148752. 8,
  148753. 1,
  148754. 9,
  148755. 0,
  148756. 10,
  148757. };
  148758. static long _vq_lengthlist__44u9_p7_1[] = {
  148759. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  148760. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  148761. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  148762. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148763. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148764. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148765. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  148766. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  148767. };
  148768. static float _vq_quantthresh__44u9_p7_1[] = {
  148769. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148770. 3.5, 4.5,
  148771. };
  148772. static long _vq_quantmap__44u9_p7_1[] = {
  148773. 9, 7, 5, 3, 1, 0, 2, 4,
  148774. 6, 8, 10,
  148775. };
  148776. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  148777. _vq_quantthresh__44u9_p7_1,
  148778. _vq_quantmap__44u9_p7_1,
  148779. 11,
  148780. 11
  148781. };
  148782. static static_codebook _44u9_p7_1 = {
  148783. 2, 121,
  148784. _vq_lengthlist__44u9_p7_1,
  148785. 1, -531365888, 1611661312, 4, 0,
  148786. _vq_quantlist__44u9_p7_1,
  148787. NULL,
  148788. &_vq_auxt__44u9_p7_1,
  148789. NULL,
  148790. 0
  148791. };
  148792. static long _vq_quantlist__44u9_p8_0[] = {
  148793. 7,
  148794. 6,
  148795. 8,
  148796. 5,
  148797. 9,
  148798. 4,
  148799. 10,
  148800. 3,
  148801. 11,
  148802. 2,
  148803. 12,
  148804. 1,
  148805. 13,
  148806. 0,
  148807. 14,
  148808. };
  148809. static long _vq_lengthlist__44u9_p8_0[] = {
  148810. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  148811. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  148812. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  148813. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  148814. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  148815. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  148816. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  148817. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  148818. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  148819. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  148820. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  148821. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  148822. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  148823. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  148824. 15,
  148825. };
  148826. static float _vq_quantthresh__44u9_p8_0[] = {
  148827. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  148828. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  148829. };
  148830. static long _vq_quantmap__44u9_p8_0[] = {
  148831. 13, 11, 9, 7, 5, 3, 1, 0,
  148832. 2, 4, 6, 8, 10, 12, 14,
  148833. };
  148834. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  148835. _vq_quantthresh__44u9_p8_0,
  148836. _vq_quantmap__44u9_p8_0,
  148837. 15,
  148838. 15
  148839. };
  148840. static static_codebook _44u9_p8_0 = {
  148841. 2, 225,
  148842. _vq_lengthlist__44u9_p8_0,
  148843. 1, -520986624, 1620377600, 4, 0,
  148844. _vq_quantlist__44u9_p8_0,
  148845. NULL,
  148846. &_vq_auxt__44u9_p8_0,
  148847. NULL,
  148848. 0
  148849. };
  148850. static long _vq_quantlist__44u9_p8_1[] = {
  148851. 10,
  148852. 9,
  148853. 11,
  148854. 8,
  148855. 12,
  148856. 7,
  148857. 13,
  148858. 6,
  148859. 14,
  148860. 5,
  148861. 15,
  148862. 4,
  148863. 16,
  148864. 3,
  148865. 17,
  148866. 2,
  148867. 18,
  148868. 1,
  148869. 19,
  148870. 0,
  148871. 20,
  148872. };
  148873. static long _vq_lengthlist__44u9_p8_1[] = {
  148874. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148875. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148876. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  148877. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148878. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148879. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148880. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148881. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  148882. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148883. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148884. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148885. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  148886. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148887. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148888. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148889. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148890. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148891. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148892. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  148893. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148894. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148895. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  148896. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  148897. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  148898. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148899. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148900. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148901. 10,10,10,10,10,10,10,10,10,
  148902. };
  148903. static float _vq_quantthresh__44u9_p8_1[] = {
  148904. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148905. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148906. 6.5, 7.5, 8.5, 9.5,
  148907. };
  148908. static long _vq_quantmap__44u9_p8_1[] = {
  148909. 19, 17, 15, 13, 11, 9, 7, 5,
  148910. 3, 1, 0, 2, 4, 6, 8, 10,
  148911. 12, 14, 16, 18, 20,
  148912. };
  148913. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  148914. _vq_quantthresh__44u9_p8_1,
  148915. _vq_quantmap__44u9_p8_1,
  148916. 21,
  148917. 21
  148918. };
  148919. static static_codebook _44u9_p8_1 = {
  148920. 2, 441,
  148921. _vq_lengthlist__44u9_p8_1,
  148922. 1, -529268736, 1611661312, 5, 0,
  148923. _vq_quantlist__44u9_p8_1,
  148924. NULL,
  148925. &_vq_auxt__44u9_p8_1,
  148926. NULL,
  148927. 0
  148928. };
  148929. static long _vq_quantlist__44u9_p9_0[] = {
  148930. 7,
  148931. 6,
  148932. 8,
  148933. 5,
  148934. 9,
  148935. 4,
  148936. 10,
  148937. 3,
  148938. 11,
  148939. 2,
  148940. 12,
  148941. 1,
  148942. 13,
  148943. 0,
  148944. 14,
  148945. };
  148946. static long _vq_lengthlist__44u9_p9_0[] = {
  148947. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  148948. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  148949. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148950. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148951. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148959. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148960. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148961. 10,
  148962. };
  148963. static float _vq_quantthresh__44u9_p9_0[] = {
  148964. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  148965. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  148966. };
  148967. static long _vq_quantmap__44u9_p9_0[] = {
  148968. 13, 11, 9, 7, 5, 3, 1, 0,
  148969. 2, 4, 6, 8, 10, 12, 14,
  148970. };
  148971. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  148972. _vq_quantthresh__44u9_p9_0,
  148973. _vq_quantmap__44u9_p9_0,
  148974. 15,
  148975. 15
  148976. };
  148977. static static_codebook _44u9_p9_0 = {
  148978. 2, 225,
  148979. _vq_lengthlist__44u9_p9_0,
  148980. 1, -510036736, 1631393792, 4, 0,
  148981. _vq_quantlist__44u9_p9_0,
  148982. NULL,
  148983. &_vq_auxt__44u9_p9_0,
  148984. NULL,
  148985. 0
  148986. };
  148987. static long _vq_quantlist__44u9_p9_1[] = {
  148988. 9,
  148989. 8,
  148990. 10,
  148991. 7,
  148992. 11,
  148993. 6,
  148994. 12,
  148995. 5,
  148996. 13,
  148997. 4,
  148998. 14,
  148999. 3,
  149000. 15,
  149001. 2,
  149002. 16,
  149003. 1,
  149004. 17,
  149005. 0,
  149006. 18,
  149007. };
  149008. static long _vq_lengthlist__44u9_p9_1[] = {
  149009. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  149010. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  149011. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  149012. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  149013. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  149014. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  149015. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  149016. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  149017. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  149018. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  149019. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  149020. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  149021. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  149022. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  149023. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  149024. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  149025. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  149026. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  149027. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  149028. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  149029. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  149030. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  149031. 17,17,15,17,15,17,16,16,17,
  149032. };
  149033. static float _vq_quantthresh__44u9_p9_1[] = {
  149034. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  149035. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  149036. 367.5, 416.5,
  149037. };
  149038. static long _vq_quantmap__44u9_p9_1[] = {
  149039. 17, 15, 13, 11, 9, 7, 5, 3,
  149040. 1, 0, 2, 4, 6, 8, 10, 12,
  149041. 14, 16, 18,
  149042. };
  149043. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  149044. _vq_quantthresh__44u9_p9_1,
  149045. _vq_quantmap__44u9_p9_1,
  149046. 19,
  149047. 19
  149048. };
  149049. static static_codebook _44u9_p9_1 = {
  149050. 2, 361,
  149051. _vq_lengthlist__44u9_p9_1,
  149052. 1, -518287360, 1622704128, 5, 0,
  149053. _vq_quantlist__44u9_p9_1,
  149054. NULL,
  149055. &_vq_auxt__44u9_p9_1,
  149056. NULL,
  149057. 0
  149058. };
  149059. static long _vq_quantlist__44u9_p9_2[] = {
  149060. 24,
  149061. 23,
  149062. 25,
  149063. 22,
  149064. 26,
  149065. 21,
  149066. 27,
  149067. 20,
  149068. 28,
  149069. 19,
  149070. 29,
  149071. 18,
  149072. 30,
  149073. 17,
  149074. 31,
  149075. 16,
  149076. 32,
  149077. 15,
  149078. 33,
  149079. 14,
  149080. 34,
  149081. 13,
  149082. 35,
  149083. 12,
  149084. 36,
  149085. 11,
  149086. 37,
  149087. 10,
  149088. 38,
  149089. 9,
  149090. 39,
  149091. 8,
  149092. 40,
  149093. 7,
  149094. 41,
  149095. 6,
  149096. 42,
  149097. 5,
  149098. 43,
  149099. 4,
  149100. 44,
  149101. 3,
  149102. 45,
  149103. 2,
  149104. 46,
  149105. 1,
  149106. 47,
  149107. 0,
  149108. 48,
  149109. };
  149110. static long _vq_lengthlist__44u9_p9_2[] = {
  149111. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  149112. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149113. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149114. 7,
  149115. };
  149116. static float _vq_quantthresh__44u9_p9_2[] = {
  149117. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  149118. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  149119. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149120. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149121. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  149122. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  149123. };
  149124. static long _vq_quantmap__44u9_p9_2[] = {
  149125. 47, 45, 43, 41, 39, 37, 35, 33,
  149126. 31, 29, 27, 25, 23, 21, 19, 17,
  149127. 15, 13, 11, 9, 7, 5, 3, 1,
  149128. 0, 2, 4, 6, 8, 10, 12, 14,
  149129. 16, 18, 20, 22, 24, 26, 28, 30,
  149130. 32, 34, 36, 38, 40, 42, 44, 46,
  149131. 48,
  149132. };
  149133. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  149134. _vq_quantthresh__44u9_p9_2,
  149135. _vq_quantmap__44u9_p9_2,
  149136. 49,
  149137. 49
  149138. };
  149139. static static_codebook _44u9_p9_2 = {
  149140. 1, 49,
  149141. _vq_lengthlist__44u9_p9_2,
  149142. 1, -526909440, 1611661312, 6, 0,
  149143. _vq_quantlist__44u9_p9_2,
  149144. NULL,
  149145. &_vq_auxt__44u9_p9_2,
  149146. NULL,
  149147. 0
  149148. };
  149149. static long _huff_lengthlist__44un1__long[] = {
  149150. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  149151. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  149152. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  149153. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  149154. };
  149155. static static_codebook _huff_book__44un1__long = {
  149156. 2, 64,
  149157. _huff_lengthlist__44un1__long,
  149158. 0, 0, 0, 0, 0,
  149159. NULL,
  149160. NULL,
  149161. NULL,
  149162. NULL,
  149163. 0
  149164. };
  149165. static long _vq_quantlist__44un1__p1_0[] = {
  149166. 1,
  149167. 0,
  149168. 2,
  149169. };
  149170. static long _vq_lengthlist__44un1__p1_0[] = {
  149171. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  149172. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  149173. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  149174. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  149175. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  149176. 12,
  149177. };
  149178. static float _vq_quantthresh__44un1__p1_0[] = {
  149179. -0.5, 0.5,
  149180. };
  149181. static long _vq_quantmap__44un1__p1_0[] = {
  149182. 1, 0, 2,
  149183. };
  149184. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  149185. _vq_quantthresh__44un1__p1_0,
  149186. _vq_quantmap__44un1__p1_0,
  149187. 3,
  149188. 3
  149189. };
  149190. static static_codebook _44un1__p1_0 = {
  149191. 4, 81,
  149192. _vq_lengthlist__44un1__p1_0,
  149193. 1, -535822336, 1611661312, 2, 0,
  149194. _vq_quantlist__44un1__p1_0,
  149195. NULL,
  149196. &_vq_auxt__44un1__p1_0,
  149197. NULL,
  149198. 0
  149199. };
  149200. static long _vq_quantlist__44un1__p2_0[] = {
  149201. 1,
  149202. 0,
  149203. 2,
  149204. };
  149205. static long _vq_lengthlist__44un1__p2_0[] = {
  149206. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  149207. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  149208. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  149209. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  149210. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  149211. 8,
  149212. };
  149213. static float _vq_quantthresh__44un1__p2_0[] = {
  149214. -0.5, 0.5,
  149215. };
  149216. static long _vq_quantmap__44un1__p2_0[] = {
  149217. 1, 0, 2,
  149218. };
  149219. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  149220. _vq_quantthresh__44un1__p2_0,
  149221. _vq_quantmap__44un1__p2_0,
  149222. 3,
  149223. 3
  149224. };
  149225. static static_codebook _44un1__p2_0 = {
  149226. 4, 81,
  149227. _vq_lengthlist__44un1__p2_0,
  149228. 1, -535822336, 1611661312, 2, 0,
  149229. _vq_quantlist__44un1__p2_0,
  149230. NULL,
  149231. &_vq_auxt__44un1__p2_0,
  149232. NULL,
  149233. 0
  149234. };
  149235. static long _vq_quantlist__44un1__p3_0[] = {
  149236. 2,
  149237. 1,
  149238. 3,
  149239. 0,
  149240. 4,
  149241. };
  149242. static long _vq_lengthlist__44un1__p3_0[] = {
  149243. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  149244. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  149245. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  149246. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  149247. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  149248. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  149249. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  149250. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  149251. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  149252. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  149253. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  149254. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  149255. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  149256. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  149257. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  149258. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  149259. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  149260. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  149261. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  149262. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  149263. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  149264. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  149265. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  149266. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  149267. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  149268. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  149269. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  149270. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  149271. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  149272. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  149273. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  149274. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  149275. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  149276. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  149277. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  149278. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  149279. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  149280. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  149281. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  149282. 17,
  149283. };
  149284. static float _vq_quantthresh__44un1__p3_0[] = {
  149285. -1.5, -0.5, 0.5, 1.5,
  149286. };
  149287. static long _vq_quantmap__44un1__p3_0[] = {
  149288. 3, 1, 0, 2, 4,
  149289. };
  149290. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  149291. _vq_quantthresh__44un1__p3_0,
  149292. _vq_quantmap__44un1__p3_0,
  149293. 5,
  149294. 5
  149295. };
  149296. static static_codebook _44un1__p3_0 = {
  149297. 4, 625,
  149298. _vq_lengthlist__44un1__p3_0,
  149299. 1, -533725184, 1611661312, 3, 0,
  149300. _vq_quantlist__44un1__p3_0,
  149301. NULL,
  149302. &_vq_auxt__44un1__p3_0,
  149303. NULL,
  149304. 0
  149305. };
  149306. static long _vq_quantlist__44un1__p4_0[] = {
  149307. 2,
  149308. 1,
  149309. 3,
  149310. 0,
  149311. 4,
  149312. };
  149313. static long _vq_lengthlist__44un1__p4_0[] = {
  149314. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  149315. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  149316. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  149317. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  149318. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  149319. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  149320. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  149321. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  149322. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  149323. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  149324. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  149325. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  149326. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  149327. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  149328. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  149329. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  149330. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  149331. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  149332. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  149333. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  149334. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  149335. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  149336. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  149337. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  149338. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  149339. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  149340. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  149341. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  149342. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  149343. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  149344. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  149345. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  149346. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  149347. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  149348. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  149349. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  149350. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  149351. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  149352. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  149353. 12,
  149354. };
  149355. static float _vq_quantthresh__44un1__p4_0[] = {
  149356. -1.5, -0.5, 0.5, 1.5,
  149357. };
  149358. static long _vq_quantmap__44un1__p4_0[] = {
  149359. 3, 1, 0, 2, 4,
  149360. };
  149361. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  149362. _vq_quantthresh__44un1__p4_0,
  149363. _vq_quantmap__44un1__p4_0,
  149364. 5,
  149365. 5
  149366. };
  149367. static static_codebook _44un1__p4_0 = {
  149368. 4, 625,
  149369. _vq_lengthlist__44un1__p4_0,
  149370. 1, -533725184, 1611661312, 3, 0,
  149371. _vq_quantlist__44un1__p4_0,
  149372. NULL,
  149373. &_vq_auxt__44un1__p4_0,
  149374. NULL,
  149375. 0
  149376. };
  149377. static long _vq_quantlist__44un1__p5_0[] = {
  149378. 4,
  149379. 3,
  149380. 5,
  149381. 2,
  149382. 6,
  149383. 1,
  149384. 7,
  149385. 0,
  149386. 8,
  149387. };
  149388. static long _vq_lengthlist__44un1__p5_0[] = {
  149389. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  149390. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  149391. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  149392. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  149393. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  149394. 12,
  149395. };
  149396. static float _vq_quantthresh__44un1__p5_0[] = {
  149397. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149398. };
  149399. static long _vq_quantmap__44un1__p5_0[] = {
  149400. 7, 5, 3, 1, 0, 2, 4, 6,
  149401. 8,
  149402. };
  149403. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  149404. _vq_quantthresh__44un1__p5_0,
  149405. _vq_quantmap__44un1__p5_0,
  149406. 9,
  149407. 9
  149408. };
  149409. static static_codebook _44un1__p5_0 = {
  149410. 2, 81,
  149411. _vq_lengthlist__44un1__p5_0,
  149412. 1, -531628032, 1611661312, 4, 0,
  149413. _vq_quantlist__44un1__p5_0,
  149414. NULL,
  149415. &_vq_auxt__44un1__p5_0,
  149416. NULL,
  149417. 0
  149418. };
  149419. static long _vq_quantlist__44un1__p6_0[] = {
  149420. 6,
  149421. 5,
  149422. 7,
  149423. 4,
  149424. 8,
  149425. 3,
  149426. 9,
  149427. 2,
  149428. 10,
  149429. 1,
  149430. 11,
  149431. 0,
  149432. 12,
  149433. };
  149434. static long _vq_lengthlist__44un1__p6_0[] = {
  149435. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  149436. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  149437. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  149438. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  149439. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  149440. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  149441. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  149442. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  149443. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  149444. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  149445. 16, 0,15,18,18, 0,16, 0, 0,
  149446. };
  149447. static float _vq_quantthresh__44un1__p6_0[] = {
  149448. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  149449. 12.5, 17.5, 22.5, 27.5,
  149450. };
  149451. static long _vq_quantmap__44un1__p6_0[] = {
  149452. 11, 9, 7, 5, 3, 1, 0, 2,
  149453. 4, 6, 8, 10, 12,
  149454. };
  149455. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  149456. _vq_quantthresh__44un1__p6_0,
  149457. _vq_quantmap__44un1__p6_0,
  149458. 13,
  149459. 13
  149460. };
  149461. static static_codebook _44un1__p6_0 = {
  149462. 2, 169,
  149463. _vq_lengthlist__44un1__p6_0,
  149464. 1, -526516224, 1616117760, 4, 0,
  149465. _vq_quantlist__44un1__p6_0,
  149466. NULL,
  149467. &_vq_auxt__44un1__p6_0,
  149468. NULL,
  149469. 0
  149470. };
  149471. static long _vq_quantlist__44un1__p6_1[] = {
  149472. 2,
  149473. 1,
  149474. 3,
  149475. 0,
  149476. 4,
  149477. };
  149478. static long _vq_lengthlist__44un1__p6_1[] = {
  149479. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  149480. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  149481. };
  149482. static float _vq_quantthresh__44un1__p6_1[] = {
  149483. -1.5, -0.5, 0.5, 1.5,
  149484. };
  149485. static long _vq_quantmap__44un1__p6_1[] = {
  149486. 3, 1, 0, 2, 4,
  149487. };
  149488. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  149489. _vq_quantthresh__44un1__p6_1,
  149490. _vq_quantmap__44un1__p6_1,
  149491. 5,
  149492. 5
  149493. };
  149494. static static_codebook _44un1__p6_1 = {
  149495. 2, 25,
  149496. _vq_lengthlist__44un1__p6_1,
  149497. 1, -533725184, 1611661312, 3, 0,
  149498. _vq_quantlist__44un1__p6_1,
  149499. NULL,
  149500. &_vq_auxt__44un1__p6_1,
  149501. NULL,
  149502. 0
  149503. };
  149504. static long _vq_quantlist__44un1__p7_0[] = {
  149505. 2,
  149506. 1,
  149507. 3,
  149508. 0,
  149509. 4,
  149510. };
  149511. static long _vq_lengthlist__44un1__p7_0[] = {
  149512. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  149513. 11,11,11,11,11,11,11,11,11,10,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,10,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, 8,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,10,
  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, 7,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,10,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. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149548. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149549. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149550. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149551. 10,
  149552. };
  149553. static float _vq_quantthresh__44un1__p7_0[] = {
  149554. -253.5, -84.5, 84.5, 253.5,
  149555. };
  149556. static long _vq_quantmap__44un1__p7_0[] = {
  149557. 3, 1, 0, 2, 4,
  149558. };
  149559. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  149560. _vq_quantthresh__44un1__p7_0,
  149561. _vq_quantmap__44un1__p7_0,
  149562. 5,
  149563. 5
  149564. };
  149565. static static_codebook _44un1__p7_0 = {
  149566. 4, 625,
  149567. _vq_lengthlist__44un1__p7_0,
  149568. 1, -518709248, 1626677248, 3, 0,
  149569. _vq_quantlist__44un1__p7_0,
  149570. NULL,
  149571. &_vq_auxt__44un1__p7_0,
  149572. NULL,
  149573. 0
  149574. };
  149575. static long _vq_quantlist__44un1__p7_1[] = {
  149576. 6,
  149577. 5,
  149578. 7,
  149579. 4,
  149580. 8,
  149581. 3,
  149582. 9,
  149583. 2,
  149584. 10,
  149585. 1,
  149586. 11,
  149587. 0,
  149588. 12,
  149589. };
  149590. static long _vq_lengthlist__44un1__p7_1[] = {
  149591. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  149592. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  149593. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  149594. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  149595. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  149596. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  149597. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  149598. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  149599. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  149600. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  149601. 12,13,13,12,13,13,14,14,14,
  149602. };
  149603. static float _vq_quantthresh__44un1__p7_1[] = {
  149604. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  149605. 32.5, 45.5, 58.5, 71.5,
  149606. };
  149607. static long _vq_quantmap__44un1__p7_1[] = {
  149608. 11, 9, 7, 5, 3, 1, 0, 2,
  149609. 4, 6, 8, 10, 12,
  149610. };
  149611. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  149612. _vq_quantthresh__44un1__p7_1,
  149613. _vq_quantmap__44un1__p7_1,
  149614. 13,
  149615. 13
  149616. };
  149617. static static_codebook _44un1__p7_1 = {
  149618. 2, 169,
  149619. _vq_lengthlist__44un1__p7_1,
  149620. 1, -523010048, 1618608128, 4, 0,
  149621. _vq_quantlist__44un1__p7_1,
  149622. NULL,
  149623. &_vq_auxt__44un1__p7_1,
  149624. NULL,
  149625. 0
  149626. };
  149627. static long _vq_quantlist__44un1__p7_2[] = {
  149628. 6,
  149629. 5,
  149630. 7,
  149631. 4,
  149632. 8,
  149633. 3,
  149634. 9,
  149635. 2,
  149636. 10,
  149637. 1,
  149638. 11,
  149639. 0,
  149640. 12,
  149641. };
  149642. static long _vq_lengthlist__44un1__p7_2[] = {
  149643. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  149644. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  149645. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  149646. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  149647. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  149648. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  149649. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  149650. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  149651. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  149652. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  149653. 9, 9, 9,10,10,10,10,10,10,
  149654. };
  149655. static float _vq_quantthresh__44un1__p7_2[] = {
  149656. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  149657. 2.5, 3.5, 4.5, 5.5,
  149658. };
  149659. static long _vq_quantmap__44un1__p7_2[] = {
  149660. 11, 9, 7, 5, 3, 1, 0, 2,
  149661. 4, 6, 8, 10, 12,
  149662. };
  149663. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  149664. _vq_quantthresh__44un1__p7_2,
  149665. _vq_quantmap__44un1__p7_2,
  149666. 13,
  149667. 13
  149668. };
  149669. static static_codebook _44un1__p7_2 = {
  149670. 2, 169,
  149671. _vq_lengthlist__44un1__p7_2,
  149672. 1, -531103744, 1611661312, 4, 0,
  149673. _vq_quantlist__44un1__p7_2,
  149674. NULL,
  149675. &_vq_auxt__44un1__p7_2,
  149676. NULL,
  149677. 0
  149678. };
  149679. static long _huff_lengthlist__44un1__short[] = {
  149680. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  149681. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  149682. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  149683. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  149684. };
  149685. static static_codebook _huff_book__44un1__short = {
  149686. 2, 64,
  149687. _huff_lengthlist__44un1__short,
  149688. 0, 0, 0, 0, 0,
  149689. NULL,
  149690. NULL,
  149691. NULL,
  149692. NULL,
  149693. 0
  149694. };
  149695. /*** End of inlined file: res_books_uncoupled.h ***/
  149696. /***** residue backends *********************************************/
  149697. static vorbis_info_residue0 _residue_44_low_un={
  149698. 0,-1, -1, 8,-1,
  149699. {0},
  149700. {-1},
  149701. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  149702. { -1, 25, -1, 45, -1, -1, -1}
  149703. };
  149704. static vorbis_info_residue0 _residue_44_mid_un={
  149705. 0,-1, -1, 10,-1,
  149706. /* 0 1 2 3 4 5 6 7 8 9 */
  149707. {0},
  149708. {-1},
  149709. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  149710. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  149711. };
  149712. static vorbis_info_residue0 _residue_44_hi_un={
  149713. 0,-1, -1, 10,-1,
  149714. /* 0 1 2 3 4 5 6 7 8 9 */
  149715. {0},
  149716. {-1},
  149717. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  149718. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  149719. };
  149720. /* mapping conventions:
  149721. only one submap (this would change for efficient 5.1 support for example)*/
  149722. /* Four psychoacoustic profiles are used, one for each blocktype */
  149723. static vorbis_info_mapping0 _map_nominal_u[2]={
  149724. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  149725. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  149726. };
  149727. static static_bookblock _resbook_44u_n1={
  149728. {
  149729. {0},
  149730. {0,0,&_44un1__p1_0},
  149731. {0,0,&_44un1__p2_0},
  149732. {0,0,&_44un1__p3_0},
  149733. {0,0,&_44un1__p4_0},
  149734. {0,0,&_44un1__p5_0},
  149735. {&_44un1__p6_0,&_44un1__p6_1},
  149736. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  149737. }
  149738. };
  149739. static static_bookblock _resbook_44u_0={
  149740. {
  149741. {0},
  149742. {0,0,&_44u0__p1_0},
  149743. {0,0,&_44u0__p2_0},
  149744. {0,0,&_44u0__p3_0},
  149745. {0,0,&_44u0__p4_0},
  149746. {0,0,&_44u0__p5_0},
  149747. {&_44u0__p6_0,&_44u0__p6_1},
  149748. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  149749. }
  149750. };
  149751. static static_bookblock _resbook_44u_1={
  149752. {
  149753. {0},
  149754. {0,0,&_44u1__p1_0},
  149755. {0,0,&_44u1__p2_0},
  149756. {0,0,&_44u1__p3_0},
  149757. {0,0,&_44u1__p4_0},
  149758. {0,0,&_44u1__p5_0},
  149759. {&_44u1__p6_0,&_44u1__p6_1},
  149760. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  149761. }
  149762. };
  149763. static static_bookblock _resbook_44u_2={
  149764. {
  149765. {0},
  149766. {0,0,&_44u2__p1_0},
  149767. {0,0,&_44u2__p2_0},
  149768. {0,0,&_44u2__p3_0},
  149769. {0,0,&_44u2__p4_0},
  149770. {0,0,&_44u2__p5_0},
  149771. {&_44u2__p6_0,&_44u2__p6_1},
  149772. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  149773. }
  149774. };
  149775. static static_bookblock _resbook_44u_3={
  149776. {
  149777. {0},
  149778. {0,0,&_44u3__p1_0},
  149779. {0,0,&_44u3__p2_0},
  149780. {0,0,&_44u3__p3_0},
  149781. {0,0,&_44u3__p4_0},
  149782. {0,0,&_44u3__p5_0},
  149783. {&_44u3__p6_0,&_44u3__p6_1},
  149784. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  149785. }
  149786. };
  149787. static static_bookblock _resbook_44u_4={
  149788. {
  149789. {0},
  149790. {0,0,&_44u4__p1_0},
  149791. {0,0,&_44u4__p2_0},
  149792. {0,0,&_44u4__p3_0},
  149793. {0,0,&_44u4__p4_0},
  149794. {0,0,&_44u4__p5_0},
  149795. {&_44u4__p6_0,&_44u4__p6_1},
  149796. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  149797. }
  149798. };
  149799. static static_bookblock _resbook_44u_5={
  149800. {
  149801. {0},
  149802. {0,0,&_44u5__p1_0},
  149803. {0,0,&_44u5__p2_0},
  149804. {0,0,&_44u5__p3_0},
  149805. {0,0,&_44u5__p4_0},
  149806. {0,0,&_44u5__p5_0},
  149807. {0,0,&_44u5__p6_0},
  149808. {&_44u5__p7_0,&_44u5__p7_1},
  149809. {&_44u5__p8_0,&_44u5__p8_1},
  149810. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  149811. }
  149812. };
  149813. static static_bookblock _resbook_44u_6={
  149814. {
  149815. {0},
  149816. {0,0,&_44u6__p1_0},
  149817. {0,0,&_44u6__p2_0},
  149818. {0,0,&_44u6__p3_0},
  149819. {0,0,&_44u6__p4_0},
  149820. {0,0,&_44u6__p5_0},
  149821. {0,0,&_44u6__p6_0},
  149822. {&_44u6__p7_0,&_44u6__p7_1},
  149823. {&_44u6__p8_0,&_44u6__p8_1},
  149824. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  149825. }
  149826. };
  149827. static static_bookblock _resbook_44u_7={
  149828. {
  149829. {0},
  149830. {0,0,&_44u7__p1_0},
  149831. {0,0,&_44u7__p2_0},
  149832. {0,0,&_44u7__p3_0},
  149833. {0,0,&_44u7__p4_0},
  149834. {0,0,&_44u7__p5_0},
  149835. {0,0,&_44u7__p6_0},
  149836. {&_44u7__p7_0,&_44u7__p7_1},
  149837. {&_44u7__p8_0,&_44u7__p8_1},
  149838. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  149839. }
  149840. };
  149841. static static_bookblock _resbook_44u_8={
  149842. {
  149843. {0},
  149844. {0,0,&_44u8_p1_0},
  149845. {0,0,&_44u8_p2_0},
  149846. {0,0,&_44u8_p3_0},
  149847. {0,0,&_44u8_p4_0},
  149848. {&_44u8_p5_0,&_44u8_p5_1},
  149849. {&_44u8_p6_0,&_44u8_p6_1},
  149850. {&_44u8_p7_0,&_44u8_p7_1},
  149851. {&_44u8_p8_0,&_44u8_p8_1},
  149852. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  149853. }
  149854. };
  149855. static static_bookblock _resbook_44u_9={
  149856. {
  149857. {0},
  149858. {0,0,&_44u9_p1_0},
  149859. {0,0,&_44u9_p2_0},
  149860. {0,0,&_44u9_p3_0},
  149861. {0,0,&_44u9_p4_0},
  149862. {&_44u9_p5_0,&_44u9_p5_1},
  149863. {&_44u9_p6_0,&_44u9_p6_1},
  149864. {&_44u9_p7_0,&_44u9_p7_1},
  149865. {&_44u9_p8_0,&_44u9_p8_1},
  149866. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  149867. }
  149868. };
  149869. static vorbis_residue_template _res_44u_n1[]={
  149870. {1,0, &_residue_44_low_un,
  149871. &_huff_book__44un1__short,&_huff_book__44un1__short,
  149872. &_resbook_44u_n1,&_resbook_44u_n1},
  149873. {1,0, &_residue_44_low_un,
  149874. &_huff_book__44un1__long,&_huff_book__44un1__long,
  149875. &_resbook_44u_n1,&_resbook_44u_n1}
  149876. };
  149877. static vorbis_residue_template _res_44u_0[]={
  149878. {1,0, &_residue_44_low_un,
  149879. &_huff_book__44u0__short,&_huff_book__44u0__short,
  149880. &_resbook_44u_0,&_resbook_44u_0},
  149881. {1,0, &_residue_44_low_un,
  149882. &_huff_book__44u0__long,&_huff_book__44u0__long,
  149883. &_resbook_44u_0,&_resbook_44u_0}
  149884. };
  149885. static vorbis_residue_template _res_44u_1[]={
  149886. {1,0, &_residue_44_low_un,
  149887. &_huff_book__44u1__short,&_huff_book__44u1__short,
  149888. &_resbook_44u_1,&_resbook_44u_1},
  149889. {1,0, &_residue_44_low_un,
  149890. &_huff_book__44u1__long,&_huff_book__44u1__long,
  149891. &_resbook_44u_1,&_resbook_44u_1}
  149892. };
  149893. static vorbis_residue_template _res_44u_2[]={
  149894. {1,0, &_residue_44_low_un,
  149895. &_huff_book__44u2__short,&_huff_book__44u2__short,
  149896. &_resbook_44u_2,&_resbook_44u_2},
  149897. {1,0, &_residue_44_low_un,
  149898. &_huff_book__44u2__long,&_huff_book__44u2__long,
  149899. &_resbook_44u_2,&_resbook_44u_2}
  149900. };
  149901. static vorbis_residue_template _res_44u_3[]={
  149902. {1,0, &_residue_44_low_un,
  149903. &_huff_book__44u3__short,&_huff_book__44u3__short,
  149904. &_resbook_44u_3,&_resbook_44u_3},
  149905. {1,0, &_residue_44_low_un,
  149906. &_huff_book__44u3__long,&_huff_book__44u3__long,
  149907. &_resbook_44u_3,&_resbook_44u_3}
  149908. };
  149909. static vorbis_residue_template _res_44u_4[]={
  149910. {1,0, &_residue_44_low_un,
  149911. &_huff_book__44u4__short,&_huff_book__44u4__short,
  149912. &_resbook_44u_4,&_resbook_44u_4},
  149913. {1,0, &_residue_44_low_un,
  149914. &_huff_book__44u4__long,&_huff_book__44u4__long,
  149915. &_resbook_44u_4,&_resbook_44u_4}
  149916. };
  149917. static vorbis_residue_template _res_44u_5[]={
  149918. {1,0, &_residue_44_mid_un,
  149919. &_huff_book__44u5__short,&_huff_book__44u5__short,
  149920. &_resbook_44u_5,&_resbook_44u_5},
  149921. {1,0, &_residue_44_mid_un,
  149922. &_huff_book__44u5__long,&_huff_book__44u5__long,
  149923. &_resbook_44u_5,&_resbook_44u_5}
  149924. };
  149925. static vorbis_residue_template _res_44u_6[]={
  149926. {1,0, &_residue_44_mid_un,
  149927. &_huff_book__44u6__short,&_huff_book__44u6__short,
  149928. &_resbook_44u_6,&_resbook_44u_6},
  149929. {1,0, &_residue_44_mid_un,
  149930. &_huff_book__44u6__long,&_huff_book__44u6__long,
  149931. &_resbook_44u_6,&_resbook_44u_6}
  149932. };
  149933. static vorbis_residue_template _res_44u_7[]={
  149934. {1,0, &_residue_44_mid_un,
  149935. &_huff_book__44u7__short,&_huff_book__44u7__short,
  149936. &_resbook_44u_7,&_resbook_44u_7},
  149937. {1,0, &_residue_44_mid_un,
  149938. &_huff_book__44u7__long,&_huff_book__44u7__long,
  149939. &_resbook_44u_7,&_resbook_44u_7}
  149940. };
  149941. static vorbis_residue_template _res_44u_8[]={
  149942. {1,0, &_residue_44_hi_un,
  149943. &_huff_book__44u8__short,&_huff_book__44u8__short,
  149944. &_resbook_44u_8,&_resbook_44u_8},
  149945. {1,0, &_residue_44_hi_un,
  149946. &_huff_book__44u8__long,&_huff_book__44u8__long,
  149947. &_resbook_44u_8,&_resbook_44u_8}
  149948. };
  149949. static vorbis_residue_template _res_44u_9[]={
  149950. {1,0, &_residue_44_hi_un,
  149951. &_huff_book__44u9__short,&_huff_book__44u9__short,
  149952. &_resbook_44u_9,&_resbook_44u_9},
  149953. {1,0, &_residue_44_hi_un,
  149954. &_huff_book__44u9__long,&_huff_book__44u9__long,
  149955. &_resbook_44u_9,&_resbook_44u_9}
  149956. };
  149957. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  149958. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  149959. { _map_nominal_u, _res_44u_0 }, /* 0 */
  149960. { _map_nominal_u, _res_44u_1 }, /* 1 */
  149961. { _map_nominal_u, _res_44u_2 }, /* 2 */
  149962. { _map_nominal_u, _res_44u_3 }, /* 3 */
  149963. { _map_nominal_u, _res_44u_4 }, /* 4 */
  149964. { _map_nominal_u, _res_44u_5 }, /* 5 */
  149965. { _map_nominal_u, _res_44u_6 }, /* 6 */
  149966. { _map_nominal_u, _res_44u_7 }, /* 7 */
  149967. { _map_nominal_u, _res_44u_8 }, /* 8 */
  149968. { _map_nominal_u, _res_44u_9 }, /* 9 */
  149969. };
  149970. /*** End of inlined file: residue_44u.h ***/
  149971. static double rate_mapping_44_un[12]={
  149972. 32000.,48000.,60000.,70000.,80000.,86000.,
  149973. 96000.,110000.,120000.,140000.,160000.,240001.
  149974. };
  149975. ve_setup_data_template ve_setup_44_uncoupled={
  149976. 11,
  149977. rate_mapping_44_un,
  149978. quality_mapping_44,
  149979. -1,
  149980. 40000,
  149981. 50000,
  149982. blocksize_short_44,
  149983. blocksize_long_44,
  149984. _psy_tone_masteratt_44,
  149985. _psy_tone_0dB,
  149986. _psy_tone_suppress,
  149987. _vp_tonemask_adj_otherblock,
  149988. _vp_tonemask_adj_longblock,
  149989. _vp_tonemask_adj_otherblock,
  149990. _psy_noiseguards_44,
  149991. _psy_noisebias_impulse,
  149992. _psy_noisebias_padding,
  149993. _psy_noisebias_trans,
  149994. _psy_noisebias_long,
  149995. _psy_noise_suppress,
  149996. _psy_compand_44,
  149997. _psy_compand_short_mapping,
  149998. _psy_compand_long_mapping,
  149999. {_noise_start_short_44,_noise_start_long_44},
  150000. {_noise_part_short_44,_noise_part_long_44},
  150001. _noise_thresh_44,
  150002. _psy_ath_floater,
  150003. _psy_ath_abs,
  150004. _psy_lowpass_44,
  150005. _psy_global_44,
  150006. _global_mapping_44,
  150007. NULL,
  150008. _floor_books,
  150009. _floor,
  150010. _floor_short_mapping_44,
  150011. _floor_long_mapping_44,
  150012. _mapres_template_44_uncoupled
  150013. };
  150014. /*** End of inlined file: setup_44u.h ***/
  150015. /*** Start of inlined file: setup_32.h ***/
  150016. static double rate_mapping_32[12]={
  150017. 18000.,28000.,35000.,45000.,56000.,60000.,
  150018. 75000.,90000.,100000.,115000.,150000.,190000.,
  150019. };
  150020. static double rate_mapping_32_un[12]={
  150021. 30000.,42000.,52000.,64000.,72000.,78000.,
  150022. 86000.,92000.,110000.,120000.,140000.,190000.,
  150023. };
  150024. static double _psy_lowpass_32[12]={
  150025. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  150026. };
  150027. ve_setup_data_template ve_setup_32_stereo={
  150028. 11,
  150029. rate_mapping_32,
  150030. quality_mapping_44,
  150031. 2,
  150032. 26000,
  150033. 40000,
  150034. blocksize_short_44,
  150035. blocksize_long_44,
  150036. _psy_tone_masteratt_44,
  150037. _psy_tone_0dB,
  150038. _psy_tone_suppress,
  150039. _vp_tonemask_adj_otherblock,
  150040. _vp_tonemask_adj_longblock,
  150041. _vp_tonemask_adj_otherblock,
  150042. _psy_noiseguards_44,
  150043. _psy_noisebias_impulse,
  150044. _psy_noisebias_padding,
  150045. _psy_noisebias_trans,
  150046. _psy_noisebias_long,
  150047. _psy_noise_suppress,
  150048. _psy_compand_44,
  150049. _psy_compand_short_mapping,
  150050. _psy_compand_long_mapping,
  150051. {_noise_start_short_44,_noise_start_long_44},
  150052. {_noise_part_short_44,_noise_part_long_44},
  150053. _noise_thresh_44,
  150054. _psy_ath_floater,
  150055. _psy_ath_abs,
  150056. _psy_lowpass_32,
  150057. _psy_global_44,
  150058. _global_mapping_44,
  150059. _psy_stereo_modes_44,
  150060. _floor_books,
  150061. _floor,
  150062. _floor_short_mapping_44,
  150063. _floor_long_mapping_44,
  150064. _mapres_template_44_stereo
  150065. };
  150066. ve_setup_data_template ve_setup_32_uncoupled={
  150067. 11,
  150068. rate_mapping_32_un,
  150069. quality_mapping_44,
  150070. -1,
  150071. 26000,
  150072. 40000,
  150073. blocksize_short_44,
  150074. blocksize_long_44,
  150075. _psy_tone_masteratt_44,
  150076. _psy_tone_0dB,
  150077. _psy_tone_suppress,
  150078. _vp_tonemask_adj_otherblock,
  150079. _vp_tonemask_adj_longblock,
  150080. _vp_tonemask_adj_otherblock,
  150081. _psy_noiseguards_44,
  150082. _psy_noisebias_impulse,
  150083. _psy_noisebias_padding,
  150084. _psy_noisebias_trans,
  150085. _psy_noisebias_long,
  150086. _psy_noise_suppress,
  150087. _psy_compand_44,
  150088. _psy_compand_short_mapping,
  150089. _psy_compand_long_mapping,
  150090. {_noise_start_short_44,_noise_start_long_44},
  150091. {_noise_part_short_44,_noise_part_long_44},
  150092. _noise_thresh_44,
  150093. _psy_ath_floater,
  150094. _psy_ath_abs,
  150095. _psy_lowpass_32,
  150096. _psy_global_44,
  150097. _global_mapping_44,
  150098. NULL,
  150099. _floor_books,
  150100. _floor,
  150101. _floor_short_mapping_44,
  150102. _floor_long_mapping_44,
  150103. _mapres_template_44_uncoupled
  150104. };
  150105. /*** End of inlined file: setup_32.h ***/
  150106. /*** Start of inlined file: setup_8.h ***/
  150107. /*** Start of inlined file: psych_8.h ***/
  150108. static att3 _psy_tone_masteratt_8[3]={
  150109. {{ 32, 25, 12}, 0, 0}, /* 0 */
  150110. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150111. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150112. };
  150113. static vp_adjblock _vp_tonemask_adj_8[3]={
  150114. /* adjust for mode zero */
  150115. /* 63 125 250 500 1 2 4 8 16 */
  150116. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150117. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150118. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  150119. };
  150120. static noise3 _psy_noisebias_8[3]={
  150121. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150122. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150123. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  150124. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150125. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150126. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150127. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150128. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150129. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150130. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150131. };
  150132. /* stereo mode by base quality level */
  150133. static adj_stereo _psy_stereo_modes_8[3]={
  150134. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150135. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150136. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150137. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150138. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150139. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150140. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150141. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150142. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150143. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150144. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150145. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150146. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150147. };
  150148. static noiseguard _psy_noiseguards_8[2]={
  150149. {10,10,-1},
  150150. {10,10,-1},
  150151. };
  150152. static compandblock _psy_compand_8[2]={
  150153. {{
  150154. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  150155. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  150156. 12,12,13,13,14,14,15, 15, /* 23dB */
  150157. 16,16,17,17,17,18,18, 19, /* 31dB */
  150158. 19,19,20,21,22,23,24, 25, /* 39dB */
  150159. }},
  150160. {{
  150161. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  150162. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  150163. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  150164. 9,10,11,12,13,14,15, 16, /* 31dB */
  150165. 17,18,19,20,21,22,23, 24, /* 39dB */
  150166. }},
  150167. };
  150168. static double _psy_lowpass_8[3]={3.,4.,4.};
  150169. static int _noise_start_8[2]={
  150170. 64,64,
  150171. };
  150172. static int _noise_part_8[2]={
  150173. 8,8,
  150174. };
  150175. static int _psy_ath_floater_8[3]={
  150176. -100,-100,-105,
  150177. };
  150178. static int _psy_ath_abs_8[3]={
  150179. -130,-130,-140,
  150180. };
  150181. /*** End of inlined file: psych_8.h ***/
  150182. /*** Start of inlined file: residue_8.h ***/
  150183. /***** residue backends *********************************************/
  150184. static static_bookblock _resbook_8s_0={
  150185. {
  150186. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  150187. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  150188. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  150189. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  150190. }
  150191. };
  150192. static static_bookblock _resbook_8s_1={
  150193. {
  150194. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  150195. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  150196. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  150197. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  150198. }
  150199. };
  150200. static vorbis_residue_template _res_8s_0[]={
  150201. {2,0, &_residue_44_mid,
  150202. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  150203. &_resbook_8s_0,&_resbook_8s_0},
  150204. };
  150205. static vorbis_residue_template _res_8s_1[]={
  150206. {2,0, &_residue_44_mid,
  150207. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  150208. &_resbook_8s_1,&_resbook_8s_1},
  150209. };
  150210. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  150211. { _map_nominal, _res_8s_0 }, /* 0 */
  150212. { _map_nominal, _res_8s_1 }, /* 1 */
  150213. };
  150214. static static_bookblock _resbook_8u_0={
  150215. {
  150216. {0},
  150217. {0,0,&_8u0__p1_0},
  150218. {0,0,&_8u0__p2_0},
  150219. {0,0,&_8u0__p3_0},
  150220. {0,0,&_8u0__p4_0},
  150221. {0,0,&_8u0__p5_0},
  150222. {&_8u0__p6_0,&_8u0__p6_1},
  150223. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  150224. }
  150225. };
  150226. static static_bookblock _resbook_8u_1={
  150227. {
  150228. {0},
  150229. {0,0,&_8u1__p1_0},
  150230. {0,0,&_8u1__p2_0},
  150231. {0,0,&_8u1__p3_0},
  150232. {0,0,&_8u1__p4_0},
  150233. {0,0,&_8u1__p5_0},
  150234. {0,0,&_8u1__p6_0},
  150235. {&_8u1__p7_0,&_8u1__p7_1},
  150236. {&_8u1__p8_0,&_8u1__p8_1},
  150237. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  150238. }
  150239. };
  150240. static vorbis_residue_template _res_8u_0[]={
  150241. {1,0, &_residue_44_low_un,
  150242. &_huff_book__8u0__single,&_huff_book__8u0__single,
  150243. &_resbook_8u_0,&_resbook_8u_0},
  150244. };
  150245. static vorbis_residue_template _res_8u_1[]={
  150246. {1,0, &_residue_44_mid_un,
  150247. &_huff_book__8u1__single,&_huff_book__8u1__single,
  150248. &_resbook_8u_1,&_resbook_8u_1},
  150249. };
  150250. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  150251. { _map_nominal_u, _res_8u_0 }, /* 0 */
  150252. { _map_nominal_u, _res_8u_1 }, /* 1 */
  150253. };
  150254. /*** End of inlined file: residue_8.h ***/
  150255. static int blocksize_8[2]={
  150256. 512,512
  150257. };
  150258. static int _floor_mapping_8[2]={
  150259. 6,6,
  150260. };
  150261. static double rate_mapping_8[3]={
  150262. 6000.,9000.,32000.,
  150263. };
  150264. static double rate_mapping_8_uncoupled[3]={
  150265. 8000.,14000.,42000.,
  150266. };
  150267. static double quality_mapping_8[3]={
  150268. -.1,.0,1.
  150269. };
  150270. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  150271. static double _global_mapping_8[3]={ 1., 2., 3. };
  150272. ve_setup_data_template ve_setup_8_stereo={
  150273. 2,
  150274. rate_mapping_8,
  150275. quality_mapping_8,
  150276. 2,
  150277. 8000,
  150278. 9000,
  150279. blocksize_8,
  150280. blocksize_8,
  150281. _psy_tone_masteratt_8,
  150282. _psy_tone_0dB,
  150283. _psy_tone_suppress,
  150284. _vp_tonemask_adj_8,
  150285. NULL,
  150286. _vp_tonemask_adj_8,
  150287. _psy_noiseguards_8,
  150288. _psy_noisebias_8,
  150289. _psy_noisebias_8,
  150290. NULL,
  150291. NULL,
  150292. _psy_noise_suppress,
  150293. _psy_compand_8,
  150294. _psy_compand_8_mapping,
  150295. NULL,
  150296. {_noise_start_8,_noise_start_8},
  150297. {_noise_part_8,_noise_part_8},
  150298. _noise_thresh_5only,
  150299. _psy_ath_floater_8,
  150300. _psy_ath_abs_8,
  150301. _psy_lowpass_8,
  150302. _psy_global_44,
  150303. _global_mapping_8,
  150304. _psy_stereo_modes_8,
  150305. _floor_books,
  150306. _floor,
  150307. _floor_mapping_8,
  150308. NULL,
  150309. _mapres_template_8_stereo
  150310. };
  150311. ve_setup_data_template ve_setup_8_uncoupled={
  150312. 2,
  150313. rate_mapping_8_uncoupled,
  150314. quality_mapping_8,
  150315. -1,
  150316. 8000,
  150317. 9000,
  150318. blocksize_8,
  150319. blocksize_8,
  150320. _psy_tone_masteratt_8,
  150321. _psy_tone_0dB,
  150322. _psy_tone_suppress,
  150323. _vp_tonemask_adj_8,
  150324. NULL,
  150325. _vp_tonemask_adj_8,
  150326. _psy_noiseguards_8,
  150327. _psy_noisebias_8,
  150328. _psy_noisebias_8,
  150329. NULL,
  150330. NULL,
  150331. _psy_noise_suppress,
  150332. _psy_compand_8,
  150333. _psy_compand_8_mapping,
  150334. NULL,
  150335. {_noise_start_8,_noise_start_8},
  150336. {_noise_part_8,_noise_part_8},
  150337. _noise_thresh_5only,
  150338. _psy_ath_floater_8,
  150339. _psy_ath_abs_8,
  150340. _psy_lowpass_8,
  150341. _psy_global_44,
  150342. _global_mapping_8,
  150343. _psy_stereo_modes_8,
  150344. _floor_books,
  150345. _floor,
  150346. _floor_mapping_8,
  150347. NULL,
  150348. _mapres_template_8_uncoupled
  150349. };
  150350. /*** End of inlined file: setup_8.h ***/
  150351. /*** Start of inlined file: setup_11.h ***/
  150352. /*** Start of inlined file: psych_11.h ***/
  150353. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  150354. static att3 _psy_tone_masteratt_11[3]={
  150355. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150356. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150357. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150358. };
  150359. static vp_adjblock _vp_tonemask_adj_11[3]={
  150360. /* adjust for mode zero */
  150361. /* 63 125 250 500 1 2 4 8 16 */
  150362. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  150363. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  150364. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  150365. };
  150366. static noise3 _psy_noisebias_11[3]={
  150367. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150368. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  150369. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  150370. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150371. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  150372. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150373. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150374. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150375. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150376. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150377. };
  150378. static double _noise_thresh_11[3]={ .3,.5,.5 };
  150379. /*** End of inlined file: psych_11.h ***/
  150380. static int blocksize_11[2]={
  150381. 512,512
  150382. };
  150383. static int _floor_mapping_11[2]={
  150384. 6,6,
  150385. };
  150386. static double rate_mapping_11[3]={
  150387. 8000.,13000.,44000.,
  150388. };
  150389. static double rate_mapping_11_uncoupled[3]={
  150390. 12000.,20000.,50000.,
  150391. };
  150392. static double quality_mapping_11[3]={
  150393. -.1,.0,1.
  150394. };
  150395. ve_setup_data_template ve_setup_11_stereo={
  150396. 2,
  150397. rate_mapping_11,
  150398. quality_mapping_11,
  150399. 2,
  150400. 9000,
  150401. 15000,
  150402. blocksize_11,
  150403. blocksize_11,
  150404. _psy_tone_masteratt_11,
  150405. _psy_tone_0dB,
  150406. _psy_tone_suppress,
  150407. _vp_tonemask_adj_11,
  150408. NULL,
  150409. _vp_tonemask_adj_11,
  150410. _psy_noiseguards_8,
  150411. _psy_noisebias_11,
  150412. _psy_noisebias_11,
  150413. NULL,
  150414. NULL,
  150415. _psy_noise_suppress,
  150416. _psy_compand_8,
  150417. _psy_compand_8_mapping,
  150418. NULL,
  150419. {_noise_start_8,_noise_start_8},
  150420. {_noise_part_8,_noise_part_8},
  150421. _noise_thresh_11,
  150422. _psy_ath_floater_8,
  150423. _psy_ath_abs_8,
  150424. _psy_lowpass_11,
  150425. _psy_global_44,
  150426. _global_mapping_8,
  150427. _psy_stereo_modes_8,
  150428. _floor_books,
  150429. _floor,
  150430. _floor_mapping_11,
  150431. NULL,
  150432. _mapres_template_8_stereo
  150433. };
  150434. ve_setup_data_template ve_setup_11_uncoupled={
  150435. 2,
  150436. rate_mapping_11_uncoupled,
  150437. quality_mapping_11,
  150438. -1,
  150439. 9000,
  150440. 15000,
  150441. blocksize_11,
  150442. blocksize_11,
  150443. _psy_tone_masteratt_11,
  150444. _psy_tone_0dB,
  150445. _psy_tone_suppress,
  150446. _vp_tonemask_adj_11,
  150447. NULL,
  150448. _vp_tonemask_adj_11,
  150449. _psy_noiseguards_8,
  150450. _psy_noisebias_11,
  150451. _psy_noisebias_11,
  150452. NULL,
  150453. NULL,
  150454. _psy_noise_suppress,
  150455. _psy_compand_8,
  150456. _psy_compand_8_mapping,
  150457. NULL,
  150458. {_noise_start_8,_noise_start_8},
  150459. {_noise_part_8,_noise_part_8},
  150460. _noise_thresh_11,
  150461. _psy_ath_floater_8,
  150462. _psy_ath_abs_8,
  150463. _psy_lowpass_11,
  150464. _psy_global_44,
  150465. _global_mapping_8,
  150466. _psy_stereo_modes_8,
  150467. _floor_books,
  150468. _floor,
  150469. _floor_mapping_11,
  150470. NULL,
  150471. _mapres_template_8_uncoupled
  150472. };
  150473. /*** End of inlined file: setup_11.h ***/
  150474. /*** Start of inlined file: setup_16.h ***/
  150475. /*** Start of inlined file: psych_16.h ***/
  150476. /* stereo mode by base quality level */
  150477. static adj_stereo _psy_stereo_modes_16[4]={
  150478. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150479. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150480. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150481. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  150482. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150483. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150484. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150485. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  150486. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150487. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150488. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150489. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150490. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150491. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  150492. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  150493. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  150494. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150495. };
  150496. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  150497. static att3 _psy_tone_masteratt_16[4]={
  150498. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150499. {{ 25, 22, 12}, 0, 0}, /* 0 */
  150500. {{ 20, 12, 0}, 0, 0}, /* 0 */
  150501. {{ 15, 0, -14}, 0, 0}, /* 0 */
  150502. };
  150503. static vp_adjblock _vp_tonemask_adj_16[4]={
  150504. /* adjust for mode zero */
  150505. /* 63 125 250 500 1 2 4 8 16 */
  150506. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  150507. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  150508. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  150509. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  150510. };
  150511. static noise3 _psy_noisebias_16_short[4]={
  150512. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150513. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  150514. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  150515. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150516. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  150517. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  150518. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  150519. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  150520. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  150521. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150522. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  150523. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  150524. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150525. };
  150526. static noise3 _psy_noisebias_16_impulse[4]={
  150527. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150528. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  150529. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  150530. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150531. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  150532. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  150533. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  150534. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  150535. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  150536. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150537. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  150538. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  150539. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150540. };
  150541. static noise3 _psy_noisebias_16[4]={
  150542. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150543. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  150544. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  150545. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150546. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  150547. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  150548. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150549. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  150550. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  150551. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150552. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  150553. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  150554. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150555. };
  150556. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  150557. static int _noise_start_16[3]={ 256,256,9999 };
  150558. static int _noise_part_16[4]={ 8,8,8,8 };
  150559. static int _psy_ath_floater_16[4]={
  150560. -100,-100,-100,-105,
  150561. };
  150562. static int _psy_ath_abs_16[4]={
  150563. -130,-130,-130,-140,
  150564. };
  150565. /*** End of inlined file: psych_16.h ***/
  150566. /*** Start of inlined file: residue_16.h ***/
  150567. /***** residue backends *********************************************/
  150568. static static_bookblock _resbook_16s_0={
  150569. {
  150570. {0},
  150571. {0,0,&_16c0_s_p1_0},
  150572. {0,0,&_16c0_s_p2_0},
  150573. {0,0,&_16c0_s_p3_0},
  150574. {0,0,&_16c0_s_p4_0},
  150575. {0,0,&_16c0_s_p5_0},
  150576. {0,0,&_16c0_s_p6_0},
  150577. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  150578. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  150579. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  150580. }
  150581. };
  150582. static static_bookblock _resbook_16s_1={
  150583. {
  150584. {0},
  150585. {0,0,&_16c1_s_p1_0},
  150586. {0,0,&_16c1_s_p2_0},
  150587. {0,0,&_16c1_s_p3_0},
  150588. {0,0,&_16c1_s_p4_0},
  150589. {0,0,&_16c1_s_p5_0},
  150590. {0,0,&_16c1_s_p6_0},
  150591. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  150592. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  150593. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  150594. }
  150595. };
  150596. static static_bookblock _resbook_16s_2={
  150597. {
  150598. {0},
  150599. {0,0,&_16c2_s_p1_0},
  150600. {0,0,&_16c2_s_p2_0},
  150601. {0,0,&_16c2_s_p3_0},
  150602. {0,0,&_16c2_s_p4_0},
  150603. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  150604. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  150605. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  150606. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  150607. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  150608. }
  150609. };
  150610. static vorbis_residue_template _res_16s_0[]={
  150611. {2,0, &_residue_44_mid,
  150612. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  150613. &_resbook_16s_0,&_resbook_16s_0},
  150614. };
  150615. static vorbis_residue_template _res_16s_1[]={
  150616. {2,0, &_residue_44_mid,
  150617. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  150618. &_resbook_16s_1,&_resbook_16s_1},
  150619. {2,0, &_residue_44_mid,
  150620. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  150621. &_resbook_16s_1,&_resbook_16s_1}
  150622. };
  150623. static vorbis_residue_template _res_16s_2[]={
  150624. {2,0, &_residue_44_high,
  150625. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  150626. &_resbook_16s_2,&_resbook_16s_2},
  150627. {2,0, &_residue_44_high,
  150628. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  150629. &_resbook_16s_2,&_resbook_16s_2}
  150630. };
  150631. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  150632. { _map_nominal, _res_16s_0 }, /* 0 */
  150633. { _map_nominal, _res_16s_1 }, /* 1 */
  150634. { _map_nominal, _res_16s_2 }, /* 2 */
  150635. };
  150636. static static_bookblock _resbook_16u_0={
  150637. {
  150638. {0},
  150639. {0,0,&_16u0__p1_0},
  150640. {0,0,&_16u0__p2_0},
  150641. {0,0,&_16u0__p3_0},
  150642. {0,0,&_16u0__p4_0},
  150643. {0,0,&_16u0__p5_0},
  150644. {&_16u0__p6_0,&_16u0__p6_1},
  150645. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  150646. }
  150647. };
  150648. static static_bookblock _resbook_16u_1={
  150649. {
  150650. {0},
  150651. {0,0,&_16u1__p1_0},
  150652. {0,0,&_16u1__p2_0},
  150653. {0,0,&_16u1__p3_0},
  150654. {0,0,&_16u1__p4_0},
  150655. {0,0,&_16u1__p5_0},
  150656. {0,0,&_16u1__p6_0},
  150657. {&_16u1__p7_0,&_16u1__p7_1},
  150658. {&_16u1__p8_0,&_16u1__p8_1},
  150659. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  150660. }
  150661. };
  150662. static static_bookblock _resbook_16u_2={
  150663. {
  150664. {0},
  150665. {0,0,&_16u2_p1_0},
  150666. {0,0,&_16u2_p2_0},
  150667. {0,0,&_16u2_p3_0},
  150668. {0,0,&_16u2_p4_0},
  150669. {&_16u2_p5_0,&_16u2_p5_1},
  150670. {&_16u2_p6_0,&_16u2_p6_1},
  150671. {&_16u2_p7_0,&_16u2_p7_1},
  150672. {&_16u2_p8_0,&_16u2_p8_1},
  150673. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  150674. }
  150675. };
  150676. static vorbis_residue_template _res_16u_0[]={
  150677. {1,0, &_residue_44_low_un,
  150678. &_huff_book__16u0__single,&_huff_book__16u0__single,
  150679. &_resbook_16u_0,&_resbook_16u_0},
  150680. };
  150681. static vorbis_residue_template _res_16u_1[]={
  150682. {1,0, &_residue_44_mid_un,
  150683. &_huff_book__16u1__short,&_huff_book__16u1__short,
  150684. &_resbook_16u_1,&_resbook_16u_1},
  150685. {1,0, &_residue_44_mid_un,
  150686. &_huff_book__16u1__long,&_huff_book__16u1__long,
  150687. &_resbook_16u_1,&_resbook_16u_1}
  150688. };
  150689. static vorbis_residue_template _res_16u_2[]={
  150690. {1,0, &_residue_44_hi_un,
  150691. &_huff_book__16u2__short,&_huff_book__16u2__short,
  150692. &_resbook_16u_2,&_resbook_16u_2},
  150693. {1,0, &_residue_44_hi_un,
  150694. &_huff_book__16u2__long,&_huff_book__16u2__long,
  150695. &_resbook_16u_2,&_resbook_16u_2}
  150696. };
  150697. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  150698. { _map_nominal_u, _res_16u_0 }, /* 0 */
  150699. { _map_nominal_u, _res_16u_1 }, /* 1 */
  150700. { _map_nominal_u, _res_16u_2 }, /* 2 */
  150701. };
  150702. /*** End of inlined file: residue_16.h ***/
  150703. static int blocksize_16_short[3]={
  150704. 1024,512,512
  150705. };
  150706. static int blocksize_16_long[3]={
  150707. 1024,1024,1024
  150708. };
  150709. static int _floor_mapping_16_short[3]={
  150710. 9,3,3
  150711. };
  150712. static int _floor_mapping_16[3]={
  150713. 9,9,9
  150714. };
  150715. static double rate_mapping_16[4]={
  150716. 12000.,20000.,44000.,86000.
  150717. };
  150718. static double rate_mapping_16_uncoupled[4]={
  150719. 16000.,28000.,64000.,100000.
  150720. };
  150721. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  150722. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  150723. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  150724. ve_setup_data_template ve_setup_16_stereo={
  150725. 3,
  150726. rate_mapping_16,
  150727. quality_mapping_16,
  150728. 2,
  150729. 15000,
  150730. 19000,
  150731. blocksize_16_short,
  150732. blocksize_16_long,
  150733. _psy_tone_masteratt_16,
  150734. _psy_tone_0dB,
  150735. _psy_tone_suppress,
  150736. _vp_tonemask_adj_16,
  150737. _vp_tonemask_adj_16,
  150738. _vp_tonemask_adj_16,
  150739. _psy_noiseguards_8,
  150740. _psy_noisebias_16_impulse,
  150741. _psy_noisebias_16_short,
  150742. _psy_noisebias_16_short,
  150743. _psy_noisebias_16,
  150744. _psy_noise_suppress,
  150745. _psy_compand_8,
  150746. _psy_compand_16_mapping,
  150747. _psy_compand_16_mapping,
  150748. {_noise_start_16,_noise_start_16},
  150749. { _noise_part_16, _noise_part_16},
  150750. _noise_thresh_16,
  150751. _psy_ath_floater_16,
  150752. _psy_ath_abs_16,
  150753. _psy_lowpass_16,
  150754. _psy_global_44,
  150755. _global_mapping_16,
  150756. _psy_stereo_modes_16,
  150757. _floor_books,
  150758. _floor,
  150759. _floor_mapping_16_short,
  150760. _floor_mapping_16,
  150761. _mapres_template_16_stereo
  150762. };
  150763. ve_setup_data_template ve_setup_16_uncoupled={
  150764. 3,
  150765. rate_mapping_16_uncoupled,
  150766. quality_mapping_16,
  150767. -1,
  150768. 15000,
  150769. 19000,
  150770. blocksize_16_short,
  150771. blocksize_16_long,
  150772. _psy_tone_masteratt_16,
  150773. _psy_tone_0dB,
  150774. _psy_tone_suppress,
  150775. _vp_tonemask_adj_16,
  150776. _vp_tonemask_adj_16,
  150777. _vp_tonemask_adj_16,
  150778. _psy_noiseguards_8,
  150779. _psy_noisebias_16_impulse,
  150780. _psy_noisebias_16_short,
  150781. _psy_noisebias_16_short,
  150782. _psy_noisebias_16,
  150783. _psy_noise_suppress,
  150784. _psy_compand_8,
  150785. _psy_compand_16_mapping,
  150786. _psy_compand_16_mapping,
  150787. {_noise_start_16,_noise_start_16},
  150788. { _noise_part_16, _noise_part_16},
  150789. _noise_thresh_16,
  150790. _psy_ath_floater_16,
  150791. _psy_ath_abs_16,
  150792. _psy_lowpass_16,
  150793. _psy_global_44,
  150794. _global_mapping_16,
  150795. _psy_stereo_modes_16,
  150796. _floor_books,
  150797. _floor,
  150798. _floor_mapping_16_short,
  150799. _floor_mapping_16,
  150800. _mapres_template_16_uncoupled
  150801. };
  150802. /*** End of inlined file: setup_16.h ***/
  150803. /*** Start of inlined file: setup_22.h ***/
  150804. static double rate_mapping_22[4]={
  150805. 15000.,20000.,44000.,86000.
  150806. };
  150807. static double rate_mapping_22_uncoupled[4]={
  150808. 16000.,28000.,50000.,90000.
  150809. };
  150810. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  150811. ve_setup_data_template ve_setup_22_stereo={
  150812. 3,
  150813. rate_mapping_22,
  150814. quality_mapping_16,
  150815. 2,
  150816. 19000,
  150817. 26000,
  150818. blocksize_16_short,
  150819. blocksize_16_long,
  150820. _psy_tone_masteratt_16,
  150821. _psy_tone_0dB,
  150822. _psy_tone_suppress,
  150823. _vp_tonemask_adj_16,
  150824. _vp_tonemask_adj_16,
  150825. _vp_tonemask_adj_16,
  150826. _psy_noiseguards_8,
  150827. _psy_noisebias_16_impulse,
  150828. _psy_noisebias_16_short,
  150829. _psy_noisebias_16_short,
  150830. _psy_noisebias_16,
  150831. _psy_noise_suppress,
  150832. _psy_compand_8,
  150833. _psy_compand_8_mapping,
  150834. _psy_compand_8_mapping,
  150835. {_noise_start_16,_noise_start_16},
  150836. { _noise_part_16, _noise_part_16},
  150837. _noise_thresh_16,
  150838. _psy_ath_floater_16,
  150839. _psy_ath_abs_16,
  150840. _psy_lowpass_22,
  150841. _psy_global_44,
  150842. _global_mapping_16,
  150843. _psy_stereo_modes_16,
  150844. _floor_books,
  150845. _floor,
  150846. _floor_mapping_16_short,
  150847. _floor_mapping_16,
  150848. _mapres_template_16_stereo
  150849. };
  150850. ve_setup_data_template ve_setup_22_uncoupled={
  150851. 3,
  150852. rate_mapping_22_uncoupled,
  150853. quality_mapping_16,
  150854. -1,
  150855. 19000,
  150856. 26000,
  150857. blocksize_16_short,
  150858. blocksize_16_long,
  150859. _psy_tone_masteratt_16,
  150860. _psy_tone_0dB,
  150861. _psy_tone_suppress,
  150862. _vp_tonemask_adj_16,
  150863. _vp_tonemask_adj_16,
  150864. _vp_tonemask_adj_16,
  150865. _psy_noiseguards_8,
  150866. _psy_noisebias_16_impulse,
  150867. _psy_noisebias_16_short,
  150868. _psy_noisebias_16_short,
  150869. _psy_noisebias_16,
  150870. _psy_noise_suppress,
  150871. _psy_compand_8,
  150872. _psy_compand_8_mapping,
  150873. _psy_compand_8_mapping,
  150874. {_noise_start_16,_noise_start_16},
  150875. { _noise_part_16, _noise_part_16},
  150876. _noise_thresh_16,
  150877. _psy_ath_floater_16,
  150878. _psy_ath_abs_16,
  150879. _psy_lowpass_22,
  150880. _psy_global_44,
  150881. _global_mapping_16,
  150882. _psy_stereo_modes_16,
  150883. _floor_books,
  150884. _floor,
  150885. _floor_mapping_16_short,
  150886. _floor_mapping_16,
  150887. _mapres_template_16_uncoupled
  150888. };
  150889. /*** End of inlined file: setup_22.h ***/
  150890. /*** Start of inlined file: setup_X.h ***/
  150891. static double rate_mapping_X[12]={
  150892. -1.,-1.,-1.,-1.,-1.,-1.,
  150893. -1.,-1.,-1.,-1.,-1.,-1.
  150894. };
  150895. ve_setup_data_template ve_setup_X_stereo={
  150896. 11,
  150897. rate_mapping_X,
  150898. quality_mapping_44,
  150899. 2,
  150900. 50000,
  150901. 200000,
  150902. blocksize_short_44,
  150903. blocksize_long_44,
  150904. _psy_tone_masteratt_44,
  150905. _psy_tone_0dB,
  150906. _psy_tone_suppress,
  150907. _vp_tonemask_adj_otherblock,
  150908. _vp_tonemask_adj_longblock,
  150909. _vp_tonemask_adj_otherblock,
  150910. _psy_noiseguards_44,
  150911. _psy_noisebias_impulse,
  150912. _psy_noisebias_padding,
  150913. _psy_noisebias_trans,
  150914. _psy_noisebias_long,
  150915. _psy_noise_suppress,
  150916. _psy_compand_44,
  150917. _psy_compand_short_mapping,
  150918. _psy_compand_long_mapping,
  150919. {_noise_start_short_44,_noise_start_long_44},
  150920. {_noise_part_short_44,_noise_part_long_44},
  150921. _noise_thresh_44,
  150922. _psy_ath_floater,
  150923. _psy_ath_abs,
  150924. _psy_lowpass_44,
  150925. _psy_global_44,
  150926. _global_mapping_44,
  150927. _psy_stereo_modes_44,
  150928. _floor_books,
  150929. _floor,
  150930. _floor_short_mapping_44,
  150931. _floor_long_mapping_44,
  150932. _mapres_template_44_stereo
  150933. };
  150934. ve_setup_data_template ve_setup_X_uncoupled={
  150935. 11,
  150936. rate_mapping_X,
  150937. quality_mapping_44,
  150938. -1,
  150939. 50000,
  150940. 200000,
  150941. blocksize_short_44,
  150942. blocksize_long_44,
  150943. _psy_tone_masteratt_44,
  150944. _psy_tone_0dB,
  150945. _psy_tone_suppress,
  150946. _vp_tonemask_adj_otherblock,
  150947. _vp_tonemask_adj_longblock,
  150948. _vp_tonemask_adj_otherblock,
  150949. _psy_noiseguards_44,
  150950. _psy_noisebias_impulse,
  150951. _psy_noisebias_padding,
  150952. _psy_noisebias_trans,
  150953. _psy_noisebias_long,
  150954. _psy_noise_suppress,
  150955. _psy_compand_44,
  150956. _psy_compand_short_mapping,
  150957. _psy_compand_long_mapping,
  150958. {_noise_start_short_44,_noise_start_long_44},
  150959. {_noise_part_short_44,_noise_part_long_44},
  150960. _noise_thresh_44,
  150961. _psy_ath_floater,
  150962. _psy_ath_abs,
  150963. _psy_lowpass_44,
  150964. _psy_global_44,
  150965. _global_mapping_44,
  150966. NULL,
  150967. _floor_books,
  150968. _floor,
  150969. _floor_short_mapping_44,
  150970. _floor_long_mapping_44,
  150971. _mapres_template_44_uncoupled
  150972. };
  150973. ve_setup_data_template ve_setup_XX_stereo={
  150974. 2,
  150975. rate_mapping_X,
  150976. quality_mapping_8,
  150977. 2,
  150978. 0,
  150979. 8000,
  150980. blocksize_8,
  150981. blocksize_8,
  150982. _psy_tone_masteratt_8,
  150983. _psy_tone_0dB,
  150984. _psy_tone_suppress,
  150985. _vp_tonemask_adj_8,
  150986. NULL,
  150987. _vp_tonemask_adj_8,
  150988. _psy_noiseguards_8,
  150989. _psy_noisebias_8,
  150990. _psy_noisebias_8,
  150991. NULL,
  150992. NULL,
  150993. _psy_noise_suppress,
  150994. _psy_compand_8,
  150995. _psy_compand_8_mapping,
  150996. NULL,
  150997. {_noise_start_8,_noise_start_8},
  150998. {_noise_part_8,_noise_part_8},
  150999. _noise_thresh_5only,
  151000. _psy_ath_floater_8,
  151001. _psy_ath_abs_8,
  151002. _psy_lowpass_8,
  151003. _psy_global_44,
  151004. _global_mapping_8,
  151005. _psy_stereo_modes_8,
  151006. _floor_books,
  151007. _floor,
  151008. _floor_mapping_8,
  151009. NULL,
  151010. _mapres_template_8_stereo
  151011. };
  151012. ve_setup_data_template ve_setup_XX_uncoupled={
  151013. 2,
  151014. rate_mapping_X,
  151015. quality_mapping_8,
  151016. -1,
  151017. 0,
  151018. 8000,
  151019. blocksize_8,
  151020. blocksize_8,
  151021. _psy_tone_masteratt_8,
  151022. _psy_tone_0dB,
  151023. _psy_tone_suppress,
  151024. _vp_tonemask_adj_8,
  151025. NULL,
  151026. _vp_tonemask_adj_8,
  151027. _psy_noiseguards_8,
  151028. _psy_noisebias_8,
  151029. _psy_noisebias_8,
  151030. NULL,
  151031. NULL,
  151032. _psy_noise_suppress,
  151033. _psy_compand_8,
  151034. _psy_compand_8_mapping,
  151035. NULL,
  151036. {_noise_start_8,_noise_start_8},
  151037. {_noise_part_8,_noise_part_8},
  151038. _noise_thresh_5only,
  151039. _psy_ath_floater_8,
  151040. _psy_ath_abs_8,
  151041. _psy_lowpass_8,
  151042. _psy_global_44,
  151043. _global_mapping_8,
  151044. _psy_stereo_modes_8,
  151045. _floor_books,
  151046. _floor,
  151047. _floor_mapping_8,
  151048. NULL,
  151049. _mapres_template_8_uncoupled
  151050. };
  151051. /*** End of inlined file: setup_X.h ***/
  151052. static ve_setup_data_template *setup_list[]={
  151053. &ve_setup_44_stereo,
  151054. &ve_setup_44_uncoupled,
  151055. &ve_setup_32_stereo,
  151056. &ve_setup_32_uncoupled,
  151057. &ve_setup_22_stereo,
  151058. &ve_setup_22_uncoupled,
  151059. &ve_setup_16_stereo,
  151060. &ve_setup_16_uncoupled,
  151061. &ve_setup_11_stereo,
  151062. &ve_setup_11_uncoupled,
  151063. &ve_setup_8_stereo,
  151064. &ve_setup_8_uncoupled,
  151065. &ve_setup_X_stereo,
  151066. &ve_setup_X_uncoupled,
  151067. &ve_setup_XX_stereo,
  151068. &ve_setup_XX_uncoupled,
  151069. 0
  151070. };
  151071. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  151072. if(vi && vi->codec_setup){
  151073. vi->version=0;
  151074. vi->channels=ch;
  151075. vi->rate=rate;
  151076. return(0);
  151077. }
  151078. return(OV_EINVAL);
  151079. }
  151080. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  151081. static_codebook ***books,
  151082. vorbis_info_floor1 *in,
  151083. int *x){
  151084. int i,k,is=s;
  151085. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  151086. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151087. memcpy(f,in+x[is],sizeof(*f));
  151088. /* fill in the lowpass field, even if it's temporary */
  151089. f->n=ci->blocksizes[block]>>1;
  151090. /* books */
  151091. {
  151092. int partitions=f->partitions;
  151093. int maxclass=-1;
  151094. int maxbook=-1;
  151095. for(i=0;i<partitions;i++)
  151096. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  151097. for(i=0;i<=maxclass;i++){
  151098. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  151099. f->class_book[i]+=ci->books;
  151100. for(k=0;k<(1<<f->class_subs[i]);k++){
  151101. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  151102. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  151103. }
  151104. }
  151105. for(i=0;i<=maxbook;i++)
  151106. ci->book_param[ci->books++]=books[x[is]][i];
  151107. }
  151108. /* for now, we're only using floor 1 */
  151109. ci->floor_type[ci->floors]=1;
  151110. ci->floor_param[ci->floors]=f;
  151111. ci->floors++;
  151112. return;
  151113. }
  151114. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  151115. vorbis_info_psy_global *in,
  151116. double *x){
  151117. int i,is=s;
  151118. double ds=s-is;
  151119. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151120. vorbis_info_psy_global *g=&ci->psy_g_param;
  151121. memcpy(g,in+(int)x[is],sizeof(*g));
  151122. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151123. is=(int)ds;
  151124. ds-=is;
  151125. if(ds==0 && is>0){
  151126. is--;
  151127. ds=1.;
  151128. }
  151129. /* interpolate the trigger threshholds */
  151130. for(i=0;i<4;i++){
  151131. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  151132. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  151133. }
  151134. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  151135. return;
  151136. }
  151137. static void vorbis_encode_global_stereo(vorbis_info *vi,
  151138. highlevel_encode_setup *hi,
  151139. adj_stereo *p){
  151140. float s=hi->stereo_point_setting;
  151141. int i,is=s;
  151142. double ds=s-is;
  151143. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151144. vorbis_info_psy_global *g=&ci->psy_g_param;
  151145. if(p){
  151146. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  151147. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  151148. if(hi->managed){
  151149. /* interpolate the kHz threshholds */
  151150. for(i=0;i<PACKETBLOBS;i++){
  151151. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  151152. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151153. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151154. g->coupling_pkHz[i]=kHz;
  151155. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  151156. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151157. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151158. }
  151159. }else{
  151160. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  151161. for(i=0;i<PACKETBLOBS;i++){
  151162. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151163. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151164. g->coupling_pkHz[i]=kHz;
  151165. }
  151166. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  151167. for(i=0;i<PACKETBLOBS;i++){
  151168. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151169. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151170. }
  151171. }
  151172. }else{
  151173. for(i=0;i<PACKETBLOBS;i++){
  151174. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  151175. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  151176. }
  151177. }
  151178. return;
  151179. }
  151180. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  151181. int *nn_start,
  151182. int *nn_partition,
  151183. double *nn_thresh,
  151184. int block){
  151185. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151186. vorbis_info_psy *p=ci->psy_param[block];
  151187. highlevel_encode_setup *hi=&ci->hi;
  151188. int is=s;
  151189. if(block>=ci->psys)
  151190. ci->psys=block+1;
  151191. if(!p){
  151192. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  151193. ci->psy_param[block]=p;
  151194. }
  151195. memcpy(p,&_psy_info_template,sizeof(*p));
  151196. p->blockflag=block>>1;
  151197. if(hi->noise_normalize_p){
  151198. p->normal_channel_p=1;
  151199. p->normal_point_p=1;
  151200. p->normal_start=nn_start[is];
  151201. p->normal_partition=nn_partition[is];
  151202. p->normal_thresh=nn_thresh[is];
  151203. }
  151204. return;
  151205. }
  151206. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  151207. att3 *att,
  151208. int *max,
  151209. vp_adjblock *in){
  151210. int i,is=s;
  151211. double ds=s-is;
  151212. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151213. vorbis_info_psy *p=ci->psy_param[block];
  151214. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  151215. filling the values in here */
  151216. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  151217. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  151218. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  151219. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  151220. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  151221. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  151222. for(i=0;i<P_BANDS;i++)
  151223. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  151224. return;
  151225. }
  151226. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  151227. compandblock *in, double *x){
  151228. int i,is=s;
  151229. double ds=s-is;
  151230. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151231. vorbis_info_psy *p=ci->psy_param[block];
  151232. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151233. is=(int)ds;
  151234. ds-=is;
  151235. if(ds==0 && is>0){
  151236. is--;
  151237. ds=1.;
  151238. }
  151239. /* interpolate the compander settings */
  151240. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  151241. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  151242. return;
  151243. }
  151244. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  151245. int *suppress){
  151246. int is=s;
  151247. double ds=s-is;
  151248. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151249. vorbis_info_psy *p=ci->psy_param[block];
  151250. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151251. return;
  151252. }
  151253. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  151254. int *suppress,
  151255. noise3 *in,
  151256. noiseguard *guard,
  151257. double userbias){
  151258. int i,is=s,j;
  151259. double ds=s-is;
  151260. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151261. vorbis_info_psy *p=ci->psy_param[block];
  151262. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151263. p->noisewindowlomin=guard[block].lo;
  151264. p->noisewindowhimin=guard[block].hi;
  151265. p->noisewindowfixed=guard[block].fixed;
  151266. for(j=0;j<P_NOISECURVES;j++)
  151267. for(i=0;i<P_BANDS;i++)
  151268. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  151269. /* impulse blocks may take a user specified bias to boost the
  151270. nominal/high noise encoding depth */
  151271. for(j=0;j<P_NOISECURVES;j++){
  151272. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  151273. for(i=0;i<P_BANDS;i++){
  151274. p->noiseoff[j][i]+=userbias;
  151275. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  151276. }
  151277. }
  151278. return;
  151279. }
  151280. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  151281. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151282. vorbis_info_psy *p=ci->psy_param[block];
  151283. p->ath_adjatt=ci->hi.ath_floating_dB;
  151284. p->ath_maxatt=ci->hi.ath_absolute_dB;
  151285. return;
  151286. }
  151287. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  151288. int i;
  151289. for(i=0;i<ci->books;i++)
  151290. if(ci->book_param[i]==book)return(i);
  151291. return(ci->books++);
  151292. }
  151293. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  151294. int *shortb,int *longb){
  151295. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151296. int is=s;
  151297. int blockshort=shortb[is];
  151298. int blocklong=longb[is];
  151299. ci->blocksizes[0]=blockshort;
  151300. ci->blocksizes[1]=blocklong;
  151301. }
  151302. static void vorbis_encode_residue_setup(vorbis_info *vi,
  151303. int number, int block,
  151304. vorbis_residue_template *res){
  151305. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151306. int i,n;
  151307. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  151308. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  151309. memcpy(r,res->res,sizeof(*r));
  151310. if(ci->residues<=number)ci->residues=number+1;
  151311. switch(ci->blocksizes[block]){
  151312. case 64:case 128:case 256:
  151313. r->grouping=16;
  151314. break;
  151315. default:
  151316. r->grouping=32;
  151317. break;
  151318. }
  151319. ci->residue_type[number]=res->res_type;
  151320. /* to be adjusted by lowpass/pointlimit later */
  151321. n=r->end=ci->blocksizes[block]>>1;
  151322. if(res->res_type==2)
  151323. n=r->end*=vi->channels;
  151324. /* fill in all the books */
  151325. {
  151326. int booklist=0,k;
  151327. if(ci->hi.managed){
  151328. for(i=0;i<r->partitions;i++)
  151329. for(k=0;k<3;k++)
  151330. if(res->books_base_managed->books[i][k])
  151331. r->secondstages[i]|=(1<<k);
  151332. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  151333. ci->book_param[r->groupbook]=res->book_aux_managed;
  151334. for(i=0;i<r->partitions;i++){
  151335. for(k=0;k<3;k++){
  151336. if(res->books_base_managed->books[i][k]){
  151337. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  151338. r->booklist[booklist++]=bookid;
  151339. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  151340. }
  151341. }
  151342. }
  151343. }else{
  151344. for(i=0;i<r->partitions;i++)
  151345. for(k=0;k<3;k++)
  151346. if(res->books_base->books[i][k])
  151347. r->secondstages[i]|=(1<<k);
  151348. r->groupbook=book_dup_or_new(ci,res->book_aux);
  151349. ci->book_param[r->groupbook]=res->book_aux;
  151350. for(i=0;i<r->partitions;i++){
  151351. for(k=0;k<3;k++){
  151352. if(res->books_base->books[i][k]){
  151353. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  151354. r->booklist[booklist++]=bookid;
  151355. ci->book_param[bookid]=res->books_base->books[i][k];
  151356. }
  151357. }
  151358. }
  151359. }
  151360. }
  151361. /* lowpass setup/pointlimit */
  151362. {
  151363. double freq=ci->hi.lowpass_kHz*1000.;
  151364. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  151365. double nyq=vi->rate/2.;
  151366. long blocksize=ci->blocksizes[block]>>1;
  151367. /* lowpass needs to be set in the floor and the residue. */
  151368. if(freq>nyq)freq=nyq;
  151369. /* in the floor, the granularity can be very fine; it doesn't alter
  151370. the encoding structure, only the samples used to fit the floor
  151371. approximation */
  151372. f->n=freq/nyq*blocksize;
  151373. /* this res may by limited by the maximum pointlimit of the mode,
  151374. not the lowpass. the floor is always lowpass limited. */
  151375. if(res->limit_type){
  151376. if(ci->hi.managed)
  151377. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  151378. else
  151379. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  151380. if(freq>nyq)freq=nyq;
  151381. }
  151382. /* in the residue, we're constrained, physically, by partition
  151383. boundaries. We still lowpass 'wherever', but we have to round up
  151384. here to next boundary, or the vorbis spec will round it *down* to
  151385. previous boundary in encode/decode */
  151386. if(ci->residue_type[block]==2)
  151387. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  151388. r->grouping;
  151389. else
  151390. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  151391. r->grouping;
  151392. }
  151393. }
  151394. /* we assume two maps in this encoder */
  151395. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  151396. vorbis_mapping_template *maps){
  151397. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151398. int i,j,is=s,modes=2;
  151399. vorbis_info_mapping0 *map=maps[is].map;
  151400. vorbis_info_mode *mode=_mode_template;
  151401. vorbis_residue_template *res=maps[is].res;
  151402. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  151403. for(i=0;i<modes;i++){
  151404. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  151405. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  151406. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  151407. if(i>=ci->modes)ci->modes=i+1;
  151408. ci->map_type[i]=0;
  151409. memcpy(ci->map_param[i],map+i,sizeof(*map));
  151410. if(i>=ci->maps)ci->maps=i+1;
  151411. for(j=0;j<map[i].submaps;j++)
  151412. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  151413. ,res+map[i].residuesubmap[j]);
  151414. }
  151415. }
  151416. static double setting_to_approx_bitrate(vorbis_info *vi){
  151417. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151418. highlevel_encode_setup *hi=&ci->hi;
  151419. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  151420. int is=hi->base_setting;
  151421. double ds=hi->base_setting-is;
  151422. int ch=vi->channels;
  151423. double *r=setup->rate_mapping;
  151424. if(r==NULL)
  151425. return(-1);
  151426. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  151427. }
  151428. static void get_setup_template(vorbis_info *vi,
  151429. long ch,long srate,
  151430. double req,int q_or_bitrate){
  151431. int i=0,j;
  151432. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151433. highlevel_encode_setup *hi=&ci->hi;
  151434. if(q_or_bitrate)req/=ch;
  151435. while(setup_list[i]){
  151436. if(setup_list[i]->coupling_restriction==-1 ||
  151437. setup_list[i]->coupling_restriction==ch){
  151438. if(srate>=setup_list[i]->samplerate_min_restriction &&
  151439. srate<=setup_list[i]->samplerate_max_restriction){
  151440. int mappings=setup_list[i]->mappings;
  151441. double *map=(q_or_bitrate?
  151442. setup_list[i]->rate_mapping:
  151443. setup_list[i]->quality_mapping);
  151444. /* the template matches. Does the requested quality mode
  151445. fall within this template's modes? */
  151446. if(req<map[0]){++i;continue;}
  151447. if(req>map[setup_list[i]->mappings]){++i;continue;}
  151448. for(j=0;j<mappings;j++)
  151449. if(req>=map[j] && req<map[j+1])break;
  151450. /* an all-points match */
  151451. hi->setup=setup_list[i];
  151452. if(j==mappings)
  151453. hi->base_setting=j-.001;
  151454. else{
  151455. float low=map[j];
  151456. float high=map[j+1];
  151457. float del=(req-low)/(high-low);
  151458. hi->base_setting=j+del;
  151459. }
  151460. return;
  151461. }
  151462. }
  151463. i++;
  151464. }
  151465. hi->setup=NULL;
  151466. }
  151467. /* encoders will need to use vorbis_info_init beforehand and call
  151468. vorbis_info clear when all done */
  151469. /* two interfaces; this, more detailed one, and later a convenience
  151470. layer on top */
  151471. /* the final setup call */
  151472. int vorbis_encode_setup_init(vorbis_info *vi){
  151473. int i0=0,singleblock=0;
  151474. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151475. ve_setup_data_template *setup=NULL;
  151476. highlevel_encode_setup *hi=&ci->hi;
  151477. if(ci==NULL)return(OV_EINVAL);
  151478. if(!hi->impulse_block_p)i0=1;
  151479. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  151480. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  151481. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  151482. /* again, bound this to avoid the app shooting itself int he foot
  151483. too badly */
  151484. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  151485. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  151486. /* get the appropriate setup template; matches the fetch in previous
  151487. stages */
  151488. setup=(ve_setup_data_template *)hi->setup;
  151489. if(setup==NULL)return(OV_EINVAL);
  151490. hi->set_in_stone=1;
  151491. /* choose block sizes from configured sizes as well as paying
  151492. attention to long_block_p and short_block_p. If the configured
  151493. short and long blocks are the same length, we set long_block_p
  151494. and unset short_block_p */
  151495. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  151496. setup->blocksize_short,
  151497. setup->blocksize_long);
  151498. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  151499. /* floor setup; choose proper floor params. Allocated on the floor
  151500. stack in order; if we alloc only long floor, it's 0 */
  151501. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  151502. setup->floor_books,
  151503. setup->floor_params,
  151504. setup->floor_short_mapping);
  151505. if(!singleblock)
  151506. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  151507. setup->floor_books,
  151508. setup->floor_params,
  151509. setup->floor_long_mapping);
  151510. /* setup of [mostly] short block detection and stereo*/
  151511. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  151512. setup->global_params,
  151513. setup->global_mapping);
  151514. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  151515. /* basic psych setup and noise normalization */
  151516. vorbis_encode_psyset_setup(vi,hi->short_setting,
  151517. setup->psy_noise_normal_start[0],
  151518. setup->psy_noise_normal_partition[0],
  151519. setup->psy_noise_normal_thresh,
  151520. 0);
  151521. vorbis_encode_psyset_setup(vi,hi->short_setting,
  151522. setup->psy_noise_normal_start[0],
  151523. setup->psy_noise_normal_partition[0],
  151524. setup->psy_noise_normal_thresh,
  151525. 1);
  151526. if(!singleblock){
  151527. vorbis_encode_psyset_setup(vi,hi->long_setting,
  151528. setup->psy_noise_normal_start[1],
  151529. setup->psy_noise_normal_partition[1],
  151530. setup->psy_noise_normal_thresh,
  151531. 2);
  151532. vorbis_encode_psyset_setup(vi,hi->long_setting,
  151533. setup->psy_noise_normal_start[1],
  151534. setup->psy_noise_normal_partition[1],
  151535. setup->psy_noise_normal_thresh,
  151536. 3);
  151537. }
  151538. /* tone masking setup */
  151539. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  151540. setup->psy_tone_masteratt,
  151541. setup->psy_tone_0dB,
  151542. setup->psy_tone_adj_impulse);
  151543. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  151544. setup->psy_tone_masteratt,
  151545. setup->psy_tone_0dB,
  151546. setup->psy_tone_adj_other);
  151547. if(!singleblock){
  151548. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  151549. setup->psy_tone_masteratt,
  151550. setup->psy_tone_0dB,
  151551. setup->psy_tone_adj_other);
  151552. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  151553. setup->psy_tone_masteratt,
  151554. setup->psy_tone_0dB,
  151555. setup->psy_tone_adj_long);
  151556. }
  151557. /* noise companding setup */
  151558. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  151559. setup->psy_noise_compand,
  151560. setup->psy_noise_compand_short_mapping);
  151561. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  151562. setup->psy_noise_compand,
  151563. setup->psy_noise_compand_short_mapping);
  151564. if(!singleblock){
  151565. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  151566. setup->psy_noise_compand,
  151567. setup->psy_noise_compand_long_mapping);
  151568. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  151569. setup->psy_noise_compand,
  151570. setup->psy_noise_compand_long_mapping);
  151571. }
  151572. /* peak guarding setup */
  151573. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  151574. setup->psy_tone_dBsuppress);
  151575. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  151576. setup->psy_tone_dBsuppress);
  151577. if(!singleblock){
  151578. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  151579. setup->psy_tone_dBsuppress);
  151580. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  151581. setup->psy_tone_dBsuppress);
  151582. }
  151583. /* noise bias setup */
  151584. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  151585. setup->psy_noise_dBsuppress,
  151586. setup->psy_noise_bias_impulse,
  151587. setup->psy_noiseguards,
  151588. (i0==0?hi->impulse_noisetune:0.));
  151589. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  151590. setup->psy_noise_dBsuppress,
  151591. setup->psy_noise_bias_padding,
  151592. setup->psy_noiseguards,0.);
  151593. if(!singleblock){
  151594. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  151595. setup->psy_noise_dBsuppress,
  151596. setup->psy_noise_bias_trans,
  151597. setup->psy_noiseguards,0.);
  151598. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  151599. setup->psy_noise_dBsuppress,
  151600. setup->psy_noise_bias_long,
  151601. setup->psy_noiseguards,0.);
  151602. }
  151603. vorbis_encode_ath_setup(vi,0);
  151604. vorbis_encode_ath_setup(vi,1);
  151605. if(!singleblock){
  151606. vorbis_encode_ath_setup(vi,2);
  151607. vorbis_encode_ath_setup(vi,3);
  151608. }
  151609. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  151610. /* set bitrate readonlies and management */
  151611. if(hi->bitrate_av>0)
  151612. vi->bitrate_nominal=hi->bitrate_av;
  151613. else{
  151614. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  151615. }
  151616. vi->bitrate_lower=hi->bitrate_min;
  151617. vi->bitrate_upper=hi->bitrate_max;
  151618. if(hi->bitrate_av)
  151619. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  151620. else
  151621. vi->bitrate_window=0.;
  151622. if(hi->managed){
  151623. ci->bi.avg_rate=hi->bitrate_av;
  151624. ci->bi.min_rate=hi->bitrate_min;
  151625. ci->bi.max_rate=hi->bitrate_max;
  151626. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  151627. ci->bi.reservoir_bias=
  151628. hi->bitrate_reservoir_bias;
  151629. ci->bi.slew_damp=hi->bitrate_av_damp;
  151630. }
  151631. return(0);
  151632. }
  151633. static int vorbis_encode_setup_setting(vorbis_info *vi,
  151634. long channels,
  151635. long rate){
  151636. int ret=0,i,is;
  151637. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151638. highlevel_encode_setup *hi=&ci->hi;
  151639. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  151640. double ds;
  151641. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  151642. if(ret)return(ret);
  151643. is=hi->base_setting;
  151644. ds=hi->base_setting-is;
  151645. hi->short_setting=hi->base_setting;
  151646. hi->long_setting=hi->base_setting;
  151647. hi->managed=0;
  151648. hi->impulse_block_p=1;
  151649. hi->noise_normalize_p=1;
  151650. hi->stereo_point_setting=hi->base_setting;
  151651. hi->lowpass_kHz=
  151652. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  151653. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  151654. setup->psy_ath_float[is+1]*ds;
  151655. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  151656. setup->psy_ath_abs[is+1]*ds;
  151657. hi->amplitude_track_dBpersec=-6.;
  151658. hi->trigger_setting=hi->base_setting;
  151659. for(i=0;i<4;i++){
  151660. hi->block[i].tone_mask_setting=hi->base_setting;
  151661. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  151662. hi->block[i].noise_bias_setting=hi->base_setting;
  151663. hi->block[i].noise_compand_setting=hi->base_setting;
  151664. }
  151665. return(ret);
  151666. }
  151667. int vorbis_encode_setup_vbr(vorbis_info *vi,
  151668. long channels,
  151669. long rate,
  151670. float quality){
  151671. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151672. highlevel_encode_setup *hi=&ci->hi;
  151673. quality+=.0000001;
  151674. if(quality>=1.)quality=.9999;
  151675. get_setup_template(vi,channels,rate,quality,0);
  151676. if(!hi->setup)return OV_EIMPL;
  151677. return vorbis_encode_setup_setting(vi,channels,rate);
  151678. }
  151679. int vorbis_encode_init_vbr(vorbis_info *vi,
  151680. long channels,
  151681. long rate,
  151682. float base_quality /* 0. to 1. */
  151683. ){
  151684. int ret=0;
  151685. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  151686. if(ret){
  151687. vorbis_info_clear(vi);
  151688. return ret;
  151689. }
  151690. ret=vorbis_encode_setup_init(vi);
  151691. if(ret)
  151692. vorbis_info_clear(vi);
  151693. return(ret);
  151694. }
  151695. int vorbis_encode_setup_managed(vorbis_info *vi,
  151696. long channels,
  151697. long rate,
  151698. long max_bitrate,
  151699. long nominal_bitrate,
  151700. long min_bitrate){
  151701. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151702. highlevel_encode_setup *hi=&ci->hi;
  151703. double tnominal=nominal_bitrate;
  151704. int ret=0;
  151705. if(nominal_bitrate<=0.){
  151706. if(max_bitrate>0.){
  151707. if(min_bitrate>0.)
  151708. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  151709. else
  151710. nominal_bitrate=max_bitrate*.875;
  151711. }else{
  151712. if(min_bitrate>0.){
  151713. nominal_bitrate=min_bitrate;
  151714. }else{
  151715. return(OV_EINVAL);
  151716. }
  151717. }
  151718. }
  151719. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  151720. if(!hi->setup)return OV_EIMPL;
  151721. ret=vorbis_encode_setup_setting(vi,channels,rate);
  151722. if(ret){
  151723. vorbis_info_clear(vi);
  151724. return ret;
  151725. }
  151726. /* initialize management with sane defaults */
  151727. hi->managed=1;
  151728. hi->bitrate_min=min_bitrate;
  151729. hi->bitrate_max=max_bitrate;
  151730. hi->bitrate_av=tnominal;
  151731. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  151732. hi->bitrate_reservoir=nominal_bitrate*2;
  151733. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  151734. return(ret);
  151735. }
  151736. int vorbis_encode_init(vorbis_info *vi,
  151737. long channels,
  151738. long rate,
  151739. long max_bitrate,
  151740. long nominal_bitrate,
  151741. long min_bitrate){
  151742. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  151743. max_bitrate,
  151744. nominal_bitrate,
  151745. min_bitrate);
  151746. if(ret){
  151747. vorbis_info_clear(vi);
  151748. return(ret);
  151749. }
  151750. ret=vorbis_encode_setup_init(vi);
  151751. if(ret)
  151752. vorbis_info_clear(vi);
  151753. return(ret);
  151754. }
  151755. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  151756. if(vi){
  151757. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151758. highlevel_encode_setup *hi=&ci->hi;
  151759. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  151760. if(setp && hi->set_in_stone)return(OV_EINVAL);
  151761. switch(number){
  151762. /* now deprecated *****************/
  151763. case OV_ECTL_RATEMANAGE_GET:
  151764. {
  151765. struct ovectl_ratemanage_arg *ai=
  151766. (struct ovectl_ratemanage_arg *)arg;
  151767. ai->management_active=hi->managed;
  151768. ai->bitrate_hard_window=ai->bitrate_av_window=
  151769. (double)hi->bitrate_reservoir/vi->rate;
  151770. ai->bitrate_av_window_center=1.;
  151771. ai->bitrate_hard_min=hi->bitrate_min;
  151772. ai->bitrate_hard_max=hi->bitrate_max;
  151773. ai->bitrate_av_lo=hi->bitrate_av;
  151774. ai->bitrate_av_hi=hi->bitrate_av;
  151775. }
  151776. return(0);
  151777. /* now deprecated *****************/
  151778. case OV_ECTL_RATEMANAGE_SET:
  151779. {
  151780. struct ovectl_ratemanage_arg *ai=
  151781. (struct ovectl_ratemanage_arg *)arg;
  151782. if(ai==NULL){
  151783. hi->managed=0;
  151784. }else{
  151785. hi->managed=ai->management_active;
  151786. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  151787. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  151788. }
  151789. }
  151790. return 0;
  151791. /* now deprecated *****************/
  151792. case OV_ECTL_RATEMANAGE_AVG:
  151793. {
  151794. struct ovectl_ratemanage_arg *ai=
  151795. (struct ovectl_ratemanage_arg *)arg;
  151796. if(ai==NULL){
  151797. hi->bitrate_av=0;
  151798. }else{
  151799. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  151800. }
  151801. }
  151802. return(0);
  151803. /* now deprecated *****************/
  151804. case OV_ECTL_RATEMANAGE_HARD:
  151805. {
  151806. struct ovectl_ratemanage_arg *ai=
  151807. (struct ovectl_ratemanage_arg *)arg;
  151808. if(ai==NULL){
  151809. hi->bitrate_min=0;
  151810. hi->bitrate_max=0;
  151811. }else{
  151812. hi->bitrate_min=ai->bitrate_hard_min;
  151813. hi->bitrate_max=ai->bitrate_hard_max;
  151814. hi->bitrate_reservoir=ai->bitrate_hard_window*
  151815. (hi->bitrate_max+hi->bitrate_min)*.5;
  151816. }
  151817. if(hi->bitrate_reservoir<128.)
  151818. hi->bitrate_reservoir=128.;
  151819. }
  151820. return(0);
  151821. /* replacement ratemanage interface */
  151822. case OV_ECTL_RATEMANAGE2_GET:
  151823. {
  151824. struct ovectl_ratemanage2_arg *ai=
  151825. (struct ovectl_ratemanage2_arg *)arg;
  151826. if(ai==NULL)return OV_EINVAL;
  151827. ai->management_active=hi->managed;
  151828. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  151829. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  151830. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  151831. ai->bitrate_average_damping=hi->bitrate_av_damp;
  151832. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  151833. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  151834. }
  151835. return (0);
  151836. case OV_ECTL_RATEMANAGE2_SET:
  151837. {
  151838. struct ovectl_ratemanage2_arg *ai=
  151839. (struct ovectl_ratemanage2_arg *)arg;
  151840. if(ai==NULL){
  151841. hi->managed=0;
  151842. }else{
  151843. /* sanity check; only catch invariant violations */
  151844. if(ai->bitrate_limit_min_kbps>0 &&
  151845. ai->bitrate_average_kbps>0 &&
  151846. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  151847. return OV_EINVAL;
  151848. if(ai->bitrate_limit_max_kbps>0 &&
  151849. ai->bitrate_average_kbps>0 &&
  151850. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  151851. return OV_EINVAL;
  151852. if(ai->bitrate_limit_min_kbps>0 &&
  151853. ai->bitrate_limit_max_kbps>0 &&
  151854. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  151855. return OV_EINVAL;
  151856. if(ai->bitrate_average_damping <= 0.)
  151857. return OV_EINVAL;
  151858. if(ai->bitrate_limit_reservoir_bits < 0)
  151859. return OV_EINVAL;
  151860. if(ai->bitrate_limit_reservoir_bias < 0.)
  151861. return OV_EINVAL;
  151862. if(ai->bitrate_limit_reservoir_bias > 1.)
  151863. return OV_EINVAL;
  151864. hi->managed=ai->management_active;
  151865. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  151866. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  151867. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  151868. hi->bitrate_av_damp=ai->bitrate_average_damping;
  151869. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  151870. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  151871. }
  151872. }
  151873. return 0;
  151874. case OV_ECTL_LOWPASS_GET:
  151875. {
  151876. double *farg=(double *)arg;
  151877. *farg=hi->lowpass_kHz;
  151878. }
  151879. return(0);
  151880. case OV_ECTL_LOWPASS_SET:
  151881. {
  151882. double *farg=(double *)arg;
  151883. hi->lowpass_kHz=*farg;
  151884. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  151885. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  151886. }
  151887. return(0);
  151888. case OV_ECTL_IBLOCK_GET:
  151889. {
  151890. double *farg=(double *)arg;
  151891. *farg=hi->impulse_noisetune;
  151892. }
  151893. return(0);
  151894. case OV_ECTL_IBLOCK_SET:
  151895. {
  151896. double *farg=(double *)arg;
  151897. hi->impulse_noisetune=*farg;
  151898. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  151899. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  151900. }
  151901. return(0);
  151902. }
  151903. return(OV_EIMPL);
  151904. }
  151905. return(OV_EINVAL);
  151906. }
  151907. #endif
  151908. /*** End of inlined file: vorbisenc.c ***/
  151909. /*** Start of inlined file: vorbisfile.c ***/
  151910. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  151911. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151912. // tasks..
  151913. #if JUCE_MSVC
  151914. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151915. #endif
  151916. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  151917. #if JUCE_USE_OGGVORBIS
  151918. #include <stdlib.h>
  151919. #include <stdio.h>
  151920. #include <errno.h>
  151921. #include <string.h>
  151922. #include <math.h>
  151923. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  151924. one logical bitstream arranged end to end (the only form of Ogg
  151925. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  151926. multiplexing] is not allowed in Vorbis) */
  151927. /* A Vorbis file can be played beginning to end (streamed) without
  151928. worrying ahead of time about chaining (see decoder_example.c). If
  151929. we have the whole file, however, and want random access
  151930. (seeking/scrubbing) or desire to know the total length/time of a
  151931. file, we need to account for the possibility of chaining. */
  151932. /* We can handle things a number of ways; we can determine the entire
  151933. bitstream structure right off the bat, or find pieces on demand.
  151934. This example determines and caches structure for the entire
  151935. bitstream, but builds a virtual decoder on the fly when moving
  151936. between links in the chain. */
  151937. /* There are also different ways to implement seeking. Enough
  151938. information exists in an Ogg bitstream to seek to
  151939. sample-granularity positions in the output. Or, one can seek by
  151940. picking some portion of the stream roughly in the desired area if
  151941. we only want coarse navigation through the stream. */
  151942. /*************************************************************************
  151943. * Many, many internal helpers. The intention is not to be confusing;
  151944. * rampant duplication and monolithic function implementation would be
  151945. * harder to understand anyway. The high level functions are last. Begin
  151946. * grokking near the end of the file */
  151947. /* read a little more data from the file/pipe into the ogg_sync framer
  151948. */
  151949. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  151950. over 8k gets what they deserve */
  151951. static long _get_data(OggVorbis_File *vf){
  151952. errno=0;
  151953. if(vf->datasource){
  151954. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  151955. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  151956. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  151957. if(bytes==0 && errno)return(-1);
  151958. return(bytes);
  151959. }else
  151960. return(0);
  151961. }
  151962. /* save a tiny smidge of verbosity to make the code more readable */
  151963. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  151964. if(vf->datasource){
  151965. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  151966. vf->offset=offset;
  151967. ogg_sync_reset(&vf->oy);
  151968. }else{
  151969. /* shouldn't happen unless someone writes a broken callback */
  151970. return;
  151971. }
  151972. }
  151973. /* The read/seek functions track absolute position within the stream */
  151974. /* from the head of the stream, get the next page. boundary specifies
  151975. if the function is allowed to fetch more data from the stream (and
  151976. how much) or only use internally buffered data.
  151977. boundary: -1) unbounded search
  151978. 0) read no additional data; use cached only
  151979. n) search for a new page beginning for n bytes
  151980. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  151981. n) found a page at absolute offset n */
  151982. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  151983. ogg_int64_t boundary){
  151984. if(boundary>0)boundary+=vf->offset;
  151985. while(1){
  151986. long more;
  151987. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  151988. more=ogg_sync_pageseek(&vf->oy,og);
  151989. if(more<0){
  151990. /* skipped n bytes */
  151991. vf->offset-=more;
  151992. }else{
  151993. if(more==0){
  151994. /* send more paramedics */
  151995. if(!boundary)return(OV_FALSE);
  151996. {
  151997. long ret=_get_data(vf);
  151998. if(ret==0)return(OV_EOF);
  151999. if(ret<0)return(OV_EREAD);
  152000. }
  152001. }else{
  152002. /* got a page. Return the offset at the page beginning,
  152003. advance the internal offset past the page end */
  152004. ogg_int64_t ret=vf->offset;
  152005. vf->offset+=more;
  152006. return(ret);
  152007. }
  152008. }
  152009. }
  152010. }
  152011. /* find the latest page beginning before the current stream cursor
  152012. position. Much dirtier than the above as Ogg doesn't have any
  152013. backward search linkage. no 'readp' as it will certainly have to
  152014. read. */
  152015. /* returns offset or OV_EREAD, OV_FAULT */
  152016. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  152017. ogg_int64_t begin=vf->offset;
  152018. ogg_int64_t end=begin;
  152019. ogg_int64_t ret;
  152020. ogg_int64_t offset=-1;
  152021. while(offset==-1){
  152022. begin-=CHUNKSIZE;
  152023. if(begin<0)
  152024. begin=0;
  152025. _seek_helper(vf,begin);
  152026. while(vf->offset<end){
  152027. ret=_get_next_page(vf,og,end-vf->offset);
  152028. if(ret==OV_EREAD)return(OV_EREAD);
  152029. if(ret<0){
  152030. break;
  152031. }else{
  152032. offset=ret;
  152033. }
  152034. }
  152035. }
  152036. /* we have the offset. Actually snork and hold the page now */
  152037. _seek_helper(vf,offset);
  152038. ret=_get_next_page(vf,og,CHUNKSIZE);
  152039. if(ret<0)
  152040. /* this shouldn't be possible */
  152041. return(OV_EFAULT);
  152042. return(offset);
  152043. }
  152044. /* finds each bitstream link one at a time using a bisection search
  152045. (has to begin by knowing the offset of the lb's initial page).
  152046. Recurses for each link so it can alloc the link storage after
  152047. finding them all, then unroll and fill the cache at the same time */
  152048. static int _bisect_forward_serialno(OggVorbis_File *vf,
  152049. ogg_int64_t begin,
  152050. ogg_int64_t searched,
  152051. ogg_int64_t end,
  152052. long currentno,
  152053. long m){
  152054. ogg_int64_t endsearched=end;
  152055. ogg_int64_t next=end;
  152056. ogg_page og;
  152057. ogg_int64_t ret;
  152058. /* the below guards against garbage seperating the last and
  152059. first pages of two links. */
  152060. while(searched<endsearched){
  152061. ogg_int64_t bisect;
  152062. if(endsearched-searched<CHUNKSIZE){
  152063. bisect=searched;
  152064. }else{
  152065. bisect=(searched+endsearched)/2;
  152066. }
  152067. _seek_helper(vf,bisect);
  152068. ret=_get_next_page(vf,&og,-1);
  152069. if(ret==OV_EREAD)return(OV_EREAD);
  152070. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  152071. endsearched=bisect;
  152072. if(ret>=0)next=ret;
  152073. }else{
  152074. searched=ret+og.header_len+og.body_len;
  152075. }
  152076. }
  152077. _seek_helper(vf,next);
  152078. ret=_get_next_page(vf,&og,-1);
  152079. if(ret==OV_EREAD)return(OV_EREAD);
  152080. if(searched>=end || ret<0){
  152081. vf->links=m+1;
  152082. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  152083. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  152084. vf->offsets[m+1]=searched;
  152085. }else{
  152086. ret=_bisect_forward_serialno(vf,next,vf->offset,
  152087. end,ogg_page_serialno(&og),m+1);
  152088. if(ret==OV_EREAD)return(OV_EREAD);
  152089. }
  152090. vf->offsets[m]=begin;
  152091. vf->serialnos[m]=currentno;
  152092. return(0);
  152093. }
  152094. /* uses the local ogg_stream storage in vf; this is important for
  152095. non-streaming input sources */
  152096. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  152097. long *serialno,ogg_page *og_ptr){
  152098. ogg_page og;
  152099. ogg_packet op;
  152100. int i,ret;
  152101. if(!og_ptr){
  152102. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  152103. if(llret==OV_EREAD)return(OV_EREAD);
  152104. if(llret<0)return OV_ENOTVORBIS;
  152105. og_ptr=&og;
  152106. }
  152107. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  152108. if(serialno)*serialno=vf->os.serialno;
  152109. vf->ready_state=STREAMSET;
  152110. /* extract the initial header from the first page and verify that the
  152111. Ogg bitstream is in fact Vorbis data */
  152112. vorbis_info_init(vi);
  152113. vorbis_comment_init(vc);
  152114. i=0;
  152115. while(i<3){
  152116. ogg_stream_pagein(&vf->os,og_ptr);
  152117. while(i<3){
  152118. int result=ogg_stream_packetout(&vf->os,&op);
  152119. if(result==0)break;
  152120. if(result==-1){
  152121. ret=OV_EBADHEADER;
  152122. goto bail_header;
  152123. }
  152124. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  152125. goto bail_header;
  152126. }
  152127. i++;
  152128. }
  152129. if(i<3)
  152130. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  152131. ret=OV_EBADHEADER;
  152132. goto bail_header;
  152133. }
  152134. }
  152135. return 0;
  152136. bail_header:
  152137. vorbis_info_clear(vi);
  152138. vorbis_comment_clear(vc);
  152139. vf->ready_state=OPENED;
  152140. return ret;
  152141. }
  152142. /* last step of the OggVorbis_File initialization; get all the
  152143. vorbis_info structs and PCM positions. Only called by the seekable
  152144. initialization (local stream storage is hacked slightly; pay
  152145. attention to how that's done) */
  152146. /* this is void and does not propogate errors up because we want to be
  152147. able to open and use damaged bitstreams as well as we can. Just
  152148. watch out for missing information for links in the OggVorbis_File
  152149. struct */
  152150. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  152151. ogg_page og;
  152152. int i;
  152153. ogg_int64_t ret;
  152154. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  152155. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  152156. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  152157. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  152158. for(i=0;i<vf->links;i++){
  152159. if(i==0){
  152160. /* we already grabbed the initial header earlier. Just set the offset */
  152161. vf->dataoffsets[i]=dataoffset;
  152162. _seek_helper(vf,dataoffset);
  152163. }else{
  152164. /* seek to the location of the initial header */
  152165. _seek_helper(vf,vf->offsets[i]);
  152166. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  152167. vf->dataoffsets[i]=-1;
  152168. }else{
  152169. vf->dataoffsets[i]=vf->offset;
  152170. }
  152171. }
  152172. /* fetch beginning PCM offset */
  152173. if(vf->dataoffsets[i]!=-1){
  152174. ogg_int64_t accumulated=0;
  152175. long lastblock=-1;
  152176. int result;
  152177. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  152178. while(1){
  152179. ogg_packet op;
  152180. ret=_get_next_page(vf,&og,-1);
  152181. if(ret<0)
  152182. /* this should not be possible unless the file is
  152183. truncated/mangled */
  152184. break;
  152185. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  152186. break;
  152187. /* count blocksizes of all frames in the page */
  152188. ogg_stream_pagein(&vf->os,&og);
  152189. while((result=ogg_stream_packetout(&vf->os,&op))){
  152190. if(result>0){ /* ignore holes */
  152191. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  152192. if(lastblock!=-1)
  152193. accumulated+=(lastblock+thisblock)>>2;
  152194. lastblock=thisblock;
  152195. }
  152196. }
  152197. if(ogg_page_granulepos(&og)!=-1){
  152198. /* pcm offset of last packet on the first audio page */
  152199. accumulated= ogg_page_granulepos(&og)-accumulated;
  152200. break;
  152201. }
  152202. }
  152203. /* less than zero? This is a stream with samples trimmed off
  152204. the beginning, a normal occurrence; set the offset to zero */
  152205. if(accumulated<0)accumulated=0;
  152206. vf->pcmlengths[i*2]=accumulated;
  152207. }
  152208. /* get the PCM length of this link. To do this,
  152209. get the last page of the stream */
  152210. {
  152211. ogg_int64_t end=vf->offsets[i+1];
  152212. _seek_helper(vf,end);
  152213. while(1){
  152214. ret=_get_prev_page(vf,&og);
  152215. if(ret<0){
  152216. /* this should not be possible */
  152217. vorbis_info_clear(vf->vi+i);
  152218. vorbis_comment_clear(vf->vc+i);
  152219. break;
  152220. }
  152221. if(ogg_page_granulepos(&og)!=-1){
  152222. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  152223. break;
  152224. }
  152225. vf->offset=ret;
  152226. }
  152227. }
  152228. }
  152229. }
  152230. static int _make_decode_ready(OggVorbis_File *vf){
  152231. if(vf->ready_state>STREAMSET)return 0;
  152232. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  152233. if(vf->seekable){
  152234. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  152235. return OV_EBADLINK;
  152236. }else{
  152237. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  152238. return OV_EBADLINK;
  152239. }
  152240. vorbis_block_init(&vf->vd,&vf->vb);
  152241. vf->ready_state=INITSET;
  152242. vf->bittrack=0.f;
  152243. vf->samptrack=0.f;
  152244. return 0;
  152245. }
  152246. static int _open_seekable2(OggVorbis_File *vf){
  152247. long serialno=vf->current_serialno;
  152248. ogg_int64_t dataoffset=vf->offset, end;
  152249. ogg_page og;
  152250. /* we're partially open and have a first link header state in
  152251. storage in vf */
  152252. /* we can seek, so set out learning all about this file */
  152253. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  152254. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  152255. /* We get the offset for the last page of the physical bitstream.
  152256. Most OggVorbis files will contain a single logical bitstream */
  152257. end=_get_prev_page(vf,&og);
  152258. if(end<0)return(end);
  152259. /* more than one logical bitstream? */
  152260. if(ogg_page_serialno(&og)!=serialno){
  152261. /* Chained bitstream. Bisect-search each logical bitstream
  152262. section. Do so based on serial number only */
  152263. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  152264. }else{
  152265. /* Only one logical bitstream */
  152266. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  152267. }
  152268. /* the initial header memory is referenced by vf after; don't free it */
  152269. _prefetch_all_headers(vf,dataoffset);
  152270. return(ov_raw_seek(vf,0));
  152271. }
  152272. /* clear out the current logical bitstream decoder */
  152273. static void _decode_clear(OggVorbis_File *vf){
  152274. vorbis_dsp_clear(&vf->vd);
  152275. vorbis_block_clear(&vf->vb);
  152276. vf->ready_state=OPENED;
  152277. }
  152278. /* fetch and process a packet. Handles the case where we're at a
  152279. bitstream boundary and dumps the decoding machine. If the decoding
  152280. machine is unloaded, it loads it. It also keeps pcm_offset up to
  152281. date (seek and read both use this. seek uses a special hack with
  152282. readp).
  152283. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  152284. 0) need more data (only if readp==0)
  152285. 1) got a packet
  152286. */
  152287. static int _fetch_and_process_packet(OggVorbis_File *vf,
  152288. ogg_packet *op_in,
  152289. int readp,
  152290. int spanp){
  152291. ogg_page og;
  152292. /* handle one packet. Try to fetch it from current stream state */
  152293. /* extract packets from page */
  152294. while(1){
  152295. /* process a packet if we can. If the machine isn't loaded,
  152296. neither is a page */
  152297. if(vf->ready_state==INITSET){
  152298. while(1) {
  152299. ogg_packet op;
  152300. ogg_packet *op_ptr=(op_in?op_in:&op);
  152301. int result=ogg_stream_packetout(&vf->os,op_ptr);
  152302. ogg_int64_t granulepos;
  152303. op_in=NULL;
  152304. if(result==-1)return(OV_HOLE); /* hole in the data. */
  152305. if(result>0){
  152306. /* got a packet. process it */
  152307. granulepos=op_ptr->granulepos;
  152308. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  152309. header handling. The
  152310. header packets aren't
  152311. audio, so if/when we
  152312. submit them,
  152313. vorbis_synthesis will
  152314. reject them */
  152315. /* suck in the synthesis data and track bitrate */
  152316. {
  152317. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152318. /* for proper use of libvorbis within libvorbisfile,
  152319. oldsamples will always be zero. */
  152320. if(oldsamples)return(OV_EFAULT);
  152321. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152322. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  152323. vf->bittrack+=op_ptr->bytes*8;
  152324. }
  152325. /* update the pcm offset. */
  152326. if(granulepos!=-1 && !op_ptr->e_o_s){
  152327. int link=(vf->seekable?vf->current_link:0);
  152328. int i,samples;
  152329. /* this packet has a pcm_offset on it (the last packet
  152330. completed on a page carries the offset) After processing
  152331. (above), we know the pcm position of the *last* sample
  152332. ready to be returned. Find the offset of the *first*
  152333. As an aside, this trick is inaccurate if we begin
  152334. reading anew right at the last page; the end-of-stream
  152335. granulepos declares the last frame in the stream, and the
  152336. last packet of the last page may be a partial frame.
  152337. So, we need a previous granulepos from an in-sequence page
  152338. to have a reference point. Thus the !op_ptr->e_o_s clause
  152339. above */
  152340. if(vf->seekable && link>0)
  152341. granulepos-=vf->pcmlengths[link*2];
  152342. if(granulepos<0)granulepos=0; /* actually, this
  152343. shouldn't be possible
  152344. here unless the stream
  152345. is very broken */
  152346. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152347. granulepos-=samples;
  152348. for(i=0;i<link;i++)
  152349. granulepos+=vf->pcmlengths[i*2+1];
  152350. vf->pcm_offset=granulepos;
  152351. }
  152352. return(1);
  152353. }
  152354. }
  152355. else
  152356. break;
  152357. }
  152358. }
  152359. if(vf->ready_state>=OPENED){
  152360. ogg_int64_t ret;
  152361. if(!readp)return(0);
  152362. if((ret=_get_next_page(vf,&og,-1))<0){
  152363. return(OV_EOF); /* eof.
  152364. leave unitialized */
  152365. }
  152366. /* bitrate tracking; add the header's bytes here, the body bytes
  152367. are done by packet above */
  152368. vf->bittrack+=og.header_len*8;
  152369. /* has our decoding just traversed a bitstream boundary? */
  152370. if(vf->ready_state==INITSET){
  152371. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152372. if(!spanp)
  152373. return(OV_EOF);
  152374. _decode_clear(vf);
  152375. if(!vf->seekable){
  152376. vorbis_info_clear(vf->vi);
  152377. vorbis_comment_clear(vf->vc);
  152378. }
  152379. }
  152380. }
  152381. }
  152382. /* Do we need to load a new machine before submitting the page? */
  152383. /* This is different in the seekable and non-seekable cases.
  152384. In the seekable case, we already have all the header
  152385. information loaded and cached; we just initialize the machine
  152386. with it and continue on our merry way.
  152387. In the non-seekable (streaming) case, we'll only be at a
  152388. boundary if we just left the previous logical bitstream and
  152389. we're now nominally at the header of the next bitstream
  152390. */
  152391. if(vf->ready_state!=INITSET){
  152392. int link;
  152393. if(vf->ready_state<STREAMSET){
  152394. if(vf->seekable){
  152395. vf->current_serialno=ogg_page_serialno(&og);
  152396. /* match the serialno to bitstream section. We use this rather than
  152397. offset positions to avoid problems near logical bitstream
  152398. boundaries */
  152399. for(link=0;link<vf->links;link++)
  152400. if(vf->serialnos[link]==vf->current_serialno)break;
  152401. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  152402. stream. error out,
  152403. leave machine
  152404. uninitialized */
  152405. vf->current_link=link;
  152406. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152407. vf->ready_state=STREAMSET;
  152408. }else{
  152409. /* we're streaming */
  152410. /* fetch the three header packets, build the info struct */
  152411. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  152412. if(ret)return(ret);
  152413. vf->current_link++;
  152414. link=0;
  152415. }
  152416. }
  152417. {
  152418. int ret=_make_decode_ready(vf);
  152419. if(ret<0)return ret;
  152420. }
  152421. }
  152422. ogg_stream_pagein(&vf->os,&og);
  152423. }
  152424. }
  152425. /* if, eg, 64 bit stdio is configured by default, this will build with
  152426. fseek64 */
  152427. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  152428. if(f==NULL)return(-1);
  152429. return fseek(f,off,whence);
  152430. }
  152431. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  152432. long ibytes, ov_callbacks callbacks){
  152433. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  152434. int ret;
  152435. memset(vf,0,sizeof(*vf));
  152436. vf->datasource=f;
  152437. vf->callbacks = callbacks;
  152438. /* init the framing state */
  152439. ogg_sync_init(&vf->oy);
  152440. /* perhaps some data was previously read into a buffer for testing
  152441. against other stream types. Allow initialization from this
  152442. previously read data (as we may be reading from a non-seekable
  152443. stream) */
  152444. if(initial){
  152445. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  152446. memcpy(buffer,initial,ibytes);
  152447. ogg_sync_wrote(&vf->oy,ibytes);
  152448. }
  152449. /* can we seek? Stevens suggests the seek test was portable */
  152450. if(offsettest!=-1)vf->seekable=1;
  152451. /* No seeking yet; Set up a 'single' (current) logical bitstream
  152452. entry for partial open */
  152453. vf->links=1;
  152454. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  152455. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  152456. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  152457. /* Try to fetch the headers, maintaining all the storage */
  152458. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  152459. vf->datasource=NULL;
  152460. ov_clear(vf);
  152461. }else
  152462. vf->ready_state=PARTOPEN;
  152463. return(ret);
  152464. }
  152465. static int _ov_open2(OggVorbis_File *vf){
  152466. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  152467. vf->ready_state=OPENED;
  152468. if(vf->seekable){
  152469. int ret=_open_seekable2(vf);
  152470. if(ret){
  152471. vf->datasource=NULL;
  152472. ov_clear(vf);
  152473. }
  152474. return(ret);
  152475. }else
  152476. vf->ready_state=STREAMSET;
  152477. return 0;
  152478. }
  152479. /* clear out the OggVorbis_File struct */
  152480. int ov_clear(OggVorbis_File *vf){
  152481. if(vf){
  152482. vorbis_block_clear(&vf->vb);
  152483. vorbis_dsp_clear(&vf->vd);
  152484. ogg_stream_clear(&vf->os);
  152485. if(vf->vi && vf->links){
  152486. int i;
  152487. for(i=0;i<vf->links;i++){
  152488. vorbis_info_clear(vf->vi+i);
  152489. vorbis_comment_clear(vf->vc+i);
  152490. }
  152491. _ogg_free(vf->vi);
  152492. _ogg_free(vf->vc);
  152493. }
  152494. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  152495. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  152496. if(vf->serialnos)_ogg_free(vf->serialnos);
  152497. if(vf->offsets)_ogg_free(vf->offsets);
  152498. ogg_sync_clear(&vf->oy);
  152499. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  152500. memset(vf,0,sizeof(*vf));
  152501. }
  152502. #ifdef DEBUG_LEAKS
  152503. _VDBG_dump();
  152504. #endif
  152505. return(0);
  152506. }
  152507. /* inspects the OggVorbis file and finds/documents all the logical
  152508. bitstreams contained in it. Tries to be tolerant of logical
  152509. bitstream sections that are truncated/woogie.
  152510. return: -1) error
  152511. 0) OK
  152512. */
  152513. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  152514. ov_callbacks callbacks){
  152515. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  152516. if(ret)return ret;
  152517. return _ov_open2(vf);
  152518. }
  152519. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  152520. ov_callbacks callbacks = {
  152521. (size_t (*)(void *, size_t, size_t, void *)) fread,
  152522. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  152523. (int (*)(void *)) fclose,
  152524. (long (*)(void *)) ftell
  152525. };
  152526. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  152527. }
  152528. /* cheap hack for game usage where downsampling is desirable; there's
  152529. no need for SRC as we can just do it cheaply in libvorbis. */
  152530. int ov_halfrate(OggVorbis_File *vf,int flag){
  152531. int i;
  152532. if(vf->vi==NULL)return OV_EINVAL;
  152533. if(!vf->seekable)return OV_EINVAL;
  152534. if(vf->ready_state>=STREAMSET)
  152535. _decode_clear(vf); /* clear out stream state; later on libvorbis
  152536. will be able to swap this on the fly, but
  152537. for now dumping the decode machine is needed
  152538. to reinit the MDCT lookups. 1.1 libvorbis
  152539. is planned to be able to switch on the fly */
  152540. for(i=0;i<vf->links;i++){
  152541. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  152542. ov_halfrate(vf,0);
  152543. return OV_EINVAL;
  152544. }
  152545. }
  152546. return 0;
  152547. }
  152548. int ov_halfrate_p(OggVorbis_File *vf){
  152549. if(vf->vi==NULL)return OV_EINVAL;
  152550. return vorbis_synthesis_halfrate_p(vf->vi);
  152551. }
  152552. /* Only partially open the vorbis file; test for Vorbisness, and load
  152553. the headers for the first chain. Do not seek (although test for
  152554. seekability). Use ov_test_open to finish opening the file, else
  152555. ov_clear to close/free it. Same return codes as open. */
  152556. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  152557. ov_callbacks callbacks)
  152558. {
  152559. return _ov_open1(f,vf,initial,ibytes,callbacks);
  152560. }
  152561. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  152562. ov_callbacks callbacks = {
  152563. (size_t (*)(void *, size_t, size_t, void *)) fread,
  152564. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  152565. (int (*)(void *)) fclose,
  152566. (long (*)(void *)) ftell
  152567. };
  152568. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  152569. }
  152570. int ov_test_open(OggVorbis_File *vf){
  152571. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  152572. return _ov_open2(vf);
  152573. }
  152574. /* How many logical bitstreams in this physical bitstream? */
  152575. long ov_streams(OggVorbis_File *vf){
  152576. return vf->links;
  152577. }
  152578. /* Is the FILE * associated with vf seekable? */
  152579. long ov_seekable(OggVorbis_File *vf){
  152580. return vf->seekable;
  152581. }
  152582. /* returns the bitrate for a given logical bitstream or the entire
  152583. physical bitstream. If the file is open for random access, it will
  152584. find the *actual* average bitrate. If the file is streaming, it
  152585. returns the nominal bitrate (if set) else the average of the
  152586. upper/lower bounds (if set) else -1 (unset).
  152587. If you want the actual bitrate field settings, get them from the
  152588. vorbis_info structs */
  152589. long ov_bitrate(OggVorbis_File *vf,int i){
  152590. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152591. if(i>=vf->links)return(OV_EINVAL);
  152592. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  152593. if(i<0){
  152594. ogg_int64_t bits=0;
  152595. int i;
  152596. float br;
  152597. for(i=0;i<vf->links;i++)
  152598. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  152599. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  152600. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  152601. * so this is slightly transformed to make it work.
  152602. */
  152603. br = bits/ov_time_total(vf,-1);
  152604. return(rint(br));
  152605. }else{
  152606. if(vf->seekable){
  152607. /* return the actual bitrate */
  152608. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  152609. }else{
  152610. /* return nominal if set */
  152611. if(vf->vi[i].bitrate_nominal>0){
  152612. return vf->vi[i].bitrate_nominal;
  152613. }else{
  152614. if(vf->vi[i].bitrate_upper>0){
  152615. if(vf->vi[i].bitrate_lower>0){
  152616. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  152617. }else{
  152618. return vf->vi[i].bitrate_upper;
  152619. }
  152620. }
  152621. return(OV_FALSE);
  152622. }
  152623. }
  152624. }
  152625. }
  152626. /* returns the actual bitrate since last call. returns -1 if no
  152627. additional data to offer since last call (or at beginning of stream),
  152628. EINVAL if stream is only partially open
  152629. */
  152630. long ov_bitrate_instant(OggVorbis_File *vf){
  152631. int link=(vf->seekable?vf->current_link:0);
  152632. long ret;
  152633. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152634. if(vf->samptrack==0)return(OV_FALSE);
  152635. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  152636. vf->bittrack=0.f;
  152637. vf->samptrack=0.f;
  152638. return(ret);
  152639. }
  152640. /* Guess */
  152641. long ov_serialnumber(OggVorbis_File *vf,int i){
  152642. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  152643. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  152644. if(i<0){
  152645. return(vf->current_serialno);
  152646. }else{
  152647. return(vf->serialnos[i]);
  152648. }
  152649. }
  152650. /* returns: total raw (compressed) length of content if i==-1
  152651. raw (compressed) length of that logical bitstream for i==0 to n
  152652. OV_EINVAL if the stream is not seekable (we can't know the length)
  152653. or if stream is only partially open
  152654. */
  152655. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  152656. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152657. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  152658. if(i<0){
  152659. ogg_int64_t acc=0;
  152660. int i;
  152661. for(i=0;i<vf->links;i++)
  152662. acc+=ov_raw_total(vf,i);
  152663. return(acc);
  152664. }else{
  152665. return(vf->offsets[i+1]-vf->offsets[i]);
  152666. }
  152667. }
  152668. /* returns: total PCM length (samples) of content if i==-1 PCM length
  152669. (samples) of that logical bitstream for i==0 to n
  152670. OV_EINVAL if the stream is not seekable (we can't know the
  152671. length) or only partially open
  152672. */
  152673. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  152674. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152675. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  152676. if(i<0){
  152677. ogg_int64_t acc=0;
  152678. int i;
  152679. for(i=0;i<vf->links;i++)
  152680. acc+=ov_pcm_total(vf,i);
  152681. return(acc);
  152682. }else{
  152683. return(vf->pcmlengths[i*2+1]);
  152684. }
  152685. }
  152686. /* returns: total seconds of content if i==-1
  152687. seconds in that logical bitstream for i==0 to n
  152688. OV_EINVAL if the stream is not seekable (we can't know the
  152689. length) or only partially open
  152690. */
  152691. double ov_time_total(OggVorbis_File *vf,int i){
  152692. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152693. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  152694. if(i<0){
  152695. double acc=0;
  152696. int i;
  152697. for(i=0;i<vf->links;i++)
  152698. acc+=ov_time_total(vf,i);
  152699. return(acc);
  152700. }else{
  152701. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  152702. }
  152703. }
  152704. /* seek to an offset relative to the *compressed* data. This also
  152705. scans packets to update the PCM cursor. It will cross a logical
  152706. bitstream boundary, but only if it can't get any packets out of the
  152707. tail of the bitstream we seek to (so no surprises).
  152708. returns zero on success, nonzero on failure */
  152709. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152710. ogg_stream_state work_os;
  152711. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152712. if(!vf->seekable)
  152713. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  152714. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  152715. /* don't yet clear out decoding machine (if it's initialized), in
  152716. the case we're in the same link. Restart the decode lapping, and
  152717. let _fetch_and_process_packet deal with a potential bitstream
  152718. boundary */
  152719. vf->pcm_offset=-1;
  152720. ogg_stream_reset_serialno(&vf->os,
  152721. vf->current_serialno); /* must set serialno */
  152722. vorbis_synthesis_restart(&vf->vd);
  152723. _seek_helper(vf,pos);
  152724. /* we need to make sure the pcm_offset is set, but we don't want to
  152725. advance the raw cursor past good packets just to get to the first
  152726. with a granulepos. That's not equivalent behavior to beginning
  152727. decoding as immediately after the seek position as possible.
  152728. So, a hack. We use two stream states; a local scratch state and
  152729. the shared vf->os stream state. We use the local state to
  152730. scan, and the shared state as a buffer for later decode.
  152731. Unfortuantely, on the last page we still advance to last packet
  152732. because the granulepos on the last page is not necessarily on a
  152733. packet boundary, and we need to make sure the granpos is
  152734. correct.
  152735. */
  152736. {
  152737. ogg_page og;
  152738. ogg_packet op;
  152739. int lastblock=0;
  152740. int accblock=0;
  152741. int thisblock;
  152742. int eosflag;
  152743. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  152744. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  152745. return from not necessarily
  152746. starting from the beginning */
  152747. while(1){
  152748. if(vf->ready_state>=STREAMSET){
  152749. /* snarf/scan a packet if we can */
  152750. int result=ogg_stream_packetout(&work_os,&op);
  152751. if(result>0){
  152752. if(vf->vi[vf->current_link].codec_setup){
  152753. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152754. if(thisblock<0){
  152755. ogg_stream_packetout(&vf->os,NULL);
  152756. thisblock=0;
  152757. }else{
  152758. if(eosflag)
  152759. ogg_stream_packetout(&vf->os,NULL);
  152760. else
  152761. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  152762. }
  152763. if(op.granulepos!=-1){
  152764. int i,link=vf->current_link;
  152765. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  152766. if(granulepos<0)granulepos=0;
  152767. for(i=0;i<link;i++)
  152768. granulepos+=vf->pcmlengths[i*2+1];
  152769. vf->pcm_offset=granulepos-accblock;
  152770. break;
  152771. }
  152772. lastblock=thisblock;
  152773. continue;
  152774. }else
  152775. ogg_stream_packetout(&vf->os,NULL);
  152776. }
  152777. }
  152778. if(!lastblock){
  152779. if(_get_next_page(vf,&og,-1)<0){
  152780. vf->pcm_offset=ov_pcm_total(vf,-1);
  152781. break;
  152782. }
  152783. }else{
  152784. /* huh? Bogus stream with packets but no granulepos */
  152785. vf->pcm_offset=-1;
  152786. break;
  152787. }
  152788. /* has our decoding just traversed a bitstream boundary? */
  152789. if(vf->ready_state>=STREAMSET)
  152790. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152791. _decode_clear(vf); /* clear out stream state */
  152792. ogg_stream_clear(&work_os);
  152793. }
  152794. if(vf->ready_state<STREAMSET){
  152795. int link;
  152796. vf->current_serialno=ogg_page_serialno(&og);
  152797. for(link=0;link<vf->links;link++)
  152798. if(vf->serialnos[link]==vf->current_serialno)break;
  152799. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  152800. error out, leave
  152801. machine uninitialized */
  152802. vf->current_link=link;
  152803. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152804. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  152805. vf->ready_state=STREAMSET;
  152806. }
  152807. ogg_stream_pagein(&vf->os,&og);
  152808. ogg_stream_pagein(&work_os,&og);
  152809. eosflag=ogg_page_eos(&og);
  152810. }
  152811. }
  152812. ogg_stream_clear(&work_os);
  152813. vf->bittrack=0.f;
  152814. vf->samptrack=0.f;
  152815. return(0);
  152816. seek_error:
  152817. /* dump the machine so we're in a known state */
  152818. vf->pcm_offset=-1;
  152819. ogg_stream_clear(&work_os);
  152820. _decode_clear(vf);
  152821. return OV_EBADLINK;
  152822. }
  152823. /* Page granularity seek (faster than sample granularity because we
  152824. don't do the last bit of decode to find a specific sample).
  152825. Seek to the last [granule marked] page preceeding the specified pos
  152826. location, such that decoding past the returned point will quickly
  152827. arrive at the requested position. */
  152828. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  152829. int link=-1;
  152830. ogg_int64_t result=0;
  152831. ogg_int64_t total=ov_pcm_total(vf,-1);
  152832. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152833. if(!vf->seekable)return(OV_ENOSEEK);
  152834. if(pos<0 || pos>total)return(OV_EINVAL);
  152835. /* which bitstream section does this pcm offset occur in? */
  152836. for(link=vf->links-1;link>=0;link--){
  152837. total-=vf->pcmlengths[link*2+1];
  152838. if(pos>=total)break;
  152839. }
  152840. /* search within the logical bitstream for the page with the highest
  152841. pcm_pos preceeding (or equal to) pos. There is a danger here;
  152842. missing pages or incorrect frame number information in the
  152843. bitstream could make our task impossible. Account for that (it
  152844. would be an error condition) */
  152845. /* new search algorithm by HB (Nicholas Vinen) */
  152846. {
  152847. ogg_int64_t end=vf->offsets[link+1];
  152848. ogg_int64_t begin=vf->offsets[link];
  152849. ogg_int64_t begintime = vf->pcmlengths[link*2];
  152850. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  152851. ogg_int64_t target=pos-total+begintime;
  152852. ogg_int64_t best=begin;
  152853. ogg_page og;
  152854. while(begin<end){
  152855. ogg_int64_t bisect;
  152856. if(end-begin<CHUNKSIZE){
  152857. bisect=begin;
  152858. }else{
  152859. /* take a (pretty decent) guess. */
  152860. bisect=begin +
  152861. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  152862. if(bisect<=begin)
  152863. bisect=begin+1;
  152864. }
  152865. _seek_helper(vf,bisect);
  152866. while(begin<end){
  152867. result=_get_next_page(vf,&og,end-vf->offset);
  152868. if(result==OV_EREAD) goto seek_error;
  152869. if(result<0){
  152870. if(bisect<=begin+1)
  152871. end=begin; /* found it */
  152872. else{
  152873. if(bisect==0) goto seek_error;
  152874. bisect-=CHUNKSIZE;
  152875. if(bisect<=begin)bisect=begin+1;
  152876. _seek_helper(vf,bisect);
  152877. }
  152878. }else{
  152879. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  152880. if(granulepos==-1)continue;
  152881. if(granulepos<target){
  152882. best=result; /* raw offset of packet with granulepos */
  152883. begin=vf->offset; /* raw offset of next page */
  152884. begintime=granulepos;
  152885. if(target-begintime>44100)break;
  152886. bisect=begin; /* *not* begin + 1 */
  152887. }else{
  152888. if(bisect<=begin+1)
  152889. end=begin; /* found it */
  152890. else{
  152891. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  152892. end=result;
  152893. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  152894. if(bisect<=begin)bisect=begin+1;
  152895. _seek_helper(vf,bisect);
  152896. }else{
  152897. end=result;
  152898. endtime=granulepos;
  152899. break;
  152900. }
  152901. }
  152902. }
  152903. }
  152904. }
  152905. }
  152906. /* found our page. seek to it, update pcm offset. Easier case than
  152907. raw_seek, don't keep packets preceeding granulepos. */
  152908. {
  152909. ogg_page og;
  152910. ogg_packet op;
  152911. /* seek */
  152912. _seek_helper(vf,best);
  152913. vf->pcm_offset=-1;
  152914. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  152915. if(link!=vf->current_link){
  152916. /* Different link; dump entire decode machine */
  152917. _decode_clear(vf);
  152918. vf->current_link=link;
  152919. vf->current_serialno=ogg_page_serialno(&og);
  152920. vf->ready_state=STREAMSET;
  152921. }else{
  152922. vorbis_synthesis_restart(&vf->vd);
  152923. }
  152924. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152925. ogg_stream_pagein(&vf->os,&og);
  152926. /* pull out all but last packet; the one with granulepos */
  152927. while(1){
  152928. result=ogg_stream_packetpeek(&vf->os,&op);
  152929. if(result==0){
  152930. /* !!! the packet finishing this page originated on a
  152931. preceeding page. Keep fetching previous pages until we
  152932. get one with a granulepos or without the 'continued' flag
  152933. set. Then just use raw_seek for simplicity. */
  152934. _seek_helper(vf,best);
  152935. while(1){
  152936. result=_get_prev_page(vf,&og);
  152937. if(result<0) goto seek_error;
  152938. if(ogg_page_granulepos(&og)>-1 ||
  152939. !ogg_page_continued(&og)){
  152940. return ov_raw_seek(vf,result);
  152941. }
  152942. vf->offset=result;
  152943. }
  152944. }
  152945. if(result<0){
  152946. result = OV_EBADPACKET;
  152947. goto seek_error;
  152948. }
  152949. if(op.granulepos!=-1){
  152950. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152951. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152952. vf->pcm_offset+=total;
  152953. break;
  152954. }else
  152955. result=ogg_stream_packetout(&vf->os,NULL);
  152956. }
  152957. }
  152958. }
  152959. /* verify result */
  152960. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  152961. result=OV_EFAULT;
  152962. goto seek_error;
  152963. }
  152964. vf->bittrack=0.f;
  152965. vf->samptrack=0.f;
  152966. return(0);
  152967. seek_error:
  152968. /* dump machine so we're in a known state */
  152969. vf->pcm_offset=-1;
  152970. _decode_clear(vf);
  152971. return (int)result;
  152972. }
  152973. /* seek to a sample offset relative to the decompressed pcm stream
  152974. returns zero on success, nonzero on failure */
  152975. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152976. int thisblock,lastblock=0;
  152977. int ret=ov_pcm_seek_page(vf,pos);
  152978. if(ret<0)return(ret);
  152979. if((ret=_make_decode_ready(vf)))return ret;
  152980. /* discard leading packets we don't need for the lapping of the
  152981. position we want; don't decode them */
  152982. while(1){
  152983. ogg_packet op;
  152984. ogg_page og;
  152985. int ret=ogg_stream_packetpeek(&vf->os,&op);
  152986. if(ret>0){
  152987. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152988. if(thisblock<0){
  152989. ogg_stream_packetout(&vf->os,NULL);
  152990. continue; /* non audio packet */
  152991. }
  152992. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  152993. if(vf->pcm_offset+((thisblock+
  152994. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  152995. /* remove the packet from packet queue and track its granulepos */
  152996. ogg_stream_packetout(&vf->os,NULL);
  152997. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  152998. only tracking, no
  152999. pcm_decode */
  153000. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  153001. /* end of logical stream case is hard, especially with exact
  153002. length positioning. */
  153003. if(op.granulepos>-1){
  153004. int i;
  153005. /* always believe the stream markers */
  153006. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  153007. if(vf->pcm_offset<0)vf->pcm_offset=0;
  153008. for(i=0;i<vf->current_link;i++)
  153009. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  153010. }
  153011. lastblock=thisblock;
  153012. }else{
  153013. if(ret<0 && ret!=OV_HOLE)break;
  153014. /* suck in a new page */
  153015. if(_get_next_page(vf,&og,-1)<0)break;
  153016. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  153017. if(vf->ready_state<STREAMSET){
  153018. int link;
  153019. vf->current_serialno=ogg_page_serialno(&og);
  153020. for(link=0;link<vf->links;link++)
  153021. if(vf->serialnos[link]==vf->current_serialno)break;
  153022. if(link==vf->links)return(OV_EBADLINK);
  153023. vf->current_link=link;
  153024. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153025. vf->ready_state=STREAMSET;
  153026. ret=_make_decode_ready(vf);
  153027. if(ret)return ret;
  153028. lastblock=0;
  153029. }
  153030. ogg_stream_pagein(&vf->os,&og);
  153031. }
  153032. }
  153033. vf->bittrack=0.f;
  153034. vf->samptrack=0.f;
  153035. /* discard samples until we reach the desired position. Crossing a
  153036. logical bitstream boundary with abandon is OK. */
  153037. while(vf->pcm_offset<pos){
  153038. ogg_int64_t target=pos-vf->pcm_offset;
  153039. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  153040. if(samples>target)samples=target;
  153041. vorbis_synthesis_read(&vf->vd,samples);
  153042. vf->pcm_offset+=samples;
  153043. if(samples<target)
  153044. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  153045. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  153046. }
  153047. return 0;
  153048. }
  153049. /* seek to a playback time relative to the decompressed pcm stream
  153050. returns zero on success, nonzero on failure */
  153051. int ov_time_seek(OggVorbis_File *vf,double seconds){
  153052. /* translate time to PCM position and call ov_pcm_seek */
  153053. int link=-1;
  153054. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153055. double time_total=ov_time_total(vf,-1);
  153056. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153057. if(!vf->seekable)return(OV_ENOSEEK);
  153058. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153059. /* which bitstream section does this time offset occur in? */
  153060. for(link=vf->links-1;link>=0;link--){
  153061. pcm_total-=vf->pcmlengths[link*2+1];
  153062. time_total-=ov_time_total(vf,link);
  153063. if(seconds>=time_total)break;
  153064. }
  153065. /* enough information to convert time offset to pcm offset */
  153066. {
  153067. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153068. return(ov_pcm_seek(vf,target));
  153069. }
  153070. }
  153071. /* page-granularity version of ov_time_seek
  153072. returns zero on success, nonzero on failure */
  153073. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  153074. /* translate time to PCM position and call ov_pcm_seek */
  153075. int link=-1;
  153076. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153077. double time_total=ov_time_total(vf,-1);
  153078. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153079. if(!vf->seekable)return(OV_ENOSEEK);
  153080. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153081. /* which bitstream section does this time offset occur in? */
  153082. for(link=vf->links-1;link>=0;link--){
  153083. pcm_total-=vf->pcmlengths[link*2+1];
  153084. time_total-=ov_time_total(vf,link);
  153085. if(seconds>=time_total)break;
  153086. }
  153087. /* enough information to convert time offset to pcm offset */
  153088. {
  153089. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153090. return(ov_pcm_seek_page(vf,target));
  153091. }
  153092. }
  153093. /* tell the current stream offset cursor. Note that seek followed by
  153094. tell will likely not give the set offset due to caching */
  153095. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  153096. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153097. return(vf->offset);
  153098. }
  153099. /* return PCM offset (sample) of next PCM sample to be read */
  153100. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  153101. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153102. return(vf->pcm_offset);
  153103. }
  153104. /* return time offset (seconds) of next PCM sample to be read */
  153105. double ov_time_tell(OggVorbis_File *vf){
  153106. int link=0;
  153107. ogg_int64_t pcm_total=0;
  153108. double time_total=0.f;
  153109. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153110. if(vf->seekable){
  153111. pcm_total=ov_pcm_total(vf,-1);
  153112. time_total=ov_time_total(vf,-1);
  153113. /* which bitstream section does this time offset occur in? */
  153114. for(link=vf->links-1;link>=0;link--){
  153115. pcm_total-=vf->pcmlengths[link*2+1];
  153116. time_total-=ov_time_total(vf,link);
  153117. if(vf->pcm_offset>=pcm_total)break;
  153118. }
  153119. }
  153120. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  153121. }
  153122. /* link: -1) return the vorbis_info struct for the bitstream section
  153123. currently being decoded
  153124. 0-n) to request information for a specific bitstream section
  153125. In the case of a non-seekable bitstream, any call returns the
  153126. current bitstream. NULL in the case that the machine is not
  153127. initialized */
  153128. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  153129. if(vf->seekable){
  153130. if(link<0)
  153131. if(vf->ready_state>=STREAMSET)
  153132. return vf->vi+vf->current_link;
  153133. else
  153134. return vf->vi;
  153135. else
  153136. if(link>=vf->links)
  153137. return NULL;
  153138. else
  153139. return vf->vi+link;
  153140. }else{
  153141. return vf->vi;
  153142. }
  153143. }
  153144. /* grr, strong typing, grr, no templates/inheritence, grr */
  153145. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  153146. if(vf->seekable){
  153147. if(link<0)
  153148. if(vf->ready_state>=STREAMSET)
  153149. return vf->vc+vf->current_link;
  153150. else
  153151. return vf->vc;
  153152. else
  153153. if(link>=vf->links)
  153154. return NULL;
  153155. else
  153156. return vf->vc+link;
  153157. }else{
  153158. return vf->vc;
  153159. }
  153160. }
  153161. static int host_is_big_endian() {
  153162. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  153163. unsigned char *bytewise = (unsigned char *)&pattern;
  153164. if (bytewise[0] == 0xfe) return 1;
  153165. return 0;
  153166. }
  153167. /* up to this point, everything could more or less hide the multiple
  153168. logical bitstream nature of chaining from the toplevel application
  153169. if the toplevel application didn't particularly care. However, at
  153170. the point that we actually read audio back, the multiple-section
  153171. nature must surface: Multiple bitstream sections do not necessarily
  153172. have to have the same number of channels or sampling rate.
  153173. ov_read returns the sequential logical bitstream number currently
  153174. being decoded along with the PCM data in order that the toplevel
  153175. application can take action on channel/sample rate changes. This
  153176. number will be incremented even for streamed (non-seekable) streams
  153177. (for seekable streams, it represents the actual logical bitstream
  153178. index within the physical bitstream. Note that the accessor
  153179. functions above are aware of this dichotomy).
  153180. input values: buffer) a buffer to hold packed PCM data for return
  153181. length) the byte length requested to be placed into buffer
  153182. bigendianp) should the data be packed LSB first (0) or
  153183. MSB first (1)
  153184. word) word size for output. currently 1 (byte) or
  153185. 2 (16 bit short)
  153186. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153187. 0) EOF
  153188. n) number of bytes of PCM actually returned. The
  153189. below works on a packet-by-packet basis, so the
  153190. return length is not related to the 'length' passed
  153191. in, just guaranteed to fit.
  153192. *section) set to the logical bitstream number */
  153193. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  153194. int bigendianp,int word,int sgned,int *bitstream){
  153195. int i,j;
  153196. int host_endian = host_is_big_endian();
  153197. float **pcm;
  153198. long samples;
  153199. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153200. while(1){
  153201. if(vf->ready_state==INITSET){
  153202. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153203. if(samples)break;
  153204. }
  153205. /* suck in another packet */
  153206. {
  153207. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153208. if(ret==OV_EOF)
  153209. return(0);
  153210. if(ret<=0)
  153211. return(ret);
  153212. }
  153213. }
  153214. if(samples>0){
  153215. /* yay! proceed to pack data into the byte buffer */
  153216. long channels=ov_info(vf,-1)->channels;
  153217. long bytespersample=word * channels;
  153218. vorbis_fpu_control fpu;
  153219. (void) fpu; // (to avoid a warning about it being unused)
  153220. if(samples>length/bytespersample)samples=length/bytespersample;
  153221. if(samples <= 0)
  153222. return OV_EINVAL;
  153223. /* a tight loop to pack each size */
  153224. {
  153225. int val;
  153226. if(word==1){
  153227. int off=(sgned?0:128);
  153228. vorbis_fpu_setround(&fpu);
  153229. for(j=0;j<samples;j++)
  153230. for(i=0;i<channels;i++){
  153231. val=vorbis_ftoi(pcm[i][j]*128.f);
  153232. if(val>127)val=127;
  153233. else if(val<-128)val=-128;
  153234. *buffer++=val+off;
  153235. }
  153236. vorbis_fpu_restore(fpu);
  153237. }else{
  153238. int off=(sgned?0:32768);
  153239. if(host_endian==bigendianp){
  153240. if(sgned){
  153241. vorbis_fpu_setround(&fpu);
  153242. for(i=0;i<channels;i++) { /* It's faster in this order */
  153243. float *src=pcm[i];
  153244. short *dest=((short *)buffer)+i;
  153245. for(j=0;j<samples;j++) {
  153246. val=vorbis_ftoi(src[j]*32768.f);
  153247. if(val>32767)val=32767;
  153248. else if(val<-32768)val=-32768;
  153249. *dest=val;
  153250. dest+=channels;
  153251. }
  153252. }
  153253. vorbis_fpu_restore(fpu);
  153254. }else{
  153255. vorbis_fpu_setround(&fpu);
  153256. for(i=0;i<channels;i++) {
  153257. float *src=pcm[i];
  153258. short *dest=((short *)buffer)+i;
  153259. for(j=0;j<samples;j++) {
  153260. val=vorbis_ftoi(src[j]*32768.f);
  153261. if(val>32767)val=32767;
  153262. else if(val<-32768)val=-32768;
  153263. *dest=val+off;
  153264. dest+=channels;
  153265. }
  153266. }
  153267. vorbis_fpu_restore(fpu);
  153268. }
  153269. }else if(bigendianp){
  153270. vorbis_fpu_setround(&fpu);
  153271. for(j=0;j<samples;j++)
  153272. for(i=0;i<channels;i++){
  153273. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153274. if(val>32767)val=32767;
  153275. else if(val<-32768)val=-32768;
  153276. val+=off;
  153277. *buffer++=(val>>8);
  153278. *buffer++=(val&0xff);
  153279. }
  153280. vorbis_fpu_restore(fpu);
  153281. }else{
  153282. int val;
  153283. vorbis_fpu_setround(&fpu);
  153284. for(j=0;j<samples;j++)
  153285. for(i=0;i<channels;i++){
  153286. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153287. if(val>32767)val=32767;
  153288. else if(val<-32768)val=-32768;
  153289. val+=off;
  153290. *buffer++=(val&0xff);
  153291. *buffer++=(val>>8);
  153292. }
  153293. vorbis_fpu_restore(fpu);
  153294. }
  153295. }
  153296. }
  153297. vorbis_synthesis_read(&vf->vd,samples);
  153298. vf->pcm_offset+=samples;
  153299. if(bitstream)*bitstream=vf->current_link;
  153300. return(samples*bytespersample);
  153301. }else{
  153302. return(samples);
  153303. }
  153304. }
  153305. /* input values: pcm_channels) a float vector per channel of output
  153306. length) the sample length being read by the app
  153307. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153308. 0) EOF
  153309. n) number of samples of PCM actually returned. The
  153310. below works on a packet-by-packet basis, so the
  153311. return length is not related to the 'length' passed
  153312. in, just guaranteed to fit.
  153313. *section) set to the logical bitstream number */
  153314. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  153315. int *bitstream){
  153316. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153317. while(1){
  153318. if(vf->ready_state==INITSET){
  153319. float **pcm;
  153320. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153321. if(samples){
  153322. if(pcm_channels)*pcm_channels=pcm;
  153323. if(samples>length)samples=length;
  153324. vorbis_synthesis_read(&vf->vd,samples);
  153325. vf->pcm_offset+=samples;
  153326. if(bitstream)*bitstream=vf->current_link;
  153327. return samples;
  153328. }
  153329. }
  153330. /* suck in another packet */
  153331. {
  153332. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153333. if(ret==OV_EOF)return(0);
  153334. if(ret<=0)return(ret);
  153335. }
  153336. }
  153337. }
  153338. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  153339. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  153340. ogg_int64_t off);
  153341. static void _ov_splice(float **pcm,float **lappcm,
  153342. int n1, int n2,
  153343. int ch1, int ch2,
  153344. float *w1, float *w2){
  153345. int i,j;
  153346. float *w=w1;
  153347. int n=n1;
  153348. if(n1>n2){
  153349. n=n2;
  153350. w=w2;
  153351. }
  153352. /* splice */
  153353. for(j=0;j<ch1 && j<ch2;j++){
  153354. float *s=lappcm[j];
  153355. float *d=pcm[j];
  153356. for(i=0;i<n;i++){
  153357. float wd=w[i]*w[i];
  153358. float ws=1.-wd;
  153359. d[i]=d[i]*wd + s[i]*ws;
  153360. }
  153361. }
  153362. /* window from zero */
  153363. for(;j<ch2;j++){
  153364. float *d=pcm[j];
  153365. for(i=0;i<n;i++){
  153366. float wd=w[i]*w[i];
  153367. d[i]=d[i]*wd;
  153368. }
  153369. }
  153370. }
  153371. /* make sure vf is INITSET */
  153372. static int _ov_initset(OggVorbis_File *vf){
  153373. while(1){
  153374. if(vf->ready_state==INITSET)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. /* make sure vf is INITSET and that we have a primed buffer; if
  153384. we're crosslapping at a stream section boundary, this also makes
  153385. sure we're sanity checking against the right stream information */
  153386. static int _ov_initprime(OggVorbis_File *vf){
  153387. vorbis_dsp_state *vd=&vf->vd;
  153388. while(1){
  153389. if(vf->ready_state==INITSET)
  153390. if(vorbis_synthesis_pcmout(vd,NULL))break;
  153391. /* suck in another packet */
  153392. {
  153393. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  153394. if(ret<0 && ret!=OV_HOLE)return(ret);
  153395. }
  153396. }
  153397. return 0;
  153398. }
  153399. /* grab enough data for lapping from vf; this may be in the form of
  153400. unreturned, already-decoded pcm, remaining PCM we will need to
  153401. decode, or synthetic postextrapolation from last packets. */
  153402. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  153403. float **lappcm,int lapsize){
  153404. int lapcount=0,i;
  153405. float **pcm;
  153406. /* try first to decode the lapping data */
  153407. while(lapcount<lapsize){
  153408. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  153409. if(samples){
  153410. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  153411. for(i=0;i<vi->channels;i++)
  153412. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  153413. lapcount+=samples;
  153414. vorbis_synthesis_read(vd,samples);
  153415. }else{
  153416. /* suck in another packet */
  153417. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  153418. if(ret==OV_EOF)break;
  153419. }
  153420. }
  153421. if(lapcount<lapsize){
  153422. /* failed to get lapping data from normal decode; pry it from the
  153423. postextrapolation buffering, or the second half of the MDCT
  153424. from the last packet */
  153425. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  153426. if(samples==0){
  153427. for(i=0;i<vi->channels;i++)
  153428. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  153429. lapcount=lapsize;
  153430. }else{
  153431. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  153432. for(i=0;i<vi->channels;i++)
  153433. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  153434. lapcount+=samples;
  153435. }
  153436. }
  153437. }
  153438. /* this sets up crosslapping of a sample by using trailing data from
  153439. sample 1 and lapping it into the windowing buffer of sample 2 */
  153440. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  153441. vorbis_info *vi1,*vi2;
  153442. float **lappcm;
  153443. float **pcm;
  153444. float *w1,*w2;
  153445. int n1,n2,i,ret,hs1,hs2;
  153446. if(vf1==vf2)return(0); /* degenerate case */
  153447. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  153448. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  153449. /* the relevant overlap buffers must be pre-checked and pre-primed
  153450. before looking at settings in the event that priming would cross
  153451. a bitstream boundary. So, do it now */
  153452. ret=_ov_initset(vf1);
  153453. if(ret)return(ret);
  153454. ret=_ov_initprime(vf2);
  153455. if(ret)return(ret);
  153456. vi1=ov_info(vf1,-1);
  153457. vi2=ov_info(vf2,-1);
  153458. hs1=ov_halfrate_p(vf1);
  153459. hs2=ov_halfrate_p(vf2);
  153460. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  153461. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  153462. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  153463. w1=vorbis_window(&vf1->vd,0);
  153464. w2=vorbis_window(&vf2->vd,0);
  153465. for(i=0;i<vi1->channels;i++)
  153466. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153467. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  153468. /* have a lapping buffer from vf1; now to splice it into the lapping
  153469. buffer of vf2 */
  153470. /* consolidate and expose the buffer. */
  153471. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  153472. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  153473. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  153474. /* splice */
  153475. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  153476. /* done */
  153477. return(0);
  153478. }
  153479. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  153480. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  153481. vorbis_info *vi;
  153482. float **lappcm;
  153483. float **pcm;
  153484. float *w1,*w2;
  153485. int n1,n2,ch1,ch2,hs;
  153486. int i,ret;
  153487. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153488. ret=_ov_initset(vf);
  153489. if(ret)return(ret);
  153490. vi=ov_info(vf,-1);
  153491. hs=ov_halfrate_p(vf);
  153492. ch1=vi->channels;
  153493. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  153494. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  153495. persistent; even if the decode state
  153496. from this link gets dumped, this
  153497. window array continues to exist */
  153498. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  153499. for(i=0;i<ch1;i++)
  153500. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153501. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  153502. /* have lapping data; seek and prime the buffer */
  153503. ret=localseek(vf,pos);
  153504. if(ret)return ret;
  153505. ret=_ov_initprime(vf);
  153506. if(ret)return(ret);
  153507. /* Guard against cross-link changes; they're perfectly legal */
  153508. vi=ov_info(vf,-1);
  153509. ch2=vi->channels;
  153510. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  153511. w2=vorbis_window(&vf->vd,0);
  153512. /* consolidate and expose the buffer. */
  153513. vorbis_synthesis_lapout(&vf->vd,&pcm);
  153514. /* splice */
  153515. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  153516. /* done */
  153517. return(0);
  153518. }
  153519. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  153520. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  153521. }
  153522. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  153523. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  153524. }
  153525. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  153526. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  153527. }
  153528. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  153529. int (*localseek)(OggVorbis_File *,double)){
  153530. vorbis_info *vi;
  153531. float **lappcm;
  153532. float **pcm;
  153533. float *w1,*w2;
  153534. int n1,n2,ch1,ch2,hs;
  153535. int i,ret;
  153536. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153537. ret=_ov_initset(vf);
  153538. if(ret)return(ret);
  153539. vi=ov_info(vf,-1);
  153540. hs=ov_halfrate_p(vf);
  153541. ch1=vi->channels;
  153542. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  153543. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  153544. persistent; even if the decode state
  153545. from this link gets dumped, this
  153546. window array continues to exist */
  153547. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  153548. for(i=0;i<ch1;i++)
  153549. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153550. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  153551. /* have lapping data; seek and prime the buffer */
  153552. ret=localseek(vf,pos);
  153553. if(ret)return ret;
  153554. ret=_ov_initprime(vf);
  153555. if(ret)return(ret);
  153556. /* Guard against cross-link changes; they're perfectly legal */
  153557. vi=ov_info(vf,-1);
  153558. ch2=vi->channels;
  153559. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  153560. w2=vorbis_window(&vf->vd,0);
  153561. /* consolidate and expose the buffer. */
  153562. vorbis_synthesis_lapout(&vf->vd,&pcm);
  153563. /* splice */
  153564. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  153565. /* done */
  153566. return(0);
  153567. }
  153568. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  153569. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  153570. }
  153571. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  153572. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  153573. }
  153574. #endif
  153575. /*** End of inlined file: vorbisfile.c ***/
  153576. /*** Start of inlined file: window.c ***/
  153577. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  153578. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  153579. // tasks..
  153580. #if JUCE_MSVC
  153581. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  153582. #endif
  153583. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  153584. #if JUCE_USE_OGGVORBIS
  153585. #include <stdlib.h>
  153586. #include <math.h>
  153587. static float vwin64[32] = {
  153588. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  153589. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  153590. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  153591. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  153592. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  153593. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  153594. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  153595. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  153596. };
  153597. static float vwin128[64] = {
  153598. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  153599. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  153600. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  153601. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  153602. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  153603. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  153604. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  153605. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  153606. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  153607. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  153608. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  153609. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  153610. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  153611. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  153612. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  153613. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  153614. };
  153615. static float vwin256[128] = {
  153616. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  153617. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  153618. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  153619. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  153620. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  153621. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  153622. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  153623. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  153624. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  153625. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  153626. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  153627. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  153628. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  153629. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  153630. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  153631. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  153632. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  153633. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  153634. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  153635. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  153636. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  153637. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  153638. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  153639. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  153640. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  153641. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  153642. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  153643. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  153644. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  153645. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  153646. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  153647. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  153648. };
  153649. static float vwin512[256] = {
  153650. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  153651. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  153652. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  153653. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  153654. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  153655. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  153656. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  153657. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  153658. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  153659. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  153660. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  153661. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  153662. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  153663. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  153664. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  153665. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  153666. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  153667. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  153668. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  153669. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  153670. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  153671. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  153672. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  153673. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  153674. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  153675. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  153676. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  153677. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  153678. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  153679. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  153680. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  153681. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  153682. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  153683. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  153684. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  153685. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  153686. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  153687. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  153688. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  153689. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  153690. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  153691. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  153692. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  153693. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  153694. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  153695. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  153696. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  153697. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  153698. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  153699. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  153700. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  153701. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  153702. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  153703. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  153704. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  153705. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  153706. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  153707. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  153708. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  153709. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  153710. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  153711. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  153712. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  153713. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  153714. };
  153715. static float vwin1024[512] = {
  153716. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  153717. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  153718. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  153719. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  153720. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  153721. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  153722. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  153723. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  153724. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  153725. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  153726. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  153727. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  153728. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  153729. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  153730. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  153731. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  153732. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  153733. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  153734. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  153735. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  153736. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  153737. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  153738. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  153739. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  153740. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  153741. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  153742. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  153743. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  153744. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  153745. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  153746. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  153747. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  153748. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  153749. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  153750. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  153751. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  153752. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  153753. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  153754. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  153755. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  153756. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  153757. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  153758. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  153759. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  153760. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  153761. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  153762. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  153763. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  153764. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  153765. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  153766. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  153767. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  153768. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  153769. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  153770. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  153771. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  153772. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  153773. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  153774. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  153775. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  153776. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  153777. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  153778. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  153779. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  153780. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  153781. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  153782. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  153783. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  153784. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  153785. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  153786. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  153787. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  153788. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  153789. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  153790. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  153791. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  153792. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  153793. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  153794. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  153795. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  153796. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  153797. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  153798. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  153799. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  153800. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  153801. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  153802. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  153803. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  153804. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  153805. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  153806. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  153807. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  153808. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  153809. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  153810. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  153811. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  153812. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  153813. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  153814. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  153815. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  153816. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  153817. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  153818. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  153819. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  153820. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  153821. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  153822. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  153823. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  153824. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  153825. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  153826. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  153827. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  153828. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  153829. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  153830. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  153831. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  153832. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  153833. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  153834. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  153835. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  153836. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  153837. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  153838. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  153839. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  153840. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  153841. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  153842. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  153843. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  153844. };
  153845. static float vwin2048[1024] = {
  153846. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  153847. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  153848. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  153849. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  153850. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  153851. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  153852. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  153853. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  153854. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  153855. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  153856. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  153857. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  153858. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  153859. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  153860. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  153861. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  153862. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  153863. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  153864. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  153865. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  153866. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  153867. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  153868. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  153869. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  153870. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  153871. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  153872. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  153873. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  153874. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  153875. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  153876. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  153877. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  153878. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  153879. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  153880. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  153881. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  153882. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  153883. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  153884. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  153885. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  153886. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  153887. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  153888. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  153889. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  153890. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  153891. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  153892. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  153893. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  153894. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  153895. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  153896. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  153897. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  153898. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  153899. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  153900. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  153901. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  153902. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  153903. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  153904. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  153905. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  153906. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  153907. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  153908. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  153909. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  153910. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  153911. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  153912. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  153913. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  153914. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  153915. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  153916. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  153917. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  153918. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  153919. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  153920. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  153921. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  153922. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  153923. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  153924. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  153925. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  153926. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  153927. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  153928. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  153929. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  153930. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  153931. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  153932. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  153933. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  153934. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  153935. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  153936. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  153937. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  153938. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  153939. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  153940. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  153941. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  153942. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  153943. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  153944. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  153945. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  153946. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  153947. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  153948. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  153949. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  153950. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  153951. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  153952. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  153953. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  153954. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  153955. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  153956. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  153957. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  153958. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  153959. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  153960. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  153961. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  153962. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  153963. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  153964. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  153965. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  153966. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  153967. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  153968. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  153969. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  153970. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  153971. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  153972. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  153973. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  153974. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  153975. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  153976. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  153977. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  153978. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  153979. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  153980. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  153981. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  153982. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  153983. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  153984. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  153985. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  153986. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  153987. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  153988. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  153989. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  153990. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  153991. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  153992. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  153993. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  153994. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  153995. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  153996. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  153997. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  153998. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  153999. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  154000. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  154001. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  154002. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  154003. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  154004. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  154005. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  154006. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  154007. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  154008. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  154009. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  154010. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  154011. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  154012. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  154013. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  154014. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  154015. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  154016. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  154017. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  154018. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  154019. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  154020. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  154021. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  154022. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  154023. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  154024. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  154025. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  154026. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  154027. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  154028. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  154029. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  154030. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  154031. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  154032. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  154033. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  154034. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  154035. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  154036. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  154037. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  154038. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  154039. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  154040. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  154041. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  154042. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  154043. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  154044. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  154045. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  154046. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  154047. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  154048. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  154049. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  154050. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  154051. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  154052. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  154053. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  154054. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  154055. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  154056. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  154057. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  154058. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  154059. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  154060. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  154061. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  154062. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  154063. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  154064. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  154065. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  154066. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  154067. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  154068. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  154069. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  154070. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  154071. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  154072. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  154073. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  154074. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  154075. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  154076. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  154077. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  154078. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  154079. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  154080. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  154081. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  154082. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  154083. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  154084. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  154085. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  154086. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  154087. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  154088. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  154089. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  154090. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  154091. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  154092. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  154093. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  154094. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  154095. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  154096. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  154097. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  154098. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  154099. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  154100. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  154101. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  154102. };
  154103. static float vwin4096[2048] = {
  154104. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  154105. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  154106. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  154107. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  154108. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  154109. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  154110. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  154111. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  154112. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  154113. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  154114. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  154115. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  154116. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  154117. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  154118. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  154119. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  154120. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  154121. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  154122. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  154123. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  154124. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  154125. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  154126. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  154127. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  154128. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  154129. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  154130. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  154131. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  154132. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  154133. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  154134. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  154135. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  154136. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  154137. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  154138. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  154139. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  154140. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  154141. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  154142. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  154143. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  154144. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  154145. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  154146. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  154147. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  154148. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  154149. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  154150. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  154151. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  154152. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  154153. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  154154. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  154155. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  154156. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  154157. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  154158. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  154159. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  154160. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  154161. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  154162. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  154163. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  154164. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  154165. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  154166. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  154167. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  154168. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  154169. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  154170. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  154171. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  154172. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  154173. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  154174. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  154175. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  154176. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  154177. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  154178. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  154179. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  154180. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  154181. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  154182. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  154183. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  154184. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  154185. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  154186. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  154187. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  154188. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  154189. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  154190. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  154191. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  154192. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  154193. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  154194. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  154195. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  154196. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  154197. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  154198. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  154199. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  154200. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  154201. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  154202. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  154203. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  154204. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  154205. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  154206. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  154207. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  154208. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  154209. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  154210. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  154211. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  154212. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  154213. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  154214. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  154215. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  154216. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  154217. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  154218. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  154219. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  154220. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  154221. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  154222. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  154223. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  154224. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  154225. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  154226. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  154227. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  154228. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  154229. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  154230. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  154231. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  154232. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  154233. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  154234. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  154235. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  154236. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  154237. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  154238. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  154239. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  154240. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  154241. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  154242. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  154243. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  154244. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  154245. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  154246. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  154247. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  154248. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  154249. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  154250. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  154251. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  154252. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  154253. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  154254. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  154255. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  154256. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  154257. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  154258. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  154259. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  154260. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  154261. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  154262. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  154263. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  154264. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  154265. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  154266. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  154267. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  154268. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  154269. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  154270. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  154271. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  154272. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  154273. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  154274. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  154275. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  154276. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  154277. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  154278. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  154279. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  154280. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  154281. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  154282. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  154283. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  154284. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  154285. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  154286. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  154287. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  154288. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  154289. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  154290. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  154291. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  154292. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  154293. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  154294. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  154295. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  154296. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  154297. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  154298. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  154299. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  154300. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  154301. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  154302. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  154303. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  154304. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  154305. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  154306. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  154307. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  154308. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  154309. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  154310. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  154311. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  154312. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  154313. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  154314. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  154315. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  154316. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  154317. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  154318. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  154319. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  154320. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  154321. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  154322. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  154323. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  154324. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  154325. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  154326. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  154327. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  154328. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  154329. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  154330. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  154331. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  154332. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  154333. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  154334. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  154335. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  154336. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  154337. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  154338. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  154339. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  154340. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  154341. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  154342. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  154343. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  154344. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  154345. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  154346. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  154347. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  154348. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  154349. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  154350. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  154351. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  154352. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  154353. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  154354. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  154355. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  154356. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  154357. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  154358. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  154359. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  154360. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  154361. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  154362. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  154363. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  154364. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  154365. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  154366. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  154367. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  154368. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  154369. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  154370. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  154371. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  154372. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  154373. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  154374. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  154375. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  154376. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  154377. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  154378. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  154379. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  154380. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  154381. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  154382. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  154383. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  154384. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  154385. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  154386. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  154387. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  154388. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  154389. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  154390. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  154391. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  154392. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  154393. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  154394. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  154395. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  154396. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  154397. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  154398. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  154399. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  154400. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  154401. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  154402. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  154403. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  154404. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  154405. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  154406. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  154407. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  154408. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  154409. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  154410. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  154411. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  154412. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  154413. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  154414. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  154415. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  154416. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  154417. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  154418. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  154419. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  154420. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  154421. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  154422. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  154423. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  154424. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  154425. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  154426. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  154427. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  154428. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  154429. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  154430. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  154431. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  154432. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  154433. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  154434. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  154435. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  154436. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  154437. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  154438. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  154439. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  154440. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  154441. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  154442. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  154443. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  154444. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  154445. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  154446. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  154447. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  154448. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  154449. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  154450. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  154451. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  154452. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  154453. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  154454. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  154455. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  154456. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  154457. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  154458. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  154459. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  154460. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  154461. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  154462. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  154463. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  154464. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  154465. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  154466. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  154467. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  154468. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  154469. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  154470. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  154471. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  154472. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  154473. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  154474. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  154475. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  154476. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  154477. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  154478. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  154479. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  154480. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  154481. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  154482. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  154483. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  154484. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  154485. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  154486. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  154487. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  154488. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  154489. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  154490. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  154491. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  154492. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  154493. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  154494. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  154495. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  154496. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  154497. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  154498. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  154499. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  154500. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  154501. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  154502. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  154503. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  154504. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  154505. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  154506. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  154507. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  154508. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  154509. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  154510. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  154511. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  154512. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  154513. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  154514. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  154515. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  154516. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  154517. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  154518. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  154519. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  154520. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  154521. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  154522. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  154523. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  154524. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  154525. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  154526. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  154527. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  154528. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  154529. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  154530. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  154531. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  154532. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  154533. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  154534. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  154535. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  154536. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  154537. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  154538. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  154539. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  154540. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  154541. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  154542. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  154543. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  154544. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  154545. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  154546. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  154547. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  154548. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  154549. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  154550. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  154551. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  154552. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  154553. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  154554. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  154555. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  154556. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  154557. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  154558. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  154559. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  154560. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  154561. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  154562. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  154563. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  154564. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  154565. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  154566. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  154567. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  154568. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  154569. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  154570. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  154571. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  154572. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  154573. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  154574. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  154575. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  154576. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  154577. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  154578. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  154579. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  154580. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  154581. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  154582. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  154583. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  154584. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  154585. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  154586. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  154587. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  154588. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  154589. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  154590. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  154591. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  154592. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  154593. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  154594. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  154595. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  154596. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  154597. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  154598. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  154599. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  154600. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  154601. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  154602. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  154603. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  154604. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  154605. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  154606. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  154607. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  154608. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  154609. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  154610. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  154611. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  154612. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  154613. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  154614. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  154615. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154616. };
  154617. static float vwin8192[4096] = {
  154618. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  154619. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  154620. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  154621. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  154622. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  154623. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  154624. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  154625. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  154626. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  154627. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  154628. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  154629. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  154630. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  154631. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  154632. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  154633. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  154634. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  154635. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  154636. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  154637. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  154638. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  154639. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  154640. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  154641. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  154642. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  154643. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  154644. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  154645. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  154646. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  154647. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  154648. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  154649. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  154650. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  154651. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  154652. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  154653. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  154654. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  154655. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  154656. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  154657. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  154658. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  154659. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  154660. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  154661. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  154662. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  154663. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  154664. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  154665. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  154666. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  154667. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  154668. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  154669. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  154670. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  154671. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  154672. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  154673. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  154674. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  154675. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  154676. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  154677. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  154678. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  154679. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  154680. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  154681. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  154682. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  154683. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  154684. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  154685. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  154686. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  154687. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  154688. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  154689. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  154690. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  154691. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  154692. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  154693. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  154694. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  154695. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  154696. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  154697. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  154698. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  154699. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  154700. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  154701. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  154702. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  154703. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  154704. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  154705. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  154706. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  154707. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  154708. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  154709. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  154710. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  154711. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  154712. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  154713. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  154714. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  154715. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  154716. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  154717. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  154718. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  154719. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  154720. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  154721. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  154722. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  154723. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  154724. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  154725. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  154726. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  154727. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  154728. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  154729. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  154730. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  154731. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  154732. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  154733. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  154734. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  154735. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  154736. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  154737. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  154738. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  154739. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  154740. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  154741. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  154742. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  154743. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  154744. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  154745. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  154746. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  154747. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  154748. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  154749. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  154750. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  154751. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  154752. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  154753. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  154754. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  154755. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  154756. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  154757. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  154758. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  154759. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  154760. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  154761. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  154762. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  154763. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  154764. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  154765. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  154766. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  154767. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  154768. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  154769. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  154770. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  154771. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  154772. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  154773. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  154774. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  154775. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  154776. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  154777. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  154778. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  154779. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  154780. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  154781. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  154782. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  154783. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  154784. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  154785. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  154786. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  154787. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  154788. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  154789. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  154790. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  154791. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  154792. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  154793. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  154794. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  154795. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  154796. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  154797. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  154798. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  154799. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  154800. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  154801. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  154802. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  154803. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  154804. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  154805. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  154806. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  154807. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  154808. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  154809. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  154810. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  154811. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  154812. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  154813. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  154814. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  154815. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  154816. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  154817. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  154818. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  154819. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  154820. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  154821. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  154822. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  154823. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  154824. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  154825. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  154826. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  154827. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  154828. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  154829. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  154830. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  154831. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  154832. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  154833. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  154834. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  154835. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  154836. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  154837. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  154838. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  154839. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  154840. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  154841. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  154842. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  154843. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  154844. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  154845. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  154846. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  154847. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  154848. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  154849. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  154850. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  154851. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  154852. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  154853. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  154854. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  154855. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  154856. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  154857. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  154858. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  154859. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  154860. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  154861. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  154862. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  154863. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  154864. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  154865. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  154866. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  154867. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  154868. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  154869. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  154870. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  154871. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  154872. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  154873. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  154874. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  154875. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  154876. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  154877. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  154878. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  154879. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  154880. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  154881. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  154882. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  154883. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  154884. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  154885. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  154886. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  154887. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  154888. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  154889. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  154890. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  154891. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  154892. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  154893. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  154894. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  154895. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  154896. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  154897. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  154898. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  154899. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  154900. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  154901. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  154902. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  154903. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  154904. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  154905. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  154906. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  154907. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  154908. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  154909. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  154910. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  154911. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  154912. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  154913. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  154914. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  154915. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  154916. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  154917. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  154918. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  154919. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  154920. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  154921. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  154922. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  154923. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  154924. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  154925. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  154926. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  154927. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  154928. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  154929. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  154930. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  154931. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  154932. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  154933. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  154934. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  154935. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  154936. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  154937. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  154938. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  154939. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  154940. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  154941. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  154942. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  154943. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  154944. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  154945. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  154946. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  154947. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  154948. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  154949. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  154950. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  154951. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  154952. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  154953. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  154954. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  154955. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  154956. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  154957. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  154958. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  154959. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  154960. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  154961. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  154962. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  154963. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  154964. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  154965. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  154966. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  154967. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  154968. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  154969. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  154970. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  154971. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  154972. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  154973. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  154974. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  154975. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  154976. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  154977. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  154978. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  154979. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  154980. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  154981. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  154982. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  154983. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  154984. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  154985. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  154986. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  154987. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  154988. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  154989. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  154990. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  154991. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  154992. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  154993. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  154994. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  154995. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  154996. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  154997. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  154998. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  154999. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  155000. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  155001. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  155002. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  155003. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  155004. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  155005. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  155006. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  155007. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  155008. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  155009. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  155010. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  155011. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  155012. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  155013. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  155014. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  155015. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  155016. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  155017. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  155018. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  155019. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  155020. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  155021. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  155022. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  155023. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  155024. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  155025. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  155026. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  155027. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  155028. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  155029. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  155030. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  155031. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  155032. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  155033. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  155034. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  155035. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  155036. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  155037. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  155038. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  155039. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  155040. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  155041. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  155042. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  155043. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  155044. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  155045. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  155046. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  155047. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  155048. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  155049. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  155050. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  155051. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  155052. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  155053. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  155054. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  155055. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  155056. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  155057. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  155058. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  155059. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  155060. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  155061. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  155062. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  155063. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  155064. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  155065. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  155066. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  155067. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  155068. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  155069. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  155070. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  155071. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  155072. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  155073. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  155074. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  155075. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  155076. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  155077. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  155078. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  155079. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  155080. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  155081. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  155082. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  155083. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  155084. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  155085. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  155086. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  155087. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  155088. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  155089. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  155090. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  155091. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  155092. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  155093. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  155094. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  155095. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  155096. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  155097. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  155098. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  155099. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  155100. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  155101. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  155102. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  155103. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  155104. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  155105. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  155106. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  155107. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  155108. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  155109. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  155110. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  155111. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  155112. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  155113. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  155114. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  155115. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  155116. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  155117. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  155118. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  155119. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  155120. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  155121. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  155122. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  155123. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  155124. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  155125. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  155126. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  155127. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  155128. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  155129. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  155130. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  155131. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  155132. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  155133. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  155134. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  155135. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  155136. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  155137. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  155138. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  155139. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  155140. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  155141. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  155142. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  155143. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  155144. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  155145. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  155146. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  155147. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  155148. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  155149. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  155150. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  155151. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  155152. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  155153. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  155154. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  155155. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  155156. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  155157. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  155158. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  155159. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  155160. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  155161. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  155162. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  155163. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  155164. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  155165. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  155166. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  155167. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  155168. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  155169. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  155170. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  155171. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  155172. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  155173. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  155174. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  155175. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  155176. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  155177. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  155178. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  155179. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  155180. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  155181. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  155182. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  155183. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  155184. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  155185. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  155186. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  155187. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  155188. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  155189. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  155190. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  155191. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  155192. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  155193. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  155194. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  155195. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  155196. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  155197. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  155198. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  155199. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  155200. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  155201. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  155202. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  155203. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  155204. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  155205. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  155206. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  155207. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  155208. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  155209. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  155210. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  155211. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  155212. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  155213. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  155214. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  155215. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  155216. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  155217. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  155218. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  155219. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  155220. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  155221. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  155222. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  155223. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  155224. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  155225. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  155226. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  155227. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  155228. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  155229. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  155230. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  155231. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  155232. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  155233. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  155234. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  155235. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  155236. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  155237. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  155238. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  155239. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  155240. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  155241. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  155242. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  155243. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  155244. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  155245. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  155246. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  155247. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  155248. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  155249. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  155250. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  155251. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  155252. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  155253. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  155254. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  155255. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  155256. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  155257. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  155258. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  155259. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  155260. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  155261. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  155262. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  155263. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  155264. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  155265. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  155266. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  155267. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  155268. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  155269. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  155270. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  155271. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  155272. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  155273. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  155274. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  155275. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  155276. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  155277. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  155278. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  155279. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  155280. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  155281. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  155282. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  155283. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  155284. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  155285. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  155286. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  155287. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  155288. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  155289. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  155290. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  155291. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  155292. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  155293. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  155294. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  155295. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  155296. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  155297. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  155298. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  155299. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  155300. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  155301. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  155302. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  155303. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  155304. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  155305. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  155306. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  155307. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  155308. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  155309. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  155310. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  155311. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  155312. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  155313. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  155314. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  155315. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  155316. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  155317. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  155318. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  155319. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  155320. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  155321. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  155322. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  155323. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  155324. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  155325. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  155326. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  155327. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  155328. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  155329. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  155330. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  155331. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  155332. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  155333. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  155334. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  155335. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  155336. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  155337. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  155338. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  155339. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  155340. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  155341. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  155342. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  155343. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  155344. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  155345. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  155346. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  155347. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  155348. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  155349. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  155350. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  155351. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  155352. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  155353. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  155354. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  155355. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  155356. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  155357. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  155358. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  155359. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  155360. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  155361. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  155362. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  155363. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  155364. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  155365. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  155366. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  155367. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  155368. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  155369. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  155370. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  155371. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  155372. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  155373. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  155374. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  155375. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  155376. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  155377. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  155378. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  155379. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  155380. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  155381. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  155382. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  155383. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  155384. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  155385. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  155386. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  155387. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  155388. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  155389. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  155390. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  155391. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  155392. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  155393. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  155394. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  155395. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  155396. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  155397. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  155398. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  155399. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  155400. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  155401. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  155402. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  155403. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  155404. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  155405. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  155406. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  155407. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  155408. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  155409. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  155410. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  155411. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  155412. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  155413. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  155414. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  155415. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  155416. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  155417. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  155418. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  155419. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  155420. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  155421. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  155422. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  155423. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  155424. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  155425. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  155426. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  155427. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  155428. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  155429. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  155430. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  155431. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  155432. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  155433. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  155434. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  155435. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  155436. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  155437. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  155438. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  155439. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  155440. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  155441. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  155442. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  155443. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  155444. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  155445. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  155446. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  155447. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  155448. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  155449. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  155450. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  155451. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  155452. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  155453. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  155454. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  155455. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  155456. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  155457. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  155458. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  155459. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  155460. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  155461. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  155462. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  155463. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  155464. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  155465. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  155466. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  155467. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  155468. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  155469. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  155470. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  155471. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  155472. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  155473. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  155474. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  155475. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  155476. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  155477. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  155478. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  155479. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  155480. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  155481. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  155482. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  155483. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  155484. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  155485. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  155486. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  155487. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  155488. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  155489. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  155490. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  155491. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  155492. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  155493. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  155494. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  155495. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  155496. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  155497. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  155498. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  155499. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  155500. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  155501. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  155502. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  155503. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  155504. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  155505. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  155506. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  155507. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  155508. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  155509. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  155510. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  155511. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  155512. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  155513. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  155514. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  155515. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  155516. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  155517. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  155518. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  155519. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  155520. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  155521. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  155522. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  155523. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  155524. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  155525. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  155526. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  155527. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  155528. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  155529. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  155530. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  155531. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  155532. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  155533. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  155534. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  155535. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  155536. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  155537. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  155538. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  155539. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  155540. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  155541. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  155542. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  155543. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  155544. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  155545. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  155546. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  155547. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  155548. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  155549. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  155550. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  155551. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  155552. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  155553. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  155554. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  155555. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  155556. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  155557. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  155558. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  155559. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  155560. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  155561. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  155562. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  155563. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  155564. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  155565. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  155566. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  155567. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  155568. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  155569. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  155570. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  155571. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  155572. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  155573. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  155574. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  155575. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  155576. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  155577. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  155578. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  155579. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  155580. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  155581. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  155582. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  155583. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  155584. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  155585. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  155586. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  155587. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  155588. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  155589. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  155590. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  155591. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  155592. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  155593. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  155594. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  155595. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  155596. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  155597. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  155598. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  155599. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  155600. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  155601. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  155602. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  155603. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  155604. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  155605. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  155606. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  155607. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  155608. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  155609. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  155610. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  155611. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  155612. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  155613. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  155614. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  155615. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  155616. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  155617. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  155618. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  155619. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  155620. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  155621. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  155622. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  155623. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  155624. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  155625. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  155626. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  155627. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  155628. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  155629. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  155630. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  155631. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  155632. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  155633. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  155634. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  155635. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  155636. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  155637. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  155638. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  155639. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  155640. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  155641. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  155642. };
  155643. static float *vwin[8] = {
  155644. vwin64,
  155645. vwin128,
  155646. vwin256,
  155647. vwin512,
  155648. vwin1024,
  155649. vwin2048,
  155650. vwin4096,
  155651. vwin8192,
  155652. };
  155653. float *_vorbis_window_get(int n){
  155654. return vwin[n];
  155655. }
  155656. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  155657. int lW,int W,int nW){
  155658. lW=(W?lW:0);
  155659. nW=(W?nW:0);
  155660. {
  155661. float *windowLW=vwin[winno[lW]];
  155662. float *windowNW=vwin[winno[nW]];
  155663. long n=blocksizes[W];
  155664. long ln=blocksizes[lW];
  155665. long rn=blocksizes[nW];
  155666. long leftbegin=n/4-ln/4;
  155667. long leftend=leftbegin+ln/2;
  155668. long rightbegin=n/2+n/4-rn/4;
  155669. long rightend=rightbegin+rn/2;
  155670. int i,p;
  155671. for(i=0;i<leftbegin;i++)
  155672. d[i]=0.f;
  155673. for(p=0;i<leftend;i++,p++)
  155674. d[i]*=windowLW[p];
  155675. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  155676. d[i]*=windowNW[p];
  155677. for(;i<n;i++)
  155678. d[i]=0.f;
  155679. }
  155680. }
  155681. #endif
  155682. /*** End of inlined file: window.c ***/
  155683. #else
  155684. #include <vorbis/vorbisenc.h>
  155685. #include <vorbis/codec.h>
  155686. #include <vorbis/vorbisfile.h>
  155687. #endif
  155688. }
  155689. #undef max
  155690. #undef min
  155691. BEGIN_JUCE_NAMESPACE
  155692. static const char* const oggFormatName = "Ogg-Vorbis file";
  155693. static const char* const oggExtensions[] = { ".ogg", 0 };
  155694. class OggReader : public AudioFormatReader
  155695. {
  155696. OggVorbisNamespace::OggVorbis_File ovFile;
  155697. OggVorbisNamespace::ov_callbacks callbacks;
  155698. AudioSampleBuffer reservoir;
  155699. int reservoirStart, samplesInReservoir;
  155700. public:
  155701. OggReader (InputStream* const inp)
  155702. : AudioFormatReader (inp, TRANS (oggFormatName)),
  155703. reservoir (2, 4096),
  155704. reservoirStart (0),
  155705. samplesInReservoir (0)
  155706. {
  155707. using namespace OggVorbisNamespace;
  155708. sampleRate = 0;
  155709. usesFloatingPointData = true;
  155710. callbacks.read_func = &oggReadCallback;
  155711. callbacks.seek_func = &oggSeekCallback;
  155712. callbacks.close_func = &oggCloseCallback;
  155713. callbacks.tell_func = &oggTellCallback;
  155714. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  155715. if (err == 0)
  155716. {
  155717. vorbis_info* info = ov_info (&ovFile, -1);
  155718. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  155719. numChannels = info->channels;
  155720. bitsPerSample = 16;
  155721. sampleRate = info->rate;
  155722. reservoir.setSize (numChannels,
  155723. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  155724. }
  155725. }
  155726. ~OggReader()
  155727. {
  155728. OggVorbisNamespace::ov_clear (&ovFile);
  155729. }
  155730. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  155731. int64 startSampleInFile, int numSamples)
  155732. {
  155733. while (numSamples > 0)
  155734. {
  155735. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  155736. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  155737. {
  155738. // got a few samples overlapping, so use them before seeking..
  155739. const int numToUse = jmin (numSamples, numAvailable);
  155740. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  155741. if (destSamples[i] != 0)
  155742. memcpy (destSamples[i] + startOffsetInDestBuffer,
  155743. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  155744. sizeof (float) * numToUse);
  155745. startSampleInFile += numToUse;
  155746. numSamples -= numToUse;
  155747. startOffsetInDestBuffer += numToUse;
  155748. if (numSamples == 0)
  155749. break;
  155750. }
  155751. if (startSampleInFile < reservoirStart
  155752. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  155753. {
  155754. // buffer miss, so refill the reservoir
  155755. int bitStream = 0;
  155756. reservoirStart = jmax (0, (int) startSampleInFile);
  155757. samplesInReservoir = reservoir.getNumSamples();
  155758. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  155759. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  155760. int offset = 0;
  155761. int numToRead = samplesInReservoir;
  155762. while (numToRead > 0)
  155763. {
  155764. float** dataIn = 0;
  155765. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  155766. if (samps <= 0)
  155767. break;
  155768. jassert (samps <= numToRead);
  155769. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  155770. {
  155771. memcpy (reservoir.getSampleData (i, offset),
  155772. dataIn[i],
  155773. sizeof (float) * samps);
  155774. }
  155775. numToRead -= samps;
  155776. offset += samps;
  155777. }
  155778. if (numToRead > 0)
  155779. reservoir.clear (offset, numToRead);
  155780. }
  155781. }
  155782. if (numSamples > 0)
  155783. {
  155784. for (int i = numDestChannels; --i >= 0;)
  155785. if (destSamples[i] != 0)
  155786. zeromem (destSamples[i] + startOffsetInDestBuffer,
  155787. sizeof (int) * numSamples);
  155788. }
  155789. return true;
  155790. }
  155791. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  155792. {
  155793. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  155794. }
  155795. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  155796. {
  155797. InputStream* const in = static_cast <InputStream*> (datasource);
  155798. if (whence == SEEK_CUR)
  155799. offset += in->getPosition();
  155800. else if (whence == SEEK_END)
  155801. offset += in->getTotalLength();
  155802. in->setPosition (offset);
  155803. return 0;
  155804. }
  155805. static int oggCloseCallback (void*)
  155806. {
  155807. return 0;
  155808. }
  155809. static long oggTellCallback (void* datasource)
  155810. {
  155811. return (long) static_cast <InputStream*> (datasource)->getPosition();
  155812. }
  155813. juce_UseDebuggingNewOperator
  155814. };
  155815. class OggWriter : public AudioFormatWriter
  155816. {
  155817. OggVorbisNamespace::ogg_stream_state os;
  155818. OggVorbisNamespace::ogg_page og;
  155819. OggVorbisNamespace::ogg_packet op;
  155820. OggVorbisNamespace::vorbis_info vi;
  155821. OggVorbisNamespace::vorbis_comment vc;
  155822. OggVorbisNamespace::vorbis_dsp_state vd;
  155823. OggVorbisNamespace::vorbis_block vb;
  155824. public:
  155825. bool ok;
  155826. OggWriter (OutputStream* const out,
  155827. const double sampleRate,
  155828. const int numChannels,
  155829. const int bitsPerSample,
  155830. const int qualityIndex)
  155831. : AudioFormatWriter (out, TRANS (oggFormatName),
  155832. sampleRate,
  155833. numChannels,
  155834. bitsPerSample)
  155835. {
  155836. using namespace OggVorbisNamespace;
  155837. ok = false;
  155838. vorbis_info_init (&vi);
  155839. if (vorbis_encode_init_vbr (&vi,
  155840. numChannels,
  155841. (int) sampleRate,
  155842. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  155843. {
  155844. vorbis_comment_init (&vc);
  155845. if (JUCEApplication::getInstance() != 0)
  155846. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  155847. vorbis_analysis_init (&vd, &vi);
  155848. vorbis_block_init (&vd, &vb);
  155849. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  155850. ogg_packet header;
  155851. ogg_packet header_comm;
  155852. ogg_packet header_code;
  155853. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  155854. ogg_stream_packetin (&os, &header);
  155855. ogg_stream_packetin (&os, &header_comm);
  155856. ogg_stream_packetin (&os, &header_code);
  155857. for (;;)
  155858. {
  155859. if (ogg_stream_flush (&os, &og) == 0)
  155860. break;
  155861. output->write (og.header, og.header_len);
  155862. output->write (og.body, og.body_len);
  155863. }
  155864. ok = true;
  155865. }
  155866. }
  155867. ~OggWriter()
  155868. {
  155869. using namespace OggVorbisNamespace;
  155870. if (ok)
  155871. {
  155872. // write a zero-length packet to show ogg that we're finished..
  155873. write (0, 0);
  155874. ogg_stream_clear (&os);
  155875. vorbis_block_clear (&vb);
  155876. vorbis_dsp_clear (&vd);
  155877. vorbis_comment_clear (&vc);
  155878. vorbis_info_clear (&vi);
  155879. output->flush();
  155880. }
  155881. else
  155882. {
  155883. vorbis_info_clear (&vi);
  155884. output = 0; // to stop the base class deleting this, as it needs to be returned
  155885. // to the caller of createWriter()
  155886. }
  155887. }
  155888. bool write (const int** samplesToWrite, int numSamples)
  155889. {
  155890. using namespace OggVorbisNamespace;
  155891. if (! ok)
  155892. return false;
  155893. if (numSamples > 0)
  155894. {
  155895. const double gain = 1.0 / 0x80000000u;
  155896. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  155897. for (int i = numChannels; --i >= 0;)
  155898. {
  155899. float* const dst = vorbisBuffer[i];
  155900. const int* const src = samplesToWrite [i];
  155901. if (src != 0 && dst != 0)
  155902. {
  155903. for (int j = 0; j < numSamples; ++j)
  155904. dst[j] = (float) (src[j] * gain);
  155905. }
  155906. }
  155907. }
  155908. vorbis_analysis_wrote (&vd, numSamples);
  155909. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  155910. {
  155911. vorbis_analysis (&vb, 0);
  155912. vorbis_bitrate_addblock (&vb);
  155913. while (vorbis_bitrate_flushpacket (&vd, &op))
  155914. {
  155915. ogg_stream_packetin (&os, &op);
  155916. for (;;)
  155917. {
  155918. if (ogg_stream_pageout (&os, &og) == 0)
  155919. break;
  155920. output->write (og.header, og.header_len);
  155921. output->write (og.body, og.body_len);
  155922. if (ogg_page_eos (&og))
  155923. break;
  155924. }
  155925. }
  155926. }
  155927. return true;
  155928. }
  155929. juce_UseDebuggingNewOperator
  155930. };
  155931. OggVorbisAudioFormat::OggVorbisAudioFormat()
  155932. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  155933. {
  155934. }
  155935. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  155936. {
  155937. }
  155938. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  155939. {
  155940. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  155941. return Array <int> (rates);
  155942. }
  155943. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  155944. {
  155945. Array <int> depths;
  155946. depths.add (32);
  155947. return depths;
  155948. }
  155949. bool OggVorbisAudioFormat::canDoStereo()
  155950. {
  155951. return true;
  155952. }
  155953. bool OggVorbisAudioFormat::canDoMono()
  155954. {
  155955. return true;
  155956. }
  155957. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  155958. const bool deleteStreamIfOpeningFails)
  155959. {
  155960. ScopedPointer <OggReader> r (new OggReader (in));
  155961. if (r->sampleRate != 0)
  155962. return r.release();
  155963. if (! deleteStreamIfOpeningFails)
  155964. r->input = 0;
  155965. return 0;
  155966. }
  155967. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  155968. double sampleRate,
  155969. unsigned int numChannels,
  155970. int bitsPerSample,
  155971. const StringPairArray& /*metadataValues*/,
  155972. int qualityOptionIndex)
  155973. {
  155974. ScopedPointer <OggWriter> w (new OggWriter (out,
  155975. sampleRate,
  155976. numChannels,
  155977. bitsPerSample,
  155978. qualityOptionIndex));
  155979. return w->ok ? w.release() : 0;
  155980. }
  155981. bool OggVorbisAudioFormat::isCompressed()
  155982. {
  155983. return true;
  155984. }
  155985. const StringArray OggVorbisAudioFormat::getQualityOptions()
  155986. {
  155987. StringArray s;
  155988. s.add ("Low Quality");
  155989. s.add ("Medium Quality");
  155990. s.add ("High Quality");
  155991. return s;
  155992. }
  155993. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  155994. {
  155995. FileInputStream* const in = source.createInputStream();
  155996. if (in != 0)
  155997. {
  155998. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  155999. if (r != 0)
  156000. {
  156001. const int64 numSamps = r->lengthInSamples;
  156002. r = 0;
  156003. const int64 fileNumSamps = source.getSize() / 4;
  156004. const double ratio = numSamps / (double) fileNumSamps;
  156005. if (ratio > 12.0)
  156006. return 0;
  156007. else if (ratio > 6.0)
  156008. return 1;
  156009. else
  156010. return 2;
  156011. }
  156012. }
  156013. return 1;
  156014. }
  156015. END_JUCE_NAMESPACE
  156016. #endif
  156017. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  156018. #endif
  156019. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  156020. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  156021. #if JUCE_MSVC
  156022. #pragma warning (push)
  156023. #endif
  156024. namespace jpeglibNamespace
  156025. {
  156026. #if JUCE_INCLUDE_JPEGLIB_CODE
  156027. #if JUCE_MINGW
  156028. typedef unsigned char boolean;
  156029. #endif
  156030. extern "C"
  156031. {
  156032. #define JPEG_INTERNALS
  156033. #undef FAR
  156034. /*** Start of inlined file: jpeglib.h ***/
  156035. #ifndef JPEGLIB_H
  156036. #define JPEGLIB_H
  156037. /*
  156038. * First we include the configuration files that record how this
  156039. * installation of the JPEG library is set up. jconfig.h can be
  156040. * generated automatically for many systems. jmorecfg.h contains
  156041. * manual configuration options that most people need not worry about.
  156042. */
  156043. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  156044. /*** Start of inlined file: jconfig.h ***/
  156045. /* see jconfig.doc for explanations */
  156046. // disable all the warnings under MSVC
  156047. #ifdef _MSC_VER
  156048. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156049. #endif
  156050. #ifdef __BORLANDC__
  156051. #pragma warn -8057
  156052. #pragma warn -8019
  156053. #pragma warn -8004
  156054. #pragma warn -8008
  156055. #endif
  156056. #define HAVE_PROTOTYPES
  156057. #define HAVE_UNSIGNED_CHAR
  156058. #define HAVE_UNSIGNED_SHORT
  156059. /* #define void char */
  156060. /* #define const */
  156061. #undef CHAR_IS_UNSIGNED
  156062. #define HAVE_STDDEF_H
  156063. #define HAVE_STDLIB_H
  156064. #undef NEED_BSD_STRINGS
  156065. #undef NEED_SYS_TYPES_H
  156066. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156067. #undef NEED_SHORT_EXTERNAL_NAMES
  156068. #undef INCOMPLETE_TYPES_BROKEN
  156069. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156070. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156071. typedef unsigned char boolean;
  156072. #endif
  156073. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156074. #ifdef JPEG_INTERNALS
  156075. #undef RIGHT_SHIFT_IS_UNSIGNED
  156076. #endif /* JPEG_INTERNALS */
  156077. #ifdef JPEG_CJPEG_DJPEG
  156078. #define BMP_SUPPORTED /* BMP image file format */
  156079. #define GIF_SUPPORTED /* GIF image file format */
  156080. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156081. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156082. #define TARGA_SUPPORTED /* Targa image file format */
  156083. #define TWO_FILE_COMMANDLINE /* optional */
  156084. #define USE_SETMODE /* Microsoft has setmode() */
  156085. #undef NEED_SIGNAL_CATCHER
  156086. #undef DONT_USE_B_MODE
  156087. #undef PROGRESS_REPORT /* optional */
  156088. #endif /* JPEG_CJPEG_DJPEG */
  156089. /*** End of inlined file: jconfig.h ***/
  156090. /* widely used configuration options */
  156091. #endif
  156092. /*** Start of inlined file: jmorecfg.h ***/
  156093. /*
  156094. * Define BITS_IN_JSAMPLE as either
  156095. * 8 for 8-bit sample values (the usual setting)
  156096. * 12 for 12-bit sample values
  156097. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  156098. * JPEG standard, and the IJG code does not support anything else!
  156099. * We do not support run-time selection of data precision, sorry.
  156100. */
  156101. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  156102. /*
  156103. * Maximum number of components (color channels) allowed in JPEG image.
  156104. * To meet the letter of the JPEG spec, set this to 255. However, darn
  156105. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  156106. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  156107. * really short on memory. (Each allowed component costs a hundred or so
  156108. * bytes of storage, whether actually used in an image or not.)
  156109. */
  156110. #define MAX_COMPONENTS 10 /* maximum number of image components */
  156111. /*
  156112. * Basic data types.
  156113. * You may need to change these if you have a machine with unusual data
  156114. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  156115. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  156116. * but it had better be at least 16.
  156117. */
  156118. /* Representation of a single sample (pixel element value).
  156119. * We frequently allocate large arrays of these, so it's important to keep
  156120. * them small. But if you have memory to burn and access to char or short
  156121. * arrays is very slow on your hardware, you might want to change these.
  156122. */
  156123. #if BITS_IN_JSAMPLE == 8
  156124. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  156125. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  156126. */
  156127. #ifdef HAVE_UNSIGNED_CHAR
  156128. typedef unsigned char JSAMPLE;
  156129. #define GETJSAMPLE(value) ((int) (value))
  156130. #else /* not HAVE_UNSIGNED_CHAR */
  156131. typedef char JSAMPLE;
  156132. #ifdef CHAR_IS_UNSIGNED
  156133. #define GETJSAMPLE(value) ((int) (value))
  156134. #else
  156135. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  156136. #endif /* CHAR_IS_UNSIGNED */
  156137. #endif /* HAVE_UNSIGNED_CHAR */
  156138. #define MAXJSAMPLE 255
  156139. #define CENTERJSAMPLE 128
  156140. #endif /* BITS_IN_JSAMPLE == 8 */
  156141. #if BITS_IN_JSAMPLE == 12
  156142. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  156143. * On nearly all machines "short" will do nicely.
  156144. */
  156145. typedef short JSAMPLE;
  156146. #define GETJSAMPLE(value) ((int) (value))
  156147. #define MAXJSAMPLE 4095
  156148. #define CENTERJSAMPLE 2048
  156149. #endif /* BITS_IN_JSAMPLE == 12 */
  156150. /* Representation of a DCT frequency coefficient.
  156151. * This should be a signed value of at least 16 bits; "short" is usually OK.
  156152. * Again, we allocate large arrays of these, but you can change to int
  156153. * if you have memory to burn and "short" is really slow.
  156154. */
  156155. typedef short JCOEF;
  156156. /* Compressed datastreams are represented as arrays of JOCTET.
  156157. * These must be EXACTLY 8 bits wide, at least once they are written to
  156158. * external storage. Note that when using the stdio data source/destination
  156159. * managers, this is also the data type passed to fread/fwrite.
  156160. */
  156161. #ifdef HAVE_UNSIGNED_CHAR
  156162. typedef unsigned char JOCTET;
  156163. #define GETJOCTET(value) (value)
  156164. #else /* not HAVE_UNSIGNED_CHAR */
  156165. typedef char JOCTET;
  156166. #ifdef CHAR_IS_UNSIGNED
  156167. #define GETJOCTET(value) (value)
  156168. #else
  156169. #define GETJOCTET(value) ((value) & 0xFF)
  156170. #endif /* CHAR_IS_UNSIGNED */
  156171. #endif /* HAVE_UNSIGNED_CHAR */
  156172. /* These typedefs are used for various table entries and so forth.
  156173. * They must be at least as wide as specified; but making them too big
  156174. * won't cost a huge amount of memory, so we don't provide special
  156175. * extraction code like we did for JSAMPLE. (In other words, these
  156176. * typedefs live at a different point on the speed/space tradeoff curve.)
  156177. */
  156178. /* UINT8 must hold at least the values 0..255. */
  156179. #ifdef HAVE_UNSIGNED_CHAR
  156180. typedef unsigned char UINT8;
  156181. #else /* not HAVE_UNSIGNED_CHAR */
  156182. #ifdef CHAR_IS_UNSIGNED
  156183. typedef char UINT8;
  156184. #else /* not CHAR_IS_UNSIGNED */
  156185. typedef short UINT8;
  156186. #endif /* CHAR_IS_UNSIGNED */
  156187. #endif /* HAVE_UNSIGNED_CHAR */
  156188. /* UINT16 must hold at least the values 0..65535. */
  156189. #ifdef HAVE_UNSIGNED_SHORT
  156190. typedef unsigned short UINT16;
  156191. #else /* not HAVE_UNSIGNED_SHORT */
  156192. typedef unsigned int UINT16;
  156193. #endif /* HAVE_UNSIGNED_SHORT */
  156194. /* INT16 must hold at least the values -32768..32767. */
  156195. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  156196. typedef short INT16;
  156197. #endif
  156198. /* INT32 must hold at least signed 32-bit values. */
  156199. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  156200. typedef long INT32;
  156201. #endif
  156202. /* Datatype used for image dimensions. The JPEG standard only supports
  156203. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  156204. * "unsigned int" is sufficient on all machines. However, if you need to
  156205. * handle larger images and you don't mind deviating from the spec, you
  156206. * can change this datatype.
  156207. */
  156208. typedef unsigned int JDIMENSION;
  156209. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  156210. /* These macros are used in all function definitions and extern declarations.
  156211. * You could modify them if you need to change function linkage conventions;
  156212. * in particular, you'll need to do that to make the library a Windows DLL.
  156213. * Another application is to make all functions global for use with debuggers
  156214. * or code profilers that require it.
  156215. */
  156216. /* a function called through method pointers: */
  156217. #define METHODDEF(type) static type
  156218. /* a function used only in its module: */
  156219. #define LOCAL(type) static type
  156220. /* a function referenced thru EXTERNs: */
  156221. #define GLOBAL(type) type
  156222. /* a reference to a GLOBAL function: */
  156223. #define EXTERN(type) extern type
  156224. /* This macro is used to declare a "method", that is, a function pointer.
  156225. * We want to supply prototype parameters if the compiler can cope.
  156226. * Note that the arglist parameter must be parenthesized!
  156227. * Again, you can customize this if you need special linkage keywords.
  156228. */
  156229. #ifdef HAVE_PROTOTYPES
  156230. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  156231. #else
  156232. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  156233. #endif
  156234. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  156235. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  156236. * by just saying "FAR *" where such a pointer is needed. In a few places
  156237. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  156238. */
  156239. #ifdef NEED_FAR_POINTERS
  156240. #define FAR far
  156241. #else
  156242. #define FAR
  156243. #endif
  156244. /*
  156245. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  156246. * in standard header files. Or you may have conflicts with application-
  156247. * specific header files that you want to include together with these files.
  156248. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  156249. */
  156250. #ifndef HAVE_BOOLEAN
  156251. typedef int boolean;
  156252. #endif
  156253. #ifndef FALSE /* in case these macros already exist */
  156254. #define FALSE 0 /* values of boolean */
  156255. #endif
  156256. #ifndef TRUE
  156257. #define TRUE 1
  156258. #endif
  156259. /*
  156260. * The remaining options affect code selection within the JPEG library,
  156261. * but they don't need to be visible to most applications using the library.
  156262. * To minimize application namespace pollution, the symbols won't be
  156263. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  156264. */
  156265. #ifdef JPEG_INTERNALS
  156266. #define JPEG_INTERNAL_OPTIONS
  156267. #endif
  156268. #ifdef JPEG_INTERNAL_OPTIONS
  156269. /*
  156270. * These defines indicate whether to include various optional functions.
  156271. * Undefining some of these symbols will produce a smaller but less capable
  156272. * library. Note that you can leave certain source files out of the
  156273. * compilation/linking process if you've #undef'd the corresponding symbols.
  156274. * (You may HAVE to do that if your compiler doesn't like null source files.)
  156275. */
  156276. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  156277. /* Capability options common to encoder and decoder: */
  156278. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  156279. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  156280. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  156281. /* Encoder capability options: */
  156282. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156283. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156284. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156285. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  156286. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  156287. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  156288. * precision, so jchuff.c normally uses entropy optimization to compute
  156289. * usable tables for higher precision. If you don't want to do optimization,
  156290. * you'll have to supply different default Huffman tables.
  156291. * The exact same statements apply for progressive JPEG: the default tables
  156292. * don't work for progressive mode. (This may get fixed, however.)
  156293. */
  156294. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  156295. /* Decoder capability options: */
  156296. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156297. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156298. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156299. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  156300. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  156301. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  156302. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  156303. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  156304. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  156305. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  156306. /* more capability options later, no doubt */
  156307. /*
  156308. * Ordering of RGB data in scanlines passed to or from the application.
  156309. * If your application wants to deal with data in the order B,G,R, just
  156310. * change these macros. You can also deal with formats such as R,G,B,X
  156311. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  156312. * the offsets will also change the order in which colormap data is organized.
  156313. * RESTRICTIONS:
  156314. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  156315. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  156316. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  156317. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  156318. * is not 3 (they don't understand about dummy color components!). So you
  156319. * can't use color quantization if you change that value.
  156320. */
  156321. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  156322. #define RGB_GREEN 1 /* Offset of Green */
  156323. #define RGB_BLUE 2 /* Offset of Blue */
  156324. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  156325. /* Definitions for speed-related optimizations. */
  156326. /* If your compiler supports inline functions, define INLINE
  156327. * as the inline keyword; otherwise define it as empty.
  156328. */
  156329. #ifndef INLINE
  156330. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  156331. #define INLINE __inline__
  156332. #endif
  156333. #ifndef INLINE
  156334. #define INLINE /* default is to define it as empty */
  156335. #endif
  156336. #endif
  156337. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  156338. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  156339. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  156340. */
  156341. #ifndef MULTIPLIER
  156342. #define MULTIPLIER int /* type for fastest integer multiply */
  156343. #endif
  156344. /* FAST_FLOAT should be either float or double, whichever is done faster
  156345. * by your compiler. (Note that this type is only used in the floating point
  156346. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  156347. * Typically, float is faster in ANSI C compilers, while double is faster in
  156348. * pre-ANSI compilers (because they insist on converting to double anyway).
  156349. * The code below therefore chooses float if we have ANSI-style prototypes.
  156350. */
  156351. #ifndef FAST_FLOAT
  156352. #ifdef HAVE_PROTOTYPES
  156353. #define FAST_FLOAT float
  156354. #else
  156355. #define FAST_FLOAT double
  156356. #endif
  156357. #endif
  156358. #endif /* JPEG_INTERNAL_OPTIONS */
  156359. /*** End of inlined file: jmorecfg.h ***/
  156360. /* seldom changed options */
  156361. /* Version ID for the JPEG library.
  156362. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  156363. */
  156364. #define JPEG_LIB_VERSION 62 /* Version 6b */
  156365. /* Various constants determining the sizes of things.
  156366. * All of these are specified by the JPEG standard, so don't change them
  156367. * if you want to be compatible.
  156368. */
  156369. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  156370. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  156371. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  156372. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  156373. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  156374. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  156375. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  156376. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  156377. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  156378. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  156379. * to handle it. We even let you do this from the jconfig.h file. However,
  156380. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  156381. * sometimes emits noncompliant files doesn't mean you should too.
  156382. */
  156383. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  156384. #ifndef D_MAX_BLOCKS_IN_MCU
  156385. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  156386. #endif
  156387. /* Data structures for images (arrays of samples and of DCT coefficients).
  156388. * On 80x86 machines, the image arrays are too big for near pointers,
  156389. * but the pointer arrays can fit in near memory.
  156390. */
  156391. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  156392. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  156393. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  156394. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  156395. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  156396. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  156397. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  156398. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  156399. /* Types for JPEG compression parameters and working tables. */
  156400. /* DCT coefficient quantization tables. */
  156401. typedef struct {
  156402. /* This array gives the coefficient quantizers in natural array order
  156403. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  156404. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  156405. */
  156406. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  156407. /* This field is used only during compression. It's initialized FALSE when
  156408. * the table is created, and set TRUE when it's been output to the file.
  156409. * You could suppress output of a table by setting this to TRUE.
  156410. * (See jpeg_suppress_tables for an example.)
  156411. */
  156412. boolean sent_table; /* TRUE when table has been output */
  156413. } JQUANT_TBL;
  156414. /* Huffman coding tables. */
  156415. typedef struct {
  156416. /* These two fields directly represent the contents of a JPEG DHT marker */
  156417. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  156418. /* length k bits; bits[0] is unused */
  156419. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  156420. /* This field is used only during compression. It's initialized FALSE when
  156421. * the table is created, and set TRUE when it's been output to the file.
  156422. * You could suppress output of a table by setting this to TRUE.
  156423. * (See jpeg_suppress_tables for an example.)
  156424. */
  156425. boolean sent_table; /* TRUE when table has been output */
  156426. } JHUFF_TBL;
  156427. /* Basic info about one component (color channel). */
  156428. typedef struct {
  156429. /* These values are fixed over the whole image. */
  156430. /* For compression, they must be supplied by parameter setup; */
  156431. /* for decompression, they are read from the SOF marker. */
  156432. int component_id; /* identifier for this component (0..255) */
  156433. int component_index; /* its index in SOF or cinfo->comp_info[] */
  156434. int h_samp_factor; /* horizontal sampling factor (1..4) */
  156435. int v_samp_factor; /* vertical sampling factor (1..4) */
  156436. int quant_tbl_no; /* quantization table selector (0..3) */
  156437. /* These values may vary between scans. */
  156438. /* For compression, they must be supplied by parameter setup; */
  156439. /* for decompression, they are read from the SOS marker. */
  156440. /* The decompressor output side may not use these variables. */
  156441. int dc_tbl_no; /* DC entropy table selector (0..3) */
  156442. int ac_tbl_no; /* AC entropy table selector (0..3) */
  156443. /* Remaining fields should be treated as private by applications. */
  156444. /* These values are computed during compression or decompression startup: */
  156445. /* Component's size in DCT blocks.
  156446. * Any dummy blocks added to complete an MCU are not counted; therefore
  156447. * these values do not depend on whether a scan is interleaved or not.
  156448. */
  156449. JDIMENSION width_in_blocks;
  156450. JDIMENSION height_in_blocks;
  156451. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  156452. * For decompression this is the size of the output from one DCT block,
  156453. * reflecting any scaling we choose to apply during the IDCT step.
  156454. * Values of 1,2,4,8 are likely to be supported. Note that different
  156455. * components may receive different IDCT scalings.
  156456. */
  156457. int DCT_scaled_size;
  156458. /* The downsampled dimensions are the component's actual, unpadded number
  156459. * of samples at the main buffer (preprocessing/compression interface), thus
  156460. * downsampled_width = ceil(image_width * Hi/Hmax)
  156461. * and similarly for height. For decompression, IDCT scaling is included, so
  156462. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  156463. */
  156464. JDIMENSION downsampled_width; /* actual width in samples */
  156465. JDIMENSION downsampled_height; /* actual height in samples */
  156466. /* This flag is used only for decompression. In cases where some of the
  156467. * components will be ignored (eg grayscale output from YCbCr image),
  156468. * we can skip most computations for the unused components.
  156469. */
  156470. boolean component_needed; /* do we need the value of this component? */
  156471. /* These values are computed before starting a scan of the component. */
  156472. /* The decompressor output side may not use these variables. */
  156473. int MCU_width; /* number of blocks per MCU, horizontally */
  156474. int MCU_height; /* number of blocks per MCU, vertically */
  156475. int MCU_blocks; /* MCU_width * MCU_height */
  156476. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  156477. int last_col_width; /* # of non-dummy blocks across in last MCU */
  156478. int last_row_height; /* # of non-dummy blocks down in last MCU */
  156479. /* Saved quantization table for component; NULL if none yet saved.
  156480. * See jdinput.c comments about the need for this information.
  156481. * This field is currently used only for decompression.
  156482. */
  156483. JQUANT_TBL * quant_table;
  156484. /* Private per-component storage for DCT or IDCT subsystem. */
  156485. void * dct_table;
  156486. } jpeg_component_info;
  156487. /* The script for encoding a multiple-scan file is an array of these: */
  156488. typedef struct {
  156489. int comps_in_scan; /* number of components encoded in this scan */
  156490. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  156491. int Ss, Se; /* progressive JPEG spectral selection parms */
  156492. int Ah, Al; /* progressive JPEG successive approx. parms */
  156493. } jpeg_scan_info;
  156494. /* The decompressor can save APPn and COM markers in a list of these: */
  156495. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  156496. struct jpeg_marker_struct {
  156497. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  156498. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  156499. unsigned int original_length; /* # bytes of data in the file */
  156500. unsigned int data_length; /* # bytes of data saved at data[] */
  156501. JOCTET FAR * data; /* the data contained in the marker */
  156502. /* the marker length word is not counted in data_length or original_length */
  156503. };
  156504. /* Known color spaces. */
  156505. typedef enum {
  156506. JCS_UNKNOWN, /* error/unspecified */
  156507. JCS_GRAYSCALE, /* monochrome */
  156508. JCS_RGB, /* red/green/blue */
  156509. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  156510. JCS_CMYK, /* C/M/Y/K */
  156511. JCS_YCCK /* Y/Cb/Cr/K */
  156512. } J_COLOR_SPACE;
  156513. /* DCT/IDCT algorithm options. */
  156514. typedef enum {
  156515. JDCT_ISLOW, /* slow but accurate integer algorithm */
  156516. JDCT_IFAST, /* faster, less accurate integer method */
  156517. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  156518. } J_DCT_METHOD;
  156519. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  156520. #define JDCT_DEFAULT JDCT_ISLOW
  156521. #endif
  156522. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  156523. #define JDCT_FASTEST JDCT_IFAST
  156524. #endif
  156525. /* Dithering options for decompression. */
  156526. typedef enum {
  156527. JDITHER_NONE, /* no dithering */
  156528. JDITHER_ORDERED, /* simple ordered dither */
  156529. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  156530. } J_DITHER_MODE;
  156531. /* Common fields between JPEG compression and decompression master structs. */
  156532. #define jpeg_common_fields \
  156533. struct jpeg_error_mgr * err; /* Error handler module */\
  156534. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  156535. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  156536. void * client_data; /* Available for use by application */\
  156537. boolean is_decompressor; /* So common code can tell which is which */\
  156538. int global_state /* For checking call sequence validity */
  156539. /* Routines that are to be used by both halves of the library are declared
  156540. * to receive a pointer to this structure. There are no actual instances of
  156541. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  156542. */
  156543. struct jpeg_common_struct {
  156544. jpeg_common_fields; /* Fields common to both master struct types */
  156545. /* Additional fields follow in an actual jpeg_compress_struct or
  156546. * jpeg_decompress_struct. All three structs must agree on these
  156547. * initial fields! (This would be a lot cleaner in C++.)
  156548. */
  156549. };
  156550. typedef struct jpeg_common_struct * j_common_ptr;
  156551. typedef struct jpeg_compress_struct * j_compress_ptr;
  156552. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  156553. /* Master record for a compression instance */
  156554. struct jpeg_compress_struct {
  156555. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  156556. /* Destination for compressed data */
  156557. struct jpeg_destination_mgr * dest;
  156558. /* Description of source image --- these fields must be filled in by
  156559. * outer application before starting compression. in_color_space must
  156560. * be correct before you can even call jpeg_set_defaults().
  156561. */
  156562. JDIMENSION image_width; /* input image width */
  156563. JDIMENSION image_height; /* input image height */
  156564. int input_components; /* # of color components in input image */
  156565. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  156566. double input_gamma; /* image gamma of input image */
  156567. /* Compression parameters --- these fields must be set before calling
  156568. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  156569. * initialize everything to reasonable defaults, then changing anything
  156570. * the application specifically wants to change. That way you won't get
  156571. * burnt when new parameters are added. Also note that there are several
  156572. * helper routines to simplify changing parameters.
  156573. */
  156574. int data_precision; /* bits of precision in image data */
  156575. int num_components; /* # of color components in JPEG image */
  156576. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  156577. jpeg_component_info * comp_info;
  156578. /* comp_info[i] describes component that appears i'th in SOF */
  156579. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  156580. /* ptrs to coefficient quantization tables, or NULL if not defined */
  156581. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156582. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156583. /* ptrs to Huffman coding tables, or NULL if not defined */
  156584. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  156585. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  156586. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  156587. int num_scans; /* # of entries in scan_info array */
  156588. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  156589. /* The default value of scan_info is NULL, which causes a single-scan
  156590. * sequential JPEG file to be emitted. To create a multi-scan file,
  156591. * set num_scans and scan_info to point to an array of scan definitions.
  156592. */
  156593. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  156594. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  156595. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  156596. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  156597. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  156598. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  156599. /* The restart interval can be specified in absolute MCUs by setting
  156600. * restart_interval, or in MCU rows by setting restart_in_rows
  156601. * (in which case the correct restart_interval will be figured
  156602. * for each scan).
  156603. */
  156604. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  156605. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  156606. /* Parameters controlling emission of special markers. */
  156607. boolean write_JFIF_header; /* should a JFIF marker be written? */
  156608. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  156609. UINT8 JFIF_minor_version;
  156610. /* These three values are not used by the JPEG code, merely copied */
  156611. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  156612. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  156613. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  156614. UINT8 density_unit; /* JFIF code for pixel size units */
  156615. UINT16 X_density; /* Horizontal pixel density */
  156616. UINT16 Y_density; /* Vertical pixel density */
  156617. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  156618. /* State variable: index of next scanline to be written to
  156619. * jpeg_write_scanlines(). Application may use this to control its
  156620. * processing loop, e.g., "while (next_scanline < image_height)".
  156621. */
  156622. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  156623. /* Remaining fields are known throughout compressor, but generally
  156624. * should not be touched by a surrounding application.
  156625. */
  156626. /*
  156627. * These fields are computed during compression startup
  156628. */
  156629. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  156630. int max_h_samp_factor; /* largest h_samp_factor */
  156631. int max_v_samp_factor; /* largest v_samp_factor */
  156632. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  156633. /* The coefficient controller receives data in units of MCU rows as defined
  156634. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  156635. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  156636. * "iMCU" (interleaved MCU) row.
  156637. */
  156638. /*
  156639. * These fields are valid during any one scan.
  156640. * They describe the components and MCUs actually appearing in the scan.
  156641. */
  156642. int comps_in_scan; /* # of JPEG components in this scan */
  156643. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  156644. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  156645. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  156646. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  156647. int blocks_in_MCU; /* # of DCT blocks per MCU */
  156648. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  156649. /* MCU_membership[i] is index in cur_comp_info of component owning */
  156650. /* i'th block in an MCU */
  156651. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  156652. /*
  156653. * Links to compression subobjects (methods and private variables of modules)
  156654. */
  156655. struct jpeg_comp_master * master;
  156656. struct jpeg_c_main_controller * main;
  156657. struct jpeg_c_prep_controller * prep;
  156658. struct jpeg_c_coef_controller * coef;
  156659. struct jpeg_marker_writer * marker;
  156660. struct jpeg_color_converter * cconvert;
  156661. struct jpeg_downsampler * downsample;
  156662. struct jpeg_forward_dct * fdct;
  156663. struct jpeg_entropy_encoder * entropy;
  156664. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  156665. int script_space_size;
  156666. };
  156667. /* Master record for a decompression instance */
  156668. struct jpeg_decompress_struct {
  156669. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  156670. /* Source of compressed data */
  156671. struct jpeg_source_mgr * src;
  156672. /* Basic description of image --- filled in by jpeg_read_header(). */
  156673. /* Application may inspect these values to decide how to process image. */
  156674. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  156675. JDIMENSION image_height; /* nominal image height */
  156676. int num_components; /* # of color components in JPEG image */
  156677. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  156678. /* Decompression processing parameters --- these fields must be set before
  156679. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  156680. * them to default values.
  156681. */
  156682. J_COLOR_SPACE out_color_space; /* colorspace for output */
  156683. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  156684. double output_gamma; /* image gamma wanted in output */
  156685. boolean buffered_image; /* TRUE=multiple output passes */
  156686. boolean raw_data_out; /* TRUE=downsampled data wanted */
  156687. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  156688. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  156689. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  156690. boolean quantize_colors; /* TRUE=colormapped output wanted */
  156691. /* the following are ignored if not quantize_colors: */
  156692. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  156693. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  156694. int desired_number_of_colors; /* max # colors to use in created colormap */
  156695. /* these are significant only in buffered-image mode: */
  156696. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  156697. boolean enable_external_quant;/* enable future use of external colormap */
  156698. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  156699. /* Description of actual output image that will be returned to application.
  156700. * These fields are computed by jpeg_start_decompress().
  156701. * You can also use jpeg_calc_output_dimensions() to determine these values
  156702. * in advance of calling jpeg_start_decompress().
  156703. */
  156704. JDIMENSION output_width; /* scaled image width */
  156705. JDIMENSION output_height; /* scaled image height */
  156706. int out_color_components; /* # of color components in out_color_space */
  156707. int output_components; /* # of color components returned */
  156708. /* output_components is 1 (a colormap index) when quantizing colors;
  156709. * otherwise it equals out_color_components.
  156710. */
  156711. int rec_outbuf_height; /* min recommended height of scanline buffer */
  156712. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  156713. * high, space and time will be wasted due to unnecessary data copying.
  156714. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  156715. */
  156716. /* When quantizing colors, the output colormap is described by these fields.
  156717. * The application can supply a colormap by setting colormap non-NULL before
  156718. * calling jpeg_start_decompress; otherwise a colormap is created during
  156719. * jpeg_start_decompress or jpeg_start_output.
  156720. * The map has out_color_components rows and actual_number_of_colors columns.
  156721. */
  156722. int actual_number_of_colors; /* number of entries in use */
  156723. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  156724. /* State variables: these variables indicate the progress of decompression.
  156725. * The application may examine these but must not modify them.
  156726. */
  156727. /* Row index of next scanline to be read from jpeg_read_scanlines().
  156728. * Application may use this to control its processing loop, e.g.,
  156729. * "while (output_scanline < output_height)".
  156730. */
  156731. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  156732. /* Current input scan number and number of iMCU rows completed in scan.
  156733. * These indicate the progress of the decompressor input side.
  156734. */
  156735. int input_scan_number; /* Number of SOS markers seen so far */
  156736. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  156737. /* The "output scan number" is the notional scan being displayed by the
  156738. * output side. The decompressor will not allow output scan/row number
  156739. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  156740. */
  156741. int output_scan_number; /* Nominal scan number being displayed */
  156742. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  156743. /* Current progression status. coef_bits[c][i] indicates the precision
  156744. * with which component c's DCT coefficient i (in zigzag order) is known.
  156745. * It is -1 when no data has yet been received, otherwise it is the point
  156746. * transform (shift) value for the most recent scan of the coefficient
  156747. * (thus, 0 at completion of the progression).
  156748. * This pointer is NULL when reading a non-progressive file.
  156749. */
  156750. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  156751. /* Internal JPEG parameters --- the application usually need not look at
  156752. * these fields. Note that the decompressor output side may not use
  156753. * any parameters that can change between scans.
  156754. */
  156755. /* Quantization and Huffman tables are carried forward across input
  156756. * datastreams when processing abbreviated JPEG datastreams.
  156757. */
  156758. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  156759. /* ptrs to coefficient quantization tables, or NULL if not defined */
  156760. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156761. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156762. /* ptrs to Huffman coding tables, or NULL if not defined */
  156763. /* These parameters are never carried across datastreams, since they
  156764. * are given in SOF/SOS markers or defined to be reset by SOI.
  156765. */
  156766. int data_precision; /* bits of precision in image data */
  156767. jpeg_component_info * comp_info;
  156768. /* comp_info[i] describes component that appears i'th in SOF */
  156769. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  156770. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  156771. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  156772. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  156773. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  156774. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  156775. /* These fields record data obtained from optional markers recognized by
  156776. * the JPEG library.
  156777. */
  156778. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  156779. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  156780. UINT8 JFIF_major_version; /* JFIF version number */
  156781. UINT8 JFIF_minor_version;
  156782. UINT8 density_unit; /* JFIF code for pixel size units */
  156783. UINT16 X_density; /* Horizontal pixel density */
  156784. UINT16 Y_density; /* Vertical pixel density */
  156785. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  156786. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  156787. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  156788. /* Aside from the specific data retained from APPn markers known to the
  156789. * library, the uninterpreted contents of any or all APPn and COM markers
  156790. * can be saved in a list for examination by the application.
  156791. */
  156792. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  156793. /* Remaining fields are known throughout decompressor, but generally
  156794. * should not be touched by a surrounding application.
  156795. */
  156796. /*
  156797. * These fields are computed during decompression startup
  156798. */
  156799. int max_h_samp_factor; /* largest h_samp_factor */
  156800. int max_v_samp_factor; /* largest v_samp_factor */
  156801. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  156802. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  156803. /* The coefficient controller's input and output progress is measured in
  156804. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  156805. * in fully interleaved JPEG scans, but are used whether the scan is
  156806. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  156807. * rows of each component. Therefore, the IDCT output contains
  156808. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  156809. */
  156810. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  156811. /*
  156812. * These fields are valid during any one scan.
  156813. * They describe the components and MCUs actually appearing in the scan.
  156814. * Note that the decompressor output side must not use these fields.
  156815. */
  156816. int comps_in_scan; /* # of JPEG components in this scan */
  156817. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  156818. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  156819. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  156820. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  156821. int blocks_in_MCU; /* # of DCT blocks per MCU */
  156822. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  156823. /* MCU_membership[i] is index in cur_comp_info of component owning */
  156824. /* i'th block in an MCU */
  156825. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  156826. /* This field is shared between entropy decoder and marker parser.
  156827. * It is either zero or the code of a JPEG marker that has been
  156828. * read from the data source, but has not yet been processed.
  156829. */
  156830. int unread_marker;
  156831. /*
  156832. * Links to decompression subobjects (methods, private variables of modules)
  156833. */
  156834. struct jpeg_decomp_master * master;
  156835. struct jpeg_d_main_controller * main;
  156836. struct jpeg_d_coef_controller * coef;
  156837. struct jpeg_d_post_controller * post;
  156838. struct jpeg_input_controller * inputctl;
  156839. struct jpeg_marker_reader * marker;
  156840. struct jpeg_entropy_decoder * entropy;
  156841. struct jpeg_inverse_dct * idct;
  156842. struct jpeg_upsampler * upsample;
  156843. struct jpeg_color_deconverter * cconvert;
  156844. struct jpeg_color_quantizer * cquantize;
  156845. };
  156846. /* "Object" declarations for JPEG modules that may be supplied or called
  156847. * directly by the surrounding application.
  156848. * As with all objects in the JPEG library, these structs only define the
  156849. * publicly visible methods and state variables of a module. Additional
  156850. * private fields may exist after the public ones.
  156851. */
  156852. /* Error handler object */
  156853. struct jpeg_error_mgr {
  156854. /* Error exit handler: does not return to caller */
  156855. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  156856. /* Conditionally emit a trace or warning message */
  156857. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  156858. /* Routine that actually outputs a trace or error message */
  156859. JMETHOD(void, output_message, (j_common_ptr cinfo));
  156860. /* Format a message string for the most recent JPEG error or message */
  156861. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  156862. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  156863. /* Reset error state variables at start of a new image */
  156864. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  156865. /* The message ID code and any parameters are saved here.
  156866. * A message can have one string parameter or up to 8 int parameters.
  156867. */
  156868. int msg_code;
  156869. #define JMSG_STR_PARM_MAX 80
  156870. union {
  156871. int i[8];
  156872. char s[JMSG_STR_PARM_MAX];
  156873. } msg_parm;
  156874. /* Standard state variables for error facility */
  156875. int trace_level; /* max msg_level that will be displayed */
  156876. /* For recoverable corrupt-data errors, we emit a warning message,
  156877. * but keep going unless emit_message chooses to abort. emit_message
  156878. * should count warnings in num_warnings. The surrounding application
  156879. * can check for bad data by seeing if num_warnings is nonzero at the
  156880. * end of processing.
  156881. */
  156882. long num_warnings; /* number of corrupt-data warnings */
  156883. /* These fields point to the table(s) of error message strings.
  156884. * An application can change the table pointer to switch to a different
  156885. * message list (typically, to change the language in which errors are
  156886. * reported). Some applications may wish to add additional error codes
  156887. * that will be handled by the JPEG library error mechanism; the second
  156888. * table pointer is used for this purpose.
  156889. *
  156890. * First table includes all errors generated by JPEG library itself.
  156891. * Error code 0 is reserved for a "no such error string" message.
  156892. */
  156893. const char * const * jpeg_message_table; /* Library errors */
  156894. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  156895. /* Second table can be added by application (see cjpeg/djpeg for example).
  156896. * It contains strings numbered first_addon_message..last_addon_message.
  156897. */
  156898. const char * const * addon_message_table; /* Non-library errors */
  156899. int first_addon_message; /* code for first string in addon table */
  156900. int last_addon_message; /* code for last string in addon table */
  156901. };
  156902. /* Progress monitor object */
  156903. struct jpeg_progress_mgr {
  156904. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  156905. long pass_counter; /* work units completed in this pass */
  156906. long pass_limit; /* total number of work units in this pass */
  156907. int completed_passes; /* passes completed so far */
  156908. int total_passes; /* total number of passes expected */
  156909. };
  156910. /* Data destination object for compression */
  156911. struct jpeg_destination_mgr {
  156912. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156913. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156914. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  156915. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  156916. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  156917. };
  156918. /* Data source object for decompression */
  156919. struct jpeg_source_mgr {
  156920. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  156921. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  156922. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  156923. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  156924. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  156925. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  156926. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  156927. };
  156928. /* Memory manager object.
  156929. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  156930. * and "really big" objects (virtual arrays with backing store if needed).
  156931. * The memory manager does not allow individual objects to be freed; rather,
  156932. * each created object is assigned to a pool, and whole pools can be freed
  156933. * at once. This is faster and more convenient than remembering exactly what
  156934. * to free, especially where malloc()/free() are not too speedy.
  156935. * NB: alloc routines never return NULL. They exit to error_exit if not
  156936. * successful.
  156937. */
  156938. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  156939. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  156940. #define JPOOL_NUMPOOLS 2
  156941. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  156942. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  156943. struct jpeg_memory_mgr {
  156944. /* Method pointers */
  156945. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  156946. size_t sizeofobject));
  156947. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  156948. size_t sizeofobject));
  156949. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  156950. JDIMENSION samplesperrow,
  156951. JDIMENSION numrows));
  156952. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  156953. JDIMENSION blocksperrow,
  156954. JDIMENSION numrows));
  156955. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  156956. int pool_id,
  156957. boolean pre_zero,
  156958. JDIMENSION samplesperrow,
  156959. JDIMENSION numrows,
  156960. JDIMENSION maxaccess));
  156961. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  156962. int pool_id,
  156963. boolean pre_zero,
  156964. JDIMENSION blocksperrow,
  156965. JDIMENSION numrows,
  156966. JDIMENSION maxaccess));
  156967. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  156968. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  156969. jvirt_sarray_ptr ptr,
  156970. JDIMENSION start_row,
  156971. JDIMENSION num_rows,
  156972. boolean writable));
  156973. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  156974. jvirt_barray_ptr ptr,
  156975. JDIMENSION start_row,
  156976. JDIMENSION num_rows,
  156977. boolean writable));
  156978. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  156979. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  156980. /* Limit on memory allocation for this JPEG object. (Note that this is
  156981. * merely advisory, not a guaranteed maximum; it only affects the space
  156982. * used for virtual-array buffers.) May be changed by outer application
  156983. * after creating the JPEG object.
  156984. */
  156985. long max_memory_to_use;
  156986. /* Maximum allocation request accepted by alloc_large. */
  156987. long max_alloc_chunk;
  156988. };
  156989. /* Routine signature for application-supplied marker processing methods.
  156990. * Need not pass marker code since it is stored in cinfo->unread_marker.
  156991. */
  156992. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  156993. /* Declarations for routines called by application.
  156994. * The JPP macro hides prototype parameters from compilers that can't cope.
  156995. * Note JPP requires double parentheses.
  156996. */
  156997. #ifdef HAVE_PROTOTYPES
  156998. #define JPP(arglist) arglist
  156999. #else
  157000. #define JPP(arglist) ()
  157001. #endif
  157002. /* Short forms of external names for systems with brain-damaged linkers.
  157003. * We shorten external names to be unique in the first six letters, which
  157004. * is good enough for all known systems.
  157005. * (If your compiler itself needs names to be unique in less than 15
  157006. * characters, you are out of luck. Get a better compiler.)
  157007. */
  157008. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157009. #define jpeg_std_error jStdError
  157010. #define jpeg_CreateCompress jCreaCompress
  157011. #define jpeg_CreateDecompress jCreaDecompress
  157012. #define jpeg_destroy_compress jDestCompress
  157013. #define jpeg_destroy_decompress jDestDecompress
  157014. #define jpeg_stdio_dest jStdDest
  157015. #define jpeg_stdio_src jStdSrc
  157016. #define jpeg_set_defaults jSetDefaults
  157017. #define jpeg_set_colorspace jSetColorspace
  157018. #define jpeg_default_colorspace jDefColorspace
  157019. #define jpeg_set_quality jSetQuality
  157020. #define jpeg_set_linear_quality jSetLQuality
  157021. #define jpeg_add_quant_table jAddQuantTable
  157022. #define jpeg_quality_scaling jQualityScaling
  157023. #define jpeg_simple_progression jSimProgress
  157024. #define jpeg_suppress_tables jSuppressTables
  157025. #define jpeg_alloc_quant_table jAlcQTable
  157026. #define jpeg_alloc_huff_table jAlcHTable
  157027. #define jpeg_start_compress jStrtCompress
  157028. #define jpeg_write_scanlines jWrtScanlines
  157029. #define jpeg_finish_compress jFinCompress
  157030. #define jpeg_write_raw_data jWrtRawData
  157031. #define jpeg_write_marker jWrtMarker
  157032. #define jpeg_write_m_header jWrtMHeader
  157033. #define jpeg_write_m_byte jWrtMByte
  157034. #define jpeg_write_tables jWrtTables
  157035. #define jpeg_read_header jReadHeader
  157036. #define jpeg_start_decompress jStrtDecompress
  157037. #define jpeg_read_scanlines jReadScanlines
  157038. #define jpeg_finish_decompress jFinDecompress
  157039. #define jpeg_read_raw_data jReadRawData
  157040. #define jpeg_has_multiple_scans jHasMultScn
  157041. #define jpeg_start_output jStrtOutput
  157042. #define jpeg_finish_output jFinOutput
  157043. #define jpeg_input_complete jInComplete
  157044. #define jpeg_new_colormap jNewCMap
  157045. #define jpeg_consume_input jConsumeInput
  157046. #define jpeg_calc_output_dimensions jCalcDimensions
  157047. #define jpeg_save_markers jSaveMarkers
  157048. #define jpeg_set_marker_processor jSetMarker
  157049. #define jpeg_read_coefficients jReadCoefs
  157050. #define jpeg_write_coefficients jWrtCoefs
  157051. #define jpeg_copy_critical_parameters jCopyCrit
  157052. #define jpeg_abort_compress jAbrtCompress
  157053. #define jpeg_abort_decompress jAbrtDecompress
  157054. #define jpeg_abort jAbort
  157055. #define jpeg_destroy jDestroy
  157056. #define jpeg_resync_to_restart jResyncRestart
  157057. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157058. /* Default error-management setup */
  157059. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  157060. JPP((struct jpeg_error_mgr * err));
  157061. /* Initialization of JPEG compression objects.
  157062. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  157063. * names that applications should call. These expand to calls on
  157064. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  157065. * passed for version mismatch checking.
  157066. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  157067. */
  157068. #define jpeg_create_compress(cinfo) \
  157069. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  157070. (size_t) sizeof(struct jpeg_compress_struct))
  157071. #define jpeg_create_decompress(cinfo) \
  157072. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  157073. (size_t) sizeof(struct jpeg_decompress_struct))
  157074. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  157075. int version, size_t structsize));
  157076. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  157077. int version, size_t structsize));
  157078. /* Destruction of JPEG compression objects */
  157079. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  157080. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  157081. /* Standard data source and destination managers: stdio streams. */
  157082. /* Caller is responsible for opening the file before and closing after. */
  157083. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  157084. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  157085. /* Default parameter setup for compression */
  157086. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  157087. /* Compression parameter setup aids */
  157088. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  157089. J_COLOR_SPACE colorspace));
  157090. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  157091. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  157092. boolean force_baseline));
  157093. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  157094. int scale_factor,
  157095. boolean force_baseline));
  157096. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  157097. const unsigned int *basic_table,
  157098. int scale_factor,
  157099. boolean force_baseline));
  157100. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  157101. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  157102. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  157103. boolean suppress));
  157104. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  157105. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  157106. /* Main entry points for compression */
  157107. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  157108. boolean write_all_tables));
  157109. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  157110. JSAMPARRAY scanlines,
  157111. JDIMENSION num_lines));
  157112. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  157113. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  157114. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  157115. JSAMPIMAGE data,
  157116. JDIMENSION num_lines));
  157117. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  157118. EXTERN(void) jpeg_write_marker
  157119. JPP((j_compress_ptr cinfo, int marker,
  157120. const JOCTET * dataptr, unsigned int datalen));
  157121. /* Same, but piecemeal. */
  157122. EXTERN(void) jpeg_write_m_header
  157123. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  157124. EXTERN(void) jpeg_write_m_byte
  157125. JPP((j_compress_ptr cinfo, int val));
  157126. /* Alternate compression function: just write an abbreviated table file */
  157127. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  157128. /* Decompression startup: read start of JPEG datastream to see what's there */
  157129. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  157130. boolean require_image));
  157131. /* Return value is one of: */
  157132. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  157133. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  157134. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  157135. /* If you pass require_image = TRUE (normal case), you need not check for
  157136. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  157137. * JPEG_SUSPENDED is only possible if you use a data source module that can
  157138. * give a suspension return (the stdio source module doesn't).
  157139. */
  157140. /* Main entry points for decompression */
  157141. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  157142. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  157143. JSAMPARRAY scanlines,
  157144. JDIMENSION max_lines));
  157145. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  157146. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  157147. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  157148. JSAMPIMAGE data,
  157149. JDIMENSION max_lines));
  157150. /* Additional entry points for buffered-image mode. */
  157151. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  157152. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  157153. int scan_number));
  157154. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  157155. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  157156. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  157157. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  157158. /* Return value is one of: */
  157159. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  157160. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  157161. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  157162. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  157163. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  157164. /* Precalculate output dimensions for current decompression parameters. */
  157165. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  157166. /* Control saving of COM and APPn markers into marker_list. */
  157167. EXTERN(void) jpeg_save_markers
  157168. JPP((j_decompress_ptr cinfo, int marker_code,
  157169. unsigned int length_limit));
  157170. /* Install a special processing method for COM or APPn markers. */
  157171. EXTERN(void) jpeg_set_marker_processor
  157172. JPP((j_decompress_ptr cinfo, int marker_code,
  157173. jpeg_marker_parser_method routine));
  157174. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  157175. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  157176. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  157177. jvirt_barray_ptr * coef_arrays));
  157178. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  157179. j_compress_ptr dstinfo));
  157180. /* If you choose to abort compression or decompression before completing
  157181. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  157182. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  157183. * if you're done with the JPEG object, but if you want to clean it up and
  157184. * reuse it, call this:
  157185. */
  157186. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  157187. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  157188. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  157189. * flavor of JPEG object. These may be more convenient in some places.
  157190. */
  157191. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  157192. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  157193. /* Default restart-marker-resync procedure for use by data source modules */
  157194. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  157195. int desired));
  157196. /* These marker codes are exported since applications and data source modules
  157197. * are likely to want to use them.
  157198. */
  157199. #define JPEG_RST0 0xD0 /* RST0 marker code */
  157200. #define JPEG_EOI 0xD9 /* EOI marker code */
  157201. #define JPEG_APP0 0xE0 /* APP0 marker code */
  157202. #define JPEG_COM 0xFE /* COM marker code */
  157203. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  157204. * for structure definitions that are never filled in, keep it quiet by
  157205. * supplying dummy definitions for the various substructures.
  157206. */
  157207. #ifdef INCOMPLETE_TYPES_BROKEN
  157208. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  157209. struct jvirt_sarray_control { long dummy; };
  157210. struct jvirt_barray_control { long dummy; };
  157211. struct jpeg_comp_master { long dummy; };
  157212. struct jpeg_c_main_controller { long dummy; };
  157213. struct jpeg_c_prep_controller { long dummy; };
  157214. struct jpeg_c_coef_controller { long dummy; };
  157215. struct jpeg_marker_writer { long dummy; };
  157216. struct jpeg_color_converter { long dummy; };
  157217. struct jpeg_downsampler { long dummy; };
  157218. struct jpeg_forward_dct { long dummy; };
  157219. struct jpeg_entropy_encoder { long dummy; };
  157220. struct jpeg_decomp_master { long dummy; };
  157221. struct jpeg_d_main_controller { long dummy; };
  157222. struct jpeg_d_coef_controller { long dummy; };
  157223. struct jpeg_d_post_controller { long dummy; };
  157224. struct jpeg_input_controller { long dummy; };
  157225. struct jpeg_marker_reader { long dummy; };
  157226. struct jpeg_entropy_decoder { long dummy; };
  157227. struct jpeg_inverse_dct { long dummy; };
  157228. struct jpeg_upsampler { long dummy; };
  157229. struct jpeg_color_deconverter { long dummy; };
  157230. struct jpeg_color_quantizer { long dummy; };
  157231. #endif /* JPEG_INTERNALS */
  157232. #endif /* INCOMPLETE_TYPES_BROKEN */
  157233. /*
  157234. * The JPEG library modules define JPEG_INTERNALS before including this file.
  157235. * The internal structure declarations are read only when that is true.
  157236. * Applications using the library should not include jpegint.h, but may wish
  157237. * to include jerror.h.
  157238. */
  157239. #ifdef JPEG_INTERNALS
  157240. /*** Start of inlined file: jpegint.h ***/
  157241. /* Declarations for both compression & decompression */
  157242. typedef enum { /* Operating modes for buffer controllers */
  157243. JBUF_PASS_THRU, /* Plain stripwise operation */
  157244. /* Remaining modes require a full-image buffer to have been created */
  157245. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  157246. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  157247. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  157248. } J_BUF_MODE;
  157249. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  157250. #define CSTATE_START 100 /* after create_compress */
  157251. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  157252. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  157253. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  157254. #define DSTATE_START 200 /* after create_decompress */
  157255. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  157256. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  157257. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  157258. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  157259. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  157260. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  157261. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  157262. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  157263. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  157264. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  157265. /* Declarations for compression modules */
  157266. /* Master control module */
  157267. struct jpeg_comp_master {
  157268. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  157269. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  157270. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157271. /* State variables made visible to other modules */
  157272. boolean call_pass_startup; /* True if pass_startup must be called */
  157273. boolean is_last_pass; /* True during last pass */
  157274. };
  157275. /* Main buffer control (downsampled-data buffer) */
  157276. struct jpeg_c_main_controller {
  157277. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157278. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  157279. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157280. JDIMENSION in_rows_avail));
  157281. };
  157282. /* Compression preprocessing (downsampling input buffer control) */
  157283. struct jpeg_c_prep_controller {
  157284. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157285. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  157286. JSAMPARRAY input_buf,
  157287. JDIMENSION *in_row_ctr,
  157288. JDIMENSION in_rows_avail,
  157289. JSAMPIMAGE output_buf,
  157290. JDIMENSION *out_row_group_ctr,
  157291. JDIMENSION out_row_groups_avail));
  157292. };
  157293. /* Coefficient buffer control */
  157294. struct jpeg_c_coef_controller {
  157295. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157296. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  157297. JSAMPIMAGE input_buf));
  157298. };
  157299. /* Colorspace conversion */
  157300. struct jpeg_color_converter {
  157301. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157302. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  157303. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157304. JDIMENSION output_row, int num_rows));
  157305. };
  157306. /* Downsampling */
  157307. struct jpeg_downsampler {
  157308. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157309. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  157310. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  157311. JSAMPIMAGE output_buf,
  157312. JDIMENSION out_row_group_index));
  157313. boolean need_context_rows; /* TRUE if need rows above & below */
  157314. };
  157315. /* Forward DCT (also controls coefficient quantization) */
  157316. struct jpeg_forward_dct {
  157317. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157318. /* perhaps this should be an array??? */
  157319. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  157320. jpeg_component_info * compptr,
  157321. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157322. JDIMENSION start_row, JDIMENSION start_col,
  157323. JDIMENSION num_blocks));
  157324. };
  157325. /* Entropy encoding */
  157326. struct jpeg_entropy_encoder {
  157327. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  157328. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  157329. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157330. };
  157331. /* Marker writing */
  157332. struct jpeg_marker_writer {
  157333. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  157334. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  157335. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  157336. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  157337. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  157338. /* These routines are exported to allow insertion of extra markers */
  157339. /* Probably only COM and APPn markers should be written this way */
  157340. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  157341. unsigned int datalen));
  157342. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  157343. };
  157344. /* Declarations for decompression modules */
  157345. /* Master control module */
  157346. struct jpeg_decomp_master {
  157347. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  157348. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  157349. /* State variables made visible to other modules */
  157350. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  157351. };
  157352. /* Input control module */
  157353. struct jpeg_input_controller {
  157354. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  157355. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  157356. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  157357. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  157358. /* State variables made visible to other modules */
  157359. boolean has_multiple_scans; /* True if file has multiple scans */
  157360. boolean eoi_reached; /* True when EOI has been consumed */
  157361. };
  157362. /* Main buffer control (downsampled-data buffer) */
  157363. struct jpeg_d_main_controller {
  157364. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  157365. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  157366. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  157367. JDIMENSION out_rows_avail));
  157368. };
  157369. /* Coefficient buffer control */
  157370. struct jpeg_d_coef_controller {
  157371. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  157372. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  157373. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  157374. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  157375. JSAMPIMAGE output_buf));
  157376. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  157377. jvirt_barray_ptr *coef_arrays;
  157378. };
  157379. /* Decompression postprocessing (color quantization buffer control) */
  157380. struct jpeg_d_post_controller {
  157381. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  157382. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  157383. JSAMPIMAGE input_buf,
  157384. JDIMENSION *in_row_group_ctr,
  157385. JDIMENSION in_row_groups_avail,
  157386. JSAMPARRAY output_buf,
  157387. JDIMENSION *out_row_ctr,
  157388. JDIMENSION out_rows_avail));
  157389. };
  157390. /* Marker reading & parsing */
  157391. struct jpeg_marker_reader {
  157392. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  157393. /* Read markers until SOS or EOI.
  157394. * Returns same codes as are defined for jpeg_consume_input:
  157395. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  157396. */
  157397. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  157398. /* Read a restart marker --- exported for use by entropy decoder only */
  157399. jpeg_marker_parser_method read_restart_marker;
  157400. /* State of marker reader --- nominally internal, but applications
  157401. * supplying COM or APPn handlers might like to know the state.
  157402. */
  157403. boolean saw_SOI; /* found SOI? */
  157404. boolean saw_SOF; /* found SOF? */
  157405. int next_restart_num; /* next restart number expected (0-7) */
  157406. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  157407. };
  157408. /* Entropy decoding */
  157409. struct jpeg_entropy_decoder {
  157410. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157411. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  157412. JBLOCKROW *MCU_data));
  157413. /* This is here to share code between baseline and progressive decoders; */
  157414. /* other modules probably should not use it */
  157415. boolean insufficient_data; /* set TRUE after emitting warning */
  157416. };
  157417. /* Inverse DCT (also performs dequantization) */
  157418. typedef JMETHOD(void, inverse_DCT_method_ptr,
  157419. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157420. JCOEFPTR coef_block,
  157421. JSAMPARRAY output_buf, JDIMENSION output_col));
  157422. struct jpeg_inverse_dct {
  157423. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157424. /* It is useful to allow each component to have a separate IDCT method. */
  157425. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  157426. };
  157427. /* Upsampling (note that upsampler must also call color converter) */
  157428. struct jpeg_upsampler {
  157429. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157430. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  157431. JSAMPIMAGE input_buf,
  157432. JDIMENSION *in_row_group_ctr,
  157433. JDIMENSION in_row_groups_avail,
  157434. JSAMPARRAY output_buf,
  157435. JDIMENSION *out_row_ctr,
  157436. JDIMENSION out_rows_avail));
  157437. boolean need_context_rows; /* TRUE if need rows above & below */
  157438. };
  157439. /* Colorspace conversion */
  157440. struct jpeg_color_deconverter {
  157441. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157442. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  157443. JSAMPIMAGE input_buf, JDIMENSION input_row,
  157444. JSAMPARRAY output_buf, int num_rows));
  157445. };
  157446. /* Color quantization or color precision reduction */
  157447. struct jpeg_color_quantizer {
  157448. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  157449. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  157450. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  157451. int num_rows));
  157452. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  157453. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  157454. };
  157455. /* Miscellaneous useful macros */
  157456. #undef MAX
  157457. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  157458. #undef MIN
  157459. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  157460. /* We assume that right shift corresponds to signed division by 2 with
  157461. * rounding towards minus infinity. This is correct for typical "arithmetic
  157462. * shift" instructions that shift in copies of the sign bit. But some
  157463. * C compilers implement >> with an unsigned shift. For these machines you
  157464. * must define RIGHT_SHIFT_IS_UNSIGNED.
  157465. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  157466. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  157467. * included in the variables of any routine using RIGHT_SHIFT.
  157468. */
  157469. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  157470. #define SHIFT_TEMPS INT32 shift_temp;
  157471. #define RIGHT_SHIFT(x,shft) \
  157472. ((shift_temp = (x)) < 0 ? \
  157473. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  157474. (shift_temp >> (shft)))
  157475. #else
  157476. #define SHIFT_TEMPS
  157477. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  157478. #endif
  157479. /* Short forms of external names for systems with brain-damaged linkers. */
  157480. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157481. #define jinit_compress_master jICompress
  157482. #define jinit_c_master_control jICMaster
  157483. #define jinit_c_main_controller jICMainC
  157484. #define jinit_c_prep_controller jICPrepC
  157485. #define jinit_c_coef_controller jICCoefC
  157486. #define jinit_color_converter jICColor
  157487. #define jinit_downsampler jIDownsampler
  157488. #define jinit_forward_dct jIFDCT
  157489. #define jinit_huff_encoder jIHEncoder
  157490. #define jinit_phuff_encoder jIPHEncoder
  157491. #define jinit_marker_writer jIMWriter
  157492. #define jinit_master_decompress jIDMaster
  157493. #define jinit_d_main_controller jIDMainC
  157494. #define jinit_d_coef_controller jIDCoefC
  157495. #define jinit_d_post_controller jIDPostC
  157496. #define jinit_input_controller jIInCtlr
  157497. #define jinit_marker_reader jIMReader
  157498. #define jinit_huff_decoder jIHDecoder
  157499. #define jinit_phuff_decoder jIPHDecoder
  157500. #define jinit_inverse_dct jIIDCT
  157501. #define jinit_upsampler jIUpsampler
  157502. #define jinit_color_deconverter jIDColor
  157503. #define jinit_1pass_quantizer jI1Quant
  157504. #define jinit_2pass_quantizer jI2Quant
  157505. #define jinit_merged_upsampler jIMUpsampler
  157506. #define jinit_memory_mgr jIMemMgr
  157507. #define jdiv_round_up jDivRound
  157508. #define jround_up jRound
  157509. #define jcopy_sample_rows jCopySamples
  157510. #define jcopy_block_row jCopyBlocks
  157511. #define jzero_far jZeroFar
  157512. #define jpeg_zigzag_order jZIGTable
  157513. #define jpeg_natural_order jZAGTable
  157514. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157515. /* Compression module initialization routines */
  157516. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  157517. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  157518. boolean transcode_only));
  157519. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  157520. boolean need_full_buffer));
  157521. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  157522. boolean need_full_buffer));
  157523. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  157524. boolean need_full_buffer));
  157525. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  157526. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  157527. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  157528. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  157529. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  157530. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  157531. /* Decompression module initialization routines */
  157532. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  157533. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  157534. boolean need_full_buffer));
  157535. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  157536. boolean need_full_buffer));
  157537. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  157538. boolean need_full_buffer));
  157539. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  157540. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  157541. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  157542. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  157543. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  157544. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  157545. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  157546. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  157547. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  157548. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  157549. /* Memory manager initialization */
  157550. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  157551. /* Utility routines in jutils.c */
  157552. EXTERN(long) jdiv_round_up JPP((long a, long b));
  157553. EXTERN(long) jround_up JPP((long a, long b));
  157554. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  157555. JSAMPARRAY output_array, int dest_row,
  157556. int num_rows, JDIMENSION num_cols));
  157557. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  157558. JDIMENSION num_blocks));
  157559. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  157560. /* Constant tables in jutils.c */
  157561. #if 0 /* This table is not actually needed in v6a */
  157562. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  157563. #endif
  157564. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  157565. /* Suppress undefined-structure complaints if necessary. */
  157566. #ifdef INCOMPLETE_TYPES_BROKEN
  157567. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  157568. struct jvirt_sarray_control { long dummy; };
  157569. struct jvirt_barray_control { long dummy; };
  157570. #endif
  157571. #endif /* INCOMPLETE_TYPES_BROKEN */
  157572. /*** End of inlined file: jpegint.h ***/
  157573. /* fetch private declarations */
  157574. /*** Start of inlined file: jerror.h ***/
  157575. /*
  157576. * To define the enum list of message codes, include this file without
  157577. * defining macro JMESSAGE. To create a message string table, include it
  157578. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  157579. */
  157580. #ifndef JMESSAGE
  157581. #ifndef JERROR_H
  157582. /* First time through, define the enum list */
  157583. #define JMAKE_ENUM_LIST
  157584. #else
  157585. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  157586. #define JMESSAGE(code,string)
  157587. #endif /* JERROR_H */
  157588. #endif /* JMESSAGE */
  157589. #ifdef JMAKE_ENUM_LIST
  157590. typedef enum {
  157591. #define JMESSAGE(code,string) code ,
  157592. #endif /* JMAKE_ENUM_LIST */
  157593. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  157594. /* For maintenance convenience, list is alphabetical by message code name */
  157595. JMESSAGE(JERR_ARITH_NOTIMPL,
  157596. "Sorry, there are legal restrictions on arithmetic coding")
  157597. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  157598. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  157599. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  157600. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  157601. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  157602. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  157603. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  157604. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  157605. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  157606. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  157607. JMESSAGE(JERR_BAD_LIB_VERSION,
  157608. "Wrong JPEG library version: library is %d, caller expects %d")
  157609. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  157610. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  157611. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  157612. JMESSAGE(JERR_BAD_PROGRESSION,
  157613. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  157614. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  157615. "Invalid progressive parameters at scan script entry %d")
  157616. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  157617. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  157618. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  157619. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  157620. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  157621. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  157622. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  157623. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  157624. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  157625. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  157626. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  157627. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  157628. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  157629. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  157630. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  157631. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  157632. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  157633. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  157634. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  157635. JMESSAGE(JERR_FILE_READ, "Input file read error")
  157636. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  157637. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  157638. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  157639. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  157640. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  157641. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  157642. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  157643. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  157644. "Cannot transcode due to multiple use of quantization table %d")
  157645. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  157646. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  157647. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  157648. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  157649. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  157650. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  157651. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  157652. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  157653. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  157654. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  157655. JMESSAGE(JERR_QUANT_COMPONENTS,
  157656. "Cannot quantize more than %d color components")
  157657. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  157658. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  157659. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  157660. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  157661. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  157662. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  157663. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  157664. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  157665. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  157666. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  157667. JMESSAGE(JERR_TFILE_WRITE,
  157668. "Write failed on temporary file --- out of disk space?")
  157669. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  157670. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  157671. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  157672. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  157673. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  157674. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  157675. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  157676. JMESSAGE(JMSG_VERSION, JVERSION)
  157677. JMESSAGE(JTRC_16BIT_TABLES,
  157678. "Caution: quantization tables are too coarse for baseline JPEG")
  157679. JMESSAGE(JTRC_ADOBE,
  157680. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  157681. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  157682. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  157683. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  157684. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  157685. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  157686. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  157687. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  157688. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  157689. JMESSAGE(JTRC_EOI, "End Of Image")
  157690. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  157691. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  157692. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  157693. "Warning: thumbnail image size does not match data length %u")
  157694. JMESSAGE(JTRC_JFIF_EXTENSION,
  157695. "JFIF extension marker: type 0x%02x, length %u")
  157696. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  157697. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  157698. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  157699. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  157700. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  157701. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  157702. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  157703. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  157704. JMESSAGE(JTRC_RST, "RST%d")
  157705. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  157706. "Smoothing not supported with nonstandard sampling ratios")
  157707. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  157708. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  157709. JMESSAGE(JTRC_SOI, "Start of Image")
  157710. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  157711. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  157712. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  157713. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  157714. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  157715. JMESSAGE(JTRC_THUMB_JPEG,
  157716. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  157717. JMESSAGE(JTRC_THUMB_PALETTE,
  157718. "JFIF extension marker: palette thumbnail image, length %u")
  157719. JMESSAGE(JTRC_THUMB_RGB,
  157720. "JFIF extension marker: RGB thumbnail image, length %u")
  157721. JMESSAGE(JTRC_UNKNOWN_IDS,
  157722. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  157723. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  157724. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  157725. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  157726. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  157727. "Inconsistent progression sequence for component %d coefficient %d")
  157728. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  157729. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  157730. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  157731. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  157732. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  157733. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  157734. JMESSAGE(JWRN_MUST_RESYNC,
  157735. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  157736. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  157737. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  157738. #ifdef JMAKE_ENUM_LIST
  157739. JMSG_LASTMSGCODE
  157740. } J_MESSAGE_CODE;
  157741. #undef JMAKE_ENUM_LIST
  157742. #endif /* JMAKE_ENUM_LIST */
  157743. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  157744. #undef JMESSAGE
  157745. #ifndef JERROR_H
  157746. #define JERROR_H
  157747. /* Macros to simplify using the error and trace message stuff */
  157748. /* The first parameter is either type of cinfo pointer */
  157749. /* Fatal errors (print message and exit) */
  157750. #define ERREXIT(cinfo,code) \
  157751. ((cinfo)->err->msg_code = (code), \
  157752. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157753. #define ERREXIT1(cinfo,code,p1) \
  157754. ((cinfo)->err->msg_code = (code), \
  157755. (cinfo)->err->msg_parm.i[0] = (p1), \
  157756. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157757. #define ERREXIT2(cinfo,code,p1,p2) \
  157758. ((cinfo)->err->msg_code = (code), \
  157759. (cinfo)->err->msg_parm.i[0] = (p1), \
  157760. (cinfo)->err->msg_parm.i[1] = (p2), \
  157761. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157762. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  157763. ((cinfo)->err->msg_code = (code), \
  157764. (cinfo)->err->msg_parm.i[0] = (p1), \
  157765. (cinfo)->err->msg_parm.i[1] = (p2), \
  157766. (cinfo)->err->msg_parm.i[2] = (p3), \
  157767. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157768. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  157769. ((cinfo)->err->msg_code = (code), \
  157770. (cinfo)->err->msg_parm.i[0] = (p1), \
  157771. (cinfo)->err->msg_parm.i[1] = (p2), \
  157772. (cinfo)->err->msg_parm.i[2] = (p3), \
  157773. (cinfo)->err->msg_parm.i[3] = (p4), \
  157774. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157775. #define ERREXITS(cinfo,code,str) \
  157776. ((cinfo)->err->msg_code = (code), \
  157777. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157778. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157779. #define MAKESTMT(stuff) do { stuff } while (0)
  157780. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  157781. #define WARNMS(cinfo,code) \
  157782. ((cinfo)->err->msg_code = (code), \
  157783. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157784. #define WARNMS1(cinfo,code,p1) \
  157785. ((cinfo)->err->msg_code = (code), \
  157786. (cinfo)->err->msg_parm.i[0] = (p1), \
  157787. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157788. #define WARNMS2(cinfo,code,p1,p2) \
  157789. ((cinfo)->err->msg_code = (code), \
  157790. (cinfo)->err->msg_parm.i[0] = (p1), \
  157791. (cinfo)->err->msg_parm.i[1] = (p2), \
  157792. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157793. /* Informational/debugging messages */
  157794. #define TRACEMS(cinfo,lvl,code) \
  157795. ((cinfo)->err->msg_code = (code), \
  157796. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157797. #define TRACEMS1(cinfo,lvl,code,p1) \
  157798. ((cinfo)->err->msg_code = (code), \
  157799. (cinfo)->err->msg_parm.i[0] = (p1), \
  157800. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157801. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  157802. ((cinfo)->err->msg_code = (code), \
  157803. (cinfo)->err->msg_parm.i[0] = (p1), \
  157804. (cinfo)->err->msg_parm.i[1] = (p2), \
  157805. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157806. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  157807. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157808. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  157809. (cinfo)->err->msg_code = (code); \
  157810. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157811. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  157812. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157813. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157814. (cinfo)->err->msg_code = (code); \
  157815. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157816. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  157817. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157818. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157819. _mp[4] = (p5); \
  157820. (cinfo)->err->msg_code = (code); \
  157821. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157822. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  157823. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157824. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157825. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  157826. (cinfo)->err->msg_code = (code); \
  157827. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157828. #define TRACEMSS(cinfo,lvl,code,str) \
  157829. ((cinfo)->err->msg_code = (code), \
  157830. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157831. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157832. #endif /* JERROR_H */
  157833. /*** End of inlined file: jerror.h ***/
  157834. /* fetch error codes too */
  157835. #endif
  157836. #endif /* JPEGLIB_H */
  157837. /*** End of inlined file: jpeglib.h ***/
  157838. /*** Start of inlined file: jcapimin.c ***/
  157839. #define JPEG_INTERNALS
  157840. /*** Start of inlined file: jinclude.h ***/
  157841. /* Include auto-config file to find out which system include files we need. */
  157842. #ifndef __jinclude_h__
  157843. #define __jinclude_h__
  157844. /*** Start of inlined file: jconfig.h ***/
  157845. /* see jconfig.doc for explanations */
  157846. // disable all the warnings under MSVC
  157847. #ifdef _MSC_VER
  157848. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  157849. #endif
  157850. #ifdef __BORLANDC__
  157851. #pragma warn -8057
  157852. #pragma warn -8019
  157853. #pragma warn -8004
  157854. #pragma warn -8008
  157855. #endif
  157856. #define HAVE_PROTOTYPES
  157857. #define HAVE_UNSIGNED_CHAR
  157858. #define HAVE_UNSIGNED_SHORT
  157859. /* #define void char */
  157860. /* #define const */
  157861. #undef CHAR_IS_UNSIGNED
  157862. #define HAVE_STDDEF_H
  157863. #define HAVE_STDLIB_H
  157864. #undef NEED_BSD_STRINGS
  157865. #undef NEED_SYS_TYPES_H
  157866. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  157867. #undef NEED_SHORT_EXTERNAL_NAMES
  157868. #undef INCOMPLETE_TYPES_BROKEN
  157869. /* Define "boolean" as unsigned char, not int, per Windows custom */
  157870. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  157871. typedef unsigned char boolean;
  157872. #endif
  157873. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  157874. #ifdef JPEG_INTERNALS
  157875. #undef RIGHT_SHIFT_IS_UNSIGNED
  157876. #endif /* JPEG_INTERNALS */
  157877. #ifdef JPEG_CJPEG_DJPEG
  157878. #define BMP_SUPPORTED /* BMP image file format */
  157879. #define GIF_SUPPORTED /* GIF image file format */
  157880. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  157881. #undef RLE_SUPPORTED /* Utah RLE image file format */
  157882. #define TARGA_SUPPORTED /* Targa image file format */
  157883. #define TWO_FILE_COMMANDLINE /* optional */
  157884. #define USE_SETMODE /* Microsoft has setmode() */
  157885. #undef NEED_SIGNAL_CATCHER
  157886. #undef DONT_USE_B_MODE
  157887. #undef PROGRESS_REPORT /* optional */
  157888. #endif /* JPEG_CJPEG_DJPEG */
  157889. /*** End of inlined file: jconfig.h ***/
  157890. /* auto configuration options */
  157891. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  157892. /*
  157893. * We need the NULL macro and size_t typedef.
  157894. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  157895. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  157896. * pull in <sys/types.h> as well.
  157897. * Note that the core JPEG library does not require <stdio.h>;
  157898. * only the default error handler and data source/destination modules do.
  157899. * But we must pull it in because of the references to FILE in jpeglib.h.
  157900. * You can remove those references if you want to compile without <stdio.h>.
  157901. */
  157902. #ifdef HAVE_STDDEF_H
  157903. #include <stddef.h>
  157904. #endif
  157905. #ifdef HAVE_STDLIB_H
  157906. #include <stdlib.h>
  157907. #endif
  157908. #ifdef NEED_SYS_TYPES_H
  157909. #include <sys/types.h>
  157910. #endif
  157911. #include <stdio.h>
  157912. /*
  157913. * We need memory copying and zeroing functions, plus strncpy().
  157914. * ANSI and System V implementations declare these in <string.h>.
  157915. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  157916. * Some systems may declare memset and memcpy in <memory.h>.
  157917. *
  157918. * NOTE: we assume the size parameters to these functions are of type size_t.
  157919. * Change the casts in these macros if not!
  157920. */
  157921. #ifdef NEED_BSD_STRINGS
  157922. #include <strings.h>
  157923. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  157924. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  157925. #else /* not BSD, assume ANSI/SysV string lib */
  157926. #include <string.h>
  157927. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  157928. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  157929. #endif
  157930. /*
  157931. * In ANSI C, and indeed any rational implementation, size_t is also the
  157932. * type returned by sizeof(). However, it seems there are some irrational
  157933. * implementations out there, in which sizeof() returns an int even though
  157934. * size_t is defined as long or unsigned long. To ensure consistent results
  157935. * we always use this SIZEOF() macro in place of using sizeof() directly.
  157936. */
  157937. #define SIZEOF(object) ((size_t) sizeof(object))
  157938. /*
  157939. * The modules that use fread() and fwrite() always invoke them through
  157940. * these macros. On some systems you may need to twiddle the argument casts.
  157941. * CAUTION: argument order is different from underlying functions!
  157942. */
  157943. #define JFREAD(file,buf,sizeofbuf) \
  157944. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157945. #define JFWRITE(file,buf,sizeofbuf) \
  157946. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157947. typedef enum { /* JPEG marker codes */
  157948. M_SOF0 = 0xc0,
  157949. M_SOF1 = 0xc1,
  157950. M_SOF2 = 0xc2,
  157951. M_SOF3 = 0xc3,
  157952. M_SOF5 = 0xc5,
  157953. M_SOF6 = 0xc6,
  157954. M_SOF7 = 0xc7,
  157955. M_JPG = 0xc8,
  157956. M_SOF9 = 0xc9,
  157957. M_SOF10 = 0xca,
  157958. M_SOF11 = 0xcb,
  157959. M_SOF13 = 0xcd,
  157960. M_SOF14 = 0xce,
  157961. M_SOF15 = 0xcf,
  157962. M_DHT = 0xc4,
  157963. M_DAC = 0xcc,
  157964. M_RST0 = 0xd0,
  157965. M_RST1 = 0xd1,
  157966. M_RST2 = 0xd2,
  157967. M_RST3 = 0xd3,
  157968. M_RST4 = 0xd4,
  157969. M_RST5 = 0xd5,
  157970. M_RST6 = 0xd6,
  157971. M_RST7 = 0xd7,
  157972. M_SOI = 0xd8,
  157973. M_EOI = 0xd9,
  157974. M_SOS = 0xda,
  157975. M_DQT = 0xdb,
  157976. M_DNL = 0xdc,
  157977. M_DRI = 0xdd,
  157978. M_DHP = 0xde,
  157979. M_EXP = 0xdf,
  157980. M_APP0 = 0xe0,
  157981. M_APP1 = 0xe1,
  157982. M_APP2 = 0xe2,
  157983. M_APP3 = 0xe3,
  157984. M_APP4 = 0xe4,
  157985. M_APP5 = 0xe5,
  157986. M_APP6 = 0xe6,
  157987. M_APP7 = 0xe7,
  157988. M_APP8 = 0xe8,
  157989. M_APP9 = 0xe9,
  157990. M_APP10 = 0xea,
  157991. M_APP11 = 0xeb,
  157992. M_APP12 = 0xec,
  157993. M_APP13 = 0xed,
  157994. M_APP14 = 0xee,
  157995. M_APP15 = 0xef,
  157996. M_JPG0 = 0xf0,
  157997. M_JPG13 = 0xfd,
  157998. M_COM = 0xfe,
  157999. M_TEM = 0x01,
  158000. M_ERROR = 0x100
  158001. } JPEG_MARKER;
  158002. /*
  158003. * Figure F.12: extend sign bit.
  158004. * On some machines, a shift and add will be faster than a table lookup.
  158005. */
  158006. #ifdef AVOID_TABLES
  158007. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  158008. #else
  158009. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  158010. static const int extend_test[16] = /* entry n is 2**(n-1) */
  158011. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  158012. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  158013. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  158014. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  158015. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  158016. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  158017. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  158018. #endif /* AVOID_TABLES */
  158019. #endif
  158020. /*** End of inlined file: jinclude.h ***/
  158021. /*
  158022. * Initialization of a JPEG compression object.
  158023. * The error manager must already be set up (in case memory manager fails).
  158024. */
  158025. GLOBAL(void)
  158026. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  158027. {
  158028. int i;
  158029. /* Guard against version mismatches between library and caller. */
  158030. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  158031. if (version != JPEG_LIB_VERSION)
  158032. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  158033. if (structsize != SIZEOF(struct jpeg_compress_struct))
  158034. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  158035. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  158036. /* For debugging purposes, we zero the whole master structure.
  158037. * But the application has already set the err pointer, and may have set
  158038. * client_data, so we have to save and restore those fields.
  158039. * Note: if application hasn't set client_data, tools like Purify may
  158040. * complain here.
  158041. */
  158042. {
  158043. struct jpeg_error_mgr * err = cinfo->err;
  158044. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  158045. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  158046. cinfo->err = err;
  158047. cinfo->client_data = client_data;
  158048. }
  158049. cinfo->is_decompressor = FALSE;
  158050. /* Initialize a memory manager instance for this object */
  158051. jinit_memory_mgr((j_common_ptr) cinfo);
  158052. /* Zero out pointers to permanent structures. */
  158053. cinfo->progress = NULL;
  158054. cinfo->dest = NULL;
  158055. cinfo->comp_info = NULL;
  158056. for (i = 0; i < NUM_QUANT_TBLS; i++)
  158057. cinfo->quant_tbl_ptrs[i] = NULL;
  158058. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158059. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  158060. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  158061. }
  158062. cinfo->script_space = NULL;
  158063. cinfo->input_gamma = 1.0; /* in case application forgets */
  158064. /* OK, I'm ready */
  158065. cinfo->global_state = CSTATE_START;
  158066. }
  158067. /*
  158068. * Destruction of a JPEG compression object
  158069. */
  158070. GLOBAL(void)
  158071. jpeg_destroy_compress (j_compress_ptr cinfo)
  158072. {
  158073. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  158074. }
  158075. /*
  158076. * Abort processing of a JPEG compression operation,
  158077. * but don't destroy the object itself.
  158078. */
  158079. GLOBAL(void)
  158080. jpeg_abort_compress (j_compress_ptr cinfo)
  158081. {
  158082. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  158083. }
  158084. /*
  158085. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  158086. * Marks all currently defined tables as already written (if suppress)
  158087. * or not written (if !suppress). This will control whether they get emitted
  158088. * by a subsequent jpeg_start_compress call.
  158089. *
  158090. * This routine is exported for use by applications that want to produce
  158091. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  158092. * since it is called by jpeg_start_compress, we put it here --- otherwise
  158093. * jcparam.o would be linked whether the application used it or not.
  158094. */
  158095. GLOBAL(void)
  158096. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  158097. {
  158098. int i;
  158099. JQUANT_TBL * qtbl;
  158100. JHUFF_TBL * htbl;
  158101. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158102. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  158103. qtbl->sent_table = suppress;
  158104. }
  158105. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158106. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  158107. htbl->sent_table = suppress;
  158108. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  158109. htbl->sent_table = suppress;
  158110. }
  158111. }
  158112. /*
  158113. * Finish JPEG compression.
  158114. *
  158115. * If a multipass operating mode was selected, this may do a great deal of
  158116. * work including most of the actual output.
  158117. */
  158118. GLOBAL(void)
  158119. jpeg_finish_compress (j_compress_ptr cinfo)
  158120. {
  158121. JDIMENSION iMCU_row;
  158122. if (cinfo->global_state == CSTATE_SCANNING ||
  158123. cinfo->global_state == CSTATE_RAW_OK) {
  158124. /* Terminate first pass */
  158125. if (cinfo->next_scanline < cinfo->image_height)
  158126. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  158127. (*cinfo->master->finish_pass) (cinfo);
  158128. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  158129. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158130. /* Perform any remaining passes */
  158131. while (! cinfo->master->is_last_pass) {
  158132. (*cinfo->master->prepare_for_pass) (cinfo);
  158133. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  158134. if (cinfo->progress != NULL) {
  158135. cinfo->progress->pass_counter = (long) iMCU_row;
  158136. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  158137. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158138. }
  158139. /* We bypass the main controller and invoke coef controller directly;
  158140. * all work is being done from the coefficient buffer.
  158141. */
  158142. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  158143. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158144. }
  158145. (*cinfo->master->finish_pass) (cinfo);
  158146. }
  158147. /* Write EOI, do final cleanup */
  158148. (*cinfo->marker->write_file_trailer) (cinfo);
  158149. (*cinfo->dest->term_destination) (cinfo);
  158150. /* We can use jpeg_abort to release memory and reset global_state */
  158151. jpeg_abort((j_common_ptr) cinfo);
  158152. }
  158153. /*
  158154. * Write a special marker.
  158155. * This is only recommended for writing COM or APPn markers.
  158156. * Must be called after jpeg_start_compress() and before
  158157. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  158158. */
  158159. GLOBAL(void)
  158160. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  158161. const JOCTET *dataptr, unsigned int datalen)
  158162. {
  158163. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  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. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  158171. while (datalen--) {
  158172. (*write_marker_byte) (cinfo, *dataptr);
  158173. dataptr++;
  158174. }
  158175. }
  158176. /* Same, but piecemeal. */
  158177. GLOBAL(void)
  158178. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158179. {
  158180. if (cinfo->next_scanline != 0 ||
  158181. (cinfo->global_state != CSTATE_SCANNING &&
  158182. cinfo->global_state != CSTATE_RAW_OK &&
  158183. cinfo->global_state != CSTATE_WRCOEFS))
  158184. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158185. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158186. }
  158187. GLOBAL(void)
  158188. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  158189. {
  158190. (*cinfo->marker->write_marker_byte) (cinfo, val);
  158191. }
  158192. /*
  158193. * Alternate compression function: just write an abbreviated table file.
  158194. * Before calling this, all parameters and a data destination must be set up.
  158195. *
  158196. * To produce a pair of files containing abbreviated tables and abbreviated
  158197. * image data, one would proceed as follows:
  158198. *
  158199. * initialize JPEG object
  158200. * set JPEG parameters
  158201. * set destination to table file
  158202. * jpeg_write_tables(cinfo);
  158203. * set destination to image file
  158204. * jpeg_start_compress(cinfo, FALSE);
  158205. * write data...
  158206. * jpeg_finish_compress(cinfo);
  158207. *
  158208. * jpeg_write_tables has the side effect of marking all tables written
  158209. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  158210. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  158211. */
  158212. GLOBAL(void)
  158213. jpeg_write_tables (j_compress_ptr cinfo)
  158214. {
  158215. if (cinfo->global_state != CSTATE_START)
  158216. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158217. /* (Re)initialize error mgr and destination modules */
  158218. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158219. (*cinfo->dest->init_destination) (cinfo);
  158220. /* Initialize the marker writer ... bit of a crock to do it here. */
  158221. jinit_marker_writer(cinfo);
  158222. /* Write them tables! */
  158223. (*cinfo->marker->write_tables_only) (cinfo);
  158224. /* And clean up. */
  158225. (*cinfo->dest->term_destination) (cinfo);
  158226. /*
  158227. * In library releases up through v6a, we called jpeg_abort() here to free
  158228. * any working memory allocated by the destination manager and marker
  158229. * writer. Some applications had a problem with that: they allocated space
  158230. * of their own from the library memory manager, and didn't want it to go
  158231. * away during write_tables. So now we do nothing. This will cause a
  158232. * memory leak if an app calls write_tables repeatedly without doing a full
  158233. * compression cycle or otherwise resetting the JPEG object. However, that
  158234. * seems less bad than unexpectedly freeing memory in the normal case.
  158235. * An app that prefers the old behavior can call jpeg_abort for itself after
  158236. * each call to jpeg_write_tables().
  158237. */
  158238. }
  158239. /*** End of inlined file: jcapimin.c ***/
  158240. /*** Start of inlined file: jcapistd.c ***/
  158241. #define JPEG_INTERNALS
  158242. /*
  158243. * Compression initialization.
  158244. * Before calling this, all parameters and a data destination must be set up.
  158245. *
  158246. * We require a write_all_tables parameter as a failsafe check when writing
  158247. * multiple datastreams from the same compression object. Since prior runs
  158248. * will have left all the tables marked sent_table=TRUE, a subsequent run
  158249. * would emit an abbreviated stream (no tables) by default. This may be what
  158250. * is wanted, but for safety's sake it should not be the default behavior:
  158251. * programmers should have to make a deliberate choice to emit abbreviated
  158252. * images. Therefore the documentation and examples should encourage people
  158253. * to pass write_all_tables=TRUE; then it will take active thought to do the
  158254. * wrong thing.
  158255. */
  158256. GLOBAL(void)
  158257. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  158258. {
  158259. if (cinfo->global_state != CSTATE_START)
  158260. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158261. if (write_all_tables)
  158262. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  158263. /* (Re)initialize error mgr and destination modules */
  158264. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158265. (*cinfo->dest->init_destination) (cinfo);
  158266. /* Perform master selection of active modules */
  158267. jinit_compress_master(cinfo);
  158268. /* Set up for the first pass */
  158269. (*cinfo->master->prepare_for_pass) (cinfo);
  158270. /* Ready for application to drive first pass through jpeg_write_scanlines
  158271. * or jpeg_write_raw_data.
  158272. */
  158273. cinfo->next_scanline = 0;
  158274. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  158275. }
  158276. /*
  158277. * Write some scanlines of data to the JPEG compressor.
  158278. *
  158279. * The return value will be the number of lines actually written.
  158280. * This should be less than the supplied num_lines only in case that
  158281. * the data destination module has requested suspension of the compressor,
  158282. * or if more than image_height scanlines are passed in.
  158283. *
  158284. * Note: we warn about excess calls to jpeg_write_scanlines() since
  158285. * this likely signals an application programmer error. However,
  158286. * excess scanlines passed in the last valid call are *silently* ignored,
  158287. * so that the application need not adjust num_lines for end-of-image
  158288. * when using a multiple-scanline buffer.
  158289. */
  158290. GLOBAL(JDIMENSION)
  158291. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  158292. JDIMENSION num_lines)
  158293. {
  158294. JDIMENSION row_ctr, rows_left;
  158295. if (cinfo->global_state != CSTATE_SCANNING)
  158296. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158297. if (cinfo->next_scanline >= cinfo->image_height)
  158298. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158299. /* Call progress monitor hook if present */
  158300. if (cinfo->progress != NULL) {
  158301. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158302. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158303. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158304. }
  158305. /* Give master control module another chance if this is first call to
  158306. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  158307. * delayed so that application can write COM, etc, markers between
  158308. * jpeg_start_compress and jpeg_write_scanlines.
  158309. */
  158310. if (cinfo->master->call_pass_startup)
  158311. (*cinfo->master->pass_startup) (cinfo);
  158312. /* Ignore any extra scanlines at bottom of image. */
  158313. rows_left = cinfo->image_height - cinfo->next_scanline;
  158314. if (num_lines > rows_left)
  158315. num_lines = rows_left;
  158316. row_ctr = 0;
  158317. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  158318. cinfo->next_scanline += row_ctr;
  158319. return row_ctr;
  158320. }
  158321. /*
  158322. * Alternate entry point to write raw data.
  158323. * Processes exactly one iMCU row per call, unless suspended.
  158324. */
  158325. GLOBAL(JDIMENSION)
  158326. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  158327. JDIMENSION num_lines)
  158328. {
  158329. JDIMENSION lines_per_iMCU_row;
  158330. if (cinfo->global_state != CSTATE_RAW_OK)
  158331. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158332. if (cinfo->next_scanline >= cinfo->image_height) {
  158333. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158334. return 0;
  158335. }
  158336. /* Call progress monitor hook if present */
  158337. if (cinfo->progress != NULL) {
  158338. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158339. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158340. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158341. }
  158342. /* Give master control module another chance if this is first call to
  158343. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  158344. * delayed so that application can write COM, etc, markers between
  158345. * jpeg_start_compress and jpeg_write_raw_data.
  158346. */
  158347. if (cinfo->master->call_pass_startup)
  158348. (*cinfo->master->pass_startup) (cinfo);
  158349. /* Verify that at least one iMCU row has been passed. */
  158350. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  158351. if (num_lines < lines_per_iMCU_row)
  158352. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  158353. /* Directly compress the row. */
  158354. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  158355. /* If compressor did not consume the whole row, suspend processing. */
  158356. return 0;
  158357. }
  158358. /* OK, we processed one iMCU row. */
  158359. cinfo->next_scanline += lines_per_iMCU_row;
  158360. return lines_per_iMCU_row;
  158361. }
  158362. /*** End of inlined file: jcapistd.c ***/
  158363. /*** Start of inlined file: jccoefct.c ***/
  158364. #define JPEG_INTERNALS
  158365. /* We use a full-image coefficient buffer when doing Huffman optimization,
  158366. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  158367. * step is run during the first pass, and subsequent passes need only read
  158368. * the buffered coefficients.
  158369. */
  158370. #ifdef ENTROPY_OPT_SUPPORTED
  158371. #define FULL_COEF_BUFFER_SUPPORTED
  158372. #else
  158373. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158374. #define FULL_COEF_BUFFER_SUPPORTED
  158375. #endif
  158376. #endif
  158377. /* Private buffer controller object */
  158378. typedef struct {
  158379. struct jpeg_c_coef_controller pub; /* public fields */
  158380. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  158381. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  158382. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  158383. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  158384. /* For single-pass compression, it's sufficient to buffer just one MCU
  158385. * (although this may prove a bit slow in practice). We allocate a
  158386. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  158387. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  158388. * it's not really very big; this is to keep the module interfaces unchanged
  158389. * when a large coefficient buffer is necessary.)
  158390. * In multi-pass modes, this array points to the current MCU's blocks
  158391. * within the virtual arrays.
  158392. */
  158393. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  158394. /* In multi-pass modes, we need a virtual block array for each component. */
  158395. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  158396. } my_coef_controller;
  158397. typedef my_coef_controller * my_coef_ptr;
  158398. /* Forward declarations */
  158399. METHODDEF(boolean) compress_data
  158400. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158401. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158402. METHODDEF(boolean) compress_first_pass
  158403. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158404. METHODDEF(boolean) compress_output
  158405. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158406. #endif
  158407. LOCAL(void)
  158408. start_iMCU_row (j_compress_ptr cinfo)
  158409. /* Reset within-iMCU-row counters for a new row */
  158410. {
  158411. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158412. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  158413. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  158414. * But at the bottom of the image, process only what's left.
  158415. */
  158416. if (cinfo->comps_in_scan > 1) {
  158417. coef->MCU_rows_per_iMCU_row = 1;
  158418. } else {
  158419. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  158420. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  158421. else
  158422. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  158423. }
  158424. coef->mcu_ctr = 0;
  158425. coef->MCU_vert_offset = 0;
  158426. }
  158427. /*
  158428. * Initialize for a processing pass.
  158429. */
  158430. METHODDEF(void)
  158431. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158432. {
  158433. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158434. coef->iMCU_row_num = 0;
  158435. start_iMCU_row(cinfo);
  158436. switch (pass_mode) {
  158437. case JBUF_PASS_THRU:
  158438. if (coef->whole_image[0] != NULL)
  158439. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158440. coef->pub.compress_data = compress_data;
  158441. break;
  158442. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158443. case JBUF_SAVE_AND_PASS:
  158444. if (coef->whole_image[0] == NULL)
  158445. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158446. coef->pub.compress_data = compress_first_pass;
  158447. break;
  158448. case JBUF_CRANK_DEST:
  158449. if (coef->whole_image[0] == NULL)
  158450. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158451. coef->pub.compress_data = compress_output;
  158452. break;
  158453. #endif
  158454. default:
  158455. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158456. break;
  158457. }
  158458. }
  158459. /*
  158460. * Process some data in the single-pass case.
  158461. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158462. * per call, ie, v_samp_factor block rows for each component in the image.
  158463. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  158464. *
  158465. * NB: input_buf contains a plane for each component in image,
  158466. * which we index according to the component's SOF position.
  158467. */
  158468. METHODDEF(boolean)
  158469. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  158470. {
  158471. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158472. JDIMENSION MCU_col_num; /* index of current MCU within row */
  158473. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  158474. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  158475. int blkn, bi, ci, yindex, yoffset, blockcnt;
  158476. JDIMENSION ypos, xpos;
  158477. jpeg_component_info *compptr;
  158478. /* Loop to write as much as one whole iMCU row */
  158479. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  158480. yoffset++) {
  158481. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  158482. MCU_col_num++) {
  158483. /* Determine where data comes from in input_buf and do the DCT thing.
  158484. * Each call on forward_DCT processes a horizontal row of DCT blocks
  158485. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  158486. * sequentially. Dummy blocks at the right or bottom edge are filled in
  158487. * specially. The data in them does not matter for image reconstruction,
  158488. * so we fill them with values that will encode to the smallest amount of
  158489. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  158490. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  158491. */
  158492. blkn = 0;
  158493. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158494. compptr = cinfo->cur_comp_info[ci];
  158495. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  158496. : compptr->last_col_width;
  158497. xpos = MCU_col_num * compptr->MCU_sample_width;
  158498. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  158499. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  158500. if (coef->iMCU_row_num < last_iMCU_row ||
  158501. yoffset+yindex < compptr->last_row_height) {
  158502. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  158503. input_buf[compptr->component_index],
  158504. coef->MCU_buffer[blkn],
  158505. ypos, xpos, (JDIMENSION) blockcnt);
  158506. if (blockcnt < compptr->MCU_width) {
  158507. /* Create some dummy blocks at the right edge of the image. */
  158508. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  158509. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  158510. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  158511. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  158512. }
  158513. }
  158514. } else {
  158515. /* Create a row of dummy blocks at the bottom of the image. */
  158516. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  158517. compptr->MCU_width * SIZEOF(JBLOCK));
  158518. for (bi = 0; bi < compptr->MCU_width; bi++) {
  158519. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  158520. }
  158521. }
  158522. blkn += compptr->MCU_width;
  158523. ypos += DCTSIZE;
  158524. }
  158525. }
  158526. /* Try to write the MCU. In event of a suspension failure, we will
  158527. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  158528. */
  158529. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  158530. /* Suspension forced; update state counters and exit */
  158531. coef->MCU_vert_offset = yoffset;
  158532. coef->mcu_ctr = MCU_col_num;
  158533. return FALSE;
  158534. }
  158535. }
  158536. /* Completed an MCU row, but perhaps not an iMCU row */
  158537. coef->mcu_ctr = 0;
  158538. }
  158539. /* Completed the iMCU row, advance counters for next one */
  158540. coef->iMCU_row_num++;
  158541. start_iMCU_row(cinfo);
  158542. return TRUE;
  158543. }
  158544. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158545. /*
  158546. * Process some data in the first pass of a multi-pass case.
  158547. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158548. * per call, ie, v_samp_factor block rows for each component in the image.
  158549. * This amount of data is read from the source buffer, DCT'd and quantized,
  158550. * and saved into the virtual arrays. We also generate suitable dummy blocks
  158551. * as needed at the right and lower edges. (The dummy blocks are constructed
  158552. * in the virtual arrays, which have been padded appropriately.) This makes
  158553. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  158554. *
  158555. * We must also emit the data to the entropy encoder. This is conveniently
  158556. * done by calling compress_output() after we've loaded the current strip
  158557. * of the virtual arrays.
  158558. *
  158559. * NB: input_buf contains a plane for each component in image. All
  158560. * components are DCT'd and loaded into the virtual arrays in this pass.
  158561. * However, it may be that only a subset of the components are emitted to
  158562. * the entropy encoder during this first pass; be careful about looking
  158563. * at the scan-dependent variables (MCU dimensions, etc).
  158564. */
  158565. METHODDEF(boolean)
  158566. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  158567. {
  158568. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158569. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  158570. JDIMENSION blocks_across, MCUs_across, MCUindex;
  158571. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  158572. JCOEF lastDC;
  158573. jpeg_component_info *compptr;
  158574. JBLOCKARRAY buffer;
  158575. JBLOCKROW thisblockrow, lastblockrow;
  158576. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158577. ci++, compptr++) {
  158578. /* Align the virtual buffer for this component. */
  158579. buffer = (*cinfo->mem->access_virt_barray)
  158580. ((j_common_ptr) cinfo, coef->whole_image[ci],
  158581. coef->iMCU_row_num * compptr->v_samp_factor,
  158582. (JDIMENSION) compptr->v_samp_factor, TRUE);
  158583. /* Count non-dummy DCT block rows in this iMCU row. */
  158584. if (coef->iMCU_row_num < last_iMCU_row)
  158585. block_rows = compptr->v_samp_factor;
  158586. else {
  158587. /* NB: can't use last_row_height here, since may not be set! */
  158588. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  158589. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  158590. }
  158591. blocks_across = compptr->width_in_blocks;
  158592. h_samp_factor = compptr->h_samp_factor;
  158593. /* Count number of dummy blocks to be added at the right margin. */
  158594. ndummy = (int) (blocks_across % h_samp_factor);
  158595. if (ndummy > 0)
  158596. ndummy = h_samp_factor - ndummy;
  158597. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  158598. * on forward_DCT processes a complete horizontal row of DCT blocks.
  158599. */
  158600. for (block_row = 0; block_row < block_rows; block_row++) {
  158601. thisblockrow = buffer[block_row];
  158602. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  158603. input_buf[ci], thisblockrow,
  158604. (JDIMENSION) (block_row * DCTSIZE),
  158605. (JDIMENSION) 0, blocks_across);
  158606. if (ndummy > 0) {
  158607. /* Create dummy blocks at the right edge of the image. */
  158608. thisblockrow += blocks_across; /* => first dummy block */
  158609. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  158610. lastDC = thisblockrow[-1][0];
  158611. for (bi = 0; bi < ndummy; bi++) {
  158612. thisblockrow[bi][0] = lastDC;
  158613. }
  158614. }
  158615. }
  158616. /* If at end of image, create dummy block rows as needed.
  158617. * The tricky part here is that within each MCU, we want the DC values
  158618. * of the dummy blocks to match the last real block's DC value.
  158619. * This squeezes a few more bytes out of the resulting file...
  158620. */
  158621. if (coef->iMCU_row_num == last_iMCU_row) {
  158622. blocks_across += ndummy; /* include lower right corner */
  158623. MCUs_across = blocks_across / h_samp_factor;
  158624. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  158625. block_row++) {
  158626. thisblockrow = buffer[block_row];
  158627. lastblockrow = buffer[block_row-1];
  158628. jzero_far((void FAR *) thisblockrow,
  158629. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  158630. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  158631. lastDC = lastblockrow[h_samp_factor-1][0];
  158632. for (bi = 0; bi < h_samp_factor; bi++) {
  158633. thisblockrow[bi][0] = lastDC;
  158634. }
  158635. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  158636. lastblockrow += h_samp_factor;
  158637. }
  158638. }
  158639. }
  158640. }
  158641. /* NB: compress_output will increment iMCU_row_num if successful.
  158642. * A suspension return will result in redoing all the work above next time.
  158643. */
  158644. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  158645. return compress_output(cinfo, input_buf);
  158646. }
  158647. /*
  158648. * Process some data in subsequent passes of a multi-pass case.
  158649. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158650. * per call, ie, v_samp_factor block rows for each component in the scan.
  158651. * The data is obtained from the virtual arrays and fed to the entropy coder.
  158652. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  158653. *
  158654. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  158655. */
  158656. METHODDEF(boolean)
  158657. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  158658. {
  158659. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158660. JDIMENSION MCU_col_num; /* index of current MCU within row */
  158661. int blkn, ci, xindex, yindex, yoffset;
  158662. JDIMENSION start_col;
  158663. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  158664. JBLOCKROW buffer_ptr;
  158665. jpeg_component_info *compptr;
  158666. /* Align the virtual buffers for the components used in this scan.
  158667. * NB: during first pass, this is safe only because the buffers will
  158668. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  158669. */
  158670. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158671. compptr = cinfo->cur_comp_info[ci];
  158672. buffer[ci] = (*cinfo->mem->access_virt_barray)
  158673. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  158674. coef->iMCU_row_num * compptr->v_samp_factor,
  158675. (JDIMENSION) compptr->v_samp_factor, FALSE);
  158676. }
  158677. /* Loop to process one whole iMCU row */
  158678. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  158679. yoffset++) {
  158680. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  158681. MCU_col_num++) {
  158682. /* Construct list of pointers to DCT blocks belonging to this MCU */
  158683. blkn = 0; /* index of current DCT block within MCU */
  158684. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158685. compptr = cinfo->cur_comp_info[ci];
  158686. start_col = MCU_col_num * compptr->MCU_width;
  158687. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  158688. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  158689. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  158690. coef->MCU_buffer[blkn++] = buffer_ptr++;
  158691. }
  158692. }
  158693. }
  158694. /* Try to write the MCU. */
  158695. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  158696. /* Suspension forced; update state counters and exit */
  158697. coef->MCU_vert_offset = yoffset;
  158698. coef->mcu_ctr = MCU_col_num;
  158699. return FALSE;
  158700. }
  158701. }
  158702. /* Completed an MCU row, but perhaps not an iMCU row */
  158703. coef->mcu_ctr = 0;
  158704. }
  158705. /* Completed the iMCU row, advance counters for next one */
  158706. coef->iMCU_row_num++;
  158707. start_iMCU_row(cinfo);
  158708. return TRUE;
  158709. }
  158710. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  158711. /*
  158712. * Initialize coefficient buffer controller.
  158713. */
  158714. GLOBAL(void)
  158715. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  158716. {
  158717. my_coef_ptr coef;
  158718. coef = (my_coef_ptr)
  158719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158720. SIZEOF(my_coef_controller));
  158721. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  158722. coef->pub.start_pass = start_pass_coef;
  158723. /* Create the coefficient buffer. */
  158724. if (need_full_buffer) {
  158725. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158726. /* Allocate a full-image virtual array for each component, */
  158727. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  158728. int ci;
  158729. jpeg_component_info *compptr;
  158730. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158731. ci++, compptr++) {
  158732. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  158733. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  158734. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  158735. (long) compptr->h_samp_factor),
  158736. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  158737. (long) compptr->v_samp_factor),
  158738. (JDIMENSION) compptr->v_samp_factor);
  158739. }
  158740. #else
  158741. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158742. #endif
  158743. } else {
  158744. /* We only need a single-MCU buffer. */
  158745. JBLOCKROW buffer;
  158746. int i;
  158747. buffer = (JBLOCKROW)
  158748. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158749. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  158750. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  158751. coef->MCU_buffer[i] = buffer + i;
  158752. }
  158753. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  158754. }
  158755. }
  158756. /*** End of inlined file: jccoefct.c ***/
  158757. /*** Start of inlined file: jccolor.c ***/
  158758. #define JPEG_INTERNALS
  158759. /* Private subobject */
  158760. typedef struct {
  158761. struct jpeg_color_converter pub; /* public fields */
  158762. /* Private state for RGB->YCC conversion */
  158763. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  158764. } my_color_converter;
  158765. typedef my_color_converter * my_cconvert_ptr;
  158766. /**************** RGB -> YCbCr conversion: most common case **************/
  158767. /*
  158768. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  158769. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  158770. * The conversion equations to be implemented are therefore
  158771. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  158772. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  158773. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  158774. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  158775. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  158776. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  158777. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  158778. * were not represented exactly. Now we sacrifice exact representation of
  158779. * maximum red and maximum blue in order to get exact grayscales.
  158780. *
  158781. * To avoid floating-point arithmetic, we represent the fractional constants
  158782. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  158783. * the products by 2^16, with appropriate rounding, to get the correct answer.
  158784. *
  158785. * For even more speed, we avoid doing any multiplications in the inner loop
  158786. * by precalculating the constants times R,G,B for all possible values.
  158787. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  158788. * for 12-bit samples it is still acceptable. It's not very reasonable for
  158789. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  158790. * colorspace anyway.
  158791. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  158792. * in the tables to save adding them separately in the inner loop.
  158793. */
  158794. #define SCALEBITS 16 /* speediest right-shift on some machines */
  158795. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  158796. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  158797. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  158798. /* We allocate one big table and divide it up into eight parts, instead of
  158799. * doing eight alloc_small requests. This lets us use a single table base
  158800. * address, which can be held in a register in the inner loops on many
  158801. * machines (more than can hold all eight addresses, anyway).
  158802. */
  158803. #define R_Y_OFF 0 /* offset to R => Y section */
  158804. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  158805. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  158806. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  158807. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  158808. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  158809. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  158810. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  158811. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  158812. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  158813. /*
  158814. * Initialize for RGB->YCC colorspace conversion.
  158815. */
  158816. METHODDEF(void)
  158817. rgb_ycc_start (j_compress_ptr cinfo)
  158818. {
  158819. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158820. INT32 * rgb_ycc_tab;
  158821. INT32 i;
  158822. /* Allocate and fill in the conversion tables. */
  158823. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  158824. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158825. (TABLE_SIZE * SIZEOF(INT32)));
  158826. for (i = 0; i <= MAXJSAMPLE; i++) {
  158827. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  158828. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  158829. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  158830. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  158831. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  158832. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  158833. * This ensures that the maximum output will round to MAXJSAMPLE
  158834. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  158835. */
  158836. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158837. /* B=>Cb and R=>Cr tables are the same
  158838. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158839. */
  158840. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  158841. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  158842. }
  158843. }
  158844. /*
  158845. * Convert some rows of samples to the JPEG colorspace.
  158846. *
  158847. * Note that we change from the application's interleaved-pixel format
  158848. * to our internal noninterleaved, one-plane-per-component format.
  158849. * The input buffer is therefore three times as wide as the output buffer.
  158850. *
  158851. * A starting row offset is provided only for the output buffer. The caller
  158852. * can easily adjust the passed input_buf value to accommodate any row
  158853. * offset required on that side.
  158854. */
  158855. METHODDEF(void)
  158856. rgb_ycc_convert (j_compress_ptr cinfo,
  158857. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158858. JDIMENSION output_row, int num_rows)
  158859. {
  158860. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158861. register int r, g, b;
  158862. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158863. register JSAMPROW inptr;
  158864. register JSAMPROW outptr0, outptr1, outptr2;
  158865. register JDIMENSION col;
  158866. JDIMENSION num_cols = cinfo->image_width;
  158867. while (--num_rows >= 0) {
  158868. inptr = *input_buf++;
  158869. outptr0 = output_buf[0][output_row];
  158870. outptr1 = output_buf[1][output_row];
  158871. outptr2 = output_buf[2][output_row];
  158872. output_row++;
  158873. for (col = 0; col < num_cols; col++) {
  158874. r = GETJSAMPLE(inptr[RGB_RED]);
  158875. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158876. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158877. inptr += RGB_PIXELSIZE;
  158878. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158879. * must be too; we do not need an explicit range-limiting operation.
  158880. * Hence the value being shifted is never negative, and we don't
  158881. * need the general RIGHT_SHIFT macro.
  158882. */
  158883. /* Y */
  158884. outptr0[col] = (JSAMPLE)
  158885. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158886. >> SCALEBITS);
  158887. /* Cb */
  158888. outptr1[col] = (JSAMPLE)
  158889. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158890. >> SCALEBITS);
  158891. /* Cr */
  158892. outptr2[col] = (JSAMPLE)
  158893. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158894. >> SCALEBITS);
  158895. }
  158896. }
  158897. }
  158898. /**************** Cases other than RGB -> YCbCr **************/
  158899. /*
  158900. * Convert some rows of samples to the JPEG colorspace.
  158901. * This version handles RGB->grayscale conversion, which is the same
  158902. * as the RGB->Y portion of RGB->YCbCr.
  158903. * We assume rgb_ycc_start has been called (we only use the Y tables).
  158904. */
  158905. METHODDEF(void)
  158906. rgb_gray_convert (j_compress_ptr cinfo,
  158907. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158908. JDIMENSION output_row, int num_rows)
  158909. {
  158910. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158911. register int r, g, b;
  158912. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158913. register JSAMPROW inptr;
  158914. register JSAMPROW outptr;
  158915. register JDIMENSION col;
  158916. JDIMENSION num_cols = cinfo->image_width;
  158917. while (--num_rows >= 0) {
  158918. inptr = *input_buf++;
  158919. outptr = output_buf[0][output_row];
  158920. output_row++;
  158921. for (col = 0; col < num_cols; col++) {
  158922. r = GETJSAMPLE(inptr[RGB_RED]);
  158923. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158924. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158925. inptr += RGB_PIXELSIZE;
  158926. /* Y */
  158927. outptr[col] = (JSAMPLE)
  158928. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158929. >> SCALEBITS);
  158930. }
  158931. }
  158932. }
  158933. /*
  158934. * Convert some rows of samples to the JPEG colorspace.
  158935. * This version handles Adobe-style CMYK->YCCK conversion,
  158936. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  158937. * conversion as above, while passing K (black) unchanged.
  158938. * We assume rgb_ycc_start has been called.
  158939. */
  158940. METHODDEF(void)
  158941. cmyk_ycck_convert (j_compress_ptr cinfo,
  158942. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158943. JDIMENSION output_row, int num_rows)
  158944. {
  158945. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158946. register int r, g, b;
  158947. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158948. register JSAMPROW inptr;
  158949. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  158950. register JDIMENSION col;
  158951. JDIMENSION num_cols = cinfo->image_width;
  158952. while (--num_rows >= 0) {
  158953. inptr = *input_buf++;
  158954. outptr0 = output_buf[0][output_row];
  158955. outptr1 = output_buf[1][output_row];
  158956. outptr2 = output_buf[2][output_row];
  158957. outptr3 = output_buf[3][output_row];
  158958. output_row++;
  158959. for (col = 0; col < num_cols; col++) {
  158960. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  158961. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  158962. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  158963. /* K passes through as-is */
  158964. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  158965. inptr += 4;
  158966. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158967. * must be too; we do not need an explicit range-limiting operation.
  158968. * Hence the value being shifted is never negative, and we don't
  158969. * need the general RIGHT_SHIFT macro.
  158970. */
  158971. /* Y */
  158972. outptr0[col] = (JSAMPLE)
  158973. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158974. >> SCALEBITS);
  158975. /* Cb */
  158976. outptr1[col] = (JSAMPLE)
  158977. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158978. >> SCALEBITS);
  158979. /* Cr */
  158980. outptr2[col] = (JSAMPLE)
  158981. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158982. >> SCALEBITS);
  158983. }
  158984. }
  158985. }
  158986. /*
  158987. * Convert some rows of samples to the JPEG colorspace.
  158988. * This version handles grayscale output with no conversion.
  158989. * The source can be either plain grayscale or YCbCr (since Y == gray).
  158990. */
  158991. METHODDEF(void)
  158992. grayscale_convert (j_compress_ptr cinfo,
  158993. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158994. JDIMENSION output_row, int num_rows)
  158995. {
  158996. register JSAMPROW inptr;
  158997. register JSAMPROW outptr;
  158998. register JDIMENSION col;
  158999. JDIMENSION num_cols = cinfo->image_width;
  159000. int instride = cinfo->input_components;
  159001. while (--num_rows >= 0) {
  159002. inptr = *input_buf++;
  159003. outptr = output_buf[0][output_row];
  159004. output_row++;
  159005. for (col = 0; col < num_cols; col++) {
  159006. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  159007. inptr += instride;
  159008. }
  159009. }
  159010. }
  159011. /*
  159012. * Convert some rows of samples to the JPEG colorspace.
  159013. * This version handles multi-component colorspaces without conversion.
  159014. * We assume input_components == num_components.
  159015. */
  159016. METHODDEF(void)
  159017. null_convert (j_compress_ptr cinfo,
  159018. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159019. JDIMENSION output_row, int num_rows)
  159020. {
  159021. register JSAMPROW inptr;
  159022. register JSAMPROW outptr;
  159023. register JDIMENSION col;
  159024. register int ci;
  159025. int nc = cinfo->num_components;
  159026. JDIMENSION num_cols = cinfo->image_width;
  159027. while (--num_rows >= 0) {
  159028. /* It seems fastest to make a separate pass for each component. */
  159029. for (ci = 0; ci < nc; ci++) {
  159030. inptr = *input_buf;
  159031. outptr = output_buf[ci][output_row];
  159032. for (col = 0; col < num_cols; col++) {
  159033. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  159034. inptr += nc;
  159035. }
  159036. }
  159037. input_buf++;
  159038. output_row++;
  159039. }
  159040. }
  159041. /*
  159042. * Empty method for start_pass.
  159043. */
  159044. METHODDEF(void)
  159045. null_method (j_compress_ptr)
  159046. {
  159047. /* no work needed */
  159048. }
  159049. /*
  159050. * Module initialization routine for input colorspace conversion.
  159051. */
  159052. GLOBAL(void)
  159053. jinit_color_converter (j_compress_ptr cinfo)
  159054. {
  159055. my_cconvert_ptr cconvert;
  159056. cconvert = (my_cconvert_ptr)
  159057. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159058. SIZEOF(my_color_converter));
  159059. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  159060. /* set start_pass to null method until we find out differently */
  159061. cconvert->pub.start_pass = null_method;
  159062. /* Make sure input_components agrees with in_color_space */
  159063. switch (cinfo->in_color_space) {
  159064. case JCS_GRAYSCALE:
  159065. if (cinfo->input_components != 1)
  159066. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159067. break;
  159068. case JCS_RGB:
  159069. #if RGB_PIXELSIZE != 3
  159070. if (cinfo->input_components != RGB_PIXELSIZE)
  159071. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159072. break;
  159073. #endif /* else share code with YCbCr */
  159074. case JCS_YCbCr:
  159075. if (cinfo->input_components != 3)
  159076. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159077. break;
  159078. case JCS_CMYK:
  159079. case JCS_YCCK:
  159080. if (cinfo->input_components != 4)
  159081. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159082. break;
  159083. default: /* JCS_UNKNOWN can be anything */
  159084. if (cinfo->input_components < 1)
  159085. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159086. break;
  159087. }
  159088. /* Check num_components, set conversion method based on requested space */
  159089. switch (cinfo->jpeg_color_space) {
  159090. case JCS_GRAYSCALE:
  159091. if (cinfo->num_components != 1)
  159092. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159093. if (cinfo->in_color_space == JCS_GRAYSCALE)
  159094. cconvert->pub.color_convert = grayscale_convert;
  159095. else if (cinfo->in_color_space == JCS_RGB) {
  159096. cconvert->pub.start_pass = rgb_ycc_start;
  159097. cconvert->pub.color_convert = rgb_gray_convert;
  159098. } else if (cinfo->in_color_space == JCS_YCbCr)
  159099. cconvert->pub.color_convert = grayscale_convert;
  159100. else
  159101. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159102. break;
  159103. case JCS_RGB:
  159104. if (cinfo->num_components != 3)
  159105. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159106. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  159107. cconvert->pub.color_convert = null_convert;
  159108. else
  159109. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159110. break;
  159111. case JCS_YCbCr:
  159112. if (cinfo->num_components != 3)
  159113. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159114. if (cinfo->in_color_space == JCS_RGB) {
  159115. cconvert->pub.start_pass = rgb_ycc_start;
  159116. cconvert->pub.color_convert = rgb_ycc_convert;
  159117. } else if (cinfo->in_color_space == JCS_YCbCr)
  159118. cconvert->pub.color_convert = null_convert;
  159119. else
  159120. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159121. break;
  159122. case JCS_CMYK:
  159123. if (cinfo->num_components != 4)
  159124. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159125. if (cinfo->in_color_space == JCS_CMYK)
  159126. cconvert->pub.color_convert = null_convert;
  159127. else
  159128. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159129. break;
  159130. case JCS_YCCK:
  159131. if (cinfo->num_components != 4)
  159132. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159133. if (cinfo->in_color_space == JCS_CMYK) {
  159134. cconvert->pub.start_pass = rgb_ycc_start;
  159135. cconvert->pub.color_convert = cmyk_ycck_convert;
  159136. } else if (cinfo->in_color_space == JCS_YCCK)
  159137. cconvert->pub.color_convert = null_convert;
  159138. else
  159139. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159140. break;
  159141. default: /* allow null conversion of JCS_UNKNOWN */
  159142. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  159143. cinfo->num_components != cinfo->input_components)
  159144. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159145. cconvert->pub.color_convert = null_convert;
  159146. break;
  159147. }
  159148. }
  159149. /*** End of inlined file: jccolor.c ***/
  159150. #undef FIX
  159151. /*** Start of inlined file: jcdctmgr.c ***/
  159152. #define JPEG_INTERNALS
  159153. /*** Start of inlined file: jdct.h ***/
  159154. /*
  159155. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  159156. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  159157. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  159158. * implementations use an array of type FAST_FLOAT, instead.)
  159159. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  159160. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  159161. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  159162. * convention improves accuracy in integer implementations and saves some
  159163. * work in floating-point ones.
  159164. * Quantization of the output coefficients is done by jcdctmgr.c.
  159165. */
  159166. #ifndef __jdct_h__
  159167. #define __jdct_h__
  159168. #if BITS_IN_JSAMPLE == 8
  159169. typedef int DCTELEM; /* 16 or 32 bits is fine */
  159170. #else
  159171. typedef INT32 DCTELEM; /* must have 32 bits */
  159172. #endif
  159173. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  159174. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  159175. /*
  159176. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  159177. * to an output sample array. The routine must dequantize the input data as
  159178. * well as perform the IDCT; for dequantization, it uses the multiplier table
  159179. * pointed to by compptr->dct_table. The output data is to be placed into the
  159180. * sample array starting at a specified column. (Any row offset needed will
  159181. * be applied to the array pointer before it is passed to the IDCT code.)
  159182. * Note that the number of samples emitted by the IDCT routine is
  159183. * DCT_scaled_size * DCT_scaled_size.
  159184. */
  159185. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  159186. /*
  159187. * Each IDCT routine has its own ideas about the best dct_table element type.
  159188. */
  159189. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  159190. #if BITS_IN_JSAMPLE == 8
  159191. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  159192. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  159193. #else
  159194. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  159195. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  159196. #endif
  159197. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  159198. /*
  159199. * Each IDCT routine is responsible for range-limiting its results and
  159200. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  159201. * be quite far out of range if the input data is corrupt, so a bulletproof
  159202. * range-limiting step is required. We use a mask-and-table-lookup method
  159203. * to do the combined operations quickly. See the comments with
  159204. * prepare_range_limit_table (in jdmaster.c) for more info.
  159205. */
  159206. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  159207. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  159208. /* Short forms of external names for systems with brain-damaged linkers. */
  159209. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159210. #define jpeg_fdct_islow jFDislow
  159211. #define jpeg_fdct_ifast jFDifast
  159212. #define jpeg_fdct_float jFDfloat
  159213. #define jpeg_idct_islow jRDislow
  159214. #define jpeg_idct_ifast jRDifast
  159215. #define jpeg_idct_float jRDfloat
  159216. #define jpeg_idct_4x4 jRD4x4
  159217. #define jpeg_idct_2x2 jRD2x2
  159218. #define jpeg_idct_1x1 jRD1x1
  159219. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159220. /* Extern declarations for the forward and inverse DCT routines. */
  159221. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  159222. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  159223. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  159224. EXTERN(void) jpeg_idct_islow
  159225. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159226. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159227. EXTERN(void) jpeg_idct_ifast
  159228. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159229. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159230. EXTERN(void) jpeg_idct_float
  159231. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159232. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159233. EXTERN(void) jpeg_idct_4x4
  159234. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159235. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159236. EXTERN(void) jpeg_idct_2x2
  159237. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159238. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159239. EXTERN(void) jpeg_idct_1x1
  159240. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159241. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159242. /*
  159243. * Macros for handling fixed-point arithmetic; these are used by many
  159244. * but not all of the DCT/IDCT modules.
  159245. *
  159246. * All values are expected to be of type INT32.
  159247. * Fractional constants are scaled left by CONST_BITS bits.
  159248. * CONST_BITS is defined within each module using these macros,
  159249. * and may differ from one module to the next.
  159250. */
  159251. #define ONE ((INT32) 1)
  159252. #define CONST_SCALE (ONE << CONST_BITS)
  159253. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  159254. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  159255. * thus causing a lot of useless floating-point operations at run time.
  159256. */
  159257. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  159258. /* Descale and correctly round an INT32 value that's scaled by N bits.
  159259. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  159260. * the fudge factor is correct for either sign of X.
  159261. */
  159262. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  159263. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  159264. * This macro is used only when the two inputs will actually be no more than
  159265. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  159266. * full 32x32 multiply. This provides a useful speedup on many machines.
  159267. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  159268. * in C, but some C compilers will do the right thing if you provide the
  159269. * correct combination of casts.
  159270. */
  159271. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159272. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  159273. #endif
  159274. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  159275. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  159276. #endif
  159277. #ifndef MULTIPLY16C16 /* default definition */
  159278. #define MULTIPLY16C16(var,const) ((var) * (const))
  159279. #endif
  159280. /* Same except both inputs are variables. */
  159281. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159282. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  159283. #endif
  159284. #ifndef MULTIPLY16V16 /* default definition */
  159285. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  159286. #endif
  159287. #endif
  159288. /*** End of inlined file: jdct.h ***/
  159289. /* Private declarations for DCT subsystem */
  159290. /* Private subobject for this module */
  159291. typedef struct {
  159292. struct jpeg_forward_dct pub; /* public fields */
  159293. /* Pointer to the DCT routine actually in use */
  159294. forward_DCT_method_ptr do_dct;
  159295. /* The actual post-DCT divisors --- not identical to the quant table
  159296. * entries, because of scaling (especially for an unnormalized DCT).
  159297. * Each table is given in normal array order.
  159298. */
  159299. DCTELEM * divisors[NUM_QUANT_TBLS];
  159300. #ifdef DCT_FLOAT_SUPPORTED
  159301. /* Same as above for the floating-point case. */
  159302. float_DCT_method_ptr do_float_dct;
  159303. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  159304. #endif
  159305. } my_fdct_controller;
  159306. typedef my_fdct_controller * my_fdct_ptr;
  159307. /*
  159308. * Initialize for a processing pass.
  159309. * Verify that all referenced Q-tables are present, and set up
  159310. * the divisor table for each one.
  159311. * In the current implementation, DCT of all components is done during
  159312. * the first pass, even if only some components will be output in the
  159313. * first scan. Hence all components should be examined here.
  159314. */
  159315. METHODDEF(void)
  159316. start_pass_fdctmgr (j_compress_ptr cinfo)
  159317. {
  159318. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159319. int ci, qtblno, i;
  159320. jpeg_component_info *compptr;
  159321. JQUANT_TBL * qtbl;
  159322. DCTELEM * dtbl;
  159323. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159324. ci++, compptr++) {
  159325. qtblno = compptr->quant_tbl_no;
  159326. /* Make sure specified quantization table is present */
  159327. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  159328. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  159329. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  159330. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  159331. /* Compute divisors for this quant table */
  159332. /* We may do this more than once for same table, but it's not a big deal */
  159333. switch (cinfo->dct_method) {
  159334. #ifdef DCT_ISLOW_SUPPORTED
  159335. case JDCT_ISLOW:
  159336. /* For LL&M IDCT method, divisors are equal to raw quantization
  159337. * coefficients multiplied by 8 (to counteract scaling).
  159338. */
  159339. if (fdct->divisors[qtblno] == NULL) {
  159340. fdct->divisors[qtblno] = (DCTELEM *)
  159341. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159342. DCTSIZE2 * SIZEOF(DCTELEM));
  159343. }
  159344. dtbl = fdct->divisors[qtblno];
  159345. for (i = 0; i < DCTSIZE2; i++) {
  159346. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  159347. }
  159348. break;
  159349. #endif
  159350. #ifdef DCT_IFAST_SUPPORTED
  159351. case JDCT_IFAST:
  159352. {
  159353. /* For AA&N IDCT method, divisors are equal to quantization
  159354. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159355. * scalefactor[0] = 1
  159356. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  159357. * We apply a further scale factor of 8.
  159358. */
  159359. #define CONST_BITS 14
  159360. static const INT16 aanscales[DCTSIZE2] = {
  159361. /* precomputed values scaled up by 14 bits */
  159362. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  159363. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  159364. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  159365. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  159366. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  159367. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  159368. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  159369. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  159370. };
  159371. SHIFT_TEMPS
  159372. if (fdct->divisors[qtblno] == NULL) {
  159373. fdct->divisors[qtblno] = (DCTELEM *)
  159374. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159375. DCTSIZE2 * SIZEOF(DCTELEM));
  159376. }
  159377. dtbl = fdct->divisors[qtblno];
  159378. for (i = 0; i < DCTSIZE2; i++) {
  159379. dtbl[i] = (DCTELEM)
  159380. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  159381. (INT32) aanscales[i]),
  159382. CONST_BITS-3);
  159383. }
  159384. }
  159385. break;
  159386. #endif
  159387. #ifdef DCT_FLOAT_SUPPORTED
  159388. case JDCT_FLOAT:
  159389. {
  159390. /* For float AA&N IDCT method, divisors are equal to quantization
  159391. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159392. * scalefactor[0] = 1
  159393. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  159394. * We apply a further scale factor of 8.
  159395. * What's actually stored is 1/divisor so that the inner loop can
  159396. * use a multiplication rather than a division.
  159397. */
  159398. FAST_FLOAT * fdtbl;
  159399. int row, col;
  159400. static const double aanscalefactor[DCTSIZE] = {
  159401. 1.0, 1.387039845, 1.306562965, 1.175875602,
  159402. 1.0, 0.785694958, 0.541196100, 0.275899379
  159403. };
  159404. if (fdct->float_divisors[qtblno] == NULL) {
  159405. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  159406. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159407. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  159408. }
  159409. fdtbl = fdct->float_divisors[qtblno];
  159410. i = 0;
  159411. for (row = 0; row < DCTSIZE; row++) {
  159412. for (col = 0; col < DCTSIZE; col++) {
  159413. fdtbl[i] = (FAST_FLOAT)
  159414. (1.0 / (((double) qtbl->quantval[i] *
  159415. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  159416. i++;
  159417. }
  159418. }
  159419. }
  159420. break;
  159421. #endif
  159422. default:
  159423. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159424. break;
  159425. }
  159426. }
  159427. }
  159428. /*
  159429. * Perform forward DCT on one or more blocks of a component.
  159430. *
  159431. * The input samples are taken from the sample_data[] array starting at
  159432. * position start_row/start_col, and moving to the right for any additional
  159433. * blocks. The quantized coefficients are returned in coef_blocks[].
  159434. */
  159435. METHODDEF(void)
  159436. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  159437. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159438. JDIMENSION start_row, JDIMENSION start_col,
  159439. JDIMENSION num_blocks)
  159440. /* This version is used for integer DCT implementations. */
  159441. {
  159442. /* This routine is heavily used, so it's worth coding it tightly. */
  159443. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159444. forward_DCT_method_ptr do_dct = fdct->do_dct;
  159445. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  159446. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  159447. JDIMENSION bi;
  159448. sample_data += start_row; /* fold in the vertical offset once */
  159449. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  159450. /* Load data into workspace, applying unsigned->signed conversion */
  159451. { register DCTELEM *workspaceptr;
  159452. register JSAMPROW elemptr;
  159453. register int elemr;
  159454. workspaceptr = workspace;
  159455. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  159456. elemptr = sample_data[elemr] + start_col;
  159457. #if DCTSIZE == 8 /* unroll the inner loop */
  159458. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159459. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159460. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159461. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159462. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159463. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159464. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159465. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159466. #else
  159467. { register int elemc;
  159468. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  159469. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159470. }
  159471. }
  159472. #endif
  159473. }
  159474. }
  159475. /* Perform the DCT */
  159476. (*do_dct) (workspace);
  159477. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  159478. { register DCTELEM temp, qval;
  159479. register int i;
  159480. register JCOEFPTR output_ptr = coef_blocks[bi];
  159481. for (i = 0; i < DCTSIZE2; i++) {
  159482. qval = divisors[i];
  159483. temp = workspace[i];
  159484. /* Divide the coefficient value by qval, ensuring proper rounding.
  159485. * Since C does not specify the direction of rounding for negative
  159486. * quotients, we have to force the dividend positive for portability.
  159487. *
  159488. * In most files, at least half of the output values will be zero
  159489. * (at default quantization settings, more like three-quarters...)
  159490. * so we should ensure that this case is fast. On many machines,
  159491. * a comparison is enough cheaper than a divide to make a special test
  159492. * a win. Since both inputs will be nonnegative, we need only test
  159493. * for a < b to discover whether a/b is 0.
  159494. * If your machine's division is fast enough, define FAST_DIVIDE.
  159495. */
  159496. #ifdef FAST_DIVIDE
  159497. #define DIVIDE_BY(a,b) a /= b
  159498. #else
  159499. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  159500. #endif
  159501. if (temp < 0) {
  159502. temp = -temp;
  159503. temp += qval>>1; /* for rounding */
  159504. DIVIDE_BY(temp, qval);
  159505. temp = -temp;
  159506. } else {
  159507. temp += qval>>1; /* for rounding */
  159508. DIVIDE_BY(temp, qval);
  159509. }
  159510. output_ptr[i] = (JCOEF) temp;
  159511. }
  159512. }
  159513. }
  159514. }
  159515. #ifdef DCT_FLOAT_SUPPORTED
  159516. METHODDEF(void)
  159517. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  159518. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159519. JDIMENSION start_row, JDIMENSION start_col,
  159520. JDIMENSION num_blocks)
  159521. /* This version is used for floating-point DCT implementations. */
  159522. {
  159523. /* This routine is heavily used, so it's worth coding it tightly. */
  159524. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159525. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  159526. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  159527. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  159528. JDIMENSION bi;
  159529. sample_data += start_row; /* fold in the vertical offset once */
  159530. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  159531. /* Load data into workspace, applying unsigned->signed conversion */
  159532. { register FAST_FLOAT *workspaceptr;
  159533. register JSAMPROW elemptr;
  159534. register int elemr;
  159535. workspaceptr = workspace;
  159536. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  159537. elemptr = sample_data[elemr] + start_col;
  159538. #if DCTSIZE == 8 /* unroll the inner loop */
  159539. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159540. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159541. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159542. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159543. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159544. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159545. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159546. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159547. #else
  159548. { register int elemc;
  159549. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  159550. *workspaceptr++ = (FAST_FLOAT)
  159551. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159552. }
  159553. }
  159554. #endif
  159555. }
  159556. }
  159557. /* Perform the DCT */
  159558. (*do_dct) (workspace);
  159559. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  159560. { register FAST_FLOAT temp;
  159561. register int i;
  159562. register JCOEFPTR output_ptr = coef_blocks[bi];
  159563. for (i = 0; i < DCTSIZE2; i++) {
  159564. /* Apply the quantization and scaling factor */
  159565. temp = workspace[i] * divisors[i];
  159566. /* Round to nearest integer.
  159567. * Since C does not specify the direction of rounding for negative
  159568. * quotients, we have to force the dividend positive for portability.
  159569. * The maximum coefficient size is +-16K (for 12-bit data), so this
  159570. * code should work for either 16-bit or 32-bit ints.
  159571. */
  159572. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  159573. }
  159574. }
  159575. }
  159576. }
  159577. #endif /* DCT_FLOAT_SUPPORTED */
  159578. /*
  159579. * Initialize FDCT manager.
  159580. */
  159581. GLOBAL(void)
  159582. jinit_forward_dct (j_compress_ptr cinfo)
  159583. {
  159584. my_fdct_ptr fdct;
  159585. int i;
  159586. fdct = (my_fdct_ptr)
  159587. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159588. SIZEOF(my_fdct_controller));
  159589. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  159590. fdct->pub.start_pass = start_pass_fdctmgr;
  159591. switch (cinfo->dct_method) {
  159592. #ifdef DCT_ISLOW_SUPPORTED
  159593. case JDCT_ISLOW:
  159594. fdct->pub.forward_DCT = forward_DCT;
  159595. fdct->do_dct = jpeg_fdct_islow;
  159596. break;
  159597. #endif
  159598. #ifdef DCT_IFAST_SUPPORTED
  159599. case JDCT_IFAST:
  159600. fdct->pub.forward_DCT = forward_DCT;
  159601. fdct->do_dct = jpeg_fdct_ifast;
  159602. break;
  159603. #endif
  159604. #ifdef DCT_FLOAT_SUPPORTED
  159605. case JDCT_FLOAT:
  159606. fdct->pub.forward_DCT = forward_DCT_float;
  159607. fdct->do_float_dct = jpeg_fdct_float;
  159608. break;
  159609. #endif
  159610. default:
  159611. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159612. break;
  159613. }
  159614. /* Mark divisor tables unallocated */
  159615. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  159616. fdct->divisors[i] = NULL;
  159617. #ifdef DCT_FLOAT_SUPPORTED
  159618. fdct->float_divisors[i] = NULL;
  159619. #endif
  159620. }
  159621. }
  159622. /*** End of inlined file: jcdctmgr.c ***/
  159623. #undef CONST_BITS
  159624. /*** Start of inlined file: jchuff.c ***/
  159625. #define JPEG_INTERNALS
  159626. /*** Start of inlined file: jchuff.h ***/
  159627. /* The legal range of a DCT coefficient is
  159628. * -1024 .. +1023 for 8-bit data;
  159629. * -16384 .. +16383 for 12-bit data.
  159630. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  159631. */
  159632. #ifndef _jchuff_h_
  159633. #define _jchuff_h_
  159634. #if BITS_IN_JSAMPLE == 8
  159635. #define MAX_COEF_BITS 10
  159636. #else
  159637. #define MAX_COEF_BITS 14
  159638. #endif
  159639. /* Derived data constructed for each Huffman table */
  159640. typedef struct {
  159641. unsigned int ehufco[256]; /* code for each symbol */
  159642. char ehufsi[256]; /* length of code for each symbol */
  159643. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  159644. } c_derived_tbl;
  159645. /* Short forms of external names for systems with brain-damaged linkers. */
  159646. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159647. #define jpeg_make_c_derived_tbl jMkCDerived
  159648. #define jpeg_gen_optimal_table jGenOptTbl
  159649. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159650. /* Expand a Huffman table definition into the derived format */
  159651. EXTERN(void) jpeg_make_c_derived_tbl
  159652. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  159653. c_derived_tbl ** pdtbl));
  159654. /* Generate an optimal table definition given the specified counts */
  159655. EXTERN(void) jpeg_gen_optimal_table
  159656. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  159657. #endif
  159658. /*** End of inlined file: jchuff.h ***/
  159659. /* Declarations shared with jcphuff.c */
  159660. /* Expanded entropy encoder object for Huffman encoding.
  159661. *
  159662. * The savable_state subrecord contains fields that change within an MCU,
  159663. * but must not be updated permanently until we complete the MCU.
  159664. */
  159665. typedef struct {
  159666. INT32 put_buffer; /* current bit-accumulation buffer */
  159667. int put_bits; /* # of bits now in it */
  159668. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159669. } savable_state;
  159670. /* This macro is to work around compilers with missing or broken
  159671. * structure assignment. You'll need to fix this code if you have
  159672. * such a compiler and you change MAX_COMPS_IN_SCAN.
  159673. */
  159674. #ifndef NO_STRUCT_ASSIGN
  159675. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  159676. #else
  159677. #if MAX_COMPS_IN_SCAN == 4
  159678. #define ASSIGN_STATE(dest,src) \
  159679. ((dest).put_buffer = (src).put_buffer, \
  159680. (dest).put_bits = (src).put_bits, \
  159681. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  159682. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  159683. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  159684. (dest).last_dc_val[3] = (src).last_dc_val[3])
  159685. #endif
  159686. #endif
  159687. typedef struct {
  159688. struct jpeg_entropy_encoder pub; /* public fields */
  159689. savable_state saved; /* Bit buffer & DC state at start of MCU */
  159690. /* These fields are NOT loaded into local working state. */
  159691. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159692. int next_restart_num; /* next restart number to write (0-7) */
  159693. /* Pointers to derived tables (these workspaces have image lifespan) */
  159694. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  159695. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  159696. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  159697. long * dc_count_ptrs[NUM_HUFF_TBLS];
  159698. long * ac_count_ptrs[NUM_HUFF_TBLS];
  159699. #endif
  159700. } huff_entropy_encoder;
  159701. typedef huff_entropy_encoder * huff_entropy_ptr;
  159702. /* Working state while writing an MCU.
  159703. * This struct contains all the fields that are needed by subroutines.
  159704. */
  159705. typedef struct {
  159706. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159707. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159708. savable_state cur; /* Current bit buffer & DC state */
  159709. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  159710. } working_state;
  159711. /* Forward declarations */
  159712. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  159713. JBLOCKROW *MCU_data));
  159714. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  159715. #ifdef ENTROPY_OPT_SUPPORTED
  159716. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  159717. JBLOCKROW *MCU_data));
  159718. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  159719. #endif
  159720. /*
  159721. * Initialize for a Huffman-compressed scan.
  159722. * If gather_statistics is TRUE, we do not output anything during the scan,
  159723. * just count the Huffman symbols used and generate Huffman code tables.
  159724. */
  159725. METHODDEF(void)
  159726. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  159727. {
  159728. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159729. int ci, dctbl, actbl;
  159730. jpeg_component_info * compptr;
  159731. if (gather_statistics) {
  159732. #ifdef ENTROPY_OPT_SUPPORTED
  159733. entropy->pub.encode_mcu = encode_mcu_gather;
  159734. entropy->pub.finish_pass = finish_pass_gather;
  159735. #else
  159736. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159737. #endif
  159738. } else {
  159739. entropy->pub.encode_mcu = encode_mcu_huff;
  159740. entropy->pub.finish_pass = finish_pass_huff;
  159741. }
  159742. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159743. compptr = cinfo->cur_comp_info[ci];
  159744. dctbl = compptr->dc_tbl_no;
  159745. actbl = compptr->ac_tbl_no;
  159746. if (gather_statistics) {
  159747. #ifdef ENTROPY_OPT_SUPPORTED
  159748. /* Check for invalid table indexes */
  159749. /* (make_c_derived_tbl does this in the other path) */
  159750. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  159751. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  159752. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  159753. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  159754. /* Allocate and zero the statistics tables */
  159755. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159756. if (entropy->dc_count_ptrs[dctbl] == NULL)
  159757. entropy->dc_count_ptrs[dctbl] = (long *)
  159758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159759. 257 * SIZEOF(long));
  159760. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  159761. if (entropy->ac_count_ptrs[actbl] == NULL)
  159762. entropy->ac_count_ptrs[actbl] = (long *)
  159763. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159764. 257 * SIZEOF(long));
  159765. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  159766. #endif
  159767. } else {
  159768. /* Compute derived values for Huffman tables */
  159769. /* We may do this more than once for a table, but it's not expensive */
  159770. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  159771. & entropy->dc_derived_tbls[dctbl]);
  159772. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  159773. & entropy->ac_derived_tbls[actbl]);
  159774. }
  159775. /* Initialize DC predictions to 0 */
  159776. entropy->saved.last_dc_val[ci] = 0;
  159777. }
  159778. /* Initialize bit buffer to empty */
  159779. entropy->saved.put_buffer = 0;
  159780. entropy->saved.put_bits = 0;
  159781. /* Initialize restart stuff */
  159782. entropy->restarts_to_go = cinfo->restart_interval;
  159783. entropy->next_restart_num = 0;
  159784. }
  159785. /*
  159786. * Compute the derived values for a Huffman table.
  159787. * This routine also performs some validation checks on the table.
  159788. *
  159789. * Note this is also used by jcphuff.c.
  159790. */
  159791. GLOBAL(void)
  159792. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  159793. c_derived_tbl ** pdtbl)
  159794. {
  159795. JHUFF_TBL *htbl;
  159796. c_derived_tbl *dtbl;
  159797. int p, i, l, lastp, si, maxsymbol;
  159798. char huffsize[257];
  159799. unsigned int huffcode[257];
  159800. unsigned int code;
  159801. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  159802. * paralleling the order of the symbols themselves in htbl->huffval[].
  159803. */
  159804. /* Find the input Huffman table */
  159805. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  159806. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159807. htbl =
  159808. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  159809. if (htbl == NULL)
  159810. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159811. /* Allocate a workspace if we haven't already done so. */
  159812. if (*pdtbl == NULL)
  159813. *pdtbl = (c_derived_tbl *)
  159814. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159815. SIZEOF(c_derived_tbl));
  159816. dtbl = *pdtbl;
  159817. /* Figure C.1: make table of Huffman code length for each symbol */
  159818. p = 0;
  159819. for (l = 1; l <= 16; l++) {
  159820. i = (int) htbl->bits[l];
  159821. if (i < 0 || p + i > 256) /* protect against table overrun */
  159822. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159823. while (i--)
  159824. huffsize[p++] = (char) l;
  159825. }
  159826. huffsize[p] = 0;
  159827. lastp = p;
  159828. /* Figure C.2: generate the codes themselves */
  159829. /* We also validate that the counts represent a legal Huffman code tree. */
  159830. code = 0;
  159831. si = huffsize[0];
  159832. p = 0;
  159833. while (huffsize[p]) {
  159834. while (((int) huffsize[p]) == si) {
  159835. huffcode[p++] = code;
  159836. code++;
  159837. }
  159838. /* code is now 1 more than the last code used for codelength si; but
  159839. * it must still fit in si bits, since no code is allowed to be all ones.
  159840. */
  159841. if (((INT32) code) >= (((INT32) 1) << si))
  159842. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159843. code <<= 1;
  159844. si++;
  159845. }
  159846. /* Figure C.3: generate encoding tables */
  159847. /* These are code and size indexed by symbol value */
  159848. /* Set all codeless symbols to have code length 0;
  159849. * this lets us detect duplicate VAL entries here, and later
  159850. * allows emit_bits to detect any attempt to emit such symbols.
  159851. */
  159852. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  159853. /* This is also a convenient place to check for out-of-range
  159854. * and duplicated VAL entries. We allow 0..255 for AC symbols
  159855. * but only 0..15 for DC. (We could constrain them further
  159856. * based on data depth and mode, but this seems enough.)
  159857. */
  159858. maxsymbol = isDC ? 15 : 255;
  159859. for (p = 0; p < lastp; p++) {
  159860. i = htbl->huffval[p];
  159861. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  159862. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159863. dtbl->ehufco[i] = huffcode[p];
  159864. dtbl->ehufsi[i] = huffsize[p];
  159865. }
  159866. }
  159867. /* Outputting bytes to the file */
  159868. /* Emit a byte, taking 'action' if must suspend. */
  159869. #define emit_byte(state,val,action) \
  159870. { *(state)->next_output_byte++ = (JOCTET) (val); \
  159871. if (--(state)->free_in_buffer == 0) \
  159872. if (! dump_buffer(state)) \
  159873. { action; } }
  159874. LOCAL(boolean)
  159875. dump_buffer (working_state * state)
  159876. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  159877. {
  159878. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  159879. if (! (*dest->empty_output_buffer) (state->cinfo))
  159880. return FALSE;
  159881. /* After a successful buffer dump, must reset buffer pointers */
  159882. state->next_output_byte = dest->next_output_byte;
  159883. state->free_in_buffer = dest->free_in_buffer;
  159884. return TRUE;
  159885. }
  159886. /* Outputting bits to the file */
  159887. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159888. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159889. * in one call, and we never retain more than 7 bits in put_buffer
  159890. * between calls, so 24 bits are sufficient.
  159891. */
  159892. INLINE
  159893. LOCAL(boolean)
  159894. emit_bits (working_state * state, unsigned int code, int size)
  159895. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  159896. {
  159897. /* This routine is heavily used, so it's worth coding tightly. */
  159898. register INT32 put_buffer = (INT32) code;
  159899. register int put_bits = state->cur.put_bits;
  159900. /* if size is 0, caller used an invalid Huffman table entry */
  159901. if (size == 0)
  159902. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  159903. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159904. put_bits += size; /* new number of bits in buffer */
  159905. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159906. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  159907. while (put_bits >= 8) {
  159908. int c = (int) ((put_buffer >> 16) & 0xFF);
  159909. emit_byte(state, c, return FALSE);
  159910. if (c == 0xFF) { /* need to stuff a zero byte? */
  159911. emit_byte(state, 0, return FALSE);
  159912. }
  159913. put_buffer <<= 8;
  159914. put_bits -= 8;
  159915. }
  159916. state->cur.put_buffer = put_buffer; /* update state variables */
  159917. state->cur.put_bits = put_bits;
  159918. return TRUE;
  159919. }
  159920. LOCAL(boolean)
  159921. flush_bits (working_state * state)
  159922. {
  159923. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  159924. return FALSE;
  159925. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  159926. state->cur.put_bits = 0;
  159927. return TRUE;
  159928. }
  159929. /* Encode a single block's worth of coefficients */
  159930. LOCAL(boolean)
  159931. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  159932. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  159933. {
  159934. register int temp, temp2;
  159935. register int nbits;
  159936. register int k, r, i;
  159937. /* Encode the DC coefficient difference per section F.1.2.1 */
  159938. temp = temp2 = block[0] - last_dc_val;
  159939. if (temp < 0) {
  159940. temp = -temp; /* temp is abs value of input */
  159941. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159942. /* This code assumes we are on a two's complement machine */
  159943. temp2--;
  159944. }
  159945. /* Find the number of bits needed for the magnitude of the coefficient */
  159946. nbits = 0;
  159947. while (temp) {
  159948. nbits++;
  159949. temp >>= 1;
  159950. }
  159951. /* Check for out-of-range coefficient values.
  159952. * Since we're encoding a difference, the range limit is twice as much.
  159953. */
  159954. if (nbits > MAX_COEF_BITS+1)
  159955. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159956. /* Emit the Huffman-coded symbol for the number of bits */
  159957. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  159958. return FALSE;
  159959. /* Emit that number of bits of the value, if positive, */
  159960. /* or the complement of its magnitude, if negative. */
  159961. if (nbits) /* emit_bits rejects calls with size 0 */
  159962. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159963. return FALSE;
  159964. /* Encode the AC coefficients per section F.1.2.2 */
  159965. r = 0; /* r = run length of zeros */
  159966. for (k = 1; k < DCTSIZE2; k++) {
  159967. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159968. r++;
  159969. } else {
  159970. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159971. while (r > 15) {
  159972. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  159973. return FALSE;
  159974. r -= 16;
  159975. }
  159976. temp2 = temp;
  159977. if (temp < 0) {
  159978. temp = -temp; /* temp is abs value of input */
  159979. /* This code assumes we are on a two's complement machine */
  159980. temp2--;
  159981. }
  159982. /* Find the number of bits needed for the magnitude of the coefficient */
  159983. nbits = 1; /* there must be at least one 1 bit */
  159984. while ((temp >>= 1))
  159985. nbits++;
  159986. /* Check for out-of-range coefficient values */
  159987. if (nbits > MAX_COEF_BITS)
  159988. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159989. /* Emit Huffman symbol for run length / number of bits */
  159990. i = (r << 4) + nbits;
  159991. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  159992. return FALSE;
  159993. /* Emit that number of bits of the value, if positive, */
  159994. /* or the complement of its magnitude, if negative. */
  159995. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159996. return FALSE;
  159997. r = 0;
  159998. }
  159999. }
  160000. /* If the last coef(s) were zero, emit an end-of-block code */
  160001. if (r > 0)
  160002. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  160003. return FALSE;
  160004. return TRUE;
  160005. }
  160006. /*
  160007. * Emit a restart marker & resynchronize predictions.
  160008. */
  160009. LOCAL(boolean)
  160010. emit_restart (working_state * state, int restart_num)
  160011. {
  160012. int ci;
  160013. if (! flush_bits(state))
  160014. return FALSE;
  160015. emit_byte(state, 0xFF, return FALSE);
  160016. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  160017. /* Re-initialize DC predictions to 0 */
  160018. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  160019. state->cur.last_dc_val[ci] = 0;
  160020. /* The restart counter is not updated until we successfully write the MCU. */
  160021. return TRUE;
  160022. }
  160023. /*
  160024. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  160025. */
  160026. METHODDEF(boolean)
  160027. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160028. {
  160029. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160030. working_state state;
  160031. int blkn, ci;
  160032. jpeg_component_info * compptr;
  160033. /* Load up working state */
  160034. state.next_output_byte = cinfo->dest->next_output_byte;
  160035. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160036. ASSIGN_STATE(state.cur, entropy->saved);
  160037. state.cinfo = cinfo;
  160038. /* Emit restart marker if needed */
  160039. if (cinfo->restart_interval) {
  160040. if (entropy->restarts_to_go == 0)
  160041. if (! emit_restart(&state, entropy->next_restart_num))
  160042. return FALSE;
  160043. }
  160044. /* Encode the MCU data blocks */
  160045. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160046. ci = cinfo->MCU_membership[blkn];
  160047. compptr = cinfo->cur_comp_info[ci];
  160048. if (! encode_one_block(&state,
  160049. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  160050. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  160051. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  160052. return FALSE;
  160053. /* Update last_dc_val */
  160054. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  160055. }
  160056. /* Completed MCU, so update state */
  160057. cinfo->dest->next_output_byte = state.next_output_byte;
  160058. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160059. ASSIGN_STATE(entropy->saved, state.cur);
  160060. /* Update restart-interval state too */
  160061. if (cinfo->restart_interval) {
  160062. if (entropy->restarts_to_go == 0) {
  160063. entropy->restarts_to_go = cinfo->restart_interval;
  160064. entropy->next_restart_num++;
  160065. entropy->next_restart_num &= 7;
  160066. }
  160067. entropy->restarts_to_go--;
  160068. }
  160069. return TRUE;
  160070. }
  160071. /*
  160072. * Finish up at the end of a Huffman-compressed scan.
  160073. */
  160074. METHODDEF(void)
  160075. finish_pass_huff (j_compress_ptr cinfo)
  160076. {
  160077. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160078. working_state state;
  160079. /* Load up working state ... flush_bits needs it */
  160080. state.next_output_byte = cinfo->dest->next_output_byte;
  160081. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160082. ASSIGN_STATE(state.cur, entropy->saved);
  160083. state.cinfo = cinfo;
  160084. /* Flush out the last data */
  160085. if (! flush_bits(&state))
  160086. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160087. /* Update state */
  160088. cinfo->dest->next_output_byte = state.next_output_byte;
  160089. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160090. ASSIGN_STATE(entropy->saved, state.cur);
  160091. }
  160092. /*
  160093. * Huffman coding optimization.
  160094. *
  160095. * We first scan the supplied data and count the number of uses of each symbol
  160096. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  160097. * Then we build a Huffman coding tree for the observed counts.
  160098. * Symbols which are not needed at all for the particular image are not
  160099. * assigned any code, which saves space in the DHT marker as well as in
  160100. * the compressed data.
  160101. */
  160102. #ifdef ENTROPY_OPT_SUPPORTED
  160103. /* Process a single block's worth of coefficients */
  160104. LOCAL(void)
  160105. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  160106. long dc_counts[], long ac_counts[])
  160107. {
  160108. register int temp;
  160109. register int nbits;
  160110. register int k, r;
  160111. /* Encode the DC coefficient difference per section F.1.2.1 */
  160112. temp = block[0] - last_dc_val;
  160113. if (temp < 0)
  160114. temp = -temp;
  160115. /* Find the number of bits needed for the magnitude of the coefficient */
  160116. nbits = 0;
  160117. while (temp) {
  160118. nbits++;
  160119. temp >>= 1;
  160120. }
  160121. /* Check for out-of-range coefficient values.
  160122. * Since we're encoding a difference, the range limit is twice as much.
  160123. */
  160124. if (nbits > MAX_COEF_BITS+1)
  160125. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160126. /* Count the Huffman symbol for the number of bits */
  160127. dc_counts[nbits]++;
  160128. /* Encode the AC coefficients per section F.1.2.2 */
  160129. r = 0; /* r = run length of zeros */
  160130. for (k = 1; k < DCTSIZE2; k++) {
  160131. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  160132. r++;
  160133. } else {
  160134. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160135. while (r > 15) {
  160136. ac_counts[0xF0]++;
  160137. r -= 16;
  160138. }
  160139. /* Find the number of bits needed for the magnitude of the coefficient */
  160140. if (temp < 0)
  160141. temp = -temp;
  160142. /* Find the number of bits needed for the magnitude of the coefficient */
  160143. nbits = 1; /* there must be at least one 1 bit */
  160144. while ((temp >>= 1))
  160145. nbits++;
  160146. /* Check for out-of-range coefficient values */
  160147. if (nbits > MAX_COEF_BITS)
  160148. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160149. /* Count Huffman symbol for run length / number of bits */
  160150. ac_counts[(r << 4) + nbits]++;
  160151. r = 0;
  160152. }
  160153. }
  160154. /* If the last coef(s) were zero, emit an end-of-block code */
  160155. if (r > 0)
  160156. ac_counts[0]++;
  160157. }
  160158. /*
  160159. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  160160. * No data is actually output, so no suspension return is possible.
  160161. */
  160162. METHODDEF(boolean)
  160163. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160164. {
  160165. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160166. int blkn, ci;
  160167. jpeg_component_info * compptr;
  160168. /* Take care of restart intervals if needed */
  160169. if (cinfo->restart_interval) {
  160170. if (entropy->restarts_to_go == 0) {
  160171. /* Re-initialize DC predictions to 0 */
  160172. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  160173. entropy->saved.last_dc_val[ci] = 0;
  160174. /* Update restart state */
  160175. entropy->restarts_to_go = cinfo->restart_interval;
  160176. }
  160177. entropy->restarts_to_go--;
  160178. }
  160179. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160180. ci = cinfo->MCU_membership[blkn];
  160181. compptr = cinfo->cur_comp_info[ci];
  160182. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  160183. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  160184. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  160185. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  160186. }
  160187. return TRUE;
  160188. }
  160189. /*
  160190. * Generate the best Huffman code table for the given counts, fill htbl.
  160191. * Note this is also used by jcphuff.c.
  160192. *
  160193. * The JPEG standard requires that no symbol be assigned a codeword of all
  160194. * one bits (so that padding bits added at the end of a compressed segment
  160195. * can't look like a valid code). Because of the canonical ordering of
  160196. * codewords, this just means that there must be an unused slot in the
  160197. * longest codeword length category. Section K.2 of the JPEG spec suggests
  160198. * reserving such a slot by pretending that symbol 256 is a valid symbol
  160199. * with count 1. In theory that's not optimal; giving it count zero but
  160200. * including it in the symbol set anyway should give a better Huffman code.
  160201. * But the theoretically better code actually seems to come out worse in
  160202. * practice, because it produces more all-ones bytes (which incur stuffed
  160203. * zero bytes in the final file). In any case the difference is tiny.
  160204. *
  160205. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  160206. * If some symbols have a very small but nonzero probability, the Huffman tree
  160207. * must be adjusted to meet the code length restriction. We currently use
  160208. * the adjustment method suggested in JPEG section K.2. This method is *not*
  160209. * optimal; it may not choose the best possible limited-length code. But
  160210. * typically only very-low-frequency symbols will be given less-than-optimal
  160211. * lengths, so the code is almost optimal. Experimental comparisons against
  160212. * an optimal limited-length-code algorithm indicate that the difference is
  160213. * microscopic --- usually less than a hundredth of a percent of total size.
  160214. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  160215. */
  160216. GLOBAL(void)
  160217. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  160218. {
  160219. #define MAX_CLEN 32 /* assumed maximum initial code length */
  160220. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  160221. int codesize[257]; /* codesize[k] = code length of symbol k */
  160222. int others[257]; /* next symbol in current branch of tree */
  160223. int c1, c2;
  160224. int p, i, j;
  160225. long v;
  160226. /* This algorithm is explained in section K.2 of the JPEG standard */
  160227. MEMZERO(bits, SIZEOF(bits));
  160228. MEMZERO(codesize, SIZEOF(codesize));
  160229. for (i = 0; i < 257; i++)
  160230. others[i] = -1; /* init links to empty */
  160231. freq[256] = 1; /* make sure 256 has a nonzero count */
  160232. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  160233. * that no real symbol is given code-value of all ones, because 256
  160234. * will be placed last in the largest codeword category.
  160235. */
  160236. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  160237. for (;;) {
  160238. /* Find the smallest nonzero frequency, set c1 = its symbol */
  160239. /* In case of ties, take the larger symbol number */
  160240. c1 = -1;
  160241. v = 1000000000L;
  160242. for (i = 0; i <= 256; i++) {
  160243. if (freq[i] && freq[i] <= v) {
  160244. v = freq[i];
  160245. c1 = i;
  160246. }
  160247. }
  160248. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  160249. /* In case of ties, take the larger symbol number */
  160250. c2 = -1;
  160251. v = 1000000000L;
  160252. for (i = 0; i <= 256; i++) {
  160253. if (freq[i] && freq[i] <= v && i != c1) {
  160254. v = freq[i];
  160255. c2 = i;
  160256. }
  160257. }
  160258. /* Done if we've merged everything into one frequency */
  160259. if (c2 < 0)
  160260. break;
  160261. /* Else merge the two counts/trees */
  160262. freq[c1] += freq[c2];
  160263. freq[c2] = 0;
  160264. /* Increment the codesize of everything in c1's tree branch */
  160265. codesize[c1]++;
  160266. while (others[c1] >= 0) {
  160267. c1 = others[c1];
  160268. codesize[c1]++;
  160269. }
  160270. others[c1] = c2; /* chain c2 onto c1's tree branch */
  160271. /* Increment the codesize of everything in c2's tree branch */
  160272. codesize[c2]++;
  160273. while (others[c2] >= 0) {
  160274. c2 = others[c2];
  160275. codesize[c2]++;
  160276. }
  160277. }
  160278. /* Now count the number of symbols of each code length */
  160279. for (i = 0; i <= 256; i++) {
  160280. if (codesize[i]) {
  160281. /* The JPEG standard seems to think that this can't happen, */
  160282. /* but I'm paranoid... */
  160283. if (codesize[i] > MAX_CLEN)
  160284. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  160285. bits[codesize[i]]++;
  160286. }
  160287. }
  160288. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  160289. * Huffman procedure assigned any such lengths, we must adjust the coding.
  160290. * Here is what the JPEG spec says about how this next bit works:
  160291. * Since symbols are paired for the longest Huffman code, the symbols are
  160292. * removed from this length category two at a time. The prefix for the pair
  160293. * (which is one bit shorter) is allocated to one of the pair; then,
  160294. * skipping the BITS entry for that prefix length, a code word from the next
  160295. * shortest nonzero BITS entry is converted into a prefix for two code words
  160296. * one bit longer.
  160297. */
  160298. for (i = MAX_CLEN; i > 16; i--) {
  160299. while (bits[i] > 0) {
  160300. j = i - 2; /* find length of new prefix to be used */
  160301. while (bits[j] == 0)
  160302. j--;
  160303. bits[i] -= 2; /* remove two symbols */
  160304. bits[i-1]++; /* one goes in this length */
  160305. bits[j+1] += 2; /* two new symbols in this length */
  160306. bits[j]--; /* symbol of this length is now a prefix */
  160307. }
  160308. }
  160309. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  160310. while (bits[i] == 0) /* find largest codelength still in use */
  160311. i--;
  160312. bits[i]--;
  160313. /* Return final symbol counts (only for lengths 0..16) */
  160314. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  160315. /* Return a list of the symbols sorted by code length */
  160316. /* It's not real clear to me why we don't need to consider the codelength
  160317. * changes made above, but the JPEG spec seems to think this works.
  160318. */
  160319. p = 0;
  160320. for (i = 1; i <= MAX_CLEN; i++) {
  160321. for (j = 0; j <= 255; j++) {
  160322. if (codesize[j] == i) {
  160323. htbl->huffval[p] = (UINT8) j;
  160324. p++;
  160325. }
  160326. }
  160327. }
  160328. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  160329. htbl->sent_table = FALSE;
  160330. }
  160331. /*
  160332. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160333. */
  160334. METHODDEF(void)
  160335. finish_pass_gather (j_compress_ptr cinfo)
  160336. {
  160337. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160338. int ci, dctbl, actbl;
  160339. jpeg_component_info * compptr;
  160340. JHUFF_TBL **htblptr;
  160341. boolean did_dc[NUM_HUFF_TBLS];
  160342. boolean did_ac[NUM_HUFF_TBLS];
  160343. /* It's important not to apply jpeg_gen_optimal_table more than once
  160344. * per table, because it clobbers the input frequency counts!
  160345. */
  160346. MEMZERO(did_dc, SIZEOF(did_dc));
  160347. MEMZERO(did_ac, SIZEOF(did_ac));
  160348. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160349. compptr = cinfo->cur_comp_info[ci];
  160350. dctbl = compptr->dc_tbl_no;
  160351. actbl = compptr->ac_tbl_no;
  160352. if (! did_dc[dctbl]) {
  160353. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  160354. if (*htblptr == NULL)
  160355. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160356. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  160357. did_dc[dctbl] = TRUE;
  160358. }
  160359. if (! did_ac[actbl]) {
  160360. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  160361. if (*htblptr == NULL)
  160362. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160363. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  160364. did_ac[actbl] = TRUE;
  160365. }
  160366. }
  160367. }
  160368. #endif /* ENTROPY_OPT_SUPPORTED */
  160369. /*
  160370. * Module initialization routine for Huffman entropy encoding.
  160371. */
  160372. GLOBAL(void)
  160373. jinit_huff_encoder (j_compress_ptr cinfo)
  160374. {
  160375. huff_entropy_ptr entropy;
  160376. int i;
  160377. entropy = (huff_entropy_ptr)
  160378. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160379. SIZEOF(huff_entropy_encoder));
  160380. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  160381. entropy->pub.start_pass = start_pass_huff;
  160382. /* Mark tables unallocated */
  160383. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160384. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  160385. #ifdef ENTROPY_OPT_SUPPORTED
  160386. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  160387. #endif
  160388. }
  160389. }
  160390. /*** End of inlined file: jchuff.c ***/
  160391. #undef emit_byte
  160392. /*** Start of inlined file: jcinit.c ***/
  160393. #define JPEG_INTERNALS
  160394. /*
  160395. * Master selection of compression modules.
  160396. * This is done once at the start of processing an image. We determine
  160397. * which modules will be used and give them appropriate initialization calls.
  160398. */
  160399. GLOBAL(void)
  160400. jinit_compress_master (j_compress_ptr cinfo)
  160401. {
  160402. /* Initialize master control (includes parameter checking/processing) */
  160403. jinit_c_master_control(cinfo, FALSE /* full compression */);
  160404. /* Preprocessing */
  160405. if (! cinfo->raw_data_in) {
  160406. jinit_color_converter(cinfo);
  160407. jinit_downsampler(cinfo);
  160408. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  160409. }
  160410. /* Forward DCT */
  160411. jinit_forward_dct(cinfo);
  160412. /* Entropy encoding: either Huffman or arithmetic coding. */
  160413. if (cinfo->arith_code) {
  160414. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  160415. } else {
  160416. if (cinfo->progressive_mode) {
  160417. #ifdef C_PROGRESSIVE_SUPPORTED
  160418. jinit_phuff_encoder(cinfo);
  160419. #else
  160420. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160421. #endif
  160422. } else
  160423. jinit_huff_encoder(cinfo);
  160424. }
  160425. /* Need a full-image coefficient buffer in any multi-pass mode. */
  160426. jinit_c_coef_controller(cinfo,
  160427. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  160428. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  160429. jinit_marker_writer(cinfo);
  160430. /* We can now tell the memory manager to allocate virtual arrays. */
  160431. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  160432. /* Write the datastream header (SOI) immediately.
  160433. * Frame and scan headers are postponed till later.
  160434. * This lets application insert special markers after the SOI.
  160435. */
  160436. (*cinfo->marker->write_file_header) (cinfo);
  160437. }
  160438. /*** End of inlined file: jcinit.c ***/
  160439. /*** Start of inlined file: jcmainct.c ***/
  160440. #define JPEG_INTERNALS
  160441. /* Note: currently, there is no operating mode in which a full-image buffer
  160442. * is needed at this step. If there were, that mode could not be used with
  160443. * "raw data" input, since this module is bypassed in that case. However,
  160444. * we've left the code here for possible use in special applications.
  160445. */
  160446. #undef FULL_MAIN_BUFFER_SUPPORTED
  160447. /* Private buffer controller object */
  160448. typedef struct {
  160449. struct jpeg_c_main_controller pub; /* public fields */
  160450. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  160451. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  160452. boolean suspended; /* remember if we suspended output */
  160453. J_BUF_MODE pass_mode; /* current operating mode */
  160454. /* If using just a strip buffer, this points to the entire set of buffers
  160455. * (we allocate one for each component). In the full-image case, this
  160456. * points to the currently accessible strips of the virtual arrays.
  160457. */
  160458. JSAMPARRAY buffer[MAX_COMPONENTS];
  160459. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160460. /* If using full-image storage, this array holds pointers to virtual-array
  160461. * control blocks for each component. Unused if not full-image storage.
  160462. */
  160463. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  160464. #endif
  160465. } my_main_controller;
  160466. typedef my_main_controller * my_main_ptr;
  160467. /* Forward declarations */
  160468. METHODDEF(void) process_data_simple_main
  160469. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  160470. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  160471. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160472. METHODDEF(void) process_data_buffer_main
  160473. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  160474. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  160475. #endif
  160476. /*
  160477. * Initialize for a processing pass.
  160478. */
  160479. METHODDEF(void)
  160480. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160481. {
  160482. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  160483. /* Do nothing in raw-data mode. */
  160484. if (cinfo->raw_data_in)
  160485. return;
  160486. main_->cur_iMCU_row = 0; /* initialize counters */
  160487. main_->rowgroup_ctr = 0;
  160488. main_->suspended = FALSE;
  160489. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  160490. switch (pass_mode) {
  160491. case JBUF_PASS_THRU:
  160492. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160493. if (main_->whole_image[0] != NULL)
  160494. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160495. #endif
  160496. main_->pub.process_data = process_data_simple_main;
  160497. break;
  160498. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160499. case JBUF_SAVE_SOURCE:
  160500. case JBUF_CRANK_DEST:
  160501. case JBUF_SAVE_AND_PASS:
  160502. if (main_->whole_image[0] == NULL)
  160503. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160504. main_->pub.process_data = process_data_buffer_main;
  160505. break;
  160506. #endif
  160507. default:
  160508. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160509. break;
  160510. }
  160511. }
  160512. /*
  160513. * Process some data.
  160514. * This routine handles the simple pass-through mode,
  160515. * where we have only a strip buffer.
  160516. */
  160517. METHODDEF(void)
  160518. process_data_simple_main (j_compress_ptr cinfo,
  160519. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160520. JDIMENSION in_rows_avail)
  160521. {
  160522. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  160523. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  160524. /* Read input data if we haven't filled the main buffer yet */
  160525. if (main_->rowgroup_ctr < DCTSIZE)
  160526. (*cinfo->prep->pre_process_data) (cinfo,
  160527. input_buf, in_row_ctr, in_rows_avail,
  160528. main_->buffer, &main_->rowgroup_ctr,
  160529. (JDIMENSION) DCTSIZE);
  160530. /* If we don't have a full iMCU row buffered, return to application for
  160531. * more data. Note that preprocessor will always pad to fill the iMCU row
  160532. * at the bottom of the image.
  160533. */
  160534. if (main_->rowgroup_ctr != DCTSIZE)
  160535. return;
  160536. /* Send the completed row to the compressor */
  160537. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  160538. /* If compressor did not consume the whole row, then we must need to
  160539. * suspend processing and return to the application. In this situation
  160540. * we pretend we didn't yet consume the last input row; otherwise, if
  160541. * it happened to be the last row of the image, the application would
  160542. * think we were done.
  160543. */
  160544. if (! main_->suspended) {
  160545. (*in_row_ctr)--;
  160546. main_->suspended = TRUE;
  160547. }
  160548. return;
  160549. }
  160550. /* We did finish the row. Undo our little suspension hack if a previous
  160551. * call suspended; then mark the main buffer empty.
  160552. */
  160553. if (main_->suspended) {
  160554. (*in_row_ctr)++;
  160555. main_->suspended = FALSE;
  160556. }
  160557. main_->rowgroup_ctr = 0;
  160558. main_->cur_iMCU_row++;
  160559. }
  160560. }
  160561. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160562. /*
  160563. * Process some data.
  160564. * This routine handles all of the modes that use a full-size buffer.
  160565. */
  160566. METHODDEF(void)
  160567. process_data_buffer_main (j_compress_ptr cinfo,
  160568. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160569. JDIMENSION in_rows_avail)
  160570. {
  160571. my_main_ptr main = (my_main_ptr) cinfo->main;
  160572. int ci;
  160573. jpeg_component_info *compptr;
  160574. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  160575. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  160576. /* Realign the virtual buffers if at the start of an iMCU row. */
  160577. if (main->rowgroup_ctr == 0) {
  160578. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160579. ci++, compptr++) {
  160580. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  160581. ((j_common_ptr) cinfo, main->whole_image[ci],
  160582. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  160583. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  160584. }
  160585. /* In a read pass, pretend we just read some source data. */
  160586. if (! writing) {
  160587. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  160588. main->rowgroup_ctr = DCTSIZE;
  160589. }
  160590. }
  160591. /* If a write pass, read input data until the current iMCU row is full. */
  160592. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  160593. if (writing) {
  160594. (*cinfo->prep->pre_process_data) (cinfo,
  160595. input_buf, in_row_ctr, in_rows_avail,
  160596. main->buffer, &main->rowgroup_ctr,
  160597. (JDIMENSION) DCTSIZE);
  160598. /* Return to application if we need more data to fill the iMCU row. */
  160599. if (main->rowgroup_ctr < DCTSIZE)
  160600. return;
  160601. }
  160602. /* Emit data, unless this is a sink-only pass. */
  160603. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  160604. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  160605. /* If compressor did not consume the whole row, then we must need to
  160606. * suspend processing and return to the application. In this situation
  160607. * we pretend we didn't yet consume the last input row; otherwise, if
  160608. * it happened to be the last row of the image, the application would
  160609. * think we were done.
  160610. */
  160611. if (! main->suspended) {
  160612. (*in_row_ctr)--;
  160613. main->suspended = TRUE;
  160614. }
  160615. return;
  160616. }
  160617. /* We did finish the row. Undo our little suspension hack if a previous
  160618. * call suspended; then mark the main buffer empty.
  160619. */
  160620. if (main->suspended) {
  160621. (*in_row_ctr)++;
  160622. main->suspended = FALSE;
  160623. }
  160624. }
  160625. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  160626. main->rowgroup_ctr = 0;
  160627. main->cur_iMCU_row++;
  160628. }
  160629. }
  160630. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  160631. /*
  160632. * Initialize main buffer controller.
  160633. */
  160634. GLOBAL(void)
  160635. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160636. {
  160637. my_main_ptr main_;
  160638. int ci;
  160639. jpeg_component_info *compptr;
  160640. main_ = (my_main_ptr)
  160641. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160642. SIZEOF(my_main_controller));
  160643. cinfo->main = (struct jpeg_c_main_controller *) main_;
  160644. main_->pub.start_pass = start_pass_main;
  160645. /* We don't need to create a buffer in raw-data mode. */
  160646. if (cinfo->raw_data_in)
  160647. return;
  160648. /* Create the buffer. It holds downsampled data, so each component
  160649. * may be of a different size.
  160650. */
  160651. if (need_full_buffer) {
  160652. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160653. /* Allocate a full-image virtual array for each component */
  160654. /* Note we pad the bottom to a multiple of the iMCU height */
  160655. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160656. ci++, compptr++) {
  160657. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  160658. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  160659. compptr->width_in_blocks * DCTSIZE,
  160660. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  160661. (long) compptr->v_samp_factor) * DCTSIZE,
  160662. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  160663. }
  160664. #else
  160665. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160666. #endif
  160667. } else {
  160668. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160669. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  160670. #endif
  160671. /* Allocate a strip buffer for each component */
  160672. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160673. ci++, compptr++) {
  160674. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  160675. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160676. compptr->width_in_blocks * DCTSIZE,
  160677. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  160678. }
  160679. }
  160680. }
  160681. /*** End of inlined file: jcmainct.c ***/
  160682. /*** Start of inlined file: jcmarker.c ***/
  160683. #define JPEG_INTERNALS
  160684. /* Private state */
  160685. typedef struct {
  160686. struct jpeg_marker_writer pub; /* public fields */
  160687. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  160688. } my_marker_writer;
  160689. typedef my_marker_writer * my_marker_ptr;
  160690. /*
  160691. * Basic output routines.
  160692. *
  160693. * Note that we do not support suspension while writing a marker.
  160694. * Therefore, an application using suspension must ensure that there is
  160695. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  160696. * calling jpeg_start_compress, and enough space to write the trailing EOI
  160697. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  160698. * modes are not supported at all with suspension, so those two are the only
  160699. * points where markers will be written.
  160700. */
  160701. LOCAL(void)
  160702. emit_byte (j_compress_ptr cinfo, int val)
  160703. /* Emit a byte */
  160704. {
  160705. struct jpeg_destination_mgr * dest = cinfo->dest;
  160706. *(dest->next_output_byte)++ = (JOCTET) val;
  160707. if (--dest->free_in_buffer == 0) {
  160708. if (! (*dest->empty_output_buffer) (cinfo))
  160709. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160710. }
  160711. }
  160712. LOCAL(void)
  160713. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  160714. /* Emit a marker code */
  160715. {
  160716. emit_byte(cinfo, 0xFF);
  160717. emit_byte(cinfo, (int) mark);
  160718. }
  160719. LOCAL(void)
  160720. emit_2bytes (j_compress_ptr cinfo, int value)
  160721. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  160722. {
  160723. emit_byte(cinfo, (value >> 8) & 0xFF);
  160724. emit_byte(cinfo, value & 0xFF);
  160725. }
  160726. /*
  160727. * Routines to write specific marker types.
  160728. */
  160729. LOCAL(int)
  160730. emit_dqt (j_compress_ptr cinfo, int index)
  160731. /* Emit a DQT marker */
  160732. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  160733. {
  160734. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  160735. int prec;
  160736. int i;
  160737. if (qtbl == NULL)
  160738. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  160739. prec = 0;
  160740. for (i = 0; i < DCTSIZE2; i++) {
  160741. if (qtbl->quantval[i] > 255)
  160742. prec = 1;
  160743. }
  160744. if (! qtbl->sent_table) {
  160745. emit_marker(cinfo, M_DQT);
  160746. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  160747. emit_byte(cinfo, index + (prec<<4));
  160748. for (i = 0; i < DCTSIZE2; i++) {
  160749. /* The table entries must be emitted in zigzag order. */
  160750. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  160751. if (prec)
  160752. emit_byte(cinfo, (int) (qval >> 8));
  160753. emit_byte(cinfo, (int) (qval & 0xFF));
  160754. }
  160755. qtbl->sent_table = TRUE;
  160756. }
  160757. return prec;
  160758. }
  160759. LOCAL(void)
  160760. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  160761. /* Emit a DHT marker */
  160762. {
  160763. JHUFF_TBL * htbl;
  160764. int length, i;
  160765. if (is_ac) {
  160766. htbl = cinfo->ac_huff_tbl_ptrs[index];
  160767. index += 0x10; /* output index has AC bit set */
  160768. } else {
  160769. htbl = cinfo->dc_huff_tbl_ptrs[index];
  160770. }
  160771. if (htbl == NULL)
  160772. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  160773. if (! htbl->sent_table) {
  160774. emit_marker(cinfo, M_DHT);
  160775. length = 0;
  160776. for (i = 1; i <= 16; i++)
  160777. length += htbl->bits[i];
  160778. emit_2bytes(cinfo, length + 2 + 1 + 16);
  160779. emit_byte(cinfo, index);
  160780. for (i = 1; i <= 16; i++)
  160781. emit_byte(cinfo, htbl->bits[i]);
  160782. for (i = 0; i < length; i++)
  160783. emit_byte(cinfo, htbl->huffval[i]);
  160784. htbl->sent_table = TRUE;
  160785. }
  160786. }
  160787. LOCAL(void)
  160788. emit_dac (j_compress_ptr)
  160789. /* Emit a DAC marker */
  160790. /* Since the useful info is so small, we want to emit all the tables in */
  160791. /* one DAC marker. Therefore this routine does its own scan of the table. */
  160792. {
  160793. #ifdef C_ARITH_CODING_SUPPORTED
  160794. char dc_in_use[NUM_ARITH_TBLS];
  160795. char ac_in_use[NUM_ARITH_TBLS];
  160796. int length, i;
  160797. jpeg_component_info *compptr;
  160798. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160799. dc_in_use[i] = ac_in_use[i] = 0;
  160800. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160801. compptr = cinfo->cur_comp_info[i];
  160802. dc_in_use[compptr->dc_tbl_no] = 1;
  160803. ac_in_use[compptr->ac_tbl_no] = 1;
  160804. }
  160805. length = 0;
  160806. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160807. length += dc_in_use[i] + ac_in_use[i];
  160808. emit_marker(cinfo, M_DAC);
  160809. emit_2bytes(cinfo, length*2 + 2);
  160810. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  160811. if (dc_in_use[i]) {
  160812. emit_byte(cinfo, i);
  160813. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  160814. }
  160815. if (ac_in_use[i]) {
  160816. emit_byte(cinfo, i + 0x10);
  160817. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  160818. }
  160819. }
  160820. #endif /* C_ARITH_CODING_SUPPORTED */
  160821. }
  160822. LOCAL(void)
  160823. emit_dri (j_compress_ptr cinfo)
  160824. /* Emit a DRI marker */
  160825. {
  160826. emit_marker(cinfo, M_DRI);
  160827. emit_2bytes(cinfo, 4); /* fixed length */
  160828. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  160829. }
  160830. LOCAL(void)
  160831. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  160832. /* Emit a SOF marker */
  160833. {
  160834. int ci;
  160835. jpeg_component_info *compptr;
  160836. emit_marker(cinfo, code);
  160837. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  160838. /* Make sure image isn't bigger than SOF field can handle */
  160839. if ((long) cinfo->image_height > 65535L ||
  160840. (long) cinfo->image_width > 65535L)
  160841. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  160842. emit_byte(cinfo, cinfo->data_precision);
  160843. emit_2bytes(cinfo, (int) cinfo->image_height);
  160844. emit_2bytes(cinfo, (int) cinfo->image_width);
  160845. emit_byte(cinfo, cinfo->num_components);
  160846. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160847. ci++, compptr++) {
  160848. emit_byte(cinfo, compptr->component_id);
  160849. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  160850. emit_byte(cinfo, compptr->quant_tbl_no);
  160851. }
  160852. }
  160853. LOCAL(void)
  160854. emit_sos (j_compress_ptr cinfo)
  160855. /* Emit a SOS marker */
  160856. {
  160857. int i, td, ta;
  160858. jpeg_component_info *compptr;
  160859. emit_marker(cinfo, M_SOS);
  160860. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  160861. emit_byte(cinfo, cinfo->comps_in_scan);
  160862. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160863. compptr = cinfo->cur_comp_info[i];
  160864. emit_byte(cinfo, compptr->component_id);
  160865. td = compptr->dc_tbl_no;
  160866. ta = compptr->ac_tbl_no;
  160867. if (cinfo->progressive_mode) {
  160868. /* Progressive mode: only DC or only AC tables are used in one scan;
  160869. * furthermore, Huffman coding of DC refinement uses no table at all.
  160870. * We emit 0 for unused field(s); this is recommended by the P&M text
  160871. * but does not seem to be specified in the standard.
  160872. */
  160873. if (cinfo->Ss == 0) {
  160874. ta = 0; /* DC scan */
  160875. if (cinfo->Ah != 0 && !cinfo->arith_code)
  160876. td = 0; /* no DC table either */
  160877. } else {
  160878. td = 0; /* AC scan */
  160879. }
  160880. }
  160881. emit_byte(cinfo, (td << 4) + ta);
  160882. }
  160883. emit_byte(cinfo, cinfo->Ss);
  160884. emit_byte(cinfo, cinfo->Se);
  160885. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  160886. }
  160887. LOCAL(void)
  160888. emit_jfif_app0 (j_compress_ptr cinfo)
  160889. /* Emit a JFIF-compliant APP0 marker */
  160890. {
  160891. /*
  160892. * Length of APP0 block (2 bytes)
  160893. * Block ID (4 bytes - ASCII "JFIF")
  160894. * Zero byte (1 byte to terminate the ID string)
  160895. * Version Major, Minor (2 bytes - major first)
  160896. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  160897. * Xdpu (2 bytes - dots per unit horizontal)
  160898. * Ydpu (2 bytes - dots per unit vertical)
  160899. * Thumbnail X size (1 byte)
  160900. * Thumbnail Y size (1 byte)
  160901. */
  160902. emit_marker(cinfo, M_APP0);
  160903. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  160904. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  160905. emit_byte(cinfo, 0x46);
  160906. emit_byte(cinfo, 0x49);
  160907. emit_byte(cinfo, 0x46);
  160908. emit_byte(cinfo, 0);
  160909. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  160910. emit_byte(cinfo, cinfo->JFIF_minor_version);
  160911. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  160912. emit_2bytes(cinfo, (int) cinfo->X_density);
  160913. emit_2bytes(cinfo, (int) cinfo->Y_density);
  160914. emit_byte(cinfo, 0); /* No thumbnail image */
  160915. emit_byte(cinfo, 0);
  160916. }
  160917. LOCAL(void)
  160918. emit_adobe_app14 (j_compress_ptr cinfo)
  160919. /* Emit an Adobe APP14 marker */
  160920. {
  160921. /*
  160922. * Length of APP14 block (2 bytes)
  160923. * Block ID (5 bytes - ASCII "Adobe")
  160924. * Version Number (2 bytes - currently 100)
  160925. * Flags0 (2 bytes - currently 0)
  160926. * Flags1 (2 bytes - currently 0)
  160927. * Color transform (1 byte)
  160928. *
  160929. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  160930. * now in circulation seem to use Version = 100, so that's what we write.
  160931. *
  160932. * We write the color transform byte as 1 if the JPEG color space is
  160933. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  160934. * whether the encoder performed a transformation, which is pretty useless.
  160935. */
  160936. emit_marker(cinfo, M_APP14);
  160937. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  160938. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  160939. emit_byte(cinfo, 0x64);
  160940. emit_byte(cinfo, 0x6F);
  160941. emit_byte(cinfo, 0x62);
  160942. emit_byte(cinfo, 0x65);
  160943. emit_2bytes(cinfo, 100); /* Version */
  160944. emit_2bytes(cinfo, 0); /* Flags0 */
  160945. emit_2bytes(cinfo, 0); /* Flags1 */
  160946. switch (cinfo->jpeg_color_space) {
  160947. case JCS_YCbCr:
  160948. emit_byte(cinfo, 1); /* Color transform = 1 */
  160949. break;
  160950. case JCS_YCCK:
  160951. emit_byte(cinfo, 2); /* Color transform = 2 */
  160952. break;
  160953. default:
  160954. emit_byte(cinfo, 0); /* Color transform = 0 */
  160955. break;
  160956. }
  160957. }
  160958. /*
  160959. * These routines allow writing an arbitrary marker with parameters.
  160960. * The only intended use is to emit COM or APPn markers after calling
  160961. * write_file_header and before calling write_frame_header.
  160962. * Other uses are not guaranteed to produce desirable results.
  160963. * Counting the parameter bytes properly is the caller's responsibility.
  160964. */
  160965. METHODDEF(void)
  160966. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160967. /* Emit an arbitrary marker header */
  160968. {
  160969. if (datalen > (unsigned int) 65533) /* safety check */
  160970. ERREXIT(cinfo, JERR_BAD_LENGTH);
  160971. emit_marker(cinfo, (JPEG_MARKER) marker);
  160972. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  160973. }
  160974. METHODDEF(void)
  160975. write_marker_byte (j_compress_ptr cinfo, int val)
  160976. /* Emit one byte of marker parameters following write_marker_header */
  160977. {
  160978. emit_byte(cinfo, val);
  160979. }
  160980. /*
  160981. * Write datastream header.
  160982. * This consists of an SOI and optional APPn markers.
  160983. * We recommend use of the JFIF marker, but not the Adobe marker,
  160984. * when using YCbCr or grayscale data. The JFIF marker should NOT
  160985. * be used for any other JPEG colorspace. The Adobe marker is helpful
  160986. * to distinguish RGB, CMYK, and YCCK colorspaces.
  160987. * Note that an application can write additional header markers after
  160988. * jpeg_start_compress returns.
  160989. */
  160990. METHODDEF(void)
  160991. write_file_header (j_compress_ptr cinfo)
  160992. {
  160993. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160994. emit_marker(cinfo, M_SOI); /* first the SOI */
  160995. /* SOI is defined to reset restart interval to 0 */
  160996. marker->last_restart_interval = 0;
  160997. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  160998. emit_jfif_app0(cinfo);
  160999. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  161000. emit_adobe_app14(cinfo);
  161001. }
  161002. /*
  161003. * Write frame header.
  161004. * This consists of DQT and SOFn markers.
  161005. * Note that we do not emit the SOF until we have emitted the DQT(s).
  161006. * This avoids compatibility problems with incorrect implementations that
  161007. * try to error-check the quant table numbers as soon as they see the SOF.
  161008. */
  161009. METHODDEF(void)
  161010. write_frame_header (j_compress_ptr cinfo)
  161011. {
  161012. int ci, prec;
  161013. boolean is_baseline;
  161014. jpeg_component_info *compptr;
  161015. /* Emit DQT for each quantization table.
  161016. * Note that emit_dqt() suppresses any duplicate tables.
  161017. */
  161018. prec = 0;
  161019. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161020. ci++, compptr++) {
  161021. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  161022. }
  161023. /* now prec is nonzero iff there are any 16-bit quant tables. */
  161024. /* Check for a non-baseline specification.
  161025. * Note we assume that Huffman table numbers won't be changed later.
  161026. */
  161027. if (cinfo->arith_code || cinfo->progressive_mode ||
  161028. cinfo->data_precision != 8) {
  161029. is_baseline = FALSE;
  161030. } else {
  161031. is_baseline = TRUE;
  161032. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161033. ci++, compptr++) {
  161034. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  161035. is_baseline = FALSE;
  161036. }
  161037. if (prec && is_baseline) {
  161038. is_baseline = FALSE;
  161039. /* If it's baseline except for quantizer size, warn the user */
  161040. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  161041. }
  161042. }
  161043. /* Emit the proper SOF marker */
  161044. if (cinfo->arith_code) {
  161045. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  161046. } else {
  161047. if (cinfo->progressive_mode)
  161048. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  161049. else if (is_baseline)
  161050. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  161051. else
  161052. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  161053. }
  161054. }
  161055. /*
  161056. * Write scan header.
  161057. * This consists of DHT or DAC markers, optional DRI, and SOS.
  161058. * Compressed data will be written following the SOS.
  161059. */
  161060. METHODDEF(void)
  161061. write_scan_header (j_compress_ptr cinfo)
  161062. {
  161063. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  161064. int i;
  161065. jpeg_component_info *compptr;
  161066. if (cinfo->arith_code) {
  161067. /* Emit arith conditioning info. We may have some duplication
  161068. * if the file has multiple scans, but it's so small it's hardly
  161069. * worth worrying about.
  161070. */
  161071. emit_dac(cinfo);
  161072. } else {
  161073. /* Emit Huffman tables.
  161074. * Note that emit_dht() suppresses any duplicate tables.
  161075. */
  161076. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161077. compptr = cinfo->cur_comp_info[i];
  161078. if (cinfo->progressive_mode) {
  161079. /* Progressive mode: only DC or only AC tables are used in one scan */
  161080. if (cinfo->Ss == 0) {
  161081. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  161082. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161083. } else {
  161084. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161085. }
  161086. } else {
  161087. /* Sequential mode: need both DC and AC tables */
  161088. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161089. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161090. }
  161091. }
  161092. }
  161093. /* Emit DRI if required --- note that DRI value could change for each scan.
  161094. * We avoid wasting space with unnecessary DRIs, however.
  161095. */
  161096. if (cinfo->restart_interval != marker->last_restart_interval) {
  161097. emit_dri(cinfo);
  161098. marker->last_restart_interval = cinfo->restart_interval;
  161099. }
  161100. emit_sos(cinfo);
  161101. }
  161102. /*
  161103. * Write datastream trailer.
  161104. */
  161105. METHODDEF(void)
  161106. write_file_trailer (j_compress_ptr cinfo)
  161107. {
  161108. emit_marker(cinfo, M_EOI);
  161109. }
  161110. /*
  161111. * Write an abbreviated table-specification datastream.
  161112. * This consists of SOI, DQT and DHT tables, and EOI.
  161113. * Any table that is defined and not marked sent_table = TRUE will be
  161114. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  161115. */
  161116. METHODDEF(void)
  161117. write_tables_only (j_compress_ptr cinfo)
  161118. {
  161119. int i;
  161120. emit_marker(cinfo, M_SOI);
  161121. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161122. if (cinfo->quant_tbl_ptrs[i] != NULL)
  161123. (void) emit_dqt(cinfo, i);
  161124. }
  161125. if (! cinfo->arith_code) {
  161126. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161127. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  161128. emit_dht(cinfo, i, FALSE);
  161129. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  161130. emit_dht(cinfo, i, TRUE);
  161131. }
  161132. }
  161133. emit_marker(cinfo, M_EOI);
  161134. }
  161135. /*
  161136. * Initialize the marker writer module.
  161137. */
  161138. GLOBAL(void)
  161139. jinit_marker_writer (j_compress_ptr cinfo)
  161140. {
  161141. my_marker_ptr marker;
  161142. /* Create the subobject */
  161143. marker = (my_marker_ptr)
  161144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161145. SIZEOF(my_marker_writer));
  161146. cinfo->marker = (struct jpeg_marker_writer *) marker;
  161147. /* Initialize method pointers */
  161148. marker->pub.write_file_header = write_file_header;
  161149. marker->pub.write_frame_header = write_frame_header;
  161150. marker->pub.write_scan_header = write_scan_header;
  161151. marker->pub.write_file_trailer = write_file_trailer;
  161152. marker->pub.write_tables_only = write_tables_only;
  161153. marker->pub.write_marker_header = write_marker_header;
  161154. marker->pub.write_marker_byte = write_marker_byte;
  161155. /* Initialize private state */
  161156. marker->last_restart_interval = 0;
  161157. }
  161158. /*** End of inlined file: jcmarker.c ***/
  161159. /*** Start of inlined file: jcmaster.c ***/
  161160. #define JPEG_INTERNALS
  161161. /* Private state */
  161162. typedef enum {
  161163. main_pass, /* input data, also do first output step */
  161164. huff_opt_pass, /* Huffman code optimization pass */
  161165. output_pass /* data output pass */
  161166. } c_pass_type;
  161167. typedef struct {
  161168. struct jpeg_comp_master pub; /* public fields */
  161169. c_pass_type pass_type; /* the type of the current pass */
  161170. int pass_number; /* # of passes completed */
  161171. int total_passes; /* total # of passes needed */
  161172. int scan_number; /* current index in scan_info[] */
  161173. } my_comp_master;
  161174. typedef my_comp_master * my_master_ptr;
  161175. /*
  161176. * Support routines that do various essential calculations.
  161177. */
  161178. LOCAL(void)
  161179. initial_setup (j_compress_ptr cinfo)
  161180. /* Do computations that are needed before master selection phase */
  161181. {
  161182. int ci;
  161183. jpeg_component_info *compptr;
  161184. long samplesperrow;
  161185. JDIMENSION jd_samplesperrow;
  161186. /* Sanity check on image dimensions */
  161187. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  161188. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  161189. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  161190. /* Make sure image isn't bigger than I can handle */
  161191. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  161192. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  161193. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  161194. /* Width of an input scanline must be representable as JDIMENSION. */
  161195. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  161196. jd_samplesperrow = (JDIMENSION) samplesperrow;
  161197. if ((long) jd_samplesperrow != samplesperrow)
  161198. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  161199. /* For now, precision must match compiled-in value... */
  161200. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  161201. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  161202. /* Check that number of components won't exceed internal array sizes */
  161203. if (cinfo->num_components > MAX_COMPONENTS)
  161204. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161205. MAX_COMPONENTS);
  161206. /* Compute maximum sampling factors; check factor validity */
  161207. cinfo->max_h_samp_factor = 1;
  161208. cinfo->max_v_samp_factor = 1;
  161209. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161210. ci++, compptr++) {
  161211. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  161212. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  161213. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  161214. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  161215. compptr->h_samp_factor);
  161216. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  161217. compptr->v_samp_factor);
  161218. }
  161219. /* Compute dimensions of components */
  161220. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161221. ci++, compptr++) {
  161222. /* Fill in the correct component_index value; don't rely on application */
  161223. compptr->component_index = ci;
  161224. /* For compression, we never do DCT scaling. */
  161225. compptr->DCT_scaled_size = DCTSIZE;
  161226. /* Size in DCT blocks */
  161227. compptr->width_in_blocks = (JDIMENSION)
  161228. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161229. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  161230. compptr->height_in_blocks = (JDIMENSION)
  161231. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161232. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  161233. /* Size in samples */
  161234. compptr->downsampled_width = (JDIMENSION)
  161235. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161236. (long) cinfo->max_h_samp_factor);
  161237. compptr->downsampled_height = (JDIMENSION)
  161238. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161239. (long) cinfo->max_v_samp_factor);
  161240. /* Mark component needed (this flag isn't actually used for compression) */
  161241. compptr->component_needed = TRUE;
  161242. }
  161243. /* Compute number of fully interleaved MCU rows (number of times that
  161244. * main controller will call coefficient controller).
  161245. */
  161246. cinfo->total_iMCU_rows = (JDIMENSION)
  161247. jdiv_round_up((long) cinfo->image_height,
  161248. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161249. }
  161250. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161251. LOCAL(void)
  161252. validate_script (j_compress_ptr cinfo)
  161253. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  161254. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  161255. */
  161256. {
  161257. const jpeg_scan_info * scanptr;
  161258. int scanno, ncomps, ci, coefi, thisi;
  161259. int Ss, Se, Ah, Al;
  161260. boolean component_sent[MAX_COMPONENTS];
  161261. #ifdef C_PROGRESSIVE_SUPPORTED
  161262. int * last_bitpos_ptr;
  161263. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  161264. /* -1 until that coefficient has been seen; then last Al for it */
  161265. #endif
  161266. if (cinfo->num_scans <= 0)
  161267. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  161268. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  161269. * for progressive JPEG, no scan can have this.
  161270. */
  161271. scanptr = cinfo->scan_info;
  161272. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  161273. #ifdef C_PROGRESSIVE_SUPPORTED
  161274. cinfo->progressive_mode = TRUE;
  161275. last_bitpos_ptr = & last_bitpos[0][0];
  161276. for (ci = 0; ci < cinfo->num_components; ci++)
  161277. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  161278. *last_bitpos_ptr++ = -1;
  161279. #else
  161280. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161281. #endif
  161282. } else {
  161283. cinfo->progressive_mode = FALSE;
  161284. for (ci = 0; ci < cinfo->num_components; ci++)
  161285. component_sent[ci] = FALSE;
  161286. }
  161287. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  161288. /* Validate component indexes */
  161289. ncomps = scanptr->comps_in_scan;
  161290. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  161291. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  161292. for (ci = 0; ci < ncomps; ci++) {
  161293. thisi = scanptr->component_index[ci];
  161294. if (thisi < 0 || thisi >= cinfo->num_components)
  161295. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161296. /* Components must appear in SOF order within each scan */
  161297. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  161298. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161299. }
  161300. /* Validate progression parameters */
  161301. Ss = scanptr->Ss;
  161302. Se = scanptr->Se;
  161303. Ah = scanptr->Ah;
  161304. Al = scanptr->Al;
  161305. if (cinfo->progressive_mode) {
  161306. #ifdef C_PROGRESSIVE_SUPPORTED
  161307. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  161308. * seems wrong: the upper bound ought to depend on data precision.
  161309. * Perhaps they really meant 0..N+1 for N-bit precision.
  161310. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  161311. * out-of-range reconstructed DC values during the first DC scan,
  161312. * which might cause problems for some decoders.
  161313. */
  161314. #if BITS_IN_JSAMPLE == 8
  161315. #define MAX_AH_AL 10
  161316. #else
  161317. #define MAX_AH_AL 13
  161318. #endif
  161319. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  161320. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  161321. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161322. if (Ss == 0) {
  161323. if (Se != 0) /* DC and AC together not OK */
  161324. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161325. } else {
  161326. if (ncomps != 1) /* AC scans must be for only one component */
  161327. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161328. }
  161329. for (ci = 0; ci < ncomps; ci++) {
  161330. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  161331. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  161332. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161333. for (coefi = Ss; coefi <= Se; coefi++) {
  161334. if (last_bitpos_ptr[coefi] < 0) {
  161335. /* first scan of this coefficient */
  161336. if (Ah != 0)
  161337. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161338. } else {
  161339. /* not first scan */
  161340. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  161341. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161342. }
  161343. last_bitpos_ptr[coefi] = Al;
  161344. }
  161345. }
  161346. #endif
  161347. } else {
  161348. /* For sequential JPEG, all progression parameters must be these: */
  161349. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  161350. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161351. /* Make sure components are not sent twice */
  161352. for (ci = 0; ci < ncomps; ci++) {
  161353. thisi = scanptr->component_index[ci];
  161354. if (component_sent[thisi])
  161355. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161356. component_sent[thisi] = TRUE;
  161357. }
  161358. }
  161359. }
  161360. /* Now verify that everything got sent. */
  161361. if (cinfo->progressive_mode) {
  161362. #ifdef C_PROGRESSIVE_SUPPORTED
  161363. /* For progressive mode, we only check that at least some DC data
  161364. * got sent for each component; the spec does not require that all bits
  161365. * of all coefficients be transmitted. Would it be wiser to enforce
  161366. * transmission of all coefficient bits??
  161367. */
  161368. for (ci = 0; ci < cinfo->num_components; ci++) {
  161369. if (last_bitpos[ci][0] < 0)
  161370. ERREXIT(cinfo, JERR_MISSING_DATA);
  161371. }
  161372. #endif
  161373. } else {
  161374. for (ci = 0; ci < cinfo->num_components; ci++) {
  161375. if (! component_sent[ci])
  161376. ERREXIT(cinfo, JERR_MISSING_DATA);
  161377. }
  161378. }
  161379. }
  161380. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  161381. LOCAL(void)
  161382. select_scan_parameters (j_compress_ptr cinfo)
  161383. /* Set up the scan parameters for the current scan */
  161384. {
  161385. int ci;
  161386. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161387. if (cinfo->scan_info != NULL) {
  161388. /* Prepare for current scan --- the script is already validated */
  161389. my_master_ptr master = (my_master_ptr) cinfo->master;
  161390. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  161391. cinfo->comps_in_scan = scanptr->comps_in_scan;
  161392. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  161393. cinfo->cur_comp_info[ci] =
  161394. &cinfo->comp_info[scanptr->component_index[ci]];
  161395. }
  161396. cinfo->Ss = scanptr->Ss;
  161397. cinfo->Se = scanptr->Se;
  161398. cinfo->Ah = scanptr->Ah;
  161399. cinfo->Al = scanptr->Al;
  161400. }
  161401. else
  161402. #endif
  161403. {
  161404. /* Prepare for single sequential-JPEG scan containing all components */
  161405. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  161406. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161407. MAX_COMPS_IN_SCAN);
  161408. cinfo->comps_in_scan = cinfo->num_components;
  161409. for (ci = 0; ci < cinfo->num_components; ci++) {
  161410. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  161411. }
  161412. cinfo->Ss = 0;
  161413. cinfo->Se = DCTSIZE2-1;
  161414. cinfo->Ah = 0;
  161415. cinfo->Al = 0;
  161416. }
  161417. }
  161418. LOCAL(void)
  161419. per_scan_setup (j_compress_ptr cinfo)
  161420. /* Do computations that are needed before processing a JPEG scan */
  161421. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  161422. {
  161423. int ci, mcublks, tmp;
  161424. jpeg_component_info *compptr;
  161425. if (cinfo->comps_in_scan == 1) {
  161426. /* Noninterleaved (single-component) scan */
  161427. compptr = cinfo->cur_comp_info[0];
  161428. /* Overall image size in MCUs */
  161429. cinfo->MCUs_per_row = compptr->width_in_blocks;
  161430. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  161431. /* For noninterleaved scan, always one block per MCU */
  161432. compptr->MCU_width = 1;
  161433. compptr->MCU_height = 1;
  161434. compptr->MCU_blocks = 1;
  161435. compptr->MCU_sample_width = DCTSIZE;
  161436. compptr->last_col_width = 1;
  161437. /* For noninterleaved scans, it is convenient to define last_row_height
  161438. * as the number of block rows present in the last iMCU row.
  161439. */
  161440. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161441. if (tmp == 0) tmp = compptr->v_samp_factor;
  161442. compptr->last_row_height = tmp;
  161443. /* Prepare array describing MCU composition */
  161444. cinfo->blocks_in_MCU = 1;
  161445. cinfo->MCU_membership[0] = 0;
  161446. } else {
  161447. /* Interleaved (multi-component) scan */
  161448. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  161449. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  161450. MAX_COMPS_IN_SCAN);
  161451. /* Overall image size in MCUs */
  161452. cinfo->MCUs_per_row = (JDIMENSION)
  161453. jdiv_round_up((long) cinfo->image_width,
  161454. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  161455. cinfo->MCU_rows_in_scan = (JDIMENSION)
  161456. jdiv_round_up((long) cinfo->image_height,
  161457. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161458. cinfo->blocks_in_MCU = 0;
  161459. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161460. compptr = cinfo->cur_comp_info[ci];
  161461. /* Sampling factors give # of blocks of component in each MCU */
  161462. compptr->MCU_width = compptr->h_samp_factor;
  161463. compptr->MCU_height = compptr->v_samp_factor;
  161464. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  161465. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  161466. /* Figure number of non-dummy blocks in last MCU column & row */
  161467. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  161468. if (tmp == 0) tmp = compptr->MCU_width;
  161469. compptr->last_col_width = tmp;
  161470. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  161471. if (tmp == 0) tmp = compptr->MCU_height;
  161472. compptr->last_row_height = tmp;
  161473. /* Prepare array describing MCU composition */
  161474. mcublks = compptr->MCU_blocks;
  161475. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  161476. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  161477. while (mcublks-- > 0) {
  161478. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  161479. }
  161480. }
  161481. }
  161482. /* Convert restart specified in rows to actual MCU count. */
  161483. /* Note that count must fit in 16 bits, so we provide limiting. */
  161484. if (cinfo->restart_in_rows > 0) {
  161485. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  161486. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  161487. }
  161488. }
  161489. /*
  161490. * Per-pass setup.
  161491. * This is called at the beginning of each pass. We determine which modules
  161492. * will be active during this pass and give them appropriate start_pass calls.
  161493. * We also set is_last_pass to indicate whether any more passes will be
  161494. * required.
  161495. */
  161496. METHODDEF(void)
  161497. prepare_for_pass (j_compress_ptr cinfo)
  161498. {
  161499. my_master_ptr master = (my_master_ptr) cinfo->master;
  161500. switch (master->pass_type) {
  161501. case main_pass:
  161502. /* Initial pass: will collect input data, and do either Huffman
  161503. * optimization or data output for the first scan.
  161504. */
  161505. select_scan_parameters(cinfo);
  161506. per_scan_setup(cinfo);
  161507. if (! cinfo->raw_data_in) {
  161508. (*cinfo->cconvert->start_pass) (cinfo);
  161509. (*cinfo->downsample->start_pass) (cinfo);
  161510. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  161511. }
  161512. (*cinfo->fdct->start_pass) (cinfo);
  161513. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  161514. (*cinfo->coef->start_pass) (cinfo,
  161515. (master->total_passes > 1 ?
  161516. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  161517. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  161518. if (cinfo->optimize_coding) {
  161519. /* No immediate data output; postpone writing frame/scan headers */
  161520. master->pub.call_pass_startup = FALSE;
  161521. } else {
  161522. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  161523. master->pub.call_pass_startup = TRUE;
  161524. }
  161525. break;
  161526. #ifdef ENTROPY_OPT_SUPPORTED
  161527. case huff_opt_pass:
  161528. /* Do Huffman optimization for a scan after the first one. */
  161529. select_scan_parameters(cinfo);
  161530. per_scan_setup(cinfo);
  161531. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  161532. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  161533. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  161534. master->pub.call_pass_startup = FALSE;
  161535. break;
  161536. }
  161537. /* Special case: Huffman DC refinement scans need no Huffman table
  161538. * and therefore we can skip the optimization pass for them.
  161539. */
  161540. master->pass_type = output_pass;
  161541. master->pass_number++;
  161542. /*FALLTHROUGH*/
  161543. #endif
  161544. case output_pass:
  161545. /* Do a data-output pass. */
  161546. /* We need not repeat per-scan setup if prior optimization pass did it. */
  161547. if (! cinfo->optimize_coding) {
  161548. select_scan_parameters(cinfo);
  161549. per_scan_setup(cinfo);
  161550. }
  161551. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  161552. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  161553. /* We emit frame/scan headers now */
  161554. if (master->scan_number == 0)
  161555. (*cinfo->marker->write_frame_header) (cinfo);
  161556. (*cinfo->marker->write_scan_header) (cinfo);
  161557. master->pub.call_pass_startup = FALSE;
  161558. break;
  161559. default:
  161560. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161561. }
  161562. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  161563. /* Set up progress monitor's pass info if present */
  161564. if (cinfo->progress != NULL) {
  161565. cinfo->progress->completed_passes = master->pass_number;
  161566. cinfo->progress->total_passes = master->total_passes;
  161567. }
  161568. }
  161569. /*
  161570. * Special start-of-pass hook.
  161571. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  161572. * In single-pass processing, we need this hook because we don't want to
  161573. * write frame/scan headers during jpeg_start_compress; we want to let the
  161574. * application write COM markers etc. between jpeg_start_compress and the
  161575. * jpeg_write_scanlines loop.
  161576. * In multi-pass processing, this routine is not used.
  161577. */
  161578. METHODDEF(void)
  161579. pass_startup (j_compress_ptr cinfo)
  161580. {
  161581. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  161582. (*cinfo->marker->write_frame_header) (cinfo);
  161583. (*cinfo->marker->write_scan_header) (cinfo);
  161584. }
  161585. /*
  161586. * Finish up at end of pass.
  161587. */
  161588. METHODDEF(void)
  161589. finish_pass_master (j_compress_ptr cinfo)
  161590. {
  161591. my_master_ptr master = (my_master_ptr) cinfo->master;
  161592. /* The entropy coder always needs an end-of-pass call,
  161593. * either to analyze statistics or to flush its output buffer.
  161594. */
  161595. (*cinfo->entropy->finish_pass) (cinfo);
  161596. /* Update state for next pass */
  161597. switch (master->pass_type) {
  161598. case main_pass:
  161599. /* next pass is either output of scan 0 (after optimization)
  161600. * or output of scan 1 (if no optimization).
  161601. */
  161602. master->pass_type = output_pass;
  161603. if (! cinfo->optimize_coding)
  161604. master->scan_number++;
  161605. break;
  161606. case huff_opt_pass:
  161607. /* next pass is always output of current scan */
  161608. master->pass_type = output_pass;
  161609. break;
  161610. case output_pass:
  161611. /* next pass is either optimization or output of next scan */
  161612. if (cinfo->optimize_coding)
  161613. master->pass_type = huff_opt_pass;
  161614. master->scan_number++;
  161615. break;
  161616. }
  161617. master->pass_number++;
  161618. }
  161619. /*
  161620. * Initialize master compression control.
  161621. */
  161622. GLOBAL(void)
  161623. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  161624. {
  161625. my_master_ptr master;
  161626. master = (my_master_ptr)
  161627. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161628. SIZEOF(my_comp_master));
  161629. cinfo->master = (struct jpeg_comp_master *) master;
  161630. master->pub.prepare_for_pass = prepare_for_pass;
  161631. master->pub.pass_startup = pass_startup;
  161632. master->pub.finish_pass = finish_pass_master;
  161633. master->pub.is_last_pass = FALSE;
  161634. /* Validate parameters, determine derived values */
  161635. initial_setup(cinfo);
  161636. if (cinfo->scan_info != NULL) {
  161637. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161638. validate_script(cinfo);
  161639. #else
  161640. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161641. #endif
  161642. } else {
  161643. cinfo->progressive_mode = FALSE;
  161644. cinfo->num_scans = 1;
  161645. }
  161646. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  161647. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  161648. /* Initialize my private state */
  161649. if (transcode_only) {
  161650. /* no main pass in transcoding */
  161651. if (cinfo->optimize_coding)
  161652. master->pass_type = huff_opt_pass;
  161653. else
  161654. master->pass_type = output_pass;
  161655. } else {
  161656. /* for normal compression, first pass is always this type: */
  161657. master->pass_type = main_pass;
  161658. }
  161659. master->scan_number = 0;
  161660. master->pass_number = 0;
  161661. if (cinfo->optimize_coding)
  161662. master->total_passes = cinfo->num_scans * 2;
  161663. else
  161664. master->total_passes = cinfo->num_scans;
  161665. }
  161666. /*** End of inlined file: jcmaster.c ***/
  161667. /*** Start of inlined file: jcomapi.c ***/
  161668. #define JPEG_INTERNALS
  161669. /*
  161670. * Abort processing of a JPEG compression or decompression operation,
  161671. * but don't destroy the object itself.
  161672. *
  161673. * For this, we merely clean up all the nonpermanent memory pools.
  161674. * Note that temp files (virtual arrays) are not allowed to belong to
  161675. * the permanent pool, so we will be able to close all temp files here.
  161676. * Closing a data source or destination, if necessary, is the application's
  161677. * responsibility.
  161678. */
  161679. GLOBAL(void)
  161680. jpeg_abort (j_common_ptr cinfo)
  161681. {
  161682. int pool;
  161683. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  161684. if (cinfo->mem == NULL)
  161685. return;
  161686. /* Releasing pools in reverse order might help avoid fragmentation
  161687. * with some (brain-damaged) malloc libraries.
  161688. */
  161689. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  161690. (*cinfo->mem->free_pool) (cinfo, pool);
  161691. }
  161692. /* Reset overall state for possible reuse of object */
  161693. if (cinfo->is_decompressor) {
  161694. cinfo->global_state = DSTATE_START;
  161695. /* Try to keep application from accessing now-deleted marker list.
  161696. * A bit kludgy to do it here, but this is the most central place.
  161697. */
  161698. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  161699. } else {
  161700. cinfo->global_state = CSTATE_START;
  161701. }
  161702. }
  161703. /*
  161704. * Destruction of a JPEG object.
  161705. *
  161706. * Everything gets deallocated except the master jpeg_compress_struct itself
  161707. * and the error manager struct. Both of these are supplied by the application
  161708. * and must be freed, if necessary, by the application. (Often they are on
  161709. * the stack and so don't need to be freed anyway.)
  161710. * Closing a data source or destination, if necessary, is the application's
  161711. * responsibility.
  161712. */
  161713. GLOBAL(void)
  161714. jpeg_destroy (j_common_ptr cinfo)
  161715. {
  161716. /* We need only tell the memory manager to release everything. */
  161717. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  161718. if (cinfo->mem != NULL)
  161719. (*cinfo->mem->self_destruct) (cinfo);
  161720. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  161721. cinfo->global_state = 0; /* mark it destroyed */
  161722. }
  161723. /*
  161724. * Convenience routines for allocating quantization and Huffman tables.
  161725. * (Would jutils.c be a more reasonable place to put these?)
  161726. */
  161727. GLOBAL(JQUANT_TBL *)
  161728. jpeg_alloc_quant_table (j_common_ptr cinfo)
  161729. {
  161730. JQUANT_TBL *tbl;
  161731. tbl = (JQUANT_TBL *)
  161732. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  161733. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  161734. return tbl;
  161735. }
  161736. GLOBAL(JHUFF_TBL *)
  161737. jpeg_alloc_huff_table (j_common_ptr cinfo)
  161738. {
  161739. JHUFF_TBL *tbl;
  161740. tbl = (JHUFF_TBL *)
  161741. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  161742. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  161743. return tbl;
  161744. }
  161745. /*** End of inlined file: jcomapi.c ***/
  161746. /*** Start of inlined file: jcparam.c ***/
  161747. #define JPEG_INTERNALS
  161748. /*
  161749. * Quantization table setup routines
  161750. */
  161751. GLOBAL(void)
  161752. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  161753. const unsigned int *basic_table,
  161754. int scale_factor, boolean force_baseline)
  161755. /* Define a quantization table equal to the basic_table times
  161756. * a scale factor (given as a percentage).
  161757. * If force_baseline is TRUE, the computed quantization table entries
  161758. * are limited to 1..255 for JPEG baseline compatibility.
  161759. */
  161760. {
  161761. JQUANT_TBL ** qtblptr;
  161762. int i;
  161763. long temp;
  161764. /* Safety check to ensure start_compress not called yet. */
  161765. if (cinfo->global_state != CSTATE_START)
  161766. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161767. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  161768. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  161769. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  161770. if (*qtblptr == NULL)
  161771. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  161772. for (i = 0; i < DCTSIZE2; i++) {
  161773. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  161774. /* limit the values to the valid range */
  161775. if (temp <= 0L) temp = 1L;
  161776. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  161777. if (force_baseline && temp > 255L)
  161778. temp = 255L; /* limit to baseline range if requested */
  161779. (*qtblptr)->quantval[i] = (UINT16) temp;
  161780. }
  161781. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161782. (*qtblptr)->sent_table = FALSE;
  161783. }
  161784. GLOBAL(void)
  161785. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  161786. boolean force_baseline)
  161787. /* Set or change the 'quality' (quantization) setting, using default tables
  161788. * and a straight percentage-scaling quality scale. In most cases it's better
  161789. * to use jpeg_set_quality (below); this entry point is provided for
  161790. * applications that insist on a linear percentage scaling.
  161791. */
  161792. {
  161793. /* These are the sample quantization tables given in JPEG spec section K.1.
  161794. * The spec says that the values given produce "good" quality, and
  161795. * when divided by 2, "very good" quality.
  161796. */
  161797. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  161798. 16, 11, 10, 16, 24, 40, 51, 61,
  161799. 12, 12, 14, 19, 26, 58, 60, 55,
  161800. 14, 13, 16, 24, 40, 57, 69, 56,
  161801. 14, 17, 22, 29, 51, 87, 80, 62,
  161802. 18, 22, 37, 56, 68, 109, 103, 77,
  161803. 24, 35, 55, 64, 81, 104, 113, 92,
  161804. 49, 64, 78, 87, 103, 121, 120, 101,
  161805. 72, 92, 95, 98, 112, 100, 103, 99
  161806. };
  161807. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  161808. 17, 18, 24, 47, 99, 99, 99, 99,
  161809. 18, 21, 26, 66, 99, 99, 99, 99,
  161810. 24, 26, 56, 99, 99, 99, 99, 99,
  161811. 47, 66, 99, 99, 99, 99, 99, 99,
  161812. 99, 99, 99, 99, 99, 99, 99, 99,
  161813. 99, 99, 99, 99, 99, 99, 99, 99,
  161814. 99, 99, 99, 99, 99, 99, 99, 99,
  161815. 99, 99, 99, 99, 99, 99, 99, 99
  161816. };
  161817. /* Set up two quantization tables using the specified scaling */
  161818. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  161819. scale_factor, force_baseline);
  161820. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  161821. scale_factor, force_baseline);
  161822. }
  161823. GLOBAL(int)
  161824. jpeg_quality_scaling (int quality)
  161825. /* Convert a user-specified quality rating to a percentage scaling factor
  161826. * for an underlying quantization table, using our recommended scaling curve.
  161827. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  161828. */
  161829. {
  161830. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  161831. if (quality <= 0) quality = 1;
  161832. if (quality > 100) quality = 100;
  161833. /* The basic table is used as-is (scaling 100) for a quality of 50.
  161834. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  161835. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  161836. * to make all the table entries 1 (hence, minimum quantization loss).
  161837. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  161838. */
  161839. if (quality < 50)
  161840. quality = 5000 / quality;
  161841. else
  161842. quality = 200 - quality*2;
  161843. return quality;
  161844. }
  161845. GLOBAL(void)
  161846. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  161847. /* Set or change the 'quality' (quantization) setting, using default tables.
  161848. * This is the standard quality-adjusting entry point for typical user
  161849. * interfaces; only those who want detailed control over quantization tables
  161850. * would use the preceding three routines directly.
  161851. */
  161852. {
  161853. /* Convert user 0-100 rating to percentage scaling */
  161854. quality = jpeg_quality_scaling(quality);
  161855. /* Set up standard quality tables */
  161856. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  161857. }
  161858. /*
  161859. * Huffman table setup routines
  161860. */
  161861. LOCAL(void)
  161862. add_huff_table (j_compress_ptr cinfo,
  161863. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  161864. /* Define a Huffman table */
  161865. {
  161866. int nsymbols, len;
  161867. if (*htblptr == NULL)
  161868. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161869. /* Copy the number-of-symbols-of-each-code-length counts */
  161870. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  161871. /* Validate the counts. We do this here mainly so we can copy the right
  161872. * number of symbols from the val[] array, without risking marching off
  161873. * the end of memory. jchuff.c will do a more thorough test later.
  161874. */
  161875. nsymbols = 0;
  161876. for (len = 1; len <= 16; len++)
  161877. nsymbols += bits[len];
  161878. if (nsymbols < 1 || nsymbols > 256)
  161879. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  161880. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  161881. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161882. (*htblptr)->sent_table = FALSE;
  161883. }
  161884. LOCAL(void)
  161885. std_huff_tables (j_compress_ptr cinfo)
  161886. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  161887. /* IMPORTANT: these are only valid for 8-bit data precision! */
  161888. {
  161889. static const UINT8 bits_dc_luminance[17] =
  161890. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  161891. static const UINT8 val_dc_luminance[] =
  161892. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161893. static const UINT8 bits_dc_chrominance[17] =
  161894. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  161895. static const UINT8 val_dc_chrominance[] =
  161896. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161897. static const UINT8 bits_ac_luminance[17] =
  161898. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  161899. static const UINT8 val_ac_luminance[] =
  161900. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  161901. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  161902. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  161903. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  161904. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  161905. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  161906. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  161907. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  161908. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  161909. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  161910. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  161911. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  161912. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  161913. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  161914. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  161915. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  161916. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  161917. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  161918. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  161919. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161920. 0xf9, 0xfa };
  161921. static const UINT8 bits_ac_chrominance[17] =
  161922. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  161923. static const UINT8 val_ac_chrominance[] =
  161924. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  161925. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  161926. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  161927. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  161928. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  161929. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  161930. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  161931. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  161932. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  161933. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  161934. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  161935. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  161936. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  161937. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  161938. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  161939. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  161940. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  161941. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  161942. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  161943. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161944. 0xf9, 0xfa };
  161945. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  161946. bits_dc_luminance, val_dc_luminance);
  161947. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  161948. bits_ac_luminance, val_ac_luminance);
  161949. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  161950. bits_dc_chrominance, val_dc_chrominance);
  161951. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  161952. bits_ac_chrominance, val_ac_chrominance);
  161953. }
  161954. /*
  161955. * Default parameter setup for compression.
  161956. *
  161957. * Applications that don't choose to use this routine must do their
  161958. * own setup of all these parameters. Alternately, you can call this
  161959. * to establish defaults and then alter parameters selectively. This
  161960. * is the recommended approach since, if we add any new parameters,
  161961. * your code will still work (they'll be set to reasonable defaults).
  161962. */
  161963. GLOBAL(void)
  161964. jpeg_set_defaults (j_compress_ptr cinfo)
  161965. {
  161966. int i;
  161967. /* Safety check to ensure start_compress not called yet. */
  161968. if (cinfo->global_state != CSTATE_START)
  161969. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161970. /* Allocate comp_info array large enough for maximum component count.
  161971. * Array is made permanent in case application wants to compress
  161972. * multiple images at same param settings.
  161973. */
  161974. if (cinfo->comp_info == NULL)
  161975. cinfo->comp_info = (jpeg_component_info *)
  161976. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161977. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  161978. /* Initialize everything not dependent on the color space */
  161979. cinfo->data_precision = BITS_IN_JSAMPLE;
  161980. /* Set up two quantization tables using default quality of 75 */
  161981. jpeg_set_quality(cinfo, 75, TRUE);
  161982. /* Set up two Huffman tables */
  161983. std_huff_tables(cinfo);
  161984. /* Initialize default arithmetic coding conditioning */
  161985. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161986. cinfo->arith_dc_L[i] = 0;
  161987. cinfo->arith_dc_U[i] = 1;
  161988. cinfo->arith_ac_K[i] = 5;
  161989. }
  161990. /* Default is no multiple-scan output */
  161991. cinfo->scan_info = NULL;
  161992. cinfo->num_scans = 0;
  161993. /* Expect normal source image, not raw downsampled data */
  161994. cinfo->raw_data_in = FALSE;
  161995. /* Use Huffman coding, not arithmetic coding, by default */
  161996. cinfo->arith_code = FALSE;
  161997. /* By default, don't do extra passes to optimize entropy coding */
  161998. cinfo->optimize_coding = FALSE;
  161999. /* The standard Huffman tables are only valid for 8-bit data precision.
  162000. * If the precision is higher, force optimization on so that usable
  162001. * tables will be computed. This test can be removed if default tables
  162002. * are supplied that are valid for the desired precision.
  162003. */
  162004. if (cinfo->data_precision > 8)
  162005. cinfo->optimize_coding = TRUE;
  162006. /* By default, use the simpler non-cosited sampling alignment */
  162007. cinfo->CCIR601_sampling = FALSE;
  162008. /* No input smoothing */
  162009. cinfo->smoothing_factor = 0;
  162010. /* DCT algorithm preference */
  162011. cinfo->dct_method = JDCT_DEFAULT;
  162012. /* No restart markers */
  162013. cinfo->restart_interval = 0;
  162014. cinfo->restart_in_rows = 0;
  162015. /* Fill in default JFIF marker parameters. Note that whether the marker
  162016. * will actually be written is determined by jpeg_set_colorspace.
  162017. *
  162018. * By default, the library emits JFIF version code 1.01.
  162019. * An application that wants to emit JFIF 1.02 extension markers should set
  162020. * JFIF_minor_version to 2. We could probably get away with just defaulting
  162021. * to 1.02, but there may still be some decoders in use that will complain
  162022. * about that; saying 1.01 should minimize compatibility problems.
  162023. */
  162024. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  162025. cinfo->JFIF_minor_version = 1;
  162026. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  162027. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  162028. cinfo->Y_density = 1;
  162029. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  162030. jpeg_default_colorspace(cinfo);
  162031. }
  162032. /*
  162033. * Select an appropriate JPEG colorspace for in_color_space.
  162034. */
  162035. GLOBAL(void)
  162036. jpeg_default_colorspace (j_compress_ptr cinfo)
  162037. {
  162038. switch (cinfo->in_color_space) {
  162039. case JCS_GRAYSCALE:
  162040. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  162041. break;
  162042. case JCS_RGB:
  162043. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162044. break;
  162045. case JCS_YCbCr:
  162046. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162047. break;
  162048. case JCS_CMYK:
  162049. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  162050. break;
  162051. case JCS_YCCK:
  162052. jpeg_set_colorspace(cinfo, JCS_YCCK);
  162053. break;
  162054. case JCS_UNKNOWN:
  162055. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  162056. break;
  162057. default:
  162058. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162059. }
  162060. }
  162061. /*
  162062. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  162063. */
  162064. GLOBAL(void)
  162065. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  162066. {
  162067. jpeg_component_info * compptr;
  162068. int ci;
  162069. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  162070. (compptr = &cinfo->comp_info[index], \
  162071. compptr->component_id = (id), \
  162072. compptr->h_samp_factor = (hsamp), \
  162073. compptr->v_samp_factor = (vsamp), \
  162074. compptr->quant_tbl_no = (quant), \
  162075. compptr->dc_tbl_no = (dctbl), \
  162076. compptr->ac_tbl_no = (actbl) )
  162077. /* Safety check to ensure start_compress not called yet. */
  162078. if (cinfo->global_state != CSTATE_START)
  162079. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162080. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  162081. * tables 1 for chrominance components.
  162082. */
  162083. cinfo->jpeg_color_space = colorspace;
  162084. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  162085. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  162086. switch (colorspace) {
  162087. case JCS_GRAYSCALE:
  162088. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162089. cinfo->num_components = 1;
  162090. /* JFIF specifies component ID 1 */
  162091. SET_COMP(0, 1, 1,1, 0, 0,0);
  162092. break;
  162093. case JCS_RGB:
  162094. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  162095. cinfo->num_components = 3;
  162096. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  162097. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  162098. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  162099. break;
  162100. case JCS_YCbCr:
  162101. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162102. cinfo->num_components = 3;
  162103. /* JFIF specifies component IDs 1,2,3 */
  162104. /* We default to 2x2 subsamples of chrominance */
  162105. SET_COMP(0, 1, 2,2, 0, 0,0);
  162106. SET_COMP(1, 2, 1,1, 1, 1,1);
  162107. SET_COMP(2, 3, 1,1, 1, 1,1);
  162108. break;
  162109. case JCS_CMYK:
  162110. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  162111. cinfo->num_components = 4;
  162112. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  162113. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  162114. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  162115. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  162116. break;
  162117. case JCS_YCCK:
  162118. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  162119. cinfo->num_components = 4;
  162120. SET_COMP(0, 1, 2,2, 0, 0,0);
  162121. SET_COMP(1, 2, 1,1, 1, 1,1);
  162122. SET_COMP(2, 3, 1,1, 1, 1,1);
  162123. SET_COMP(3, 4, 2,2, 0, 0,0);
  162124. break;
  162125. case JCS_UNKNOWN:
  162126. cinfo->num_components = cinfo->input_components;
  162127. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  162128. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  162129. MAX_COMPONENTS);
  162130. for (ci = 0; ci < cinfo->num_components; ci++) {
  162131. SET_COMP(ci, ci, 1,1, 0, 0,0);
  162132. }
  162133. break;
  162134. default:
  162135. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162136. }
  162137. }
  162138. #ifdef C_PROGRESSIVE_SUPPORTED
  162139. LOCAL(jpeg_scan_info *)
  162140. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  162141. int Ss, int Se, int Ah, int Al)
  162142. /* Support routine: generate one scan for specified component */
  162143. {
  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. return scanptr;
  162152. }
  162153. LOCAL(jpeg_scan_info *)
  162154. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  162155. int Ss, int Se, int Ah, int Al)
  162156. /* Support routine: generate one scan for each component */
  162157. {
  162158. int ci;
  162159. for (ci = 0; ci < ncomps; ci++) {
  162160. scanptr->comps_in_scan = 1;
  162161. scanptr->component_index[0] = ci;
  162162. scanptr->Ss = Ss;
  162163. scanptr->Se = Se;
  162164. scanptr->Ah = Ah;
  162165. scanptr->Al = Al;
  162166. scanptr++;
  162167. }
  162168. return scanptr;
  162169. }
  162170. LOCAL(jpeg_scan_info *)
  162171. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  162172. /* Support routine: generate interleaved DC scan if possible, else N scans */
  162173. {
  162174. int ci;
  162175. if (ncomps <= MAX_COMPS_IN_SCAN) {
  162176. /* Single interleaved DC scan */
  162177. scanptr->comps_in_scan = ncomps;
  162178. for (ci = 0; ci < ncomps; ci++)
  162179. scanptr->component_index[ci] = ci;
  162180. scanptr->Ss = scanptr->Se = 0;
  162181. scanptr->Ah = Ah;
  162182. scanptr->Al = Al;
  162183. scanptr++;
  162184. } else {
  162185. /* Noninterleaved DC scan for each component */
  162186. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  162187. }
  162188. return scanptr;
  162189. }
  162190. /*
  162191. * Create a recommended progressive-JPEG script.
  162192. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  162193. */
  162194. GLOBAL(void)
  162195. jpeg_simple_progression (j_compress_ptr cinfo)
  162196. {
  162197. int ncomps = cinfo->num_components;
  162198. int nscans;
  162199. jpeg_scan_info * scanptr;
  162200. /* Safety check to ensure start_compress not called yet. */
  162201. if (cinfo->global_state != CSTATE_START)
  162202. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162203. /* Figure space needed for script. Calculation must match code below! */
  162204. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162205. /* Custom script for YCbCr color images. */
  162206. nscans = 10;
  162207. } else {
  162208. /* All-purpose script for other color spaces. */
  162209. if (ncomps > MAX_COMPS_IN_SCAN)
  162210. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  162211. else
  162212. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  162213. }
  162214. /* Allocate space for script.
  162215. * We need to put it in the permanent pool in case the application performs
  162216. * multiple compressions without changing the settings. To avoid a memory
  162217. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  162218. * object, we try to re-use previously allocated space, and we allocate
  162219. * enough space to handle YCbCr even if initially asked for grayscale.
  162220. */
  162221. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  162222. cinfo->script_space_size = MAX(nscans, 10);
  162223. cinfo->script_space = (jpeg_scan_info *)
  162224. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162225. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  162226. }
  162227. scanptr = cinfo->script_space;
  162228. cinfo->scan_info = scanptr;
  162229. cinfo->num_scans = nscans;
  162230. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162231. /* Custom script for YCbCr color images. */
  162232. /* Initial DC scan */
  162233. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162234. /* Initial AC scan: get some luma data out in a hurry */
  162235. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  162236. /* Chroma data is too small to be worth expending many scans on */
  162237. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  162238. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  162239. /* Complete spectral selection for luma AC */
  162240. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  162241. /* Refine next bit of luma AC */
  162242. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  162243. /* Finish DC successive approximation */
  162244. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162245. /* Finish AC successive approximation */
  162246. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  162247. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  162248. /* Luma bottom bit comes last since it's usually largest scan */
  162249. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  162250. } else {
  162251. /* All-purpose script for other color spaces. */
  162252. /* Successive approximation first pass */
  162253. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162254. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  162255. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  162256. /* Successive approximation second pass */
  162257. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  162258. /* Successive approximation final pass */
  162259. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162260. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  162261. }
  162262. }
  162263. #endif /* C_PROGRESSIVE_SUPPORTED */
  162264. /*** End of inlined file: jcparam.c ***/
  162265. /*** Start of inlined file: jcphuff.c ***/
  162266. #define JPEG_INTERNALS
  162267. #ifdef C_PROGRESSIVE_SUPPORTED
  162268. /* Expanded entropy encoder object for progressive Huffman encoding. */
  162269. typedef struct {
  162270. struct jpeg_entropy_encoder pub; /* public fields */
  162271. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  162272. boolean gather_statistics;
  162273. /* Bit-level coding status.
  162274. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  162275. */
  162276. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162277. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162278. INT32 put_buffer; /* current bit-accumulation buffer */
  162279. int put_bits; /* # of bits now in it */
  162280. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  162281. /* Coding status for DC components */
  162282. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162283. /* Coding status for AC components */
  162284. int ac_tbl_no; /* the table number of the single component */
  162285. unsigned int EOBRUN; /* run length of EOBs */
  162286. unsigned int BE; /* # of buffered correction bits before MCU */
  162287. char * bit_buffer; /* buffer for correction bits (1 per char) */
  162288. /* packing correction bits tightly would save some space but cost time... */
  162289. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162290. int next_restart_num; /* next restart number to write (0-7) */
  162291. /* Pointers to derived tables (these workspaces have image lifespan).
  162292. * Since any one scan codes only DC or only AC, we only need one set
  162293. * of tables, not one for DC and one for AC.
  162294. */
  162295. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  162296. /* Statistics tables for optimization; again, one set is enough */
  162297. long * count_ptrs[NUM_HUFF_TBLS];
  162298. } phuff_entropy_encoder;
  162299. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  162300. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  162301. * buffer can hold. Larger sizes may slightly improve compression, but
  162302. * 1000 is already well into the realm of overkill.
  162303. * The minimum safe size is 64 bits.
  162304. */
  162305. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  162306. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  162307. * We assume that int right shift is unsigned if INT32 right shift is,
  162308. * which should be safe.
  162309. */
  162310. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  162311. #define ISHIFT_TEMPS int ishift_temp;
  162312. #define IRIGHT_SHIFT(x,shft) \
  162313. ((ishift_temp = (x)) < 0 ? \
  162314. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  162315. (ishift_temp >> (shft)))
  162316. #else
  162317. #define ISHIFT_TEMPS
  162318. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  162319. #endif
  162320. /* Forward declarations */
  162321. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  162322. JBLOCKROW *MCU_data));
  162323. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  162324. JBLOCKROW *MCU_data));
  162325. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  162326. JBLOCKROW *MCU_data));
  162327. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  162328. JBLOCKROW *MCU_data));
  162329. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  162330. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  162331. /*
  162332. * Initialize for a Huffman-compressed scan using progressive JPEG.
  162333. */
  162334. METHODDEF(void)
  162335. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  162336. {
  162337. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162338. boolean is_DC_band;
  162339. int ci, tbl;
  162340. jpeg_component_info * compptr;
  162341. entropy->cinfo = cinfo;
  162342. entropy->gather_statistics = gather_statistics;
  162343. is_DC_band = (cinfo->Ss == 0);
  162344. /* We assume jcmaster.c already validated the scan parameters. */
  162345. /* Select execution routines */
  162346. if (cinfo->Ah == 0) {
  162347. if (is_DC_band)
  162348. entropy->pub.encode_mcu = encode_mcu_DC_first;
  162349. else
  162350. entropy->pub.encode_mcu = encode_mcu_AC_first;
  162351. } else {
  162352. if (is_DC_band)
  162353. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  162354. else {
  162355. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  162356. /* AC refinement needs a correction bit buffer */
  162357. if (entropy->bit_buffer == NULL)
  162358. entropy->bit_buffer = (char *)
  162359. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162360. MAX_CORR_BITS * SIZEOF(char));
  162361. }
  162362. }
  162363. if (gather_statistics)
  162364. entropy->pub.finish_pass = finish_pass_gather_phuff;
  162365. else
  162366. entropy->pub.finish_pass = finish_pass_phuff;
  162367. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  162368. * for AC coefficients.
  162369. */
  162370. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162371. compptr = cinfo->cur_comp_info[ci];
  162372. /* Initialize DC predictions to 0 */
  162373. entropy->last_dc_val[ci] = 0;
  162374. /* Get table index */
  162375. if (is_DC_band) {
  162376. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162377. continue;
  162378. tbl = compptr->dc_tbl_no;
  162379. } else {
  162380. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  162381. }
  162382. if (gather_statistics) {
  162383. /* Check for invalid table index */
  162384. /* (make_c_derived_tbl does this in the other path) */
  162385. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  162386. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  162387. /* Allocate and zero the statistics tables */
  162388. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162389. if (entropy->count_ptrs[tbl] == NULL)
  162390. entropy->count_ptrs[tbl] = (long *)
  162391. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162392. 257 * SIZEOF(long));
  162393. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  162394. } else {
  162395. /* Compute derived values for Huffman table */
  162396. /* We may do this more than once for a table, but it's not expensive */
  162397. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  162398. & entropy->derived_tbls[tbl]);
  162399. }
  162400. }
  162401. /* Initialize AC stuff */
  162402. entropy->EOBRUN = 0;
  162403. entropy->BE = 0;
  162404. /* Initialize bit buffer to empty */
  162405. entropy->put_buffer = 0;
  162406. entropy->put_bits = 0;
  162407. /* Initialize restart stuff */
  162408. entropy->restarts_to_go = cinfo->restart_interval;
  162409. entropy->next_restart_num = 0;
  162410. }
  162411. /* Outputting bytes to the file.
  162412. * NB: these must be called only when actually outputting,
  162413. * that is, entropy->gather_statistics == FALSE.
  162414. */
  162415. /* Emit a byte */
  162416. #define emit_byte(entropy,val) \
  162417. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  162418. if (--(entropy)->free_in_buffer == 0) \
  162419. dump_buffer_p(entropy); }
  162420. LOCAL(void)
  162421. dump_buffer_p (phuff_entropy_ptr entropy)
  162422. /* Empty the output buffer; we do not support suspension in this module. */
  162423. {
  162424. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  162425. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  162426. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  162427. /* After a successful buffer dump, must reset buffer pointers */
  162428. entropy->next_output_byte = dest->next_output_byte;
  162429. entropy->free_in_buffer = dest->free_in_buffer;
  162430. }
  162431. /* Outputting bits to the file */
  162432. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162433. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162434. * in one call, and we never retain more than 7 bits in put_buffer
  162435. * between calls, so 24 bits are sufficient.
  162436. */
  162437. INLINE
  162438. LOCAL(void)
  162439. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  162440. /* Emit some bits, unless we are in gather mode */
  162441. {
  162442. /* This routine is heavily used, so it's worth coding tightly. */
  162443. register INT32 put_buffer = (INT32) code;
  162444. register int put_bits = entropy->put_bits;
  162445. /* if size is 0, caller used an invalid Huffman table entry */
  162446. if (size == 0)
  162447. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  162448. if (entropy->gather_statistics)
  162449. return; /* do nothing if we're only getting stats */
  162450. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162451. put_bits += size; /* new number of bits in buffer */
  162452. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162453. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  162454. while (put_bits >= 8) {
  162455. int c = (int) ((put_buffer >> 16) & 0xFF);
  162456. emit_byte(entropy, c);
  162457. if (c == 0xFF) { /* need to stuff a zero byte? */
  162458. emit_byte(entropy, 0);
  162459. }
  162460. put_buffer <<= 8;
  162461. put_bits -= 8;
  162462. }
  162463. entropy->put_buffer = put_buffer; /* update variables */
  162464. entropy->put_bits = put_bits;
  162465. }
  162466. LOCAL(void)
  162467. flush_bits_p (phuff_entropy_ptr entropy)
  162468. {
  162469. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  162470. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  162471. entropy->put_bits = 0;
  162472. }
  162473. /*
  162474. * Emit (or just count) a Huffman symbol.
  162475. */
  162476. INLINE
  162477. LOCAL(void)
  162478. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  162479. {
  162480. if (entropy->gather_statistics)
  162481. entropy->count_ptrs[tbl_no][symbol]++;
  162482. else {
  162483. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  162484. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  162485. }
  162486. }
  162487. /*
  162488. * Emit bits from a correction bit buffer.
  162489. */
  162490. LOCAL(void)
  162491. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  162492. unsigned int nbits)
  162493. {
  162494. if (entropy->gather_statistics)
  162495. return; /* no real work */
  162496. while (nbits > 0) {
  162497. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  162498. bufstart++;
  162499. nbits--;
  162500. }
  162501. }
  162502. /*
  162503. * Emit any pending EOBRUN symbol.
  162504. */
  162505. LOCAL(void)
  162506. emit_eobrun (phuff_entropy_ptr entropy)
  162507. {
  162508. register int temp, nbits;
  162509. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  162510. temp = entropy->EOBRUN;
  162511. nbits = 0;
  162512. while ((temp >>= 1))
  162513. nbits++;
  162514. /* safety check: shouldn't happen given limited correction-bit buffer */
  162515. if (nbits > 14)
  162516. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  162517. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  162518. if (nbits)
  162519. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  162520. entropy->EOBRUN = 0;
  162521. /* Emit any buffered correction bits */
  162522. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  162523. entropy->BE = 0;
  162524. }
  162525. }
  162526. /*
  162527. * Emit a restart marker & resynchronize predictions.
  162528. */
  162529. LOCAL(void)
  162530. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  162531. {
  162532. int ci;
  162533. emit_eobrun(entropy);
  162534. if (! entropy->gather_statistics) {
  162535. flush_bits_p(entropy);
  162536. emit_byte(entropy, 0xFF);
  162537. emit_byte(entropy, JPEG_RST0 + restart_num);
  162538. }
  162539. if (entropy->cinfo->Ss == 0) {
  162540. /* Re-initialize DC predictions to 0 */
  162541. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  162542. entropy->last_dc_val[ci] = 0;
  162543. } else {
  162544. /* Re-initialize all AC-related fields to 0 */
  162545. entropy->EOBRUN = 0;
  162546. entropy->BE = 0;
  162547. }
  162548. }
  162549. /*
  162550. * MCU encoding for DC initial scan (either spectral selection,
  162551. * or first pass of successive approximation).
  162552. */
  162553. METHODDEF(boolean)
  162554. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162555. {
  162556. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162557. register int temp, temp2;
  162558. register int nbits;
  162559. int blkn, ci;
  162560. int Al = cinfo->Al;
  162561. JBLOCKROW block;
  162562. jpeg_component_info * compptr;
  162563. ISHIFT_TEMPS
  162564. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162565. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162566. /* Emit restart marker if needed */
  162567. if (cinfo->restart_interval)
  162568. if (entropy->restarts_to_go == 0)
  162569. emit_restart_p(entropy, entropy->next_restart_num);
  162570. /* Encode the MCU data blocks */
  162571. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162572. block = MCU_data[blkn];
  162573. ci = cinfo->MCU_membership[blkn];
  162574. compptr = cinfo->cur_comp_info[ci];
  162575. /* Compute the DC value after the required point transform by Al.
  162576. * This is simply an arithmetic right shift.
  162577. */
  162578. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  162579. /* DC differences are figured on the point-transformed values. */
  162580. temp = temp2 - entropy->last_dc_val[ci];
  162581. entropy->last_dc_val[ci] = temp2;
  162582. /* Encode the DC coefficient difference per section G.1.2.1 */
  162583. temp2 = temp;
  162584. if (temp < 0) {
  162585. temp = -temp; /* temp is abs value of input */
  162586. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162587. /* This code assumes we are on a two's complement machine */
  162588. temp2--;
  162589. }
  162590. /* Find the number of bits needed for the magnitude of the coefficient */
  162591. nbits = 0;
  162592. while (temp) {
  162593. nbits++;
  162594. temp >>= 1;
  162595. }
  162596. /* Check for out-of-range coefficient values.
  162597. * Since we're encoding a difference, the range limit is twice as much.
  162598. */
  162599. if (nbits > MAX_COEF_BITS+1)
  162600. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162601. /* Count/emit the Huffman-coded symbol for the number of bits */
  162602. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  162603. /* Emit that number of bits of the value, if positive, */
  162604. /* or the complement of its magnitude, if negative. */
  162605. if (nbits) /* emit_bits rejects calls with size 0 */
  162606. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  162607. }
  162608. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162609. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162610. /* Update restart-interval state too */
  162611. if (cinfo->restart_interval) {
  162612. if (entropy->restarts_to_go == 0) {
  162613. entropy->restarts_to_go = cinfo->restart_interval;
  162614. entropy->next_restart_num++;
  162615. entropy->next_restart_num &= 7;
  162616. }
  162617. entropy->restarts_to_go--;
  162618. }
  162619. return TRUE;
  162620. }
  162621. /*
  162622. * MCU encoding for AC initial scan (either spectral selection,
  162623. * or first pass of successive approximation).
  162624. */
  162625. METHODDEF(boolean)
  162626. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162627. {
  162628. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162629. register int temp, temp2;
  162630. register int nbits;
  162631. register int r, k;
  162632. int Se = cinfo->Se;
  162633. int Al = cinfo->Al;
  162634. JBLOCKROW block;
  162635. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162636. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162637. /* Emit restart marker if needed */
  162638. if (cinfo->restart_interval)
  162639. if (entropy->restarts_to_go == 0)
  162640. emit_restart_p(entropy, entropy->next_restart_num);
  162641. /* Encode the MCU data block */
  162642. block = MCU_data[0];
  162643. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  162644. r = 0; /* r = run length of zeros */
  162645. for (k = cinfo->Ss; k <= Se; k++) {
  162646. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  162647. r++;
  162648. continue;
  162649. }
  162650. /* We must apply the point transform by Al. For AC coefficients this
  162651. * is an integer division with rounding towards 0. To do this portably
  162652. * in C, we shift after obtaining the absolute value; so the code is
  162653. * interwoven with finding the abs value (temp) and output bits (temp2).
  162654. */
  162655. if (temp < 0) {
  162656. temp = -temp; /* temp is abs value of input */
  162657. temp >>= Al; /* apply the point transform */
  162658. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  162659. temp2 = ~temp;
  162660. } else {
  162661. temp >>= Al; /* apply the point transform */
  162662. temp2 = temp;
  162663. }
  162664. /* Watch out for case that nonzero coef is zero after point transform */
  162665. if (temp == 0) {
  162666. r++;
  162667. continue;
  162668. }
  162669. /* Emit any pending EOBRUN */
  162670. if (entropy->EOBRUN > 0)
  162671. emit_eobrun(entropy);
  162672. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162673. while (r > 15) {
  162674. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  162675. r -= 16;
  162676. }
  162677. /* Find the number of bits needed for the magnitude of the coefficient */
  162678. nbits = 1; /* there must be at least one 1 bit */
  162679. while ((temp >>= 1))
  162680. nbits++;
  162681. /* Check for out-of-range coefficient values */
  162682. if (nbits > MAX_COEF_BITS)
  162683. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162684. /* Count/emit Huffman symbol for run length / number of bits */
  162685. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  162686. /* Emit that number of bits of the value, if positive, */
  162687. /* or the complement of its magnitude, if negative. */
  162688. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  162689. r = 0; /* reset zero run length */
  162690. }
  162691. if (r > 0) { /* If there are trailing zeroes, */
  162692. entropy->EOBRUN++; /* count an EOB */
  162693. if (entropy->EOBRUN == 0x7FFF)
  162694. emit_eobrun(entropy); /* force it out to avoid overflow */
  162695. }
  162696. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162697. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162698. /* Update restart-interval state too */
  162699. if (cinfo->restart_interval) {
  162700. if (entropy->restarts_to_go == 0) {
  162701. entropy->restarts_to_go = cinfo->restart_interval;
  162702. entropy->next_restart_num++;
  162703. entropy->next_restart_num &= 7;
  162704. }
  162705. entropy->restarts_to_go--;
  162706. }
  162707. return TRUE;
  162708. }
  162709. /*
  162710. * MCU encoding for DC successive approximation refinement scan.
  162711. * Note: we assume such scans can be multi-component, although the spec
  162712. * is not very clear on the point.
  162713. */
  162714. METHODDEF(boolean)
  162715. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162716. {
  162717. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162718. register int temp;
  162719. int blkn;
  162720. int Al = cinfo->Al;
  162721. JBLOCKROW block;
  162722. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162723. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162724. /* Emit restart marker if needed */
  162725. if (cinfo->restart_interval)
  162726. if (entropy->restarts_to_go == 0)
  162727. emit_restart_p(entropy, entropy->next_restart_num);
  162728. /* Encode the MCU data blocks */
  162729. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162730. block = MCU_data[blkn];
  162731. /* We simply emit the Al'th bit of the DC coefficient value. */
  162732. temp = (*block)[0];
  162733. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  162734. }
  162735. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162736. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162737. /* Update restart-interval state too */
  162738. if (cinfo->restart_interval) {
  162739. if (entropy->restarts_to_go == 0) {
  162740. entropy->restarts_to_go = cinfo->restart_interval;
  162741. entropy->next_restart_num++;
  162742. entropy->next_restart_num &= 7;
  162743. }
  162744. entropy->restarts_to_go--;
  162745. }
  162746. return TRUE;
  162747. }
  162748. /*
  162749. * MCU encoding for AC successive approximation refinement scan.
  162750. */
  162751. METHODDEF(boolean)
  162752. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162753. {
  162754. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162755. register int temp;
  162756. register int r, k;
  162757. int EOB;
  162758. char *BR_buffer;
  162759. unsigned int BR;
  162760. int Se = cinfo->Se;
  162761. int Al = cinfo->Al;
  162762. JBLOCKROW block;
  162763. int absvalues[DCTSIZE2];
  162764. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162765. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162766. /* Emit restart marker if needed */
  162767. if (cinfo->restart_interval)
  162768. if (entropy->restarts_to_go == 0)
  162769. emit_restart_p(entropy, entropy->next_restart_num);
  162770. /* Encode the MCU data block */
  162771. block = MCU_data[0];
  162772. /* It is convenient to make a pre-pass to determine the transformed
  162773. * coefficients' absolute values and the EOB position.
  162774. */
  162775. EOB = 0;
  162776. for (k = cinfo->Ss; k <= Se; k++) {
  162777. temp = (*block)[jpeg_natural_order[k]];
  162778. /* We must apply the point transform by Al. For AC coefficients this
  162779. * is an integer division with rounding towards 0. To do this portably
  162780. * in C, we shift after obtaining the absolute value.
  162781. */
  162782. if (temp < 0)
  162783. temp = -temp; /* temp is abs value of input */
  162784. temp >>= Al; /* apply the point transform */
  162785. absvalues[k] = temp; /* save abs value for main pass */
  162786. if (temp == 1)
  162787. EOB = k; /* EOB = index of last newly-nonzero coef */
  162788. }
  162789. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  162790. r = 0; /* r = run length of zeros */
  162791. BR = 0; /* BR = count of buffered bits added now */
  162792. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  162793. for (k = cinfo->Ss; k <= Se; k++) {
  162794. if ((temp = absvalues[k]) == 0) {
  162795. r++;
  162796. continue;
  162797. }
  162798. /* Emit any required ZRLs, but not if they can be folded into EOB */
  162799. while (r > 15 && k <= EOB) {
  162800. /* emit any pending EOBRUN and the BE correction bits */
  162801. emit_eobrun(entropy);
  162802. /* Emit ZRL */
  162803. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  162804. r -= 16;
  162805. /* Emit buffered correction bits that must be associated with ZRL */
  162806. emit_buffered_bits(entropy, BR_buffer, BR);
  162807. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162808. BR = 0;
  162809. }
  162810. /* If the coef was previously nonzero, it only needs a correction bit.
  162811. * NOTE: a straight translation of the spec's figure G.7 would suggest
  162812. * that we also need to test r > 15. But if r > 15, we can only get here
  162813. * if k > EOB, which implies that this coefficient is not 1.
  162814. */
  162815. if (temp > 1) {
  162816. /* The correction bit is the next bit of the absolute value. */
  162817. BR_buffer[BR++] = (char) (temp & 1);
  162818. continue;
  162819. }
  162820. /* Emit any pending EOBRUN and the BE correction bits */
  162821. emit_eobrun(entropy);
  162822. /* Count/emit Huffman symbol for run length / number of bits */
  162823. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  162824. /* Emit output bit for newly-nonzero coef */
  162825. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  162826. emit_bits_p(entropy, (unsigned int) temp, 1);
  162827. /* Emit buffered correction bits that must be associated with this code */
  162828. emit_buffered_bits(entropy, BR_buffer, BR);
  162829. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162830. BR = 0;
  162831. r = 0; /* reset zero run length */
  162832. }
  162833. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  162834. entropy->EOBRUN++; /* count an EOB */
  162835. entropy->BE += BR; /* concat my correction bits to older ones */
  162836. /* We force out the EOB if we risk either:
  162837. * 1. overflow of the EOB counter;
  162838. * 2. overflow of the correction bit buffer during the next MCU.
  162839. */
  162840. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  162841. emit_eobrun(entropy);
  162842. }
  162843. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162844. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162845. /* Update restart-interval state too */
  162846. if (cinfo->restart_interval) {
  162847. if (entropy->restarts_to_go == 0) {
  162848. entropy->restarts_to_go = cinfo->restart_interval;
  162849. entropy->next_restart_num++;
  162850. entropy->next_restart_num &= 7;
  162851. }
  162852. entropy->restarts_to_go--;
  162853. }
  162854. return TRUE;
  162855. }
  162856. /*
  162857. * Finish up at the end of a Huffman-compressed progressive scan.
  162858. */
  162859. METHODDEF(void)
  162860. finish_pass_phuff (j_compress_ptr cinfo)
  162861. {
  162862. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162863. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162864. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162865. /* Flush out any buffered data */
  162866. emit_eobrun(entropy);
  162867. flush_bits_p(entropy);
  162868. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162869. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162870. }
  162871. /*
  162872. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162873. */
  162874. METHODDEF(void)
  162875. finish_pass_gather_phuff (j_compress_ptr cinfo)
  162876. {
  162877. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162878. boolean is_DC_band;
  162879. int ci, tbl;
  162880. jpeg_component_info * compptr;
  162881. JHUFF_TBL **htblptr;
  162882. boolean did[NUM_HUFF_TBLS];
  162883. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  162884. emit_eobrun(entropy);
  162885. is_DC_band = (cinfo->Ss == 0);
  162886. /* It's important not to apply jpeg_gen_optimal_table more than once
  162887. * per table, because it clobbers the input frequency counts!
  162888. */
  162889. MEMZERO(did, SIZEOF(did));
  162890. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162891. compptr = cinfo->cur_comp_info[ci];
  162892. if (is_DC_band) {
  162893. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162894. continue;
  162895. tbl = compptr->dc_tbl_no;
  162896. } else {
  162897. tbl = compptr->ac_tbl_no;
  162898. }
  162899. if (! did[tbl]) {
  162900. if (is_DC_band)
  162901. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  162902. else
  162903. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  162904. if (*htblptr == NULL)
  162905. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162906. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  162907. did[tbl] = TRUE;
  162908. }
  162909. }
  162910. }
  162911. /*
  162912. * Module initialization routine for progressive Huffman entropy encoding.
  162913. */
  162914. GLOBAL(void)
  162915. jinit_phuff_encoder (j_compress_ptr cinfo)
  162916. {
  162917. phuff_entropy_ptr entropy;
  162918. int i;
  162919. entropy = (phuff_entropy_ptr)
  162920. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162921. SIZEOF(phuff_entropy_encoder));
  162922. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162923. entropy->pub.start_pass = start_pass_phuff;
  162924. /* Mark tables unallocated */
  162925. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162926. entropy->derived_tbls[i] = NULL;
  162927. entropy->count_ptrs[i] = NULL;
  162928. }
  162929. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  162930. }
  162931. #endif /* C_PROGRESSIVE_SUPPORTED */
  162932. /*** End of inlined file: jcphuff.c ***/
  162933. /*** Start of inlined file: jcprepct.c ***/
  162934. #define JPEG_INTERNALS
  162935. /* At present, jcsample.c can request context rows only for smoothing.
  162936. * In the future, we might also need context rows for CCIR601 sampling
  162937. * or other more-complex downsampling procedures. The code to support
  162938. * context rows should be compiled only if needed.
  162939. */
  162940. #ifdef INPUT_SMOOTHING_SUPPORTED
  162941. #define CONTEXT_ROWS_SUPPORTED
  162942. #endif
  162943. /*
  162944. * For the simple (no-context-row) case, we just need to buffer one
  162945. * row group's worth of pixels for the downsampling step. At the bottom of
  162946. * the image, we pad to a full row group by replicating the last pixel row.
  162947. * The downsampler's last output row is then replicated if needed to pad
  162948. * out to a full iMCU row.
  162949. *
  162950. * When providing context rows, we must buffer three row groups' worth of
  162951. * pixels. Three row groups are physically allocated, but the row pointer
  162952. * arrays are made five row groups high, with the extra pointers above and
  162953. * below "wrapping around" to point to the last and first real row groups.
  162954. * This allows the downsampler to access the proper context rows.
  162955. * At the top and bottom of the image, we create dummy context rows by
  162956. * copying the first or last real pixel row. This copying could be avoided
  162957. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  162958. * trouble on the compression side.
  162959. */
  162960. /* Private buffer controller object */
  162961. typedef struct {
  162962. struct jpeg_c_prep_controller pub; /* public fields */
  162963. /* Downsampling input buffer. This buffer holds color-converted data
  162964. * until we have enough to do a downsample step.
  162965. */
  162966. JSAMPARRAY color_buf[MAX_COMPONENTS];
  162967. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  162968. int next_buf_row; /* index of next row to store in color_buf */
  162969. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  162970. int this_row_group; /* starting row index of group to process */
  162971. int next_buf_stop; /* downsample when we reach this index */
  162972. #endif
  162973. } my_prep_controller;
  162974. typedef my_prep_controller * my_prep_ptr;
  162975. /*
  162976. * Initialize for a processing pass.
  162977. */
  162978. METHODDEF(void)
  162979. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162980. {
  162981. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162982. if (pass_mode != JBUF_PASS_THRU)
  162983. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162984. /* Initialize total-height counter for detecting bottom of image */
  162985. prep->rows_to_go = cinfo->image_height;
  162986. /* Mark the conversion buffer empty */
  162987. prep->next_buf_row = 0;
  162988. #ifdef CONTEXT_ROWS_SUPPORTED
  162989. /* Preset additional state variables for context mode.
  162990. * These aren't used in non-context mode, so we needn't test which mode.
  162991. */
  162992. prep->this_row_group = 0;
  162993. /* Set next_buf_stop to stop after two row groups have been read in. */
  162994. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  162995. #endif
  162996. }
  162997. /*
  162998. * Expand an image vertically from height input_rows to height output_rows,
  162999. * by duplicating the bottom row.
  163000. */
  163001. LOCAL(void)
  163002. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  163003. int input_rows, int output_rows)
  163004. {
  163005. register int row;
  163006. for (row = input_rows; row < output_rows; row++) {
  163007. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  163008. 1, num_cols);
  163009. }
  163010. }
  163011. /*
  163012. * Process some data in the simple no-context case.
  163013. *
  163014. * Preprocessor output data is counted in "row groups". A row group
  163015. * is defined to be v_samp_factor sample rows of each component.
  163016. * Downsampling will produce this much data from each max_v_samp_factor
  163017. * input rows.
  163018. */
  163019. METHODDEF(void)
  163020. pre_process_data (j_compress_ptr cinfo,
  163021. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163022. JDIMENSION in_rows_avail,
  163023. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163024. JDIMENSION out_row_groups_avail)
  163025. {
  163026. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163027. int numrows, ci;
  163028. JDIMENSION inrows;
  163029. jpeg_component_info * compptr;
  163030. while (*in_row_ctr < in_rows_avail &&
  163031. *out_row_group_ctr < out_row_groups_avail) {
  163032. /* Do color conversion to fill the conversion buffer. */
  163033. inrows = in_rows_avail - *in_row_ctr;
  163034. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  163035. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163036. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163037. prep->color_buf,
  163038. (JDIMENSION) prep->next_buf_row,
  163039. numrows);
  163040. *in_row_ctr += numrows;
  163041. prep->next_buf_row += numrows;
  163042. prep->rows_to_go -= numrows;
  163043. /* If at bottom of image, pad to fill the conversion buffer. */
  163044. if (prep->rows_to_go == 0 &&
  163045. prep->next_buf_row < cinfo->max_v_samp_factor) {
  163046. for (ci = 0; ci < cinfo->num_components; ci++) {
  163047. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163048. prep->next_buf_row, cinfo->max_v_samp_factor);
  163049. }
  163050. prep->next_buf_row = cinfo->max_v_samp_factor;
  163051. }
  163052. /* If we've filled the conversion buffer, empty it. */
  163053. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  163054. (*cinfo->downsample->downsample) (cinfo,
  163055. prep->color_buf, (JDIMENSION) 0,
  163056. output_buf, *out_row_group_ctr);
  163057. prep->next_buf_row = 0;
  163058. (*out_row_group_ctr)++;
  163059. }
  163060. /* If at bottom of image, pad the output to a full iMCU height.
  163061. * Note we assume the caller is providing a one-iMCU-height output buffer!
  163062. */
  163063. if (prep->rows_to_go == 0 &&
  163064. *out_row_group_ctr < out_row_groups_avail) {
  163065. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163066. ci++, compptr++) {
  163067. expand_bottom_edge(output_buf[ci],
  163068. compptr->width_in_blocks * DCTSIZE,
  163069. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  163070. (int) (out_row_groups_avail * compptr->v_samp_factor));
  163071. }
  163072. *out_row_group_ctr = out_row_groups_avail;
  163073. break; /* can exit outer loop without test */
  163074. }
  163075. }
  163076. }
  163077. #ifdef CONTEXT_ROWS_SUPPORTED
  163078. /*
  163079. * Process some data in the context case.
  163080. */
  163081. METHODDEF(void)
  163082. pre_process_context (j_compress_ptr cinfo,
  163083. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163084. JDIMENSION in_rows_avail,
  163085. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163086. JDIMENSION out_row_groups_avail)
  163087. {
  163088. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163089. int numrows, ci;
  163090. int buf_height = cinfo->max_v_samp_factor * 3;
  163091. JDIMENSION inrows;
  163092. while (*out_row_group_ctr < out_row_groups_avail) {
  163093. if (*in_row_ctr < in_rows_avail) {
  163094. /* Do color conversion to fill the conversion buffer. */
  163095. inrows = in_rows_avail - *in_row_ctr;
  163096. numrows = prep->next_buf_stop - prep->next_buf_row;
  163097. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163098. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163099. prep->color_buf,
  163100. (JDIMENSION) prep->next_buf_row,
  163101. numrows);
  163102. /* Pad at top of image, if first time through */
  163103. if (prep->rows_to_go == cinfo->image_height) {
  163104. for (ci = 0; ci < cinfo->num_components; ci++) {
  163105. int row;
  163106. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  163107. jcopy_sample_rows(prep->color_buf[ci], 0,
  163108. prep->color_buf[ci], -row,
  163109. 1, cinfo->image_width);
  163110. }
  163111. }
  163112. }
  163113. *in_row_ctr += numrows;
  163114. prep->next_buf_row += numrows;
  163115. prep->rows_to_go -= numrows;
  163116. } else {
  163117. /* Return for more data, unless we are at the bottom of the image. */
  163118. if (prep->rows_to_go != 0)
  163119. break;
  163120. /* When at bottom of image, pad to fill the conversion buffer. */
  163121. if (prep->next_buf_row < prep->next_buf_stop) {
  163122. for (ci = 0; ci < cinfo->num_components; ci++) {
  163123. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163124. prep->next_buf_row, prep->next_buf_stop);
  163125. }
  163126. prep->next_buf_row = prep->next_buf_stop;
  163127. }
  163128. }
  163129. /* If we've gotten enough data, downsample a row group. */
  163130. if (prep->next_buf_row == prep->next_buf_stop) {
  163131. (*cinfo->downsample->downsample) (cinfo,
  163132. prep->color_buf,
  163133. (JDIMENSION) prep->this_row_group,
  163134. output_buf, *out_row_group_ctr);
  163135. (*out_row_group_ctr)++;
  163136. /* Advance pointers with wraparound as necessary. */
  163137. prep->this_row_group += cinfo->max_v_samp_factor;
  163138. if (prep->this_row_group >= buf_height)
  163139. prep->this_row_group = 0;
  163140. if (prep->next_buf_row >= buf_height)
  163141. prep->next_buf_row = 0;
  163142. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  163143. }
  163144. }
  163145. }
  163146. /*
  163147. * Create the wrapped-around downsampling input buffer needed for context mode.
  163148. */
  163149. LOCAL(void)
  163150. create_context_buffer (j_compress_ptr cinfo)
  163151. {
  163152. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163153. int rgroup_height = cinfo->max_v_samp_factor;
  163154. int ci, i;
  163155. jpeg_component_info * compptr;
  163156. JSAMPARRAY true_buffer, fake_buffer;
  163157. /* Grab enough space for fake row pointers for all the components;
  163158. * we need five row groups' worth of pointers for each component.
  163159. */
  163160. fake_buffer = (JSAMPARRAY)
  163161. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163162. (cinfo->num_components * 5 * rgroup_height) *
  163163. SIZEOF(JSAMPROW));
  163164. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163165. ci++, compptr++) {
  163166. /* Allocate the actual buffer space (3 row groups) for this component.
  163167. * We make the buffer wide enough to allow the downsampler to edge-expand
  163168. * horizontally within the buffer, if it so chooses.
  163169. */
  163170. true_buffer = (*cinfo->mem->alloc_sarray)
  163171. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163172. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163173. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163174. (JDIMENSION) (3 * rgroup_height));
  163175. /* Copy true buffer row pointers into the middle of the fake row array */
  163176. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  163177. 3 * rgroup_height * SIZEOF(JSAMPROW));
  163178. /* Fill in the above and below wraparound pointers */
  163179. for (i = 0; i < rgroup_height; i++) {
  163180. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  163181. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  163182. }
  163183. prep->color_buf[ci] = fake_buffer + rgroup_height;
  163184. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  163185. }
  163186. }
  163187. #endif /* CONTEXT_ROWS_SUPPORTED */
  163188. /*
  163189. * Initialize preprocessing controller.
  163190. */
  163191. GLOBAL(void)
  163192. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163193. {
  163194. my_prep_ptr prep;
  163195. int ci;
  163196. jpeg_component_info * compptr;
  163197. if (need_full_buffer) /* safety check */
  163198. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163199. prep = (my_prep_ptr)
  163200. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163201. SIZEOF(my_prep_controller));
  163202. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  163203. prep->pub.start_pass = start_pass_prep;
  163204. /* Allocate the color conversion buffer.
  163205. * We make the buffer wide enough to allow the downsampler to edge-expand
  163206. * horizontally within the buffer, if it so chooses.
  163207. */
  163208. if (cinfo->downsample->need_context_rows) {
  163209. /* Set up to provide context rows */
  163210. #ifdef CONTEXT_ROWS_SUPPORTED
  163211. prep->pub.pre_process_data = pre_process_context;
  163212. create_context_buffer(cinfo);
  163213. #else
  163214. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163215. #endif
  163216. } else {
  163217. /* No context, just make it tall enough for one row group */
  163218. prep->pub.pre_process_data = pre_process_data;
  163219. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163220. ci++, compptr++) {
  163221. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  163222. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163223. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163224. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163225. (JDIMENSION) cinfo->max_v_samp_factor);
  163226. }
  163227. }
  163228. }
  163229. /*** End of inlined file: jcprepct.c ***/
  163230. /*** Start of inlined file: jcsample.c ***/
  163231. #define JPEG_INTERNALS
  163232. /* Pointer to routine to downsample a single component */
  163233. typedef JMETHOD(void, downsample1_ptr,
  163234. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163235. JSAMPARRAY input_data, JSAMPARRAY output_data));
  163236. /* Private subobject */
  163237. typedef struct {
  163238. struct jpeg_downsampler pub; /* public fields */
  163239. /* Downsampling method pointers, one per component */
  163240. downsample1_ptr methods[MAX_COMPONENTS];
  163241. } my_downsampler;
  163242. typedef my_downsampler * my_downsample_ptr;
  163243. /*
  163244. * Initialize for a downsampling pass.
  163245. */
  163246. METHODDEF(void)
  163247. start_pass_downsample (j_compress_ptr)
  163248. {
  163249. /* no work for now */
  163250. }
  163251. /*
  163252. * Expand a component horizontally from width input_cols to width output_cols,
  163253. * by duplicating the rightmost samples.
  163254. */
  163255. LOCAL(void)
  163256. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  163257. JDIMENSION input_cols, JDIMENSION output_cols)
  163258. {
  163259. register JSAMPROW ptr;
  163260. register JSAMPLE pixval;
  163261. register int count;
  163262. int row;
  163263. int numcols = (int) (output_cols - input_cols);
  163264. if (numcols > 0) {
  163265. for (row = 0; row < num_rows; row++) {
  163266. ptr = image_data[row] + input_cols;
  163267. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  163268. for (count = numcols; count > 0; count--)
  163269. *ptr++ = pixval;
  163270. }
  163271. }
  163272. }
  163273. /*
  163274. * Do downsampling for a whole row group (all components).
  163275. *
  163276. * In this version we simply downsample each component independently.
  163277. */
  163278. METHODDEF(void)
  163279. sep_downsample (j_compress_ptr cinfo,
  163280. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  163281. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  163282. {
  163283. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  163284. int ci;
  163285. jpeg_component_info * compptr;
  163286. JSAMPARRAY in_ptr, out_ptr;
  163287. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163288. ci++, compptr++) {
  163289. in_ptr = input_buf[ci] + in_row_index;
  163290. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  163291. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  163292. }
  163293. }
  163294. /*
  163295. * Downsample pixel values of a single component.
  163296. * One row group is processed per call.
  163297. * This version handles arbitrary integral sampling ratios, without smoothing.
  163298. * Note that this version is not actually used for customary sampling ratios.
  163299. */
  163300. METHODDEF(void)
  163301. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163302. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163303. {
  163304. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  163305. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  163306. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163307. JSAMPROW inptr, outptr;
  163308. INT32 outvalue;
  163309. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  163310. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  163311. numpix = h_expand * v_expand;
  163312. numpix2 = numpix/2;
  163313. /* Expand input data enough to let all the output samples be generated
  163314. * by the standard loop. Special-casing padded output would be more
  163315. * efficient.
  163316. */
  163317. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163318. cinfo->image_width, output_cols * h_expand);
  163319. inrow = 0;
  163320. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163321. outptr = output_data[outrow];
  163322. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  163323. outcol++, outcol_h += h_expand) {
  163324. outvalue = 0;
  163325. for (v = 0; v < v_expand; v++) {
  163326. inptr = input_data[inrow+v] + outcol_h;
  163327. for (h = 0; h < h_expand; h++) {
  163328. outvalue += (INT32) GETJSAMPLE(*inptr++);
  163329. }
  163330. }
  163331. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  163332. }
  163333. inrow += v_expand;
  163334. }
  163335. }
  163336. /*
  163337. * Downsample pixel values of a single component.
  163338. * This version handles the special case of a full-size component,
  163339. * without smoothing.
  163340. */
  163341. METHODDEF(void)
  163342. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163343. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163344. {
  163345. /* Copy the data */
  163346. jcopy_sample_rows(input_data, 0, output_data, 0,
  163347. cinfo->max_v_samp_factor, cinfo->image_width);
  163348. /* Edge-expand */
  163349. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  163350. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  163351. }
  163352. /*
  163353. * Downsample pixel values of a single component.
  163354. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  163355. * without smoothing.
  163356. *
  163357. * A note about the "bias" calculations: when rounding fractional values to
  163358. * integer, we do not want to always round 0.5 up to the next integer.
  163359. * If we did that, we'd introduce a noticeable bias towards larger values.
  163360. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  163361. * alternate pixel locations (a simple ordered dither pattern).
  163362. */
  163363. METHODDEF(void)
  163364. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163365. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163366. {
  163367. int outrow;
  163368. JDIMENSION outcol;
  163369. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163370. register JSAMPROW inptr, outptr;
  163371. register int bias;
  163372. /* Expand input data enough to let all the output samples be generated
  163373. * by the standard loop. Special-casing padded output would be more
  163374. * efficient.
  163375. */
  163376. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163377. cinfo->image_width, output_cols * 2);
  163378. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163379. outptr = output_data[outrow];
  163380. inptr = input_data[outrow];
  163381. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  163382. for (outcol = 0; outcol < output_cols; outcol++) {
  163383. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  163384. + bias) >> 1);
  163385. bias ^= 1; /* 0=>1, 1=>0 */
  163386. inptr += 2;
  163387. }
  163388. }
  163389. }
  163390. /*
  163391. * Downsample pixel values of a single component.
  163392. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  163393. * without smoothing.
  163394. */
  163395. METHODDEF(void)
  163396. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163397. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163398. {
  163399. int inrow, outrow;
  163400. JDIMENSION outcol;
  163401. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163402. register JSAMPROW inptr0, inptr1, outptr;
  163403. register int bias;
  163404. /* Expand input data enough to let all the output samples be generated
  163405. * by the standard loop. Special-casing padded output would be more
  163406. * efficient.
  163407. */
  163408. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163409. cinfo->image_width, output_cols * 2);
  163410. inrow = 0;
  163411. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163412. outptr = output_data[outrow];
  163413. inptr0 = input_data[inrow];
  163414. inptr1 = input_data[inrow+1];
  163415. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  163416. for (outcol = 0; outcol < output_cols; outcol++) {
  163417. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163418. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  163419. + bias) >> 2);
  163420. bias ^= 3; /* 1=>2, 2=>1 */
  163421. inptr0 += 2; inptr1 += 2;
  163422. }
  163423. inrow += 2;
  163424. }
  163425. }
  163426. #ifdef INPUT_SMOOTHING_SUPPORTED
  163427. /*
  163428. * Downsample pixel values of a single component.
  163429. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  163430. * with smoothing. One row of context is required.
  163431. */
  163432. METHODDEF(void)
  163433. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163434. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163435. {
  163436. int inrow, outrow;
  163437. JDIMENSION colctr;
  163438. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163439. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  163440. INT32 membersum, neighsum, memberscale, neighscale;
  163441. /* Expand input data enough to let all the output samples be generated
  163442. * by the standard loop. Special-casing padded output would be more
  163443. * efficient.
  163444. */
  163445. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  163446. cinfo->image_width, output_cols * 2);
  163447. /* We don't bother to form the individual "smoothed" input pixel values;
  163448. * we can directly compute the output which is the average of the four
  163449. * smoothed values. Each of the four member pixels contributes a fraction
  163450. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  163451. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  163452. * output. The four corner-adjacent neighbor pixels contribute a fraction
  163453. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  163454. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  163455. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  163456. * factors are scaled by 2^16 = 65536.
  163457. * Also recall that SF = smoothing_factor / 1024.
  163458. */
  163459. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  163460. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  163461. inrow = 0;
  163462. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163463. outptr = output_data[outrow];
  163464. inptr0 = input_data[inrow];
  163465. inptr1 = input_data[inrow+1];
  163466. above_ptr = input_data[inrow-1];
  163467. below_ptr = input_data[inrow+2];
  163468. /* Special case for first column: pretend column -1 is same as column 0 */
  163469. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163470. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163471. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163472. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163473. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  163474. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  163475. neighsum += neighsum;
  163476. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  163477. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  163478. membersum = membersum * memberscale + neighsum * neighscale;
  163479. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163480. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  163481. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  163482. /* sum of pixels directly mapped to this output element */
  163483. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163484. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163485. /* sum of edge-neighbor pixels */
  163486. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163487. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163488. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  163489. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  163490. /* The edge-neighbors count twice as much as corner-neighbors */
  163491. neighsum += neighsum;
  163492. /* Add in the corner-neighbors */
  163493. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  163494. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  163495. /* form final output scaled up by 2^16 */
  163496. membersum = membersum * memberscale + neighsum * neighscale;
  163497. /* round, descale and output it */
  163498. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163499. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  163500. }
  163501. /* Special case for last column */
  163502. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163503. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163504. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163505. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163506. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  163507. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  163508. neighsum += neighsum;
  163509. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  163510. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  163511. membersum = membersum * memberscale + neighsum * neighscale;
  163512. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  163513. inrow += 2;
  163514. }
  163515. }
  163516. /*
  163517. * Downsample pixel values of a single component.
  163518. * This version handles the special case of a full-size component,
  163519. * with smoothing. One row of context is required.
  163520. */
  163521. METHODDEF(void)
  163522. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  163523. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163524. {
  163525. int outrow;
  163526. JDIMENSION colctr;
  163527. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163528. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  163529. INT32 membersum, neighsum, memberscale, neighscale;
  163530. int colsum, lastcolsum, nextcolsum;
  163531. /* Expand input data enough to let all the output samples be generated
  163532. * by the standard loop. Special-casing padded output would be more
  163533. * efficient.
  163534. */
  163535. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  163536. cinfo->image_width, output_cols);
  163537. /* Each of the eight neighbor pixels contributes a fraction SF to the
  163538. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  163539. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  163540. * Also recall that SF = smoothing_factor / 1024.
  163541. */
  163542. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  163543. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  163544. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163545. outptr = output_data[outrow];
  163546. inptr = input_data[outrow];
  163547. above_ptr = input_data[outrow-1];
  163548. below_ptr = input_data[outrow+1];
  163549. /* Special case for first column */
  163550. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  163551. GETJSAMPLE(*inptr);
  163552. membersum = GETJSAMPLE(*inptr++);
  163553. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  163554. GETJSAMPLE(*inptr);
  163555. neighsum = colsum + (colsum - membersum) + nextcolsum;
  163556. membersum = membersum * memberscale + neighsum * neighscale;
  163557. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163558. lastcolsum = colsum; colsum = nextcolsum;
  163559. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  163560. membersum = GETJSAMPLE(*inptr++);
  163561. above_ptr++; below_ptr++;
  163562. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  163563. GETJSAMPLE(*inptr);
  163564. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  163565. membersum = membersum * memberscale + neighsum * neighscale;
  163566. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163567. lastcolsum = colsum; colsum = nextcolsum;
  163568. }
  163569. /* Special case for last column */
  163570. membersum = GETJSAMPLE(*inptr);
  163571. neighsum = lastcolsum + (colsum - membersum) + colsum;
  163572. membersum = membersum * memberscale + neighsum * neighscale;
  163573. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  163574. }
  163575. }
  163576. #endif /* INPUT_SMOOTHING_SUPPORTED */
  163577. /*
  163578. * Module initialization routine for downsampling.
  163579. * Note that we must select a routine for each component.
  163580. */
  163581. GLOBAL(void)
  163582. jinit_downsampler (j_compress_ptr cinfo)
  163583. {
  163584. my_downsample_ptr downsample;
  163585. int ci;
  163586. jpeg_component_info * compptr;
  163587. boolean smoothok = TRUE;
  163588. downsample = (my_downsample_ptr)
  163589. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163590. SIZEOF(my_downsampler));
  163591. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  163592. downsample->pub.start_pass = start_pass_downsample;
  163593. downsample->pub.downsample = sep_downsample;
  163594. downsample->pub.need_context_rows = FALSE;
  163595. if (cinfo->CCIR601_sampling)
  163596. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  163597. /* Verify we can handle the sampling factors, and set up method pointers */
  163598. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163599. ci++, compptr++) {
  163600. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  163601. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  163602. #ifdef INPUT_SMOOTHING_SUPPORTED
  163603. if (cinfo->smoothing_factor) {
  163604. downsample->methods[ci] = fullsize_smooth_downsample;
  163605. downsample->pub.need_context_rows = TRUE;
  163606. } else
  163607. #endif
  163608. downsample->methods[ci] = fullsize_downsample;
  163609. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  163610. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  163611. smoothok = FALSE;
  163612. downsample->methods[ci] = h2v1_downsample;
  163613. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  163614. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  163615. #ifdef INPUT_SMOOTHING_SUPPORTED
  163616. if (cinfo->smoothing_factor) {
  163617. downsample->methods[ci] = h2v2_smooth_downsample;
  163618. downsample->pub.need_context_rows = TRUE;
  163619. } else
  163620. #endif
  163621. downsample->methods[ci] = h2v2_downsample;
  163622. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  163623. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  163624. smoothok = FALSE;
  163625. downsample->methods[ci] = int_downsample;
  163626. } else
  163627. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  163628. }
  163629. #ifdef INPUT_SMOOTHING_SUPPORTED
  163630. if (cinfo->smoothing_factor && !smoothok)
  163631. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  163632. #endif
  163633. }
  163634. /*** End of inlined file: jcsample.c ***/
  163635. /*** Start of inlined file: jctrans.c ***/
  163636. #define JPEG_INTERNALS
  163637. /* Forward declarations */
  163638. LOCAL(void) transencode_master_selection
  163639. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  163640. LOCAL(void) transencode_coef_controller
  163641. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  163642. /*
  163643. * Compression initialization for writing raw-coefficient data.
  163644. * Before calling this, all parameters and a data destination must be set up.
  163645. * Call jpeg_finish_compress() to actually write the data.
  163646. *
  163647. * The number of passed virtual arrays must match cinfo->num_components.
  163648. * Note that the virtual arrays need not be filled or even realized at
  163649. * the time write_coefficients is called; indeed, if the virtual arrays
  163650. * were requested from this compression object's memory manager, they
  163651. * typically will be realized during this routine and filled afterwards.
  163652. */
  163653. GLOBAL(void)
  163654. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  163655. {
  163656. if (cinfo->global_state != CSTATE_START)
  163657. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163658. /* Mark all tables to be written */
  163659. jpeg_suppress_tables(cinfo, FALSE);
  163660. /* (Re)initialize error mgr and destination modules */
  163661. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  163662. (*cinfo->dest->init_destination) (cinfo);
  163663. /* Perform master selection of active modules */
  163664. transencode_master_selection(cinfo, coef_arrays);
  163665. /* Wait for jpeg_finish_compress() call */
  163666. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  163667. cinfo->global_state = CSTATE_WRCOEFS;
  163668. }
  163669. /*
  163670. * Initialize the compression object with default parameters,
  163671. * then copy from the source object all parameters needed for lossless
  163672. * transcoding. Parameters that can be varied without loss (such as
  163673. * scan script and Huffman optimization) are left in their default states.
  163674. */
  163675. GLOBAL(void)
  163676. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  163677. j_compress_ptr dstinfo)
  163678. {
  163679. JQUANT_TBL ** qtblptr;
  163680. jpeg_component_info *incomp, *outcomp;
  163681. JQUANT_TBL *c_quant, *slot_quant;
  163682. int tblno, ci, coefi;
  163683. /* Safety check to ensure start_compress not called yet. */
  163684. if (dstinfo->global_state != CSTATE_START)
  163685. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  163686. /* Copy fundamental image dimensions */
  163687. dstinfo->image_width = srcinfo->image_width;
  163688. dstinfo->image_height = srcinfo->image_height;
  163689. dstinfo->input_components = srcinfo->num_components;
  163690. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  163691. /* Initialize all parameters to default values */
  163692. jpeg_set_defaults(dstinfo);
  163693. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  163694. * Fix it to get the right header markers for the image colorspace.
  163695. */
  163696. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  163697. dstinfo->data_precision = srcinfo->data_precision;
  163698. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  163699. /* Copy the source's quantization tables. */
  163700. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  163701. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  163702. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  163703. if (*qtblptr == NULL)
  163704. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  163705. MEMCOPY((*qtblptr)->quantval,
  163706. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  163707. SIZEOF((*qtblptr)->quantval));
  163708. (*qtblptr)->sent_table = FALSE;
  163709. }
  163710. }
  163711. /* Copy the source's per-component info.
  163712. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  163713. */
  163714. dstinfo->num_components = srcinfo->num_components;
  163715. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  163716. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  163717. MAX_COMPONENTS);
  163718. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  163719. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  163720. outcomp->component_id = incomp->component_id;
  163721. outcomp->h_samp_factor = incomp->h_samp_factor;
  163722. outcomp->v_samp_factor = incomp->v_samp_factor;
  163723. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  163724. /* Make sure saved quantization table for component matches the qtable
  163725. * slot. If not, the input file re-used this qtable slot.
  163726. * IJG encoder currently cannot duplicate this.
  163727. */
  163728. tblno = outcomp->quant_tbl_no;
  163729. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  163730. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  163731. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  163732. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  163733. c_quant = incomp->quant_table;
  163734. if (c_quant != NULL) {
  163735. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  163736. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  163737. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  163738. }
  163739. }
  163740. /* Note: we do not copy the source's Huffman table assignments;
  163741. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  163742. */
  163743. }
  163744. /* Also copy JFIF version and resolution information, if available.
  163745. * Strictly speaking this isn't "critical" info, but it's nearly
  163746. * always appropriate to copy it if available. In particular,
  163747. * if the application chooses to copy JFIF 1.02 extension markers from
  163748. * the source file, we need to copy the version to make sure we don't
  163749. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  163750. * We will *not*, however, copy version info from mislabeled "2.01" files.
  163751. */
  163752. if (srcinfo->saw_JFIF_marker) {
  163753. if (srcinfo->JFIF_major_version == 1) {
  163754. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  163755. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  163756. }
  163757. dstinfo->density_unit = srcinfo->density_unit;
  163758. dstinfo->X_density = srcinfo->X_density;
  163759. dstinfo->Y_density = srcinfo->Y_density;
  163760. }
  163761. }
  163762. /*
  163763. * Master selection of compression modules for transcoding.
  163764. * This substitutes for jcinit.c's initialization of the full compressor.
  163765. */
  163766. LOCAL(void)
  163767. transencode_master_selection (j_compress_ptr cinfo,
  163768. jvirt_barray_ptr * coef_arrays)
  163769. {
  163770. /* Although we don't actually use input_components for transcoding,
  163771. * jcmaster.c's initial_setup will complain if input_components is 0.
  163772. */
  163773. cinfo->input_components = 1;
  163774. /* Initialize master control (includes parameter checking/processing) */
  163775. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  163776. /* Entropy encoding: either Huffman or arithmetic coding. */
  163777. if (cinfo->arith_code) {
  163778. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163779. } else {
  163780. if (cinfo->progressive_mode) {
  163781. #ifdef C_PROGRESSIVE_SUPPORTED
  163782. jinit_phuff_encoder(cinfo);
  163783. #else
  163784. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163785. #endif
  163786. } else
  163787. jinit_huff_encoder(cinfo);
  163788. }
  163789. /* We need a special coefficient buffer controller. */
  163790. transencode_coef_controller(cinfo, coef_arrays);
  163791. jinit_marker_writer(cinfo);
  163792. /* We can now tell the memory manager to allocate virtual arrays. */
  163793. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163794. /* Write the datastream header (SOI, JFIF) immediately.
  163795. * Frame and scan headers are postponed till later.
  163796. * This lets application insert special markers after the SOI.
  163797. */
  163798. (*cinfo->marker->write_file_header) (cinfo);
  163799. }
  163800. /*
  163801. * The rest of this file is a special implementation of the coefficient
  163802. * buffer controller. This is similar to jccoefct.c, but it handles only
  163803. * output from presupplied virtual arrays. Furthermore, we generate any
  163804. * dummy padding blocks on-the-fly rather than expecting them to be present
  163805. * in the arrays.
  163806. */
  163807. /* Private buffer controller object */
  163808. typedef struct {
  163809. struct jpeg_c_coef_controller pub; /* public fields */
  163810. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  163811. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  163812. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  163813. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  163814. /* Virtual block array for each component. */
  163815. jvirt_barray_ptr * whole_image;
  163816. /* Workspace for constructing dummy blocks at right/bottom edges. */
  163817. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  163818. } my_coef_controller2;
  163819. typedef my_coef_controller2 * my_coef_ptr2;
  163820. LOCAL(void)
  163821. start_iMCU_row2 (j_compress_ptr cinfo)
  163822. /* Reset within-iMCU-row counters for a new row */
  163823. {
  163824. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163825. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  163826. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  163827. * But at the bottom of the image, process only what's left.
  163828. */
  163829. if (cinfo->comps_in_scan > 1) {
  163830. coef->MCU_rows_per_iMCU_row = 1;
  163831. } else {
  163832. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  163833. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  163834. else
  163835. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  163836. }
  163837. coef->mcu_ctr = 0;
  163838. coef->MCU_vert_offset = 0;
  163839. }
  163840. /*
  163841. * Initialize for a processing pass.
  163842. */
  163843. METHODDEF(void)
  163844. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163845. {
  163846. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163847. if (pass_mode != JBUF_CRANK_DEST)
  163848. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163849. coef->iMCU_row_num = 0;
  163850. start_iMCU_row2(cinfo);
  163851. }
  163852. /*
  163853. * Process some data.
  163854. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  163855. * per call, ie, v_samp_factor block rows for each component in the scan.
  163856. * The data is obtained from the virtual arrays and fed to the entropy coder.
  163857. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  163858. *
  163859. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  163860. */
  163861. METHODDEF(boolean)
  163862. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  163863. {
  163864. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163865. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163866. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163867. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163868. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  163869. JDIMENSION start_col;
  163870. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163871. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  163872. JBLOCKROW buffer_ptr;
  163873. jpeg_component_info *compptr;
  163874. /* Align the virtual buffers for the components used in this scan. */
  163875. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163876. compptr = cinfo->cur_comp_info[ci];
  163877. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163878. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163879. coef->iMCU_row_num * compptr->v_samp_factor,
  163880. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163881. }
  163882. /* Loop to process one whole iMCU row */
  163883. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163884. yoffset++) {
  163885. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163886. MCU_col_num++) {
  163887. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163888. blkn = 0; /* index of current DCT block within MCU */
  163889. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163890. compptr = cinfo->cur_comp_info[ci];
  163891. start_col = MCU_col_num * compptr->MCU_width;
  163892. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163893. : compptr->last_col_width;
  163894. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163895. if (coef->iMCU_row_num < last_iMCU_row ||
  163896. yindex+yoffset < compptr->last_row_height) {
  163897. /* Fill in pointers to real blocks in this row */
  163898. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163899. for (xindex = 0; xindex < blockcnt; xindex++)
  163900. MCU_buffer[blkn++] = buffer_ptr++;
  163901. } else {
  163902. /* At bottom of image, need a whole row of dummy blocks */
  163903. xindex = 0;
  163904. }
  163905. /* Fill in any dummy blocks needed in this row.
  163906. * Dummy blocks are filled in the same way as in jccoefct.c:
  163907. * all zeroes in the AC entries, DC entries equal to previous
  163908. * block's DC value. The init routine has already zeroed the
  163909. * AC entries, so we need only set the DC entries correctly.
  163910. */
  163911. for (; xindex < compptr->MCU_width; xindex++) {
  163912. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  163913. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  163914. blkn++;
  163915. }
  163916. }
  163917. }
  163918. /* Try to write the MCU. */
  163919. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  163920. /* Suspension forced; update state counters and exit */
  163921. coef->MCU_vert_offset = yoffset;
  163922. coef->mcu_ctr = MCU_col_num;
  163923. return FALSE;
  163924. }
  163925. }
  163926. /* Completed an MCU row, but perhaps not an iMCU row */
  163927. coef->mcu_ctr = 0;
  163928. }
  163929. /* Completed the iMCU row, advance counters for next one */
  163930. coef->iMCU_row_num++;
  163931. start_iMCU_row2(cinfo);
  163932. return TRUE;
  163933. }
  163934. /*
  163935. * Initialize coefficient buffer controller.
  163936. *
  163937. * Each passed coefficient array must be the right size for that
  163938. * coefficient: width_in_blocks wide and height_in_blocks high,
  163939. * with unitheight at least v_samp_factor.
  163940. */
  163941. LOCAL(void)
  163942. transencode_coef_controller (j_compress_ptr cinfo,
  163943. jvirt_barray_ptr * coef_arrays)
  163944. {
  163945. my_coef_ptr2 coef;
  163946. JBLOCKROW buffer;
  163947. int i;
  163948. coef = (my_coef_ptr2)
  163949. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163950. SIZEOF(my_coef_controller2));
  163951. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163952. coef->pub.start_pass = start_pass_coef2;
  163953. coef->pub.compress_data = compress_output2;
  163954. /* Save pointer to virtual arrays */
  163955. coef->whole_image = coef_arrays;
  163956. /* Allocate and pre-zero space for dummy DCT blocks. */
  163957. buffer = (JBLOCKROW)
  163958. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163959. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163960. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163961. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163962. coef->dummy_buffer[i] = buffer + i;
  163963. }
  163964. }
  163965. /*** End of inlined file: jctrans.c ***/
  163966. /*** Start of inlined file: jdapistd.c ***/
  163967. #define JPEG_INTERNALS
  163968. /* Forward declarations */
  163969. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  163970. /*
  163971. * Decompression initialization.
  163972. * jpeg_read_header must be completed before calling this.
  163973. *
  163974. * If a multipass operating mode was selected, this will do all but the
  163975. * last pass, and thus may take a great deal of time.
  163976. *
  163977. * Returns FALSE if suspended. The return value need be inspected only if
  163978. * a suspending data source is used.
  163979. */
  163980. GLOBAL(boolean)
  163981. jpeg_start_decompress (j_decompress_ptr cinfo)
  163982. {
  163983. if (cinfo->global_state == DSTATE_READY) {
  163984. /* First call: initialize master control, select active modules */
  163985. jinit_master_decompress(cinfo);
  163986. if (cinfo->buffered_image) {
  163987. /* No more work here; expecting jpeg_start_output next */
  163988. cinfo->global_state = DSTATE_BUFIMAGE;
  163989. return TRUE;
  163990. }
  163991. cinfo->global_state = DSTATE_PRELOAD;
  163992. }
  163993. if (cinfo->global_state == DSTATE_PRELOAD) {
  163994. /* If file has multiple scans, absorb them all into the coef buffer */
  163995. if (cinfo->inputctl->has_multiple_scans) {
  163996. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163997. for (;;) {
  163998. int retcode;
  163999. /* Call progress monitor hook if present */
  164000. if (cinfo->progress != NULL)
  164001. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164002. /* Absorb some more input */
  164003. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164004. if (retcode == JPEG_SUSPENDED)
  164005. return FALSE;
  164006. if (retcode == JPEG_REACHED_EOI)
  164007. break;
  164008. /* Advance progress counter if appropriate */
  164009. if (cinfo->progress != NULL &&
  164010. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  164011. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  164012. /* jdmaster underestimated number of scans; ratchet up one scan */
  164013. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  164014. }
  164015. }
  164016. }
  164017. #else
  164018. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164019. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164020. }
  164021. cinfo->output_scan_number = cinfo->input_scan_number;
  164022. } else if (cinfo->global_state != DSTATE_PRESCAN)
  164023. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164024. /* Perform any dummy output passes, and set up for the final pass */
  164025. return output_pass_setup(cinfo);
  164026. }
  164027. /*
  164028. * Set up for an output pass, and perform any dummy pass(es) needed.
  164029. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  164030. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  164031. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  164032. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  164033. */
  164034. LOCAL(boolean)
  164035. output_pass_setup (j_decompress_ptr cinfo)
  164036. {
  164037. if (cinfo->global_state != DSTATE_PRESCAN) {
  164038. /* First call: do pass setup */
  164039. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164040. cinfo->output_scanline = 0;
  164041. cinfo->global_state = DSTATE_PRESCAN;
  164042. }
  164043. /* Loop over any required dummy passes */
  164044. while (cinfo->master->is_dummy_pass) {
  164045. #ifdef QUANT_2PASS_SUPPORTED
  164046. /* Crank through the dummy pass */
  164047. while (cinfo->output_scanline < cinfo->output_height) {
  164048. JDIMENSION last_scanline;
  164049. /* Call progress monitor hook if present */
  164050. if (cinfo->progress != NULL) {
  164051. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164052. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164053. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164054. }
  164055. /* Process some data */
  164056. last_scanline = cinfo->output_scanline;
  164057. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  164058. &cinfo->output_scanline, (JDIMENSION) 0);
  164059. if (cinfo->output_scanline == last_scanline)
  164060. return FALSE; /* No progress made, must suspend */
  164061. }
  164062. /* Finish up dummy pass, and set up for another one */
  164063. (*cinfo->master->finish_output_pass) (cinfo);
  164064. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164065. cinfo->output_scanline = 0;
  164066. #else
  164067. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164068. #endif /* QUANT_2PASS_SUPPORTED */
  164069. }
  164070. /* Ready for application to drive output pass through
  164071. * jpeg_read_scanlines or jpeg_read_raw_data.
  164072. */
  164073. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  164074. return TRUE;
  164075. }
  164076. /*
  164077. * Read some scanlines of data from the JPEG decompressor.
  164078. *
  164079. * The return value will be the number of lines actually read.
  164080. * This may be less than the number requested in several cases,
  164081. * including bottom of image, data source suspension, and operating
  164082. * modes that emit multiple scanlines at a time.
  164083. *
  164084. * Note: we warn about excess calls to jpeg_read_scanlines() since
  164085. * this likely signals an application programmer error. However,
  164086. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  164087. */
  164088. GLOBAL(JDIMENSION)
  164089. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  164090. JDIMENSION max_lines)
  164091. {
  164092. JDIMENSION row_ctr;
  164093. if (cinfo->global_state != DSTATE_SCANNING)
  164094. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164095. if (cinfo->output_scanline >= cinfo->output_height) {
  164096. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164097. return 0;
  164098. }
  164099. /* Call progress monitor hook if present */
  164100. if (cinfo->progress != NULL) {
  164101. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164102. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164103. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164104. }
  164105. /* Process some data */
  164106. row_ctr = 0;
  164107. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  164108. cinfo->output_scanline += row_ctr;
  164109. return row_ctr;
  164110. }
  164111. /*
  164112. * Alternate entry point to read raw data.
  164113. * Processes exactly one iMCU row per call, unless suspended.
  164114. */
  164115. GLOBAL(JDIMENSION)
  164116. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  164117. JDIMENSION max_lines)
  164118. {
  164119. JDIMENSION lines_per_iMCU_row;
  164120. if (cinfo->global_state != DSTATE_RAW_OK)
  164121. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164122. if (cinfo->output_scanline >= cinfo->output_height) {
  164123. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164124. return 0;
  164125. }
  164126. /* Call progress monitor hook if present */
  164127. if (cinfo->progress != NULL) {
  164128. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164129. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164130. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164131. }
  164132. /* Verify that at least one iMCU row can be returned. */
  164133. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  164134. if (max_lines < lines_per_iMCU_row)
  164135. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  164136. /* Decompress directly into user's buffer. */
  164137. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  164138. return 0; /* suspension forced, can do nothing more */
  164139. /* OK, we processed one iMCU row. */
  164140. cinfo->output_scanline += lines_per_iMCU_row;
  164141. return lines_per_iMCU_row;
  164142. }
  164143. /* Additional entry points for buffered-image mode. */
  164144. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164145. /*
  164146. * Initialize for an output pass in buffered-image mode.
  164147. */
  164148. GLOBAL(boolean)
  164149. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  164150. {
  164151. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  164152. cinfo->global_state != DSTATE_PRESCAN)
  164153. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164154. /* Limit scan number to valid range */
  164155. if (scan_number <= 0)
  164156. scan_number = 1;
  164157. if (cinfo->inputctl->eoi_reached &&
  164158. scan_number > cinfo->input_scan_number)
  164159. scan_number = cinfo->input_scan_number;
  164160. cinfo->output_scan_number = scan_number;
  164161. /* Perform any dummy output passes, and set up for the real pass */
  164162. return output_pass_setup(cinfo);
  164163. }
  164164. /*
  164165. * Finish up after an output pass in buffered-image mode.
  164166. *
  164167. * Returns FALSE if suspended. The return value need be inspected only if
  164168. * a suspending data source is used.
  164169. */
  164170. GLOBAL(boolean)
  164171. jpeg_finish_output (j_decompress_ptr cinfo)
  164172. {
  164173. if ((cinfo->global_state == DSTATE_SCANNING ||
  164174. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  164175. /* Terminate this pass. */
  164176. /* We do not require the whole pass to have been completed. */
  164177. (*cinfo->master->finish_output_pass) (cinfo);
  164178. cinfo->global_state = DSTATE_BUFPOST;
  164179. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  164180. /* BUFPOST = repeat call after a suspension, anything else is error */
  164181. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164182. }
  164183. /* Read markers looking for SOS or EOI */
  164184. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164185. ! cinfo->inputctl->eoi_reached) {
  164186. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  164187. return FALSE; /* Suspend, come back later */
  164188. }
  164189. cinfo->global_state = DSTATE_BUFIMAGE;
  164190. return TRUE;
  164191. }
  164192. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164193. /*** End of inlined file: jdapistd.c ***/
  164194. /*** Start of inlined file: jdapimin.c ***/
  164195. #define JPEG_INTERNALS
  164196. /*
  164197. * Initialization of a JPEG decompression object.
  164198. * The error manager must already be set up (in case memory manager fails).
  164199. */
  164200. GLOBAL(void)
  164201. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  164202. {
  164203. int i;
  164204. /* Guard against version mismatches between library and caller. */
  164205. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  164206. if (version != JPEG_LIB_VERSION)
  164207. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  164208. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  164209. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  164210. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  164211. /* For debugging purposes, we zero the whole master structure.
  164212. * But the application has already set the err pointer, and may have set
  164213. * client_data, so we have to save and restore those fields.
  164214. * Note: if application hasn't set client_data, tools like Purify may
  164215. * complain here.
  164216. */
  164217. {
  164218. struct jpeg_error_mgr * err = cinfo->err;
  164219. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  164220. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  164221. cinfo->err = err;
  164222. cinfo->client_data = client_data;
  164223. }
  164224. cinfo->is_decompressor = TRUE;
  164225. /* Initialize a memory manager instance for this object */
  164226. jinit_memory_mgr((j_common_ptr) cinfo);
  164227. /* Zero out pointers to permanent structures. */
  164228. cinfo->progress = NULL;
  164229. cinfo->src = NULL;
  164230. for (i = 0; i < NUM_QUANT_TBLS; i++)
  164231. cinfo->quant_tbl_ptrs[i] = NULL;
  164232. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164233. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  164234. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  164235. }
  164236. /* Initialize marker processor so application can override methods
  164237. * for COM, APPn markers before calling jpeg_read_header.
  164238. */
  164239. cinfo->marker_list = NULL;
  164240. jinit_marker_reader(cinfo);
  164241. /* And initialize the overall input controller. */
  164242. jinit_input_controller(cinfo);
  164243. /* OK, I'm ready */
  164244. cinfo->global_state = DSTATE_START;
  164245. }
  164246. /*
  164247. * Destruction of a JPEG decompression object
  164248. */
  164249. GLOBAL(void)
  164250. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  164251. {
  164252. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  164253. }
  164254. /*
  164255. * Abort processing of a JPEG decompression operation,
  164256. * but don't destroy the object itself.
  164257. */
  164258. GLOBAL(void)
  164259. jpeg_abort_decompress (j_decompress_ptr cinfo)
  164260. {
  164261. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  164262. }
  164263. /*
  164264. * Set default decompression parameters.
  164265. */
  164266. LOCAL(void)
  164267. default_decompress_parms (j_decompress_ptr cinfo)
  164268. {
  164269. /* Guess the input colorspace, and set output colorspace accordingly. */
  164270. /* (Wish JPEG committee had provided a real way to specify this...) */
  164271. /* Note application may override our guesses. */
  164272. switch (cinfo->num_components) {
  164273. case 1:
  164274. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  164275. cinfo->out_color_space = JCS_GRAYSCALE;
  164276. break;
  164277. case 3:
  164278. if (cinfo->saw_JFIF_marker) {
  164279. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  164280. } else if (cinfo->saw_Adobe_marker) {
  164281. switch (cinfo->Adobe_transform) {
  164282. case 0:
  164283. cinfo->jpeg_color_space = JCS_RGB;
  164284. break;
  164285. case 1:
  164286. cinfo->jpeg_color_space = JCS_YCbCr;
  164287. break;
  164288. default:
  164289. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164290. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164291. break;
  164292. }
  164293. } else {
  164294. /* Saw no special markers, try to guess from the component IDs */
  164295. int cid0 = cinfo->comp_info[0].component_id;
  164296. int cid1 = cinfo->comp_info[1].component_id;
  164297. int cid2 = cinfo->comp_info[2].component_id;
  164298. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  164299. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  164300. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  164301. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  164302. else {
  164303. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  164304. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164305. }
  164306. }
  164307. /* Always guess RGB is proper output colorspace. */
  164308. cinfo->out_color_space = JCS_RGB;
  164309. break;
  164310. case 4:
  164311. if (cinfo->saw_Adobe_marker) {
  164312. switch (cinfo->Adobe_transform) {
  164313. case 0:
  164314. cinfo->jpeg_color_space = JCS_CMYK;
  164315. break;
  164316. case 2:
  164317. cinfo->jpeg_color_space = JCS_YCCK;
  164318. break;
  164319. default:
  164320. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164321. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  164322. break;
  164323. }
  164324. } else {
  164325. /* No special markers, assume straight CMYK. */
  164326. cinfo->jpeg_color_space = JCS_CMYK;
  164327. }
  164328. cinfo->out_color_space = JCS_CMYK;
  164329. break;
  164330. default:
  164331. cinfo->jpeg_color_space = JCS_UNKNOWN;
  164332. cinfo->out_color_space = JCS_UNKNOWN;
  164333. break;
  164334. }
  164335. /* Set defaults for other decompression parameters. */
  164336. cinfo->scale_num = 1; /* 1:1 scaling */
  164337. cinfo->scale_denom = 1;
  164338. cinfo->output_gamma = 1.0;
  164339. cinfo->buffered_image = FALSE;
  164340. cinfo->raw_data_out = FALSE;
  164341. cinfo->dct_method = JDCT_DEFAULT;
  164342. cinfo->do_fancy_upsampling = TRUE;
  164343. cinfo->do_block_smoothing = TRUE;
  164344. cinfo->quantize_colors = FALSE;
  164345. /* We set these in case application only sets quantize_colors. */
  164346. cinfo->dither_mode = JDITHER_FS;
  164347. #ifdef QUANT_2PASS_SUPPORTED
  164348. cinfo->two_pass_quantize = TRUE;
  164349. #else
  164350. cinfo->two_pass_quantize = FALSE;
  164351. #endif
  164352. cinfo->desired_number_of_colors = 256;
  164353. cinfo->colormap = NULL;
  164354. /* Initialize for no mode change in buffered-image mode. */
  164355. cinfo->enable_1pass_quant = FALSE;
  164356. cinfo->enable_external_quant = FALSE;
  164357. cinfo->enable_2pass_quant = FALSE;
  164358. }
  164359. /*
  164360. * Decompression startup: read start of JPEG datastream to see what's there.
  164361. * Need only initialize JPEG object and supply a data source before calling.
  164362. *
  164363. * This routine will read as far as the first SOS marker (ie, actual start of
  164364. * compressed data), and will save all tables and parameters in the JPEG
  164365. * object. It will also initialize the decompression parameters to default
  164366. * values, and finally return JPEG_HEADER_OK. On return, the application may
  164367. * adjust the decompression parameters and then call jpeg_start_decompress.
  164368. * (Or, if the application only wanted to determine the image parameters,
  164369. * the data need not be decompressed. In that case, call jpeg_abort or
  164370. * jpeg_destroy to release any temporary space.)
  164371. * If an abbreviated (tables only) datastream is presented, the routine will
  164372. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  164373. * re-use the JPEG object to read the abbreviated image datastream(s).
  164374. * It is unnecessary (but OK) to call jpeg_abort in this case.
  164375. * The JPEG_SUSPENDED return code only occurs if the data source module
  164376. * requests suspension of the decompressor. In this case the application
  164377. * should load more source data and then re-call jpeg_read_header to resume
  164378. * processing.
  164379. * If a non-suspending data source is used and require_image is TRUE, then the
  164380. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  164381. *
  164382. * This routine is now just a front end to jpeg_consume_input, with some
  164383. * extra error checking.
  164384. */
  164385. GLOBAL(int)
  164386. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  164387. {
  164388. int retcode;
  164389. if (cinfo->global_state != DSTATE_START &&
  164390. cinfo->global_state != DSTATE_INHEADER)
  164391. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164392. retcode = jpeg_consume_input(cinfo);
  164393. switch (retcode) {
  164394. case JPEG_REACHED_SOS:
  164395. retcode = JPEG_HEADER_OK;
  164396. break;
  164397. case JPEG_REACHED_EOI:
  164398. if (require_image) /* Complain if application wanted an image */
  164399. ERREXIT(cinfo, JERR_NO_IMAGE);
  164400. /* Reset to start state; it would be safer to require the application to
  164401. * call jpeg_abort, but we can't change it now for compatibility reasons.
  164402. * A side effect is to free any temporary memory (there shouldn't be any).
  164403. */
  164404. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  164405. retcode = JPEG_HEADER_TABLES_ONLY;
  164406. break;
  164407. case JPEG_SUSPENDED:
  164408. /* no work */
  164409. break;
  164410. }
  164411. return retcode;
  164412. }
  164413. /*
  164414. * Consume data in advance of what the decompressor requires.
  164415. * This can be called at any time once the decompressor object has
  164416. * been created and a data source has been set up.
  164417. *
  164418. * This routine is essentially a state machine that handles a couple
  164419. * of critical state-transition actions, namely initial setup and
  164420. * transition from header scanning to ready-for-start_decompress.
  164421. * All the actual input is done via the input controller's consume_input
  164422. * method.
  164423. */
  164424. GLOBAL(int)
  164425. jpeg_consume_input (j_decompress_ptr cinfo)
  164426. {
  164427. int retcode = JPEG_SUSPENDED;
  164428. /* NB: every possible DSTATE value should be listed in this switch */
  164429. switch (cinfo->global_state) {
  164430. case DSTATE_START:
  164431. /* Start-of-datastream actions: reset appropriate modules */
  164432. (*cinfo->inputctl->reset_input_controller) (cinfo);
  164433. /* Initialize application's data source module */
  164434. (*cinfo->src->init_source) (cinfo);
  164435. cinfo->global_state = DSTATE_INHEADER;
  164436. /*FALLTHROUGH*/
  164437. case DSTATE_INHEADER:
  164438. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164439. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  164440. /* Set up default parameters based on header data */
  164441. default_decompress_parms(cinfo);
  164442. /* Set global state: ready for start_decompress */
  164443. cinfo->global_state = DSTATE_READY;
  164444. }
  164445. break;
  164446. case DSTATE_READY:
  164447. /* Can't advance past first SOS until start_decompress is called */
  164448. retcode = JPEG_REACHED_SOS;
  164449. break;
  164450. case DSTATE_PRELOAD:
  164451. case DSTATE_PRESCAN:
  164452. case DSTATE_SCANNING:
  164453. case DSTATE_RAW_OK:
  164454. case DSTATE_BUFIMAGE:
  164455. case DSTATE_BUFPOST:
  164456. case DSTATE_STOPPING:
  164457. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164458. break;
  164459. default:
  164460. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164461. }
  164462. return retcode;
  164463. }
  164464. /*
  164465. * Have we finished reading the input file?
  164466. */
  164467. GLOBAL(boolean)
  164468. jpeg_input_complete (j_decompress_ptr cinfo)
  164469. {
  164470. /* Check for valid jpeg object */
  164471. if (cinfo->global_state < DSTATE_START ||
  164472. cinfo->global_state > DSTATE_STOPPING)
  164473. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164474. return cinfo->inputctl->eoi_reached;
  164475. }
  164476. /*
  164477. * Is there more than one scan?
  164478. */
  164479. GLOBAL(boolean)
  164480. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  164481. {
  164482. /* Only valid after jpeg_read_header completes */
  164483. if (cinfo->global_state < DSTATE_READY ||
  164484. cinfo->global_state > DSTATE_STOPPING)
  164485. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164486. return cinfo->inputctl->has_multiple_scans;
  164487. }
  164488. /*
  164489. * Finish JPEG decompression.
  164490. *
  164491. * This will normally just verify the file trailer and release temp storage.
  164492. *
  164493. * Returns FALSE if suspended. The return value need be inspected only if
  164494. * a suspending data source is used.
  164495. */
  164496. GLOBAL(boolean)
  164497. jpeg_finish_decompress (j_decompress_ptr cinfo)
  164498. {
  164499. if ((cinfo->global_state == DSTATE_SCANNING ||
  164500. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  164501. /* Terminate final pass of non-buffered mode */
  164502. if (cinfo->output_scanline < cinfo->output_height)
  164503. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  164504. (*cinfo->master->finish_output_pass) (cinfo);
  164505. cinfo->global_state = DSTATE_STOPPING;
  164506. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  164507. /* Finishing after a buffered-image operation */
  164508. cinfo->global_state = DSTATE_STOPPING;
  164509. } else if (cinfo->global_state != DSTATE_STOPPING) {
  164510. /* STOPPING = repeat call after a suspension, anything else is error */
  164511. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164512. }
  164513. /* Read until EOI */
  164514. while (! cinfo->inputctl->eoi_reached) {
  164515. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  164516. return FALSE; /* Suspend, come back later */
  164517. }
  164518. /* Do final cleanup */
  164519. (*cinfo->src->term_source) (cinfo);
  164520. /* We can use jpeg_abort to release memory and reset global_state */
  164521. jpeg_abort((j_common_ptr) cinfo);
  164522. return TRUE;
  164523. }
  164524. /*** End of inlined file: jdapimin.c ***/
  164525. /*** Start of inlined file: jdatasrc.c ***/
  164526. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  164527. /*** Start of inlined file: jerror.h ***/
  164528. /*
  164529. * To define the enum list of message codes, include this file without
  164530. * defining macro JMESSAGE. To create a message string table, include it
  164531. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  164532. */
  164533. #ifndef JMESSAGE
  164534. #ifndef JERROR_H
  164535. /* First time through, define the enum list */
  164536. #define JMAKE_ENUM_LIST
  164537. #else
  164538. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  164539. #define JMESSAGE(code,string)
  164540. #endif /* JERROR_H */
  164541. #endif /* JMESSAGE */
  164542. #ifdef JMAKE_ENUM_LIST
  164543. typedef enum {
  164544. #define JMESSAGE(code,string) code ,
  164545. #endif /* JMAKE_ENUM_LIST */
  164546. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  164547. /* For maintenance convenience, list is alphabetical by message code name */
  164548. JMESSAGE(JERR_ARITH_NOTIMPL,
  164549. "Sorry, there are legal restrictions on arithmetic coding")
  164550. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  164551. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  164552. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  164553. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  164554. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  164555. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  164556. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  164557. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  164558. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  164559. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  164560. JMESSAGE(JERR_BAD_LIB_VERSION,
  164561. "Wrong JPEG library version: library is %d, caller expects %d")
  164562. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  164563. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  164564. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  164565. JMESSAGE(JERR_BAD_PROGRESSION,
  164566. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  164567. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  164568. "Invalid progressive parameters at scan script entry %d")
  164569. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  164570. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  164571. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  164572. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  164573. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  164574. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  164575. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  164576. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  164577. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  164578. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  164579. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  164580. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  164581. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  164582. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  164583. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  164584. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  164585. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  164586. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  164587. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  164588. JMESSAGE(JERR_FILE_READ, "Input file read error")
  164589. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  164590. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  164591. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  164592. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  164593. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  164594. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  164595. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  164596. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  164597. "Cannot transcode due to multiple use of quantization table %d")
  164598. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  164599. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  164600. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  164601. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  164602. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  164603. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  164604. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  164605. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  164606. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  164607. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  164608. JMESSAGE(JERR_QUANT_COMPONENTS,
  164609. "Cannot quantize more than %d color components")
  164610. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  164611. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  164612. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  164613. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  164614. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  164615. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  164616. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  164617. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  164618. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  164619. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  164620. JMESSAGE(JERR_TFILE_WRITE,
  164621. "Write failed on temporary file --- out of disk space?")
  164622. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  164623. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  164624. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  164625. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  164626. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  164627. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  164628. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  164629. JMESSAGE(JMSG_VERSION, JVERSION)
  164630. JMESSAGE(JTRC_16BIT_TABLES,
  164631. "Caution: quantization tables are too coarse for baseline JPEG")
  164632. JMESSAGE(JTRC_ADOBE,
  164633. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  164634. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  164635. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  164636. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  164637. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  164638. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  164639. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  164640. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  164641. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  164642. JMESSAGE(JTRC_EOI, "End Of Image")
  164643. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  164644. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  164645. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  164646. "Warning: thumbnail image size does not match data length %u")
  164647. JMESSAGE(JTRC_JFIF_EXTENSION,
  164648. "JFIF extension marker: type 0x%02x, length %u")
  164649. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  164650. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  164651. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  164652. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  164653. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  164654. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  164655. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  164656. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  164657. JMESSAGE(JTRC_RST, "RST%d")
  164658. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  164659. "Smoothing not supported with nonstandard sampling ratios")
  164660. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  164661. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  164662. JMESSAGE(JTRC_SOI, "Start of Image")
  164663. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  164664. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  164665. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  164666. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  164667. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  164668. JMESSAGE(JTRC_THUMB_JPEG,
  164669. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  164670. JMESSAGE(JTRC_THUMB_PALETTE,
  164671. "JFIF extension marker: palette thumbnail image, length %u")
  164672. JMESSAGE(JTRC_THUMB_RGB,
  164673. "JFIF extension marker: RGB thumbnail image, length %u")
  164674. JMESSAGE(JTRC_UNKNOWN_IDS,
  164675. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  164676. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  164677. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  164678. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  164679. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  164680. "Inconsistent progression sequence for component %d coefficient %d")
  164681. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  164682. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  164683. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  164684. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  164685. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  164686. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  164687. JMESSAGE(JWRN_MUST_RESYNC,
  164688. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  164689. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  164690. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  164691. #ifdef JMAKE_ENUM_LIST
  164692. JMSG_LASTMSGCODE
  164693. } J_MESSAGE_CODE;
  164694. #undef JMAKE_ENUM_LIST
  164695. #endif /* JMAKE_ENUM_LIST */
  164696. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  164697. #undef JMESSAGE
  164698. #ifndef JERROR_H
  164699. #define JERROR_H
  164700. /* Macros to simplify using the error and trace message stuff */
  164701. /* The first parameter is either type of cinfo pointer */
  164702. /* Fatal errors (print message and exit) */
  164703. #define ERREXIT(cinfo,code) \
  164704. ((cinfo)->err->msg_code = (code), \
  164705. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164706. #define ERREXIT1(cinfo,code,p1) \
  164707. ((cinfo)->err->msg_code = (code), \
  164708. (cinfo)->err->msg_parm.i[0] = (p1), \
  164709. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164710. #define ERREXIT2(cinfo,code,p1,p2) \
  164711. ((cinfo)->err->msg_code = (code), \
  164712. (cinfo)->err->msg_parm.i[0] = (p1), \
  164713. (cinfo)->err->msg_parm.i[1] = (p2), \
  164714. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164715. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  164716. ((cinfo)->err->msg_code = (code), \
  164717. (cinfo)->err->msg_parm.i[0] = (p1), \
  164718. (cinfo)->err->msg_parm.i[1] = (p2), \
  164719. (cinfo)->err->msg_parm.i[2] = (p3), \
  164720. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164721. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  164722. ((cinfo)->err->msg_code = (code), \
  164723. (cinfo)->err->msg_parm.i[0] = (p1), \
  164724. (cinfo)->err->msg_parm.i[1] = (p2), \
  164725. (cinfo)->err->msg_parm.i[2] = (p3), \
  164726. (cinfo)->err->msg_parm.i[3] = (p4), \
  164727. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164728. #define ERREXITS(cinfo,code,str) \
  164729. ((cinfo)->err->msg_code = (code), \
  164730. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  164731. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164732. #define MAKESTMT(stuff) do { stuff } while (0)
  164733. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  164734. #define WARNMS(cinfo,code) \
  164735. ((cinfo)->err->msg_code = (code), \
  164736. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164737. #define WARNMS1(cinfo,code,p1) \
  164738. ((cinfo)->err->msg_code = (code), \
  164739. (cinfo)->err->msg_parm.i[0] = (p1), \
  164740. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164741. #define WARNMS2(cinfo,code,p1,p2) \
  164742. ((cinfo)->err->msg_code = (code), \
  164743. (cinfo)->err->msg_parm.i[0] = (p1), \
  164744. (cinfo)->err->msg_parm.i[1] = (p2), \
  164745. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164746. /* Informational/debugging messages */
  164747. #define TRACEMS(cinfo,lvl,code) \
  164748. ((cinfo)->err->msg_code = (code), \
  164749. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164750. #define TRACEMS1(cinfo,lvl,code,p1) \
  164751. ((cinfo)->err->msg_code = (code), \
  164752. (cinfo)->err->msg_parm.i[0] = (p1), \
  164753. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164754. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  164755. ((cinfo)->err->msg_code = (code), \
  164756. (cinfo)->err->msg_parm.i[0] = (p1), \
  164757. (cinfo)->err->msg_parm.i[1] = (p2), \
  164758. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164759. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  164760. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164761. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  164762. (cinfo)->err->msg_code = (code); \
  164763. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164764. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  164765. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164766. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164767. (cinfo)->err->msg_code = (code); \
  164768. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164769. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  164770. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164771. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164772. _mp[4] = (p5); \
  164773. (cinfo)->err->msg_code = (code); \
  164774. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164775. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  164776. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164777. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164778. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  164779. (cinfo)->err->msg_code = (code); \
  164780. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164781. #define TRACEMSS(cinfo,lvl,code,str) \
  164782. ((cinfo)->err->msg_code = (code), \
  164783. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  164784. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164785. #endif /* JERROR_H */
  164786. /*** End of inlined file: jerror.h ***/
  164787. /* Expanded data source object for stdio input */
  164788. typedef struct {
  164789. struct jpeg_source_mgr pub; /* public fields */
  164790. FILE * infile; /* source stream */
  164791. JOCTET * buffer; /* start of buffer */
  164792. boolean start_of_file; /* have we gotten any data yet? */
  164793. } my_source_mgr;
  164794. typedef my_source_mgr * my_src_ptr;
  164795. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  164796. /*
  164797. * Initialize source --- called by jpeg_read_header
  164798. * before any data is actually read.
  164799. */
  164800. METHODDEF(void)
  164801. init_source (j_decompress_ptr cinfo)
  164802. {
  164803. my_src_ptr src = (my_src_ptr) cinfo->src;
  164804. /* We reset the empty-input-file flag for each image,
  164805. * but we don't clear the input buffer.
  164806. * This is correct behavior for reading a series of images from one source.
  164807. */
  164808. src->start_of_file = TRUE;
  164809. }
  164810. /*
  164811. * Fill the input buffer --- called whenever buffer is emptied.
  164812. *
  164813. * In typical applications, this should read fresh data into the buffer
  164814. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  164815. * reset the pointer & count to the start of the buffer, and return TRUE
  164816. * indicating that the buffer has been reloaded. It is not necessary to
  164817. * fill the buffer entirely, only to obtain at least one more byte.
  164818. *
  164819. * There is no such thing as an EOF return. If the end of the file has been
  164820. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  164821. * the buffer. In most cases, generating a warning message and inserting a
  164822. * fake EOI marker is the best course of action --- this will allow the
  164823. * decompressor to output however much of the image is there. However,
  164824. * the resulting error message is misleading if the real problem is an empty
  164825. * input file, so we handle that case specially.
  164826. *
  164827. * In applications that need to be able to suspend compression due to input
  164828. * not being available yet, a FALSE return indicates that no more data can be
  164829. * obtained right now, but more may be forthcoming later. In this situation,
  164830. * the decompressor will return to its caller (with an indication of the
  164831. * number of scanlines it has read, if any). The application should resume
  164832. * decompression after it has loaded more data into the input buffer. Note
  164833. * that there are substantial restrictions on the use of suspension --- see
  164834. * the documentation.
  164835. *
  164836. * When suspending, the decompressor will back up to a convenient restart point
  164837. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  164838. * indicate where the restart point will be if the current call returns FALSE.
  164839. * Data beyond this point must be rescanned after resumption, so move it to
  164840. * the front of the buffer rather than discarding it.
  164841. */
  164842. METHODDEF(boolean)
  164843. fill_input_buffer (j_decompress_ptr cinfo)
  164844. {
  164845. my_src_ptr src = (my_src_ptr) cinfo->src;
  164846. size_t nbytes;
  164847. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  164848. if (nbytes <= 0) {
  164849. if (src->start_of_file) /* Treat empty input file as fatal error */
  164850. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  164851. WARNMS(cinfo, JWRN_JPEG_EOF);
  164852. /* Insert a fake EOI marker */
  164853. src->buffer[0] = (JOCTET) 0xFF;
  164854. src->buffer[1] = (JOCTET) JPEG_EOI;
  164855. nbytes = 2;
  164856. }
  164857. src->pub.next_input_byte = src->buffer;
  164858. src->pub.bytes_in_buffer = nbytes;
  164859. src->start_of_file = FALSE;
  164860. return TRUE;
  164861. }
  164862. /*
  164863. * Skip data --- used to skip over a potentially large amount of
  164864. * uninteresting data (such as an APPn marker).
  164865. *
  164866. * Writers of suspendable-input applications must note that skip_input_data
  164867. * is not granted the right to give a suspension return. If the skip extends
  164868. * beyond the data currently in the buffer, the buffer can be marked empty so
  164869. * that the next read will cause a fill_input_buffer call that can suspend.
  164870. * Arranging for additional bytes to be discarded before reloading the input
  164871. * buffer is the application writer's problem.
  164872. */
  164873. METHODDEF(void)
  164874. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  164875. {
  164876. my_src_ptr src = (my_src_ptr) cinfo->src;
  164877. /* Just a dumb implementation for now. Could use fseek() except
  164878. * it doesn't work on pipes. Not clear that being smart is worth
  164879. * any trouble anyway --- large skips are infrequent.
  164880. */
  164881. if (num_bytes > 0) {
  164882. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  164883. num_bytes -= (long) src->pub.bytes_in_buffer;
  164884. (void) fill_input_buffer(cinfo);
  164885. /* note we assume that fill_input_buffer will never return FALSE,
  164886. * so suspension need not be handled.
  164887. */
  164888. }
  164889. src->pub.next_input_byte += (size_t) num_bytes;
  164890. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  164891. }
  164892. }
  164893. /*
  164894. * An additional method that can be provided by data source modules is the
  164895. * resync_to_restart method for error recovery in the presence of RST markers.
  164896. * For the moment, this source module just uses the default resync method
  164897. * provided by the JPEG library. That method assumes that no backtracking
  164898. * is possible.
  164899. */
  164900. /*
  164901. * Terminate source --- called by jpeg_finish_decompress
  164902. * after all data has been read. Often a no-op.
  164903. *
  164904. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  164905. * application must deal with any cleanup that should happen even
  164906. * for error exit.
  164907. */
  164908. METHODDEF(void)
  164909. term_source (j_decompress_ptr)
  164910. {
  164911. /* no work necessary here */
  164912. }
  164913. /*
  164914. * Prepare for input from a stdio stream.
  164915. * The caller must have already opened the stream, and is responsible
  164916. * for closing it after finishing decompression.
  164917. */
  164918. GLOBAL(void)
  164919. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  164920. {
  164921. my_src_ptr src;
  164922. /* The source object and input buffer are made permanent so that a series
  164923. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  164924. * only before the first one. (If we discarded the buffer at the end of
  164925. * one image, we'd likely lose the start of the next one.)
  164926. * This makes it unsafe to use this manager and a different source
  164927. * manager serially with the same JPEG object. Caveat programmer.
  164928. */
  164929. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  164930. cinfo->src = (struct jpeg_source_mgr *)
  164931. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164932. SIZEOF(my_source_mgr));
  164933. src = (my_src_ptr) cinfo->src;
  164934. src->buffer = (JOCTET *)
  164935. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164936. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  164937. }
  164938. src = (my_src_ptr) cinfo->src;
  164939. src->pub.init_source = init_source;
  164940. src->pub.fill_input_buffer = fill_input_buffer;
  164941. src->pub.skip_input_data = skip_input_data;
  164942. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  164943. src->pub.term_source = term_source;
  164944. src->infile = infile;
  164945. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  164946. src->pub.next_input_byte = NULL; /* until buffer loaded */
  164947. }
  164948. /*** End of inlined file: jdatasrc.c ***/
  164949. /*** Start of inlined file: jdcoefct.c ***/
  164950. #define JPEG_INTERNALS
  164951. /* Block smoothing is only applicable for progressive JPEG, so: */
  164952. #ifndef D_PROGRESSIVE_SUPPORTED
  164953. #undef BLOCK_SMOOTHING_SUPPORTED
  164954. #endif
  164955. /* Private buffer controller object */
  164956. typedef struct {
  164957. struct jpeg_d_coef_controller pub; /* public fields */
  164958. /* These variables keep track of the current location of the input side. */
  164959. /* cinfo->input_iMCU_row is also used for this. */
  164960. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  164961. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164962. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164963. /* The output side's location is represented by cinfo->output_iMCU_row. */
  164964. /* In single-pass modes, it's sufficient to buffer just one MCU.
  164965. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  164966. * and let the entropy decoder write into that workspace each time.
  164967. * (On 80x86, the workspace is FAR even though it's not really very big;
  164968. * this is to keep the module interfaces unchanged when a large coefficient
  164969. * buffer is necessary.)
  164970. * In multi-pass modes, this array points to the current MCU's blocks
  164971. * within the virtual arrays; it is used only by the input side.
  164972. */
  164973. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  164974. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164975. /* In multi-pass modes, we need a virtual block array for each component. */
  164976. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  164977. #endif
  164978. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164979. /* When doing block smoothing, we latch coefficient Al values here */
  164980. int * coef_bits_latch;
  164981. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  164982. #endif
  164983. } my_coef_controller3;
  164984. typedef my_coef_controller3 * my_coef_ptr3;
  164985. /* Forward declarations */
  164986. METHODDEF(int) decompress_onepass
  164987. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164988. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164989. METHODDEF(int) decompress_data
  164990. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164991. #endif
  164992. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164993. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  164994. METHODDEF(int) decompress_smooth_data
  164995. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164996. #endif
  164997. LOCAL(void)
  164998. start_iMCU_row3 (j_decompress_ptr cinfo)
  164999. /* Reset within-iMCU-row counters for a new row (input side) */
  165000. {
  165001. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165002. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  165003. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  165004. * But at the bottom of the image, process only what's left.
  165005. */
  165006. if (cinfo->comps_in_scan > 1) {
  165007. coef->MCU_rows_per_iMCU_row = 1;
  165008. } else {
  165009. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  165010. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  165011. else
  165012. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  165013. }
  165014. coef->MCU_ctr = 0;
  165015. coef->MCU_vert_offset = 0;
  165016. }
  165017. /*
  165018. * Initialize for an input processing pass.
  165019. */
  165020. METHODDEF(void)
  165021. start_input_pass (j_decompress_ptr cinfo)
  165022. {
  165023. cinfo->input_iMCU_row = 0;
  165024. start_iMCU_row3(cinfo);
  165025. }
  165026. /*
  165027. * Initialize for an output processing pass.
  165028. */
  165029. METHODDEF(void)
  165030. start_output_pass (j_decompress_ptr cinfo)
  165031. {
  165032. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165033. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165034. /* If multipass, check to see whether to use block smoothing on this pass */
  165035. if (coef->pub.coef_arrays != NULL) {
  165036. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  165037. coef->pub.decompress_data = decompress_smooth_data;
  165038. else
  165039. coef->pub.decompress_data = decompress_data;
  165040. }
  165041. #endif
  165042. cinfo->output_iMCU_row = 0;
  165043. }
  165044. /*
  165045. * Decompress and return some data in the single-pass case.
  165046. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165047. * Input and output must run in lockstep since we have only a one-MCU buffer.
  165048. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165049. *
  165050. * NB: output_buf contains a plane for each component in image,
  165051. * which we index according to the component's SOF position.
  165052. */
  165053. METHODDEF(int)
  165054. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165055. {
  165056. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165057. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165058. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  165059. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165060. int blkn, ci, xindex, yindex, yoffset, useful_width;
  165061. JSAMPARRAY output_ptr;
  165062. JDIMENSION start_col, output_col;
  165063. jpeg_component_info *compptr;
  165064. inverse_DCT_method_ptr inverse_DCT;
  165065. /* Loop to process as much as one whole iMCU row */
  165066. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165067. yoffset++) {
  165068. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  165069. MCU_col_num++) {
  165070. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  165071. jzero_far((void FAR *) coef->MCU_buffer[0],
  165072. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  165073. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165074. /* Suspension forced; update state counters and exit */
  165075. coef->MCU_vert_offset = yoffset;
  165076. coef->MCU_ctr = MCU_col_num;
  165077. return JPEG_SUSPENDED;
  165078. }
  165079. /* Determine where data should go in output_buf and do the IDCT thing.
  165080. * We skip dummy blocks at the right and bottom edges (but blkn gets
  165081. * incremented past them!). Note the inner loop relies on having
  165082. * allocated the MCU_buffer[] blocks sequentially.
  165083. */
  165084. blkn = 0; /* index of current DCT block within MCU */
  165085. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165086. compptr = cinfo->cur_comp_info[ci];
  165087. /* Don't bother to IDCT an uninteresting component. */
  165088. if (! compptr->component_needed) {
  165089. blkn += compptr->MCU_blocks;
  165090. continue;
  165091. }
  165092. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  165093. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  165094. : compptr->last_col_width;
  165095. output_ptr = output_buf[compptr->component_index] +
  165096. yoffset * compptr->DCT_scaled_size;
  165097. start_col = MCU_col_num * compptr->MCU_sample_width;
  165098. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165099. if (cinfo->input_iMCU_row < last_iMCU_row ||
  165100. yoffset+yindex < compptr->last_row_height) {
  165101. output_col = start_col;
  165102. for (xindex = 0; xindex < useful_width; xindex++) {
  165103. (*inverse_DCT) (cinfo, compptr,
  165104. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  165105. output_ptr, output_col);
  165106. output_col += compptr->DCT_scaled_size;
  165107. }
  165108. }
  165109. blkn += compptr->MCU_width;
  165110. output_ptr += compptr->DCT_scaled_size;
  165111. }
  165112. }
  165113. }
  165114. /* Completed an MCU row, but perhaps not an iMCU row */
  165115. coef->MCU_ctr = 0;
  165116. }
  165117. /* Completed the iMCU row, advance counters for next one */
  165118. cinfo->output_iMCU_row++;
  165119. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165120. start_iMCU_row3(cinfo);
  165121. return JPEG_ROW_COMPLETED;
  165122. }
  165123. /* Completed the scan */
  165124. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165125. return JPEG_SCAN_COMPLETED;
  165126. }
  165127. /*
  165128. * Dummy consume-input routine for single-pass operation.
  165129. */
  165130. METHODDEF(int)
  165131. dummy_consume_data (j_decompress_ptr)
  165132. {
  165133. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  165134. }
  165135. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165136. /*
  165137. * Consume input data and store it in the full-image coefficient buffer.
  165138. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  165139. * ie, v_samp_factor block rows for each component in the scan.
  165140. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165141. */
  165142. METHODDEF(int)
  165143. consume_data (j_decompress_ptr cinfo)
  165144. {
  165145. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165146. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165147. int blkn, ci, xindex, yindex, yoffset;
  165148. JDIMENSION start_col;
  165149. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  165150. JBLOCKROW buffer_ptr;
  165151. jpeg_component_info *compptr;
  165152. /* Align the virtual buffers for the components used in this scan. */
  165153. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165154. compptr = cinfo->cur_comp_info[ci];
  165155. buffer[ci] = (*cinfo->mem->access_virt_barray)
  165156. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  165157. cinfo->input_iMCU_row * compptr->v_samp_factor,
  165158. (JDIMENSION) compptr->v_samp_factor, TRUE);
  165159. /* Note: entropy decoder expects buffer to be zeroed,
  165160. * but this is handled automatically by the memory manager
  165161. * because we requested a pre-zeroed array.
  165162. */
  165163. }
  165164. /* Loop to process one whole iMCU row */
  165165. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165166. yoffset++) {
  165167. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  165168. MCU_col_num++) {
  165169. /* Construct list of pointers to DCT blocks belonging to this MCU */
  165170. blkn = 0; /* index of current DCT block within MCU */
  165171. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165172. compptr = cinfo->cur_comp_info[ci];
  165173. start_col = MCU_col_num * compptr->MCU_width;
  165174. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165175. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  165176. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  165177. coef->MCU_buffer[blkn++] = buffer_ptr++;
  165178. }
  165179. }
  165180. }
  165181. /* Try to fetch the MCU. */
  165182. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165183. /* Suspension forced; update state counters and exit */
  165184. coef->MCU_vert_offset = yoffset;
  165185. coef->MCU_ctr = MCU_col_num;
  165186. return JPEG_SUSPENDED;
  165187. }
  165188. }
  165189. /* Completed an MCU row, but perhaps not an iMCU row */
  165190. coef->MCU_ctr = 0;
  165191. }
  165192. /* Completed the iMCU row, advance counters for next one */
  165193. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165194. start_iMCU_row3(cinfo);
  165195. return JPEG_ROW_COMPLETED;
  165196. }
  165197. /* Completed the scan */
  165198. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165199. return JPEG_SCAN_COMPLETED;
  165200. }
  165201. /*
  165202. * Decompress and return some data in the multi-pass case.
  165203. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165204. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165205. *
  165206. * NB: output_buf contains a plane for each component in image.
  165207. */
  165208. METHODDEF(int)
  165209. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165210. {
  165211. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165212. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165213. JDIMENSION block_num;
  165214. int ci, block_row, block_rows;
  165215. JBLOCKARRAY buffer;
  165216. JBLOCKROW buffer_ptr;
  165217. JSAMPARRAY output_ptr;
  165218. JDIMENSION output_col;
  165219. jpeg_component_info *compptr;
  165220. inverse_DCT_method_ptr inverse_DCT;
  165221. /* Force some input to be done if we are getting ahead of the input. */
  165222. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  165223. (cinfo->input_scan_number == cinfo->output_scan_number &&
  165224. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  165225. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165226. return JPEG_SUSPENDED;
  165227. }
  165228. /* OK, output from the virtual arrays. */
  165229. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165230. ci++, compptr++) {
  165231. /* Don't bother to IDCT an uninteresting component. */
  165232. if (! compptr->component_needed)
  165233. continue;
  165234. /* Align the virtual buffer for this component. */
  165235. buffer = (*cinfo->mem->access_virt_barray)
  165236. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165237. cinfo->output_iMCU_row * compptr->v_samp_factor,
  165238. (JDIMENSION) compptr->v_samp_factor, FALSE);
  165239. /* Count non-dummy DCT block rows in this iMCU row. */
  165240. if (cinfo->output_iMCU_row < last_iMCU_row)
  165241. block_rows = compptr->v_samp_factor;
  165242. else {
  165243. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165244. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165245. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165246. }
  165247. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165248. output_ptr = output_buf[ci];
  165249. /* Loop over all DCT blocks to be processed. */
  165250. for (block_row = 0; block_row < block_rows; block_row++) {
  165251. buffer_ptr = buffer[block_row];
  165252. output_col = 0;
  165253. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  165254. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  165255. output_ptr, output_col);
  165256. buffer_ptr++;
  165257. output_col += compptr->DCT_scaled_size;
  165258. }
  165259. output_ptr += compptr->DCT_scaled_size;
  165260. }
  165261. }
  165262. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  165263. return JPEG_ROW_COMPLETED;
  165264. return JPEG_SCAN_COMPLETED;
  165265. }
  165266. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165267. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165268. /*
  165269. * This code applies interblock smoothing as described by section K.8
  165270. * of the JPEG standard: the first 5 AC coefficients are estimated from
  165271. * the DC values of a DCT block and its 8 neighboring blocks.
  165272. * We apply smoothing only for progressive JPEG decoding, and only if
  165273. * the coefficients it can estimate are not yet known to full precision.
  165274. */
  165275. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  165276. #define Q01_POS 1
  165277. #define Q10_POS 8
  165278. #define Q20_POS 16
  165279. #define Q11_POS 9
  165280. #define Q02_POS 2
  165281. /*
  165282. * Determine whether block smoothing is applicable and safe.
  165283. * We also latch the current states of the coef_bits[] entries for the
  165284. * AC coefficients; otherwise, if the input side of the decompressor
  165285. * advances into a new scan, we might think the coefficients are known
  165286. * more accurately than they really are.
  165287. */
  165288. LOCAL(boolean)
  165289. smoothing_ok (j_decompress_ptr cinfo)
  165290. {
  165291. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165292. boolean smoothing_useful = FALSE;
  165293. int ci, coefi;
  165294. jpeg_component_info *compptr;
  165295. JQUANT_TBL * qtable;
  165296. int * coef_bits;
  165297. int * coef_bits_latch;
  165298. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  165299. return FALSE;
  165300. /* Allocate latch area if not already done */
  165301. if (coef->coef_bits_latch == NULL)
  165302. coef->coef_bits_latch = (int *)
  165303. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165304. cinfo->num_components *
  165305. (SAVED_COEFS * SIZEOF(int)));
  165306. coef_bits_latch = coef->coef_bits_latch;
  165307. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165308. ci++, compptr++) {
  165309. /* All components' quantization values must already be latched. */
  165310. if ((qtable = compptr->quant_table) == NULL)
  165311. return FALSE;
  165312. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  165313. if (qtable->quantval[0] == 0 ||
  165314. qtable->quantval[Q01_POS] == 0 ||
  165315. qtable->quantval[Q10_POS] == 0 ||
  165316. qtable->quantval[Q20_POS] == 0 ||
  165317. qtable->quantval[Q11_POS] == 0 ||
  165318. qtable->quantval[Q02_POS] == 0)
  165319. return FALSE;
  165320. /* DC values must be at least partly known for all components. */
  165321. coef_bits = cinfo->coef_bits[ci];
  165322. if (coef_bits[0] < 0)
  165323. return FALSE;
  165324. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  165325. for (coefi = 1; coefi <= 5; coefi++) {
  165326. coef_bits_latch[coefi] = coef_bits[coefi];
  165327. if (coef_bits[coefi] != 0)
  165328. smoothing_useful = TRUE;
  165329. }
  165330. coef_bits_latch += SAVED_COEFS;
  165331. }
  165332. return smoothing_useful;
  165333. }
  165334. /*
  165335. * Variant of decompress_data for use when doing block smoothing.
  165336. */
  165337. METHODDEF(int)
  165338. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165339. {
  165340. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165341. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165342. JDIMENSION block_num, last_block_column;
  165343. int ci, block_row, block_rows, access_rows;
  165344. JBLOCKARRAY buffer;
  165345. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  165346. JSAMPARRAY output_ptr;
  165347. JDIMENSION output_col;
  165348. jpeg_component_info *compptr;
  165349. inverse_DCT_method_ptr inverse_DCT;
  165350. boolean first_row, last_row;
  165351. JBLOCK workspace;
  165352. int *coef_bits;
  165353. JQUANT_TBL *quanttbl;
  165354. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  165355. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  165356. int Al, pred;
  165357. /* Force some input to be done if we are getting ahead of the input. */
  165358. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  165359. ! cinfo->inputctl->eoi_reached) {
  165360. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  165361. /* If input is working on current scan, we ordinarily want it to
  165362. * have completed the current row. But if input scan is DC,
  165363. * we want it to keep one row ahead so that next block row's DC
  165364. * values are up to date.
  165365. */
  165366. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  165367. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  165368. break;
  165369. }
  165370. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165371. return JPEG_SUSPENDED;
  165372. }
  165373. /* OK, output from the virtual arrays. */
  165374. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165375. ci++, compptr++) {
  165376. /* Don't bother to IDCT an uninteresting component. */
  165377. if (! compptr->component_needed)
  165378. continue;
  165379. /* Count non-dummy DCT block rows in this iMCU row. */
  165380. if (cinfo->output_iMCU_row < last_iMCU_row) {
  165381. block_rows = compptr->v_samp_factor;
  165382. access_rows = block_rows * 2; /* this and next iMCU row */
  165383. last_row = FALSE;
  165384. } else {
  165385. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165386. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165387. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165388. access_rows = block_rows; /* this iMCU row only */
  165389. last_row = TRUE;
  165390. }
  165391. /* Align the virtual buffer for this component. */
  165392. if (cinfo->output_iMCU_row > 0) {
  165393. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  165394. buffer = (*cinfo->mem->access_virt_barray)
  165395. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165396. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  165397. (JDIMENSION) access_rows, FALSE);
  165398. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  165399. first_row = FALSE;
  165400. } else {
  165401. buffer = (*cinfo->mem->access_virt_barray)
  165402. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165403. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  165404. first_row = TRUE;
  165405. }
  165406. /* Fetch component-dependent info */
  165407. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  165408. quanttbl = compptr->quant_table;
  165409. Q00 = quanttbl->quantval[0];
  165410. Q01 = quanttbl->quantval[Q01_POS];
  165411. Q10 = quanttbl->quantval[Q10_POS];
  165412. Q20 = quanttbl->quantval[Q20_POS];
  165413. Q11 = quanttbl->quantval[Q11_POS];
  165414. Q02 = quanttbl->quantval[Q02_POS];
  165415. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165416. output_ptr = output_buf[ci];
  165417. /* Loop over all DCT blocks to be processed. */
  165418. for (block_row = 0; block_row < block_rows; block_row++) {
  165419. buffer_ptr = buffer[block_row];
  165420. if (first_row && block_row == 0)
  165421. prev_block_row = buffer_ptr;
  165422. else
  165423. prev_block_row = buffer[block_row-1];
  165424. if (last_row && block_row == block_rows-1)
  165425. next_block_row = buffer_ptr;
  165426. else
  165427. next_block_row = buffer[block_row+1];
  165428. /* We fetch the surrounding DC values using a sliding-register approach.
  165429. * Initialize all nine here so as to do the right thing on narrow pics.
  165430. */
  165431. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  165432. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  165433. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  165434. output_col = 0;
  165435. last_block_column = compptr->width_in_blocks - 1;
  165436. for (block_num = 0; block_num <= last_block_column; block_num++) {
  165437. /* Fetch current DCT block into workspace so we can modify it. */
  165438. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  165439. /* Update DC values */
  165440. if (block_num < last_block_column) {
  165441. DC3 = (int) prev_block_row[1][0];
  165442. DC6 = (int) buffer_ptr[1][0];
  165443. DC9 = (int) next_block_row[1][0];
  165444. }
  165445. /* Compute coefficient estimates per K.8.
  165446. * An estimate is applied only if coefficient is still zero,
  165447. * and is not known to be fully accurate.
  165448. */
  165449. /* AC01 */
  165450. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  165451. num = 36 * Q00 * (DC4 - DC6);
  165452. if (num >= 0) {
  165453. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  165454. if (Al > 0 && pred >= (1<<Al))
  165455. pred = (1<<Al)-1;
  165456. } else {
  165457. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  165458. if (Al > 0 && pred >= (1<<Al))
  165459. pred = (1<<Al)-1;
  165460. pred = -pred;
  165461. }
  165462. workspace[1] = (JCOEF) pred;
  165463. }
  165464. /* AC10 */
  165465. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  165466. num = 36 * Q00 * (DC2 - DC8);
  165467. if (num >= 0) {
  165468. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  165469. if (Al > 0 && pred >= (1<<Al))
  165470. pred = (1<<Al)-1;
  165471. } else {
  165472. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  165473. if (Al > 0 && pred >= (1<<Al))
  165474. pred = (1<<Al)-1;
  165475. pred = -pred;
  165476. }
  165477. workspace[8] = (JCOEF) pred;
  165478. }
  165479. /* AC20 */
  165480. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  165481. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  165482. if (num >= 0) {
  165483. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  165484. if (Al > 0 && pred >= (1<<Al))
  165485. pred = (1<<Al)-1;
  165486. } else {
  165487. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  165488. if (Al > 0 && pred >= (1<<Al))
  165489. pred = (1<<Al)-1;
  165490. pred = -pred;
  165491. }
  165492. workspace[16] = (JCOEF) pred;
  165493. }
  165494. /* AC11 */
  165495. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  165496. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  165497. if (num >= 0) {
  165498. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  165499. if (Al > 0 && pred >= (1<<Al))
  165500. pred = (1<<Al)-1;
  165501. } else {
  165502. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  165503. if (Al > 0 && pred >= (1<<Al))
  165504. pred = (1<<Al)-1;
  165505. pred = -pred;
  165506. }
  165507. workspace[9] = (JCOEF) pred;
  165508. }
  165509. /* AC02 */
  165510. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  165511. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  165512. if (num >= 0) {
  165513. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  165514. if (Al > 0 && pred >= (1<<Al))
  165515. pred = (1<<Al)-1;
  165516. } else {
  165517. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  165518. if (Al > 0 && pred >= (1<<Al))
  165519. pred = (1<<Al)-1;
  165520. pred = -pred;
  165521. }
  165522. workspace[2] = (JCOEF) pred;
  165523. }
  165524. /* OK, do the IDCT */
  165525. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  165526. output_ptr, output_col);
  165527. /* Advance for next column */
  165528. DC1 = DC2; DC2 = DC3;
  165529. DC4 = DC5; DC5 = DC6;
  165530. DC7 = DC8; DC8 = DC9;
  165531. buffer_ptr++, prev_block_row++, next_block_row++;
  165532. output_col += compptr->DCT_scaled_size;
  165533. }
  165534. output_ptr += compptr->DCT_scaled_size;
  165535. }
  165536. }
  165537. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  165538. return JPEG_ROW_COMPLETED;
  165539. return JPEG_SCAN_COMPLETED;
  165540. }
  165541. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  165542. /*
  165543. * Initialize coefficient buffer controller.
  165544. */
  165545. GLOBAL(void)
  165546. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  165547. {
  165548. my_coef_ptr3 coef;
  165549. coef = (my_coef_ptr3)
  165550. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165551. SIZEOF(my_coef_controller3));
  165552. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  165553. coef->pub.start_input_pass = start_input_pass;
  165554. coef->pub.start_output_pass = start_output_pass;
  165555. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165556. coef->coef_bits_latch = NULL;
  165557. #endif
  165558. /* Create the coefficient buffer. */
  165559. if (need_full_buffer) {
  165560. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165561. /* Allocate a full-image virtual array for each component, */
  165562. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  165563. /* Note we ask for a pre-zeroed array. */
  165564. int ci, access_rows;
  165565. jpeg_component_info *compptr;
  165566. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165567. ci++, compptr++) {
  165568. access_rows = compptr->v_samp_factor;
  165569. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165570. /* If block smoothing could be used, need a bigger window */
  165571. if (cinfo->progressive_mode)
  165572. access_rows *= 3;
  165573. #endif
  165574. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  165575. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  165576. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  165577. (long) compptr->h_samp_factor),
  165578. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  165579. (long) compptr->v_samp_factor),
  165580. (JDIMENSION) access_rows);
  165581. }
  165582. coef->pub.consume_data = consume_data;
  165583. coef->pub.decompress_data = decompress_data;
  165584. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  165585. #else
  165586. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165587. #endif
  165588. } else {
  165589. /* We only need a single-MCU buffer. */
  165590. JBLOCKROW buffer;
  165591. int i;
  165592. buffer = (JBLOCKROW)
  165593. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165594. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  165595. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  165596. coef->MCU_buffer[i] = buffer + i;
  165597. }
  165598. coef->pub.consume_data = dummy_consume_data;
  165599. coef->pub.decompress_data = decompress_onepass;
  165600. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  165601. }
  165602. }
  165603. /*** End of inlined file: jdcoefct.c ***/
  165604. #undef FIX
  165605. /*** Start of inlined file: jdcolor.c ***/
  165606. #define JPEG_INTERNALS
  165607. /* Private subobject */
  165608. typedef struct {
  165609. struct jpeg_color_deconverter pub; /* public fields */
  165610. /* Private state for YCC->RGB conversion */
  165611. int * Cr_r_tab; /* => table for Cr to R conversion */
  165612. int * Cb_b_tab; /* => table for Cb to B conversion */
  165613. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  165614. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  165615. } my_color_deconverter2;
  165616. typedef my_color_deconverter2 * my_cconvert_ptr2;
  165617. /**************** YCbCr -> RGB conversion: most common case **************/
  165618. /*
  165619. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  165620. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  165621. * The conversion equations to be implemented are therefore
  165622. * R = Y + 1.40200 * Cr
  165623. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  165624. * B = Y + 1.77200 * Cb
  165625. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  165626. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  165627. *
  165628. * To avoid floating-point arithmetic, we represent the fractional constants
  165629. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  165630. * the products by 2^16, with appropriate rounding, to get the correct answer.
  165631. * Notice that Y, being an integral input, does not contribute any fraction
  165632. * so it need not participate in the rounding.
  165633. *
  165634. * For even more speed, we avoid doing any multiplications in the inner loop
  165635. * by precalculating the constants times Cb and Cr for all possible values.
  165636. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  165637. * for 12-bit samples it is still acceptable. It's not very reasonable for
  165638. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  165639. * colorspace anyway.
  165640. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  165641. * values for the G calculation are left scaled up, since we must add them
  165642. * together before rounding.
  165643. */
  165644. #define SCALEBITS 16 /* speediest right-shift on some machines */
  165645. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  165646. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  165647. /*
  165648. * Initialize tables for YCC->RGB colorspace conversion.
  165649. */
  165650. LOCAL(void)
  165651. build_ycc_rgb_table (j_decompress_ptr cinfo)
  165652. {
  165653. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165654. int i;
  165655. INT32 x;
  165656. SHIFT_TEMPS
  165657. cconvert->Cr_r_tab = (int *)
  165658. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165659. (MAXJSAMPLE+1) * SIZEOF(int));
  165660. cconvert->Cb_b_tab = (int *)
  165661. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165662. (MAXJSAMPLE+1) * SIZEOF(int));
  165663. cconvert->Cr_g_tab = (INT32 *)
  165664. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165665. (MAXJSAMPLE+1) * SIZEOF(INT32));
  165666. cconvert->Cb_g_tab = (INT32 *)
  165667. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165668. (MAXJSAMPLE+1) * SIZEOF(INT32));
  165669. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  165670. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  165671. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  165672. /* Cr=>R value is nearest int to 1.40200 * x */
  165673. cconvert->Cr_r_tab[i] = (int)
  165674. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  165675. /* Cb=>B value is nearest int to 1.77200 * x */
  165676. cconvert->Cb_b_tab[i] = (int)
  165677. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  165678. /* Cr=>G value is scaled-up -0.71414 * x */
  165679. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  165680. /* Cb=>G value is scaled-up -0.34414 * x */
  165681. /* We also add in ONE_HALF so that need not do it in inner loop */
  165682. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  165683. }
  165684. }
  165685. /*
  165686. * Convert some rows of samples to the output colorspace.
  165687. *
  165688. * Note that we change from noninterleaved, one-plane-per-component format
  165689. * to interleaved-pixel format. The output buffer is therefore three times
  165690. * as wide as the input buffer.
  165691. * A starting row offset is provided only for the input buffer. The caller
  165692. * can easily adjust the passed output_buf value to accommodate any row
  165693. * offset required on that side.
  165694. */
  165695. METHODDEF(void)
  165696. ycc_rgb_convert (j_decompress_ptr cinfo,
  165697. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165698. JSAMPARRAY output_buf, int num_rows)
  165699. {
  165700. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165701. register int y, cb, cr;
  165702. register JSAMPROW outptr;
  165703. register JSAMPROW inptr0, inptr1, inptr2;
  165704. register JDIMENSION col;
  165705. JDIMENSION num_cols = cinfo->output_width;
  165706. /* copy these pointers into registers if possible */
  165707. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  165708. register int * Crrtab = cconvert->Cr_r_tab;
  165709. register int * Cbbtab = cconvert->Cb_b_tab;
  165710. register INT32 * Crgtab = cconvert->Cr_g_tab;
  165711. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  165712. SHIFT_TEMPS
  165713. while (--num_rows >= 0) {
  165714. inptr0 = input_buf[0][input_row];
  165715. inptr1 = input_buf[1][input_row];
  165716. inptr2 = input_buf[2][input_row];
  165717. input_row++;
  165718. outptr = *output_buf++;
  165719. for (col = 0; col < num_cols; col++) {
  165720. y = GETJSAMPLE(inptr0[col]);
  165721. cb = GETJSAMPLE(inptr1[col]);
  165722. cr = GETJSAMPLE(inptr2[col]);
  165723. /* Range-limiting is essential due to noise introduced by DCT losses. */
  165724. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  165725. outptr[RGB_GREEN] = range_limit[y +
  165726. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  165727. SCALEBITS))];
  165728. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  165729. outptr += RGB_PIXELSIZE;
  165730. }
  165731. }
  165732. }
  165733. /**************** Cases other than YCbCr -> RGB **************/
  165734. /*
  165735. * Color conversion for no colorspace change: just copy the data,
  165736. * converting from separate-planes to interleaved representation.
  165737. */
  165738. METHODDEF(void)
  165739. null_convert2 (j_decompress_ptr cinfo,
  165740. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165741. JSAMPARRAY output_buf, int num_rows)
  165742. {
  165743. register JSAMPROW inptr, outptr;
  165744. register JDIMENSION count;
  165745. register int num_components = cinfo->num_components;
  165746. JDIMENSION num_cols = cinfo->output_width;
  165747. int ci;
  165748. while (--num_rows >= 0) {
  165749. for (ci = 0; ci < num_components; ci++) {
  165750. inptr = input_buf[ci][input_row];
  165751. outptr = output_buf[0] + ci;
  165752. for (count = num_cols; count > 0; count--) {
  165753. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  165754. outptr += num_components;
  165755. }
  165756. }
  165757. input_row++;
  165758. output_buf++;
  165759. }
  165760. }
  165761. /*
  165762. * Color conversion for grayscale: just copy the data.
  165763. * This also works for YCbCr -> grayscale conversion, in which
  165764. * we just copy the Y (luminance) component and ignore chrominance.
  165765. */
  165766. METHODDEF(void)
  165767. grayscale_convert2 (j_decompress_ptr cinfo,
  165768. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165769. JSAMPARRAY output_buf, int num_rows)
  165770. {
  165771. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  165772. num_rows, cinfo->output_width);
  165773. }
  165774. /*
  165775. * Convert grayscale to RGB: just duplicate the graylevel three times.
  165776. * This is provided to support applications that don't want to cope
  165777. * with grayscale as a separate case.
  165778. */
  165779. METHODDEF(void)
  165780. gray_rgb_convert (j_decompress_ptr cinfo,
  165781. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165782. JSAMPARRAY output_buf, int num_rows)
  165783. {
  165784. register JSAMPROW inptr, outptr;
  165785. register JDIMENSION col;
  165786. JDIMENSION num_cols = cinfo->output_width;
  165787. while (--num_rows >= 0) {
  165788. inptr = input_buf[0][input_row++];
  165789. outptr = *output_buf++;
  165790. for (col = 0; col < num_cols; col++) {
  165791. /* We can dispense with GETJSAMPLE() here */
  165792. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  165793. outptr += RGB_PIXELSIZE;
  165794. }
  165795. }
  165796. }
  165797. /*
  165798. * Adobe-style YCCK->CMYK conversion.
  165799. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  165800. * conversion as above, while passing K (black) unchanged.
  165801. * We assume build_ycc_rgb_table has been called.
  165802. */
  165803. METHODDEF(void)
  165804. ycck_cmyk_convert (j_decompress_ptr cinfo,
  165805. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165806. JSAMPARRAY output_buf, int num_rows)
  165807. {
  165808. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165809. register int y, cb, cr;
  165810. register JSAMPROW outptr;
  165811. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  165812. register JDIMENSION col;
  165813. JDIMENSION num_cols = cinfo->output_width;
  165814. /* copy these pointers into registers if possible */
  165815. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  165816. register int * Crrtab = cconvert->Cr_r_tab;
  165817. register int * Cbbtab = cconvert->Cb_b_tab;
  165818. register INT32 * Crgtab = cconvert->Cr_g_tab;
  165819. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  165820. SHIFT_TEMPS
  165821. while (--num_rows >= 0) {
  165822. inptr0 = input_buf[0][input_row];
  165823. inptr1 = input_buf[1][input_row];
  165824. inptr2 = input_buf[2][input_row];
  165825. inptr3 = input_buf[3][input_row];
  165826. input_row++;
  165827. outptr = *output_buf++;
  165828. for (col = 0; col < num_cols; col++) {
  165829. y = GETJSAMPLE(inptr0[col]);
  165830. cb = GETJSAMPLE(inptr1[col]);
  165831. cr = GETJSAMPLE(inptr2[col]);
  165832. /* Range-limiting is essential due to noise introduced by DCT losses. */
  165833. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  165834. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  165835. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  165836. SCALEBITS)))];
  165837. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  165838. /* K passes through unchanged */
  165839. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  165840. outptr += 4;
  165841. }
  165842. }
  165843. }
  165844. /*
  165845. * Empty method for start_pass.
  165846. */
  165847. METHODDEF(void)
  165848. start_pass_dcolor (j_decompress_ptr)
  165849. {
  165850. /* no work needed */
  165851. }
  165852. /*
  165853. * Module initialization routine for output colorspace conversion.
  165854. */
  165855. GLOBAL(void)
  165856. jinit_color_deconverter (j_decompress_ptr cinfo)
  165857. {
  165858. my_cconvert_ptr2 cconvert;
  165859. int ci;
  165860. cconvert = (my_cconvert_ptr2)
  165861. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165862. SIZEOF(my_color_deconverter2));
  165863. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  165864. cconvert->pub.start_pass = start_pass_dcolor;
  165865. /* Make sure num_components agrees with jpeg_color_space */
  165866. switch (cinfo->jpeg_color_space) {
  165867. case JCS_GRAYSCALE:
  165868. if (cinfo->num_components != 1)
  165869. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165870. break;
  165871. case JCS_RGB:
  165872. case JCS_YCbCr:
  165873. if (cinfo->num_components != 3)
  165874. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165875. break;
  165876. case JCS_CMYK:
  165877. case JCS_YCCK:
  165878. if (cinfo->num_components != 4)
  165879. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165880. break;
  165881. default: /* JCS_UNKNOWN can be anything */
  165882. if (cinfo->num_components < 1)
  165883. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165884. break;
  165885. }
  165886. /* Set out_color_components and conversion method based on requested space.
  165887. * Also clear the component_needed flags for any unused components,
  165888. * so that earlier pipeline stages can avoid useless computation.
  165889. */
  165890. switch (cinfo->out_color_space) {
  165891. case JCS_GRAYSCALE:
  165892. cinfo->out_color_components = 1;
  165893. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  165894. cinfo->jpeg_color_space == JCS_YCbCr) {
  165895. cconvert->pub.color_convert = grayscale_convert2;
  165896. /* For color->grayscale conversion, only the Y (0) component is needed */
  165897. for (ci = 1; ci < cinfo->num_components; ci++)
  165898. cinfo->comp_info[ci].component_needed = FALSE;
  165899. } else
  165900. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165901. break;
  165902. case JCS_RGB:
  165903. cinfo->out_color_components = RGB_PIXELSIZE;
  165904. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  165905. cconvert->pub.color_convert = ycc_rgb_convert;
  165906. build_ycc_rgb_table(cinfo);
  165907. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  165908. cconvert->pub.color_convert = gray_rgb_convert;
  165909. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  165910. cconvert->pub.color_convert = null_convert2;
  165911. } else
  165912. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165913. break;
  165914. case JCS_CMYK:
  165915. cinfo->out_color_components = 4;
  165916. if (cinfo->jpeg_color_space == JCS_YCCK) {
  165917. cconvert->pub.color_convert = ycck_cmyk_convert;
  165918. build_ycc_rgb_table(cinfo);
  165919. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  165920. cconvert->pub.color_convert = null_convert2;
  165921. } else
  165922. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165923. break;
  165924. default:
  165925. /* Permit null conversion to same output space */
  165926. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  165927. cinfo->out_color_components = cinfo->num_components;
  165928. cconvert->pub.color_convert = null_convert2;
  165929. } else /* unsupported non-null conversion */
  165930. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165931. break;
  165932. }
  165933. if (cinfo->quantize_colors)
  165934. cinfo->output_components = 1; /* single colormapped output component */
  165935. else
  165936. cinfo->output_components = cinfo->out_color_components;
  165937. }
  165938. /*** End of inlined file: jdcolor.c ***/
  165939. #undef FIX
  165940. /*** Start of inlined file: jddctmgr.c ***/
  165941. #define JPEG_INTERNALS
  165942. /*
  165943. * The decompressor input side (jdinput.c) saves away the appropriate
  165944. * quantization table for each component at the start of the first scan
  165945. * involving that component. (This is necessary in order to correctly
  165946. * decode files that reuse Q-table slots.)
  165947. * When we are ready to make an output pass, the saved Q-table is converted
  165948. * to a multiplier table that will actually be used by the IDCT routine.
  165949. * The multiplier table contents are IDCT-method-dependent. To support
  165950. * application changes in IDCT method between scans, we can remake the
  165951. * multiplier tables if necessary.
  165952. * In buffered-image mode, the first output pass may occur before any data
  165953. * has been seen for some components, and thus before their Q-tables have
  165954. * been saved away. To handle this case, multiplier tables are preset
  165955. * to zeroes; the result of the IDCT will be a neutral gray level.
  165956. */
  165957. /* Private subobject for this module */
  165958. typedef struct {
  165959. struct jpeg_inverse_dct pub; /* public fields */
  165960. /* This array contains the IDCT method code that each multiplier table
  165961. * is currently set up for, or -1 if it's not yet set up.
  165962. * The actual multiplier tables are pointed to by dct_table in the
  165963. * per-component comp_info structures.
  165964. */
  165965. int cur_method[MAX_COMPONENTS];
  165966. } my_idct_controller;
  165967. typedef my_idct_controller * my_idct_ptr;
  165968. /* Allocated multiplier tables: big enough for any supported variant */
  165969. typedef union {
  165970. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  165971. #ifdef DCT_IFAST_SUPPORTED
  165972. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  165973. #endif
  165974. #ifdef DCT_FLOAT_SUPPORTED
  165975. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  165976. #endif
  165977. } multiplier_table;
  165978. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  165979. * so be sure to compile that code if either ISLOW or SCALING is requested.
  165980. */
  165981. #ifdef DCT_ISLOW_SUPPORTED
  165982. #define PROVIDE_ISLOW_TABLES
  165983. #else
  165984. #ifdef IDCT_SCALING_SUPPORTED
  165985. #define PROVIDE_ISLOW_TABLES
  165986. #endif
  165987. #endif
  165988. /*
  165989. * Prepare for an output pass.
  165990. * Here we select the proper IDCT routine for each component and build
  165991. * a matching multiplier table.
  165992. */
  165993. METHODDEF(void)
  165994. start_pass (j_decompress_ptr cinfo)
  165995. {
  165996. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  165997. int ci, i;
  165998. jpeg_component_info *compptr;
  165999. int method = 0;
  166000. inverse_DCT_method_ptr method_ptr = NULL;
  166001. JQUANT_TBL * qtbl;
  166002. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166003. ci++, compptr++) {
  166004. /* Select the proper IDCT routine for this component's scaling */
  166005. switch (compptr->DCT_scaled_size) {
  166006. #ifdef IDCT_SCALING_SUPPORTED
  166007. case 1:
  166008. method_ptr = jpeg_idct_1x1;
  166009. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166010. break;
  166011. case 2:
  166012. method_ptr = jpeg_idct_2x2;
  166013. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166014. break;
  166015. case 4:
  166016. method_ptr = jpeg_idct_4x4;
  166017. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166018. break;
  166019. #endif
  166020. case DCTSIZE:
  166021. switch (cinfo->dct_method) {
  166022. #ifdef DCT_ISLOW_SUPPORTED
  166023. case JDCT_ISLOW:
  166024. method_ptr = jpeg_idct_islow;
  166025. method = JDCT_ISLOW;
  166026. break;
  166027. #endif
  166028. #ifdef DCT_IFAST_SUPPORTED
  166029. case JDCT_IFAST:
  166030. method_ptr = jpeg_idct_ifast;
  166031. method = JDCT_IFAST;
  166032. break;
  166033. #endif
  166034. #ifdef DCT_FLOAT_SUPPORTED
  166035. case JDCT_FLOAT:
  166036. method_ptr = jpeg_idct_float;
  166037. method = JDCT_FLOAT;
  166038. break;
  166039. #endif
  166040. default:
  166041. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166042. break;
  166043. }
  166044. break;
  166045. default:
  166046. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  166047. break;
  166048. }
  166049. idct->pub.inverse_DCT[ci] = method_ptr;
  166050. /* Create multiplier table from quant table.
  166051. * However, we can skip this if the component is uninteresting
  166052. * or if we already built the table. Also, if no quant table
  166053. * has yet been saved for the component, we leave the
  166054. * multiplier table all-zero; we'll be reading zeroes from the
  166055. * coefficient controller's buffer anyway.
  166056. */
  166057. if (! compptr->component_needed || idct->cur_method[ci] == method)
  166058. continue;
  166059. qtbl = compptr->quant_table;
  166060. if (qtbl == NULL) /* happens if no data yet for component */
  166061. continue;
  166062. idct->cur_method[ci] = method;
  166063. switch (method) {
  166064. #ifdef PROVIDE_ISLOW_TABLES
  166065. case JDCT_ISLOW:
  166066. {
  166067. /* For LL&M IDCT method, multipliers are equal to raw quantization
  166068. * coefficients, but are stored as ints to ensure access efficiency.
  166069. */
  166070. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  166071. for (i = 0; i < DCTSIZE2; i++) {
  166072. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  166073. }
  166074. }
  166075. break;
  166076. #endif
  166077. #ifdef DCT_IFAST_SUPPORTED
  166078. case JDCT_IFAST:
  166079. {
  166080. /* For AA&N IDCT method, multipliers are equal to quantization
  166081. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166082. * scalefactor[0] = 1
  166083. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166084. * For integer operation, the multiplier table is to be scaled by
  166085. * IFAST_SCALE_BITS.
  166086. */
  166087. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  166088. #define CONST_BITS 14
  166089. static const INT16 aanscales[DCTSIZE2] = {
  166090. /* precomputed values scaled up by 14 bits */
  166091. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166092. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  166093. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  166094. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  166095. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166096. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  166097. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  166098. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  166099. };
  166100. SHIFT_TEMPS
  166101. for (i = 0; i < DCTSIZE2; i++) {
  166102. ifmtbl[i] = (IFAST_MULT_TYPE)
  166103. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  166104. (INT32) aanscales[i]),
  166105. CONST_BITS-IFAST_SCALE_BITS);
  166106. }
  166107. }
  166108. break;
  166109. #endif
  166110. #ifdef DCT_FLOAT_SUPPORTED
  166111. case JDCT_FLOAT:
  166112. {
  166113. /* For float AA&N IDCT method, multipliers are equal to quantization
  166114. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166115. * scalefactor[0] = 1
  166116. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166117. */
  166118. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  166119. int row, col;
  166120. static const double aanscalefactor[DCTSIZE] = {
  166121. 1.0, 1.387039845, 1.306562965, 1.175875602,
  166122. 1.0, 0.785694958, 0.541196100, 0.275899379
  166123. };
  166124. i = 0;
  166125. for (row = 0; row < DCTSIZE; row++) {
  166126. for (col = 0; col < DCTSIZE; col++) {
  166127. fmtbl[i] = (FLOAT_MULT_TYPE)
  166128. ((double) qtbl->quantval[i] *
  166129. aanscalefactor[row] * aanscalefactor[col]);
  166130. i++;
  166131. }
  166132. }
  166133. }
  166134. break;
  166135. #endif
  166136. default:
  166137. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166138. break;
  166139. }
  166140. }
  166141. }
  166142. /*
  166143. * Initialize IDCT manager.
  166144. */
  166145. GLOBAL(void)
  166146. jinit_inverse_dct (j_decompress_ptr cinfo)
  166147. {
  166148. my_idct_ptr idct;
  166149. int ci;
  166150. jpeg_component_info *compptr;
  166151. idct = (my_idct_ptr)
  166152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166153. SIZEOF(my_idct_controller));
  166154. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  166155. idct->pub.start_pass = start_pass;
  166156. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166157. ci++, compptr++) {
  166158. /* Allocate and pre-zero a multiplier table for each component */
  166159. compptr->dct_table =
  166160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166161. SIZEOF(multiplier_table));
  166162. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  166163. /* Mark multiplier table not yet set up for any method */
  166164. idct->cur_method[ci] = -1;
  166165. }
  166166. }
  166167. /*** End of inlined file: jddctmgr.c ***/
  166168. #undef CONST_BITS
  166169. #undef ASSIGN_STATE
  166170. /*** Start of inlined file: jdhuff.c ***/
  166171. #define JPEG_INTERNALS
  166172. /*** Start of inlined file: jdhuff.h ***/
  166173. /* Short forms of external names for systems with brain-damaged linkers. */
  166174. #ifndef __jdhuff_h__
  166175. #define __jdhuff_h__
  166176. #ifdef NEED_SHORT_EXTERNAL_NAMES
  166177. #define jpeg_make_d_derived_tbl jMkDDerived
  166178. #define jpeg_fill_bit_buffer jFilBitBuf
  166179. #define jpeg_huff_decode jHufDecode
  166180. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  166181. /* Derived data constructed for each Huffman table */
  166182. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  166183. typedef struct {
  166184. /* Basic tables: (element [0] of each array is unused) */
  166185. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  166186. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  166187. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  166188. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  166189. * the smallest code of length k; so given a code of length k, the
  166190. * corresponding symbol is huffval[code + valoffset[k]]
  166191. */
  166192. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  166193. JHUFF_TBL *pub;
  166194. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  166195. * the input data stream. If the next Huffman code is no more
  166196. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  166197. * the corresponding symbol directly from these tables.
  166198. */
  166199. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  166200. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  166201. } d_derived_tbl;
  166202. /* Expand a Huffman table definition into the derived format */
  166203. EXTERN(void) jpeg_make_d_derived_tbl
  166204. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  166205. d_derived_tbl ** pdtbl));
  166206. /*
  166207. * Fetching the next N bits from the input stream is a time-critical operation
  166208. * for the Huffman decoders. We implement it with a combination of inline
  166209. * macros and out-of-line subroutines. Note that N (the number of bits
  166210. * demanded at one time) never exceeds 15 for JPEG use.
  166211. *
  166212. * We read source bytes into get_buffer and dole out bits as needed.
  166213. * If get_buffer already contains enough bits, they are fetched in-line
  166214. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  166215. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  166216. * as full as possible (not just to the number of bits needed; this
  166217. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  166218. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  166219. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  166220. * at least the requested number of bits --- dummy zeroes are inserted if
  166221. * necessary.
  166222. */
  166223. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  166224. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  166225. /* If long is > 32 bits on your machine, and shifting/masking longs is
  166226. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  166227. * appropriately should be a win. Unfortunately we can't define the size
  166228. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  166229. * because not all machines measure sizeof in 8-bit bytes.
  166230. */
  166231. typedef struct { /* Bitreading state saved across MCUs */
  166232. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166233. int bits_left; /* # of unused bits in it */
  166234. } bitread_perm_state;
  166235. typedef struct { /* Bitreading working state within an MCU */
  166236. /* Current data source location */
  166237. /* We need a copy, rather than munging the original, in case of suspension */
  166238. const JOCTET * next_input_byte; /* => next byte to read from source */
  166239. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  166240. /* Bit input buffer --- note these values are kept in register variables,
  166241. * not in this struct, inside the inner loops.
  166242. */
  166243. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166244. int bits_left; /* # of unused bits in it */
  166245. /* Pointer needed by jpeg_fill_bit_buffer. */
  166246. j_decompress_ptr cinfo; /* back link to decompress master record */
  166247. } bitread_working_state;
  166248. /* Macros to declare and load/save bitread local variables. */
  166249. #define BITREAD_STATE_VARS \
  166250. register bit_buf_type get_buffer; \
  166251. register int bits_left; \
  166252. bitread_working_state br_state
  166253. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  166254. br_state.cinfo = cinfop; \
  166255. br_state.next_input_byte = cinfop->src->next_input_byte; \
  166256. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  166257. get_buffer = permstate.get_buffer; \
  166258. bits_left = permstate.bits_left;
  166259. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  166260. cinfop->src->next_input_byte = br_state.next_input_byte; \
  166261. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  166262. permstate.get_buffer = get_buffer; \
  166263. permstate.bits_left = bits_left
  166264. /*
  166265. * These macros provide the in-line portion of bit fetching.
  166266. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  166267. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  166268. * The variables get_buffer and bits_left are assumed to be locals,
  166269. * but the state struct might not be (jpeg_huff_decode needs this).
  166270. * CHECK_BIT_BUFFER(state,n,action);
  166271. * Ensure there are N bits in get_buffer; if suspend, take action.
  166272. * val = GET_BITS(n);
  166273. * Fetch next N bits.
  166274. * val = PEEK_BITS(n);
  166275. * Fetch next N bits without removing them from the buffer.
  166276. * DROP_BITS(n);
  166277. * Discard next N bits.
  166278. * The value N should be a simple variable, not an expression, because it
  166279. * is evaluated multiple times.
  166280. */
  166281. #define CHECK_BIT_BUFFER(state,nbits,action) \
  166282. { if (bits_left < (nbits)) { \
  166283. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  166284. { action; } \
  166285. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  166286. #define GET_BITS(nbits) \
  166287. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  166288. #define PEEK_BITS(nbits) \
  166289. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  166290. #define DROP_BITS(nbits) \
  166291. (bits_left -= (nbits))
  166292. /* Load up the bit buffer to a depth of at least nbits */
  166293. EXTERN(boolean) jpeg_fill_bit_buffer
  166294. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166295. register int bits_left, int nbits));
  166296. /*
  166297. * Code for extracting next Huffman-coded symbol from input bit stream.
  166298. * Again, this is time-critical and we make the main paths be macros.
  166299. *
  166300. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  166301. * without looping. Usually, more than 95% of the Huffman codes will be 8
  166302. * or fewer bits long. The few overlength codes are handled with a loop,
  166303. * which need not be inline code.
  166304. *
  166305. * Notes about the HUFF_DECODE macro:
  166306. * 1. Near the end of the data segment, we may fail to get enough bits
  166307. * for a lookahead. In that case, we do it the hard way.
  166308. * 2. If the lookahead table contains no entry, the next code must be
  166309. * more than HUFF_LOOKAHEAD bits long.
  166310. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  166311. */
  166312. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  166313. { register int nb, look; \
  166314. if (bits_left < HUFF_LOOKAHEAD) { \
  166315. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  166316. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166317. if (bits_left < HUFF_LOOKAHEAD) { \
  166318. nb = 1; goto slowlabel; \
  166319. } \
  166320. } \
  166321. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  166322. if ((nb = htbl->look_nbits[look]) != 0) { \
  166323. DROP_BITS(nb); \
  166324. result = htbl->look_sym[look]; \
  166325. } else { \
  166326. nb = HUFF_LOOKAHEAD+1; \
  166327. slowlabel: \
  166328. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  166329. { failaction; } \
  166330. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166331. } \
  166332. }
  166333. /* Out-of-line case for Huffman code fetching */
  166334. EXTERN(int) jpeg_huff_decode
  166335. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166336. register int bits_left, d_derived_tbl * htbl, int min_bits));
  166337. #endif
  166338. /*** End of inlined file: jdhuff.h ***/
  166339. /* Declarations shared with jdphuff.c */
  166340. /*
  166341. * Expanded entropy decoder object for Huffman decoding.
  166342. *
  166343. * The savable_state subrecord contains fields that change within an MCU,
  166344. * but must not be updated permanently until we complete the MCU.
  166345. */
  166346. typedef struct {
  166347. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166348. } savable_state2;
  166349. /* This macro is to work around compilers with missing or broken
  166350. * structure assignment. You'll need to fix this code if you have
  166351. * such a compiler and you change MAX_COMPS_IN_SCAN.
  166352. */
  166353. #ifndef NO_STRUCT_ASSIGN
  166354. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  166355. #else
  166356. #if MAX_COMPS_IN_SCAN == 4
  166357. #define ASSIGN_STATE(dest,src) \
  166358. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  166359. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  166360. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  166361. (dest).last_dc_val[3] = (src).last_dc_val[3])
  166362. #endif
  166363. #endif
  166364. typedef struct {
  166365. struct jpeg_entropy_decoder pub; /* public fields */
  166366. /* These fields are loaded into local variables at start of each MCU.
  166367. * In case of suspension, we exit WITHOUT updating them.
  166368. */
  166369. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  166370. savable_state2 saved; /* Other state at start of MCU */
  166371. /* These fields are NOT loaded into local working state. */
  166372. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166373. /* Pointers to derived tables (these workspaces have image lifespan) */
  166374. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  166375. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  166376. /* Precalculated info set up by start_pass for use in decode_mcu: */
  166377. /* Pointers to derived tables to be used for each block within an MCU */
  166378. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  166379. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  166380. /* Whether we care about the DC and AC coefficient values for each block */
  166381. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  166382. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  166383. } huff_entropy_decoder2;
  166384. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  166385. /*
  166386. * Initialize for a Huffman-compressed scan.
  166387. */
  166388. METHODDEF(void)
  166389. start_pass_huff_decoder (j_decompress_ptr cinfo)
  166390. {
  166391. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166392. int ci, blkn, dctbl, actbl;
  166393. jpeg_component_info * compptr;
  166394. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  166395. * This ought to be an error condition, but we make it a warning because
  166396. * there are some baseline files out there with all zeroes in these bytes.
  166397. */
  166398. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  166399. cinfo->Ah != 0 || cinfo->Al != 0)
  166400. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  166401. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166402. compptr = cinfo->cur_comp_info[ci];
  166403. dctbl = compptr->dc_tbl_no;
  166404. actbl = compptr->ac_tbl_no;
  166405. /* Compute derived values for Huffman tables */
  166406. /* We may do this more than once for a table, but it's not expensive */
  166407. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  166408. & entropy->dc_derived_tbls[dctbl]);
  166409. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  166410. & entropy->ac_derived_tbls[actbl]);
  166411. /* Initialize DC predictions to 0 */
  166412. entropy->saved.last_dc_val[ci] = 0;
  166413. }
  166414. /* Precalculate decoding info for each block in an MCU of this scan */
  166415. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166416. ci = cinfo->MCU_membership[blkn];
  166417. compptr = cinfo->cur_comp_info[ci];
  166418. /* Precalculate which table to use for each block */
  166419. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  166420. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  166421. /* Decide whether we really care about the coefficient values */
  166422. if (compptr->component_needed) {
  166423. entropy->dc_needed[blkn] = TRUE;
  166424. /* we don't need the ACs if producing a 1/8th-size image */
  166425. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  166426. } else {
  166427. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  166428. }
  166429. }
  166430. /* Initialize bitread state variables */
  166431. entropy->bitstate.bits_left = 0;
  166432. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  166433. entropy->pub.insufficient_data = FALSE;
  166434. /* Initialize restart counter */
  166435. entropy->restarts_to_go = cinfo->restart_interval;
  166436. }
  166437. /*
  166438. * Compute the derived values for a Huffman table.
  166439. * This routine also performs some validation checks on the table.
  166440. *
  166441. * Note this is also used by jdphuff.c.
  166442. */
  166443. GLOBAL(void)
  166444. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  166445. d_derived_tbl ** pdtbl)
  166446. {
  166447. JHUFF_TBL *htbl;
  166448. d_derived_tbl *dtbl;
  166449. int p, i, l, si, numsymbols;
  166450. int lookbits, ctr;
  166451. char huffsize[257];
  166452. unsigned int huffcode[257];
  166453. unsigned int code;
  166454. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  166455. * paralleling the order of the symbols themselves in htbl->huffval[].
  166456. */
  166457. /* Find the input Huffman table */
  166458. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  166459. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  166460. htbl =
  166461. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  166462. if (htbl == NULL)
  166463. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  166464. /* Allocate a workspace if we haven't already done so. */
  166465. if (*pdtbl == NULL)
  166466. *pdtbl = (d_derived_tbl *)
  166467. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166468. SIZEOF(d_derived_tbl));
  166469. dtbl = *pdtbl;
  166470. dtbl->pub = htbl; /* fill in back link */
  166471. /* Figure C.1: make table of Huffman code length for each symbol */
  166472. p = 0;
  166473. for (l = 1; l <= 16; l++) {
  166474. i = (int) htbl->bits[l];
  166475. if (i < 0 || p + i > 256) /* protect against table overrun */
  166476. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166477. while (i--)
  166478. huffsize[p++] = (char) l;
  166479. }
  166480. huffsize[p] = 0;
  166481. numsymbols = p;
  166482. /* Figure C.2: generate the codes themselves */
  166483. /* We also validate that the counts represent a legal Huffman code tree. */
  166484. code = 0;
  166485. si = huffsize[0];
  166486. p = 0;
  166487. while (huffsize[p]) {
  166488. while (((int) huffsize[p]) == si) {
  166489. huffcode[p++] = code;
  166490. code++;
  166491. }
  166492. /* code is now 1 more than the last code used for codelength si; but
  166493. * it must still fit in si bits, since no code is allowed to be all ones.
  166494. */
  166495. if (((INT32) code) >= (((INT32) 1) << si))
  166496. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166497. code <<= 1;
  166498. si++;
  166499. }
  166500. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  166501. p = 0;
  166502. for (l = 1; l <= 16; l++) {
  166503. if (htbl->bits[l]) {
  166504. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  166505. * minus the minimum code of length l
  166506. */
  166507. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  166508. p += htbl->bits[l];
  166509. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  166510. } else {
  166511. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  166512. }
  166513. }
  166514. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  166515. /* Compute lookahead tables to speed up decoding.
  166516. * First we set all the table entries to 0, indicating "too long";
  166517. * then we iterate through the Huffman codes that are short enough and
  166518. * fill in all the entries that correspond to bit sequences starting
  166519. * with that code.
  166520. */
  166521. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  166522. p = 0;
  166523. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  166524. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  166525. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  166526. /* Generate left-justified code followed by all possible bit sequences */
  166527. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  166528. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  166529. dtbl->look_nbits[lookbits] = l;
  166530. dtbl->look_sym[lookbits] = htbl->huffval[p];
  166531. lookbits++;
  166532. }
  166533. }
  166534. }
  166535. /* Validate symbols as being reasonable.
  166536. * For AC tables, we make no check, but accept all byte values 0..255.
  166537. * For DC tables, we require the symbols to be in range 0..15.
  166538. * (Tighter bounds could be applied depending on the data depth and mode,
  166539. * but this is sufficient to ensure safe decoding.)
  166540. */
  166541. if (isDC) {
  166542. for (i = 0; i < numsymbols; i++) {
  166543. int sym = htbl->huffval[i];
  166544. if (sym < 0 || sym > 15)
  166545. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166546. }
  166547. }
  166548. }
  166549. /*
  166550. * Out-of-line code for bit fetching (shared with jdphuff.c).
  166551. * See jdhuff.h for info about usage.
  166552. * Note: current values of get_buffer and bits_left are passed as parameters,
  166553. * but are returned in the corresponding fields of the state struct.
  166554. *
  166555. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  166556. * of get_buffer to be used. (On machines with wider words, an even larger
  166557. * buffer could be used.) However, on some machines 32-bit shifts are
  166558. * quite slow and take time proportional to the number of places shifted.
  166559. * (This is true with most PC compilers, for instance.) In this case it may
  166560. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  166561. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  166562. */
  166563. #ifdef SLOW_SHIFT_32
  166564. #define MIN_GET_BITS 15 /* minimum allowable value */
  166565. #else
  166566. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  166567. #endif
  166568. GLOBAL(boolean)
  166569. jpeg_fill_bit_buffer (bitread_working_state * state,
  166570. register bit_buf_type get_buffer, register int bits_left,
  166571. int nbits)
  166572. /* Load up the bit buffer to a depth of at least nbits */
  166573. {
  166574. /* Copy heavily used state fields into locals (hopefully registers) */
  166575. register const JOCTET * next_input_byte = state->next_input_byte;
  166576. register size_t bytes_in_buffer = state->bytes_in_buffer;
  166577. j_decompress_ptr cinfo = state->cinfo;
  166578. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  166579. /* (It is assumed that no request will be for more than that many bits.) */
  166580. /* We fail to do so only if we hit a marker or are forced to suspend. */
  166581. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  166582. while (bits_left < MIN_GET_BITS) {
  166583. register int c;
  166584. /* Attempt to read a byte */
  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. /* If it's 0xFF, check and discard stuffed zero byte */
  166594. if (c == 0xFF) {
  166595. /* Loop here to discard any padding FF's on terminating marker,
  166596. * so that we can save a valid unread_marker value. NOTE: we will
  166597. * accept multiple FF's followed by a 0 as meaning a single FF data
  166598. * byte. This data pattern is not valid according to the standard.
  166599. */
  166600. do {
  166601. if (bytes_in_buffer == 0) {
  166602. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  166603. return FALSE;
  166604. next_input_byte = cinfo->src->next_input_byte;
  166605. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  166606. }
  166607. bytes_in_buffer--;
  166608. c = GETJOCTET(*next_input_byte++);
  166609. } while (c == 0xFF);
  166610. if (c == 0) {
  166611. /* Found FF/00, which represents an FF data byte */
  166612. c = 0xFF;
  166613. } else {
  166614. /* Oops, it's actually a marker indicating end of compressed data.
  166615. * Save the marker code for later use.
  166616. * Fine point: it might appear that we should save the marker into
  166617. * bitread working state, not straight into permanent state. But
  166618. * once we have hit a marker, we cannot need to suspend within the
  166619. * current MCU, because we will read no more bytes from the data
  166620. * source. So it is OK to update permanent state right away.
  166621. */
  166622. cinfo->unread_marker = c;
  166623. /* See if we need to insert some fake zero bits. */
  166624. goto no_more_bytes;
  166625. }
  166626. }
  166627. /* OK, load c into get_buffer */
  166628. get_buffer = (get_buffer << 8) | c;
  166629. bits_left += 8;
  166630. } /* end while */
  166631. } else {
  166632. no_more_bytes:
  166633. /* We get here if we've read the marker that terminates the compressed
  166634. * data segment. There should be enough bits in the buffer register
  166635. * to satisfy the request; if so, no problem.
  166636. */
  166637. if (nbits > bits_left) {
  166638. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  166639. * the data stream, so that we can produce some kind of image.
  166640. * We use a nonvolatile flag to ensure that only one warning message
  166641. * appears per data segment.
  166642. */
  166643. if (! cinfo->entropy->insufficient_data) {
  166644. WARNMS(cinfo, JWRN_HIT_MARKER);
  166645. cinfo->entropy->insufficient_data = TRUE;
  166646. }
  166647. /* Fill the buffer with zero bits */
  166648. get_buffer <<= MIN_GET_BITS - bits_left;
  166649. bits_left = MIN_GET_BITS;
  166650. }
  166651. }
  166652. /* Unload the local registers */
  166653. state->next_input_byte = next_input_byte;
  166654. state->bytes_in_buffer = bytes_in_buffer;
  166655. state->get_buffer = get_buffer;
  166656. state->bits_left = bits_left;
  166657. return TRUE;
  166658. }
  166659. /*
  166660. * Out-of-line code for Huffman code decoding.
  166661. * See jdhuff.h for info about usage.
  166662. */
  166663. GLOBAL(int)
  166664. jpeg_huff_decode (bitread_working_state * state,
  166665. register bit_buf_type get_buffer, register int bits_left,
  166666. d_derived_tbl * htbl, int min_bits)
  166667. {
  166668. register int l = min_bits;
  166669. register INT32 code;
  166670. /* HUFF_DECODE has determined that the code is at least min_bits */
  166671. /* bits long, so fetch that many bits in one swoop. */
  166672. CHECK_BIT_BUFFER(*state, l, return -1);
  166673. code = GET_BITS(l);
  166674. /* Collect the rest of the Huffman code one bit at a time. */
  166675. /* This is per Figure F.16 in the JPEG spec. */
  166676. while (code > htbl->maxcode[l]) {
  166677. code <<= 1;
  166678. CHECK_BIT_BUFFER(*state, 1, return -1);
  166679. code |= GET_BITS(1);
  166680. l++;
  166681. }
  166682. /* Unload the local registers */
  166683. state->get_buffer = get_buffer;
  166684. state->bits_left = bits_left;
  166685. /* With garbage input we may reach the sentinel value l = 17. */
  166686. if (l > 16) {
  166687. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  166688. return 0; /* fake a zero as the safest result */
  166689. }
  166690. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  166691. }
  166692. /*
  166693. * Check for a restart marker & resynchronize decoder.
  166694. * Returns FALSE if must suspend.
  166695. */
  166696. LOCAL(boolean)
  166697. process_restart (j_decompress_ptr cinfo)
  166698. {
  166699. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166700. int ci;
  166701. /* Throw away any unused bits remaining in bit buffer; */
  166702. /* include any full bytes in next_marker's count of discarded bytes */
  166703. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  166704. entropy->bitstate.bits_left = 0;
  166705. /* Advance past the RSTn marker */
  166706. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  166707. return FALSE;
  166708. /* Re-initialize DC predictions to 0 */
  166709. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  166710. entropy->saved.last_dc_val[ci] = 0;
  166711. /* Reset restart counter */
  166712. entropy->restarts_to_go = cinfo->restart_interval;
  166713. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  166714. * against a marker. In that case we will end up treating the next data
  166715. * segment as empty, and we can avoid producing bogus output pixels by
  166716. * leaving the flag set.
  166717. */
  166718. if (cinfo->unread_marker == 0)
  166719. entropy->pub.insufficient_data = FALSE;
  166720. return TRUE;
  166721. }
  166722. /*
  166723. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  166724. * The coefficients are reordered from zigzag order into natural array order,
  166725. * but are not dequantized.
  166726. *
  166727. * The i'th block of the MCU is stored into the block pointed to by
  166728. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  166729. * (Wholesale zeroing is usually a little faster than retail...)
  166730. *
  166731. * Returns FALSE if data source requested suspension. In that case no
  166732. * changes have been made to permanent state. (Exception: some output
  166733. * coefficients may already have been assigned. This is harmless for
  166734. * this module, since we'll just re-assign them on the next call.)
  166735. */
  166736. METHODDEF(boolean)
  166737. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166738. {
  166739. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166740. int blkn;
  166741. BITREAD_STATE_VARS;
  166742. savable_state2 state;
  166743. /* Process restart marker if needed; may have to suspend */
  166744. if (cinfo->restart_interval) {
  166745. if (entropy->restarts_to_go == 0)
  166746. if (! process_restart(cinfo))
  166747. return FALSE;
  166748. }
  166749. /* If we've run out of data, just leave the MCU set to zeroes.
  166750. * This way, we return uniform gray for the remainder of the segment.
  166751. */
  166752. if (! entropy->pub.insufficient_data) {
  166753. /* Load up working state */
  166754. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166755. ASSIGN_STATE(state, entropy->saved);
  166756. /* Outer loop handles each block in the MCU */
  166757. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166758. JBLOCKROW block = MCU_data[blkn];
  166759. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  166760. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  166761. register int s, k, r;
  166762. /* Decode a single block's worth of coefficients */
  166763. /* Section F.2.2.1: decode the DC coefficient difference */
  166764. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  166765. if (s) {
  166766. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166767. r = GET_BITS(s);
  166768. s = HUFF_EXTEND(r, s);
  166769. }
  166770. if (entropy->dc_needed[blkn]) {
  166771. /* Convert DC difference to actual value, update last_dc_val */
  166772. int ci = cinfo->MCU_membership[blkn];
  166773. s += state.last_dc_val[ci];
  166774. state.last_dc_val[ci] = s;
  166775. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  166776. (*block)[0] = (JCOEF) s;
  166777. }
  166778. if (entropy->ac_needed[blkn]) {
  166779. /* Section F.2.2.2: decode the AC coefficients */
  166780. /* Since zeroes are skipped, output area must be cleared beforehand */
  166781. for (k = 1; k < DCTSIZE2; k++) {
  166782. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  166783. r = s >> 4;
  166784. s &= 15;
  166785. if (s) {
  166786. k += r;
  166787. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166788. r = GET_BITS(s);
  166789. s = HUFF_EXTEND(r, s);
  166790. /* Output coefficient in natural (dezigzagged) order.
  166791. * Note: the extra entries in jpeg_natural_order[] will save us
  166792. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  166793. */
  166794. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  166795. } else {
  166796. if (r != 15)
  166797. break;
  166798. k += 15;
  166799. }
  166800. }
  166801. } else {
  166802. /* Section F.2.2.2: decode the AC coefficients */
  166803. /* In this path we just discard the values */
  166804. for (k = 1; k < DCTSIZE2; k++) {
  166805. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  166806. r = s >> 4;
  166807. s &= 15;
  166808. if (s) {
  166809. k += r;
  166810. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166811. DROP_BITS(s);
  166812. } else {
  166813. if (r != 15)
  166814. break;
  166815. k += 15;
  166816. }
  166817. }
  166818. }
  166819. }
  166820. /* Completed MCU, so update state */
  166821. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166822. ASSIGN_STATE(entropy->saved, state);
  166823. }
  166824. /* Account for restart interval (no-op if not using restarts) */
  166825. entropy->restarts_to_go--;
  166826. return TRUE;
  166827. }
  166828. /*
  166829. * Module initialization routine for Huffman entropy decoding.
  166830. */
  166831. GLOBAL(void)
  166832. jinit_huff_decoder (j_decompress_ptr cinfo)
  166833. {
  166834. huff_entropy_ptr2 entropy;
  166835. int i;
  166836. entropy = (huff_entropy_ptr2)
  166837. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166838. SIZEOF(huff_entropy_decoder2));
  166839. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  166840. entropy->pub.start_pass = start_pass_huff_decoder;
  166841. entropy->pub.decode_mcu = decode_mcu;
  166842. /* Mark tables unallocated */
  166843. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166844. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  166845. }
  166846. }
  166847. /*** End of inlined file: jdhuff.c ***/
  166848. /*** Start of inlined file: jdinput.c ***/
  166849. #define JPEG_INTERNALS
  166850. /* Private state */
  166851. typedef struct {
  166852. struct jpeg_input_controller pub; /* public fields */
  166853. boolean inheaders; /* TRUE until first SOS is reached */
  166854. } my_input_controller;
  166855. typedef my_input_controller * my_inputctl_ptr;
  166856. /* Forward declarations */
  166857. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  166858. /*
  166859. * Routines to calculate various quantities related to the size of the image.
  166860. */
  166861. LOCAL(void)
  166862. initial_setup2 (j_decompress_ptr cinfo)
  166863. /* Called once, when first SOS marker is reached */
  166864. {
  166865. int ci;
  166866. jpeg_component_info *compptr;
  166867. /* Make sure image isn't bigger than I can handle */
  166868. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  166869. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  166870. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  166871. /* For now, precision must match compiled-in value... */
  166872. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  166873. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  166874. /* Check that number of components won't exceed internal array sizes */
  166875. if (cinfo->num_components > MAX_COMPONENTS)
  166876. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  166877. MAX_COMPONENTS);
  166878. /* Compute maximum sampling factors; check factor validity */
  166879. cinfo->max_h_samp_factor = 1;
  166880. cinfo->max_v_samp_factor = 1;
  166881. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166882. ci++, compptr++) {
  166883. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  166884. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  166885. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  166886. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  166887. compptr->h_samp_factor);
  166888. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  166889. compptr->v_samp_factor);
  166890. }
  166891. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  166892. * In the full decompressor, this will be overridden by jdmaster.c;
  166893. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  166894. */
  166895. cinfo->min_DCT_scaled_size = DCTSIZE;
  166896. /* Compute dimensions of components */
  166897. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166898. ci++, compptr++) {
  166899. compptr->DCT_scaled_size = DCTSIZE;
  166900. /* Size in DCT blocks */
  166901. compptr->width_in_blocks = (JDIMENSION)
  166902. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166903. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166904. compptr->height_in_blocks = (JDIMENSION)
  166905. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166906. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166907. /* downsampled_width and downsampled_height will also be overridden by
  166908. * jdmaster.c if we are doing full decompression. The transcoder library
  166909. * doesn't use these values, but the calling application might.
  166910. */
  166911. /* Size in samples */
  166912. compptr->downsampled_width = (JDIMENSION)
  166913. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166914. (long) cinfo->max_h_samp_factor);
  166915. compptr->downsampled_height = (JDIMENSION)
  166916. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166917. (long) cinfo->max_v_samp_factor);
  166918. /* Mark component needed, until color conversion says otherwise */
  166919. compptr->component_needed = TRUE;
  166920. /* Mark no quantization table yet saved for component */
  166921. compptr->quant_table = NULL;
  166922. }
  166923. /* Compute number of fully interleaved MCU rows. */
  166924. cinfo->total_iMCU_rows = (JDIMENSION)
  166925. jdiv_round_up((long) cinfo->image_height,
  166926. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166927. /* Decide whether file contains multiple scans */
  166928. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  166929. cinfo->inputctl->has_multiple_scans = TRUE;
  166930. else
  166931. cinfo->inputctl->has_multiple_scans = FALSE;
  166932. }
  166933. LOCAL(void)
  166934. per_scan_setup2 (j_decompress_ptr cinfo)
  166935. /* Do computations that are needed before processing a JPEG scan */
  166936. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  166937. {
  166938. int ci, mcublks, tmp;
  166939. jpeg_component_info *compptr;
  166940. if (cinfo->comps_in_scan == 1) {
  166941. /* Noninterleaved (single-component) scan */
  166942. compptr = cinfo->cur_comp_info[0];
  166943. /* Overall image size in MCUs */
  166944. cinfo->MCUs_per_row = compptr->width_in_blocks;
  166945. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  166946. /* For noninterleaved scan, always one block per MCU */
  166947. compptr->MCU_width = 1;
  166948. compptr->MCU_height = 1;
  166949. compptr->MCU_blocks = 1;
  166950. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  166951. compptr->last_col_width = 1;
  166952. /* For noninterleaved scans, it is convenient to define last_row_height
  166953. * as the number of block rows present in the last iMCU row.
  166954. */
  166955. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166956. if (tmp == 0) tmp = compptr->v_samp_factor;
  166957. compptr->last_row_height = tmp;
  166958. /* Prepare array describing MCU composition */
  166959. cinfo->blocks_in_MCU = 1;
  166960. cinfo->MCU_membership[0] = 0;
  166961. } else {
  166962. /* Interleaved (multi-component) scan */
  166963. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  166964. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  166965. MAX_COMPS_IN_SCAN);
  166966. /* Overall image size in MCUs */
  166967. cinfo->MCUs_per_row = (JDIMENSION)
  166968. jdiv_round_up((long) cinfo->image_width,
  166969. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  166970. cinfo->MCU_rows_in_scan = (JDIMENSION)
  166971. jdiv_round_up((long) cinfo->image_height,
  166972. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166973. cinfo->blocks_in_MCU = 0;
  166974. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166975. compptr = cinfo->cur_comp_info[ci];
  166976. /* Sampling factors give # of blocks of component in each MCU */
  166977. compptr->MCU_width = compptr->h_samp_factor;
  166978. compptr->MCU_height = compptr->v_samp_factor;
  166979. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  166980. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  166981. /* Figure number of non-dummy blocks in last MCU column & row */
  166982. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  166983. if (tmp == 0) tmp = compptr->MCU_width;
  166984. compptr->last_col_width = tmp;
  166985. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  166986. if (tmp == 0) tmp = compptr->MCU_height;
  166987. compptr->last_row_height = tmp;
  166988. /* Prepare array describing MCU composition */
  166989. mcublks = compptr->MCU_blocks;
  166990. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  166991. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166992. while (mcublks-- > 0) {
  166993. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166994. }
  166995. }
  166996. }
  166997. }
  166998. /*
  166999. * Save away a copy of the Q-table referenced by each component present
  167000. * in the current scan, unless already saved during a prior scan.
  167001. *
  167002. * In a multiple-scan JPEG file, the encoder could assign different components
  167003. * the same Q-table slot number, but change table definitions between scans
  167004. * so that each component uses a different Q-table. (The IJG encoder is not
  167005. * currently capable of doing this, but other encoders might.) Since we want
  167006. * to be able to dequantize all the components at the end of the file, this
  167007. * means that we have to save away the table actually used for each component.
  167008. * We do this by copying the table at the start of the first scan containing
  167009. * the component.
  167010. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  167011. * slot between scans of a component using that slot. If the encoder does so
  167012. * anyway, this decoder will simply use the Q-table values that were current
  167013. * at the start of the first scan for the component.
  167014. *
  167015. * The decompressor output side looks only at the saved quant tables,
  167016. * not at the current Q-table slots.
  167017. */
  167018. LOCAL(void)
  167019. latch_quant_tables (j_decompress_ptr cinfo)
  167020. {
  167021. int ci, qtblno;
  167022. jpeg_component_info *compptr;
  167023. JQUANT_TBL * qtbl;
  167024. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167025. compptr = cinfo->cur_comp_info[ci];
  167026. /* No work if we already saved Q-table for this component */
  167027. if (compptr->quant_table != NULL)
  167028. continue;
  167029. /* Make sure specified quantization table is present */
  167030. qtblno = compptr->quant_tbl_no;
  167031. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  167032. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  167033. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  167034. /* OK, save away the quantization table */
  167035. qtbl = (JQUANT_TBL *)
  167036. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167037. SIZEOF(JQUANT_TBL));
  167038. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  167039. compptr->quant_table = qtbl;
  167040. }
  167041. }
  167042. /*
  167043. * Initialize the input modules to read a scan of compressed data.
  167044. * The first call to this is done by jdmaster.c after initializing
  167045. * the entire decompressor (during jpeg_start_decompress).
  167046. * Subsequent calls come from consume_markers, below.
  167047. */
  167048. METHODDEF(void)
  167049. start_input_pass2 (j_decompress_ptr cinfo)
  167050. {
  167051. per_scan_setup2(cinfo);
  167052. latch_quant_tables(cinfo);
  167053. (*cinfo->entropy->start_pass) (cinfo);
  167054. (*cinfo->coef->start_input_pass) (cinfo);
  167055. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  167056. }
  167057. /*
  167058. * Finish up after inputting a compressed-data scan.
  167059. * This is called by the coefficient controller after it's read all
  167060. * the expected data of the scan.
  167061. */
  167062. METHODDEF(void)
  167063. finish_input_pass (j_decompress_ptr cinfo)
  167064. {
  167065. cinfo->inputctl->consume_input = consume_markers;
  167066. }
  167067. /*
  167068. * Read JPEG markers before, between, or after compressed-data scans.
  167069. * Change state as necessary when a new scan is reached.
  167070. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167071. *
  167072. * The consume_input method pointer points either here or to the
  167073. * coefficient controller's consume_data routine, depending on whether
  167074. * we are reading a compressed data segment or inter-segment markers.
  167075. */
  167076. METHODDEF(int)
  167077. consume_markers (j_decompress_ptr cinfo)
  167078. {
  167079. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167080. int val;
  167081. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  167082. return JPEG_REACHED_EOI;
  167083. val = (*cinfo->marker->read_markers) (cinfo);
  167084. switch (val) {
  167085. case JPEG_REACHED_SOS: /* Found SOS */
  167086. if (inputctl->inheaders) { /* 1st SOS */
  167087. initial_setup2(cinfo);
  167088. inputctl->inheaders = FALSE;
  167089. /* Note: start_input_pass must be called by jdmaster.c
  167090. * before any more input can be consumed. jdapimin.c is
  167091. * responsible for enforcing this sequencing.
  167092. */
  167093. } else { /* 2nd or later SOS marker */
  167094. if (! inputctl->pub.has_multiple_scans)
  167095. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  167096. start_input_pass2(cinfo);
  167097. }
  167098. break;
  167099. case JPEG_REACHED_EOI: /* Found EOI */
  167100. inputctl->pub.eoi_reached = TRUE;
  167101. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  167102. if (cinfo->marker->saw_SOF)
  167103. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  167104. } else {
  167105. /* Prevent infinite loop in coef ctlr's decompress_data routine
  167106. * if user set output_scan_number larger than number of scans.
  167107. */
  167108. if (cinfo->output_scan_number > cinfo->input_scan_number)
  167109. cinfo->output_scan_number = cinfo->input_scan_number;
  167110. }
  167111. break;
  167112. case JPEG_SUSPENDED:
  167113. break;
  167114. }
  167115. return val;
  167116. }
  167117. /*
  167118. * Reset state to begin a fresh datastream.
  167119. */
  167120. METHODDEF(void)
  167121. reset_input_controller (j_decompress_ptr cinfo)
  167122. {
  167123. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167124. inputctl->pub.consume_input = consume_markers;
  167125. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167126. inputctl->pub.eoi_reached = FALSE;
  167127. inputctl->inheaders = TRUE;
  167128. /* Reset other modules */
  167129. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167130. (*cinfo->marker->reset_marker_reader) (cinfo);
  167131. /* Reset progression state -- would be cleaner if entropy decoder did this */
  167132. cinfo->coef_bits = NULL;
  167133. }
  167134. /*
  167135. * Initialize the input controller module.
  167136. * This is called only once, when the decompression object is created.
  167137. */
  167138. GLOBAL(void)
  167139. jinit_input_controller (j_decompress_ptr cinfo)
  167140. {
  167141. my_inputctl_ptr inputctl;
  167142. /* Create subobject in permanent pool */
  167143. inputctl = (my_inputctl_ptr)
  167144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167145. SIZEOF(my_input_controller));
  167146. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  167147. /* Initialize method pointers */
  167148. inputctl->pub.consume_input = consume_markers;
  167149. inputctl->pub.reset_input_controller = reset_input_controller;
  167150. inputctl->pub.start_input_pass = start_input_pass2;
  167151. inputctl->pub.finish_input_pass = finish_input_pass;
  167152. /* Initialize state: can't use reset_input_controller since we don't
  167153. * want to try to reset other modules yet.
  167154. */
  167155. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167156. inputctl->pub.eoi_reached = FALSE;
  167157. inputctl->inheaders = TRUE;
  167158. }
  167159. /*** End of inlined file: jdinput.c ***/
  167160. /*** Start of inlined file: jdmainct.c ***/
  167161. #define JPEG_INTERNALS
  167162. /*
  167163. * In the current system design, the main buffer need never be a full-image
  167164. * buffer; any full-height buffers will be found inside the coefficient or
  167165. * postprocessing controllers. Nonetheless, the main controller is not
  167166. * trivial. Its responsibility is to provide context rows for upsampling/
  167167. * rescaling, and doing this in an efficient fashion is a bit tricky.
  167168. *
  167169. * Postprocessor input data is counted in "row groups". A row group
  167170. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  167171. * sample rows of each component. (We require DCT_scaled_size values to be
  167172. * chosen such that these numbers are integers. In practice DCT_scaled_size
  167173. * values will likely be powers of two, so we actually have the stronger
  167174. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  167175. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  167176. * row group (times any additional scale factor that the upsampler is
  167177. * applying).
  167178. *
  167179. * The coefficient controller will deliver data to us one iMCU row at a time;
  167180. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  167181. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  167182. * to one row of MCUs when the image is fully interleaved.) Note that the
  167183. * number of sample rows varies across components, but the number of row
  167184. * groups does not. Some garbage sample rows may be included in the last iMCU
  167185. * row at the bottom of the image.
  167186. *
  167187. * Depending on the vertical scaling algorithm used, the upsampler may need
  167188. * access to the sample row(s) above and below its current input row group.
  167189. * The upsampler is required to set need_context_rows TRUE at global selection
  167190. * time if so. When need_context_rows is FALSE, this controller can simply
  167191. * obtain one iMCU row at a time from the coefficient controller and dole it
  167192. * out as row groups to the postprocessor.
  167193. *
  167194. * When need_context_rows is TRUE, this controller guarantees that the buffer
  167195. * passed to postprocessing contains at least one row group's worth of samples
  167196. * above and below the row group(s) being processed. Note that the context
  167197. * rows "above" the first passed row group appear at negative row offsets in
  167198. * the passed buffer. At the top and bottom of the image, the required
  167199. * context rows are manufactured by duplicating the first or last real sample
  167200. * row; this avoids having special cases in the upsampling inner loops.
  167201. *
  167202. * The amount of context is fixed at one row group just because that's a
  167203. * convenient number for this controller to work with. The existing
  167204. * upsamplers really only need one sample row of context. An upsampler
  167205. * supporting arbitrary output rescaling might wish for more than one row
  167206. * group of context when shrinking the image; tough, we don't handle that.
  167207. * (This is justified by the assumption that downsizing will be handled mostly
  167208. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  167209. * the upsample step needn't be much less than one.)
  167210. *
  167211. * To provide the desired context, we have to retain the last two row groups
  167212. * of one iMCU row while reading in the next iMCU row. (The last row group
  167213. * can't be processed until we have another row group for its below-context,
  167214. * and so we have to save the next-to-last group too for its above-context.)
  167215. * We could do this most simply by copying data around in our buffer, but
  167216. * that'd be very slow. We can avoid copying any data by creating a rather
  167217. * strange pointer structure. Here's how it works. We allocate a workspace
  167218. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  167219. * of row groups per iMCU row). We create two sets of redundant pointers to
  167220. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  167221. * pointer lists look like this:
  167222. * M+1 M-1
  167223. * master pointer --> 0 master pointer --> 0
  167224. * 1 1
  167225. * ... ...
  167226. * M-3 M-3
  167227. * M-2 M
  167228. * M-1 M+1
  167229. * M M-2
  167230. * M+1 M-1
  167231. * 0 0
  167232. * We read alternate iMCU rows using each master pointer; thus the last two
  167233. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  167234. * The pointer lists are set up so that the required context rows appear to
  167235. * be adjacent to the proper places when we pass the pointer lists to the
  167236. * upsampler.
  167237. *
  167238. * The above pictures describe the normal state of the pointer lists.
  167239. * At top and bottom of the image, we diddle the pointer lists to duplicate
  167240. * the first or last sample row as necessary (this is cheaper than copying
  167241. * sample rows around).
  167242. *
  167243. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  167244. * situation each iMCU row provides only one row group so the buffering logic
  167245. * must be different (eg, we must read two iMCU rows before we can emit the
  167246. * first row group). For now, we simply do not support providing context
  167247. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  167248. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  167249. * want it quick and dirty, so a context-free upsampler is sufficient.
  167250. */
  167251. /* Private buffer controller object */
  167252. typedef struct {
  167253. struct jpeg_d_main_controller pub; /* public fields */
  167254. /* Pointer to allocated workspace (M or M+2 row groups). */
  167255. JSAMPARRAY buffer[MAX_COMPONENTS];
  167256. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  167257. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  167258. /* Remaining fields are only used in the context case. */
  167259. /* These are the master pointers to the funny-order pointer lists. */
  167260. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  167261. int whichptr; /* indicates which pointer set is now in use */
  167262. int context_state; /* process_data state machine status */
  167263. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  167264. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  167265. } my_main_controller4;
  167266. typedef my_main_controller4 * my_main_ptr4;
  167267. /* context_state values: */
  167268. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  167269. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  167270. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  167271. /* Forward declarations */
  167272. METHODDEF(void) process_data_simple_main2
  167273. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167274. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167275. METHODDEF(void) process_data_context_main
  167276. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167277. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167278. #ifdef QUANT_2PASS_SUPPORTED
  167279. METHODDEF(void) process_data_crank_post
  167280. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167281. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167282. #endif
  167283. LOCAL(void)
  167284. alloc_funny_pointers (j_decompress_ptr cinfo)
  167285. /* Allocate space for the funny pointer lists.
  167286. * This is done only once, not once per pass.
  167287. */
  167288. {
  167289. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167290. int ci, rgroup;
  167291. int M = cinfo->min_DCT_scaled_size;
  167292. jpeg_component_info *compptr;
  167293. JSAMPARRAY xbuf;
  167294. /* Get top-level space for component array pointers.
  167295. * We alloc both arrays with one call to save a few cycles.
  167296. */
  167297. main_->xbuffer[0] = (JSAMPIMAGE)
  167298. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167299. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  167300. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  167301. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167302. ci++, compptr++) {
  167303. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167304. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167305. /* Get space for pointer lists --- M+4 row groups in each list.
  167306. * We alloc both pointer lists with one call to save a few cycles.
  167307. */
  167308. xbuf = (JSAMPARRAY)
  167309. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167310. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  167311. xbuf += rgroup; /* want one row group at negative offsets */
  167312. main_->xbuffer[0][ci] = xbuf;
  167313. xbuf += rgroup * (M + 4);
  167314. main_->xbuffer[1][ci] = xbuf;
  167315. }
  167316. }
  167317. LOCAL(void)
  167318. make_funny_pointers (j_decompress_ptr cinfo)
  167319. /* Create the funny pointer lists discussed in the comments above.
  167320. * The actual workspace is already allocated (in main->buffer),
  167321. * and the space for the pointer lists is allocated too.
  167322. * This routine just fills in the curiously ordered lists.
  167323. * This will be repeated at the beginning of each pass.
  167324. */
  167325. {
  167326. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167327. int ci, i, rgroup;
  167328. int M = cinfo->min_DCT_scaled_size;
  167329. jpeg_component_info *compptr;
  167330. JSAMPARRAY buf, xbuf0, xbuf1;
  167331. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167332. ci++, compptr++) {
  167333. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167334. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167335. xbuf0 = main_->xbuffer[0][ci];
  167336. xbuf1 = main_->xbuffer[1][ci];
  167337. /* First copy the workspace pointers as-is */
  167338. buf = main_->buffer[ci];
  167339. for (i = 0; i < rgroup * (M + 2); i++) {
  167340. xbuf0[i] = xbuf1[i] = buf[i];
  167341. }
  167342. /* In the second list, put the last four row groups in swapped order */
  167343. for (i = 0; i < rgroup * 2; i++) {
  167344. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  167345. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  167346. }
  167347. /* The wraparound pointers at top and bottom will be filled later
  167348. * (see set_wraparound_pointers, below). Initially we want the "above"
  167349. * pointers to duplicate the first actual data line. This only needs
  167350. * to happen in xbuffer[0].
  167351. */
  167352. for (i = 0; i < rgroup; i++) {
  167353. xbuf0[i - rgroup] = xbuf0[0];
  167354. }
  167355. }
  167356. }
  167357. LOCAL(void)
  167358. set_wraparound_pointers (j_decompress_ptr cinfo)
  167359. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  167360. * This changes the pointer list state from top-of-image to the normal state.
  167361. */
  167362. {
  167363. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167364. int ci, i, rgroup;
  167365. int M = cinfo->min_DCT_scaled_size;
  167366. jpeg_component_info *compptr;
  167367. JSAMPARRAY xbuf0, xbuf1;
  167368. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167369. ci++, compptr++) {
  167370. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167371. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167372. xbuf0 = main_->xbuffer[0][ci];
  167373. xbuf1 = main_->xbuffer[1][ci];
  167374. for (i = 0; i < rgroup; i++) {
  167375. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  167376. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  167377. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  167378. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  167379. }
  167380. }
  167381. }
  167382. LOCAL(void)
  167383. set_bottom_pointers (j_decompress_ptr cinfo)
  167384. /* Change the pointer lists to duplicate the last sample row at the bottom
  167385. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  167386. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  167387. */
  167388. {
  167389. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167390. int ci, i, rgroup, iMCUheight, rows_left;
  167391. jpeg_component_info *compptr;
  167392. JSAMPARRAY xbuf;
  167393. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167394. ci++, compptr++) {
  167395. /* Count sample rows in one iMCU row and in one row group */
  167396. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  167397. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  167398. /* Count nondummy sample rows remaining for this component */
  167399. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  167400. if (rows_left == 0) rows_left = iMCUheight;
  167401. /* Count nondummy row groups. Should get same answer for each component,
  167402. * so we need only do it once.
  167403. */
  167404. if (ci == 0) {
  167405. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  167406. }
  167407. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  167408. * last partial rowgroup and ensures at least one full rowgroup of context.
  167409. */
  167410. xbuf = main_->xbuffer[main_->whichptr][ci];
  167411. for (i = 0; i < rgroup * 2; i++) {
  167412. xbuf[rows_left + i] = xbuf[rows_left-1];
  167413. }
  167414. }
  167415. }
  167416. /*
  167417. * Initialize for a processing pass.
  167418. */
  167419. METHODDEF(void)
  167420. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  167421. {
  167422. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167423. switch (pass_mode) {
  167424. case JBUF_PASS_THRU:
  167425. if (cinfo->upsample->need_context_rows) {
  167426. main_->pub.process_data = process_data_context_main;
  167427. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  167428. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  167429. main_->context_state = CTX_PREPARE_FOR_IMCU;
  167430. main_->iMCU_row_ctr = 0;
  167431. } else {
  167432. /* Simple case with no context needed */
  167433. main_->pub.process_data = process_data_simple_main2;
  167434. }
  167435. main_->buffer_full = FALSE; /* Mark buffer empty */
  167436. main_->rowgroup_ctr = 0;
  167437. break;
  167438. #ifdef QUANT_2PASS_SUPPORTED
  167439. case JBUF_CRANK_DEST:
  167440. /* For last pass of 2-pass quantization, just crank the postprocessor */
  167441. main_->pub.process_data = process_data_crank_post;
  167442. break;
  167443. #endif
  167444. default:
  167445. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167446. break;
  167447. }
  167448. }
  167449. /*
  167450. * Process some data.
  167451. * This handles the simple case where no context is required.
  167452. */
  167453. METHODDEF(void)
  167454. process_data_simple_main2 (j_decompress_ptr cinfo,
  167455. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167456. JDIMENSION out_rows_avail)
  167457. {
  167458. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167459. JDIMENSION rowgroups_avail;
  167460. /* Read input data if we haven't filled the main buffer yet */
  167461. if (! main_->buffer_full) {
  167462. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  167463. return; /* suspension forced, can do nothing more */
  167464. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  167465. }
  167466. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  167467. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  167468. /* Note: at the bottom of the image, we may pass extra garbage row groups
  167469. * to the postprocessor. The postprocessor has to check for bottom
  167470. * of image anyway (at row resolution), so no point in us doing it too.
  167471. */
  167472. /* Feed the postprocessor */
  167473. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  167474. &main_->rowgroup_ctr, rowgroups_avail,
  167475. output_buf, out_row_ctr, out_rows_avail);
  167476. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  167477. if (main_->rowgroup_ctr >= rowgroups_avail) {
  167478. main_->buffer_full = FALSE;
  167479. main_->rowgroup_ctr = 0;
  167480. }
  167481. }
  167482. /*
  167483. * Process some data.
  167484. * This handles the case where context rows must be provided.
  167485. */
  167486. METHODDEF(void)
  167487. process_data_context_main (j_decompress_ptr cinfo,
  167488. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167489. JDIMENSION out_rows_avail)
  167490. {
  167491. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167492. /* Read input data if we haven't filled the main buffer yet */
  167493. if (! main_->buffer_full) {
  167494. if (! (*cinfo->coef->decompress_data) (cinfo,
  167495. main_->xbuffer[main_->whichptr]))
  167496. return; /* suspension forced, can do nothing more */
  167497. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  167498. main_->iMCU_row_ctr++; /* count rows received */
  167499. }
  167500. /* Postprocessor typically will not swallow all the input data it is handed
  167501. * in one call (due to filling the output buffer first). Must be prepared
  167502. * to exit and restart. This switch lets us keep track of how far we got.
  167503. * Note that each case falls through to the next on successful completion.
  167504. */
  167505. switch (main_->context_state) {
  167506. case CTX_POSTPONED_ROW:
  167507. /* Call postprocessor using previously set pointers for postponed row */
  167508. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  167509. &main_->rowgroup_ctr, main_->rowgroups_avail,
  167510. output_buf, out_row_ctr, out_rows_avail);
  167511. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  167512. return; /* Need to suspend */
  167513. main_->context_state = CTX_PREPARE_FOR_IMCU;
  167514. if (*out_row_ctr >= out_rows_avail)
  167515. return; /* Postprocessor exactly filled output buf */
  167516. /*FALLTHROUGH*/
  167517. case CTX_PREPARE_FOR_IMCU:
  167518. /* Prepare to process first M-1 row groups of this iMCU row */
  167519. main_->rowgroup_ctr = 0;
  167520. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  167521. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  167522. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  167523. */
  167524. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  167525. set_bottom_pointers(cinfo);
  167526. main_->context_state = CTX_PROCESS_IMCU;
  167527. /*FALLTHROUGH*/
  167528. case CTX_PROCESS_IMCU:
  167529. /* Call postprocessor using previously set pointers */
  167530. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  167531. &main_->rowgroup_ctr, main_->rowgroups_avail,
  167532. output_buf, out_row_ctr, out_rows_avail);
  167533. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  167534. return; /* Need to suspend */
  167535. /* After the first iMCU, change wraparound pointers to normal state */
  167536. if (main_->iMCU_row_ctr == 1)
  167537. set_wraparound_pointers(cinfo);
  167538. /* Prepare to load new iMCU row using other xbuffer list */
  167539. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  167540. main_->buffer_full = FALSE;
  167541. /* Still need to process last row group of this iMCU row, */
  167542. /* which is saved at index M+1 of the other xbuffer */
  167543. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  167544. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  167545. main_->context_state = CTX_POSTPONED_ROW;
  167546. }
  167547. }
  167548. /*
  167549. * Process some data.
  167550. * Final pass of two-pass quantization: just call the postprocessor.
  167551. * Source data will be the postprocessor controller's internal buffer.
  167552. */
  167553. #ifdef QUANT_2PASS_SUPPORTED
  167554. METHODDEF(void)
  167555. process_data_crank_post (j_decompress_ptr cinfo,
  167556. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167557. JDIMENSION out_rows_avail)
  167558. {
  167559. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  167560. (JDIMENSION *) NULL, (JDIMENSION) 0,
  167561. output_buf, out_row_ctr, out_rows_avail);
  167562. }
  167563. #endif /* QUANT_2PASS_SUPPORTED */
  167564. /*
  167565. * Initialize main buffer controller.
  167566. */
  167567. GLOBAL(void)
  167568. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167569. {
  167570. my_main_ptr4 main_;
  167571. int ci, rgroup, ngroups;
  167572. jpeg_component_info *compptr;
  167573. main_ = (my_main_ptr4)
  167574. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167575. SIZEOF(my_main_controller4));
  167576. cinfo->main = (struct jpeg_d_main_controller *) main_;
  167577. main_->pub.start_pass = start_pass_main2;
  167578. if (need_full_buffer) /* shouldn't happen */
  167579. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167580. /* Allocate the workspace.
  167581. * ngroups is the number of row groups we need.
  167582. */
  167583. if (cinfo->upsample->need_context_rows) {
  167584. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  167585. ERREXIT(cinfo, JERR_NOTIMPL);
  167586. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  167587. ngroups = cinfo->min_DCT_scaled_size + 2;
  167588. } else {
  167589. ngroups = cinfo->min_DCT_scaled_size;
  167590. }
  167591. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167592. ci++, compptr++) {
  167593. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167594. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167595. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  167596. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167597. compptr->width_in_blocks * compptr->DCT_scaled_size,
  167598. (JDIMENSION) (rgroup * ngroups));
  167599. }
  167600. }
  167601. /*** End of inlined file: jdmainct.c ***/
  167602. /*** Start of inlined file: jdmarker.c ***/
  167603. #define JPEG_INTERNALS
  167604. /* Private state */
  167605. typedef struct {
  167606. struct jpeg_marker_reader pub; /* public fields */
  167607. /* Application-overridable marker processing methods */
  167608. jpeg_marker_parser_method process_COM;
  167609. jpeg_marker_parser_method process_APPn[16];
  167610. /* Limit on marker data length to save for each marker type */
  167611. unsigned int length_limit_COM;
  167612. unsigned int length_limit_APPn[16];
  167613. /* Status of COM/APPn marker saving */
  167614. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  167615. unsigned int bytes_read; /* data bytes read so far in marker */
  167616. /* Note: cur_marker is not linked into marker_list until it's all read. */
  167617. } my_marker_reader;
  167618. typedef my_marker_reader * my_marker_ptr2;
  167619. /*
  167620. * Macros for fetching data from the data source module.
  167621. *
  167622. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  167623. * the current restart point; we update them only when we have reached a
  167624. * suitable place to restart if a suspension occurs.
  167625. */
  167626. /* Declare and initialize local copies of input pointer/count */
  167627. #define INPUT_VARS(cinfo) \
  167628. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  167629. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  167630. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  167631. /* Unload the local copies --- do this only at a restart boundary */
  167632. #define INPUT_SYNC(cinfo) \
  167633. ( datasrc->next_input_byte = next_input_byte, \
  167634. datasrc->bytes_in_buffer = bytes_in_buffer )
  167635. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  167636. #define INPUT_RELOAD(cinfo) \
  167637. ( next_input_byte = datasrc->next_input_byte, \
  167638. bytes_in_buffer = datasrc->bytes_in_buffer )
  167639. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  167640. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  167641. * but we must reload the local copies after a successful fill.
  167642. */
  167643. #define MAKE_BYTE_AVAIL(cinfo,action) \
  167644. if (bytes_in_buffer == 0) { \
  167645. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  167646. { action; } \
  167647. INPUT_RELOAD(cinfo); \
  167648. }
  167649. /* Read a byte into variable V.
  167650. * If must suspend, take the specified action (typically "return FALSE").
  167651. */
  167652. #define INPUT_BYTE(cinfo,V,action) \
  167653. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  167654. bytes_in_buffer--; \
  167655. V = GETJOCTET(*next_input_byte++); )
  167656. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  167657. * V should be declared unsigned int or perhaps INT32.
  167658. */
  167659. #define INPUT_2BYTES(cinfo,V,action) \
  167660. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  167661. bytes_in_buffer--; \
  167662. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  167663. MAKE_BYTE_AVAIL(cinfo,action); \
  167664. bytes_in_buffer--; \
  167665. V += GETJOCTET(*next_input_byte++); )
  167666. /*
  167667. * Routines to process JPEG markers.
  167668. *
  167669. * Entry condition: JPEG marker itself has been read and its code saved
  167670. * in cinfo->unread_marker; input restart point is just after the marker.
  167671. *
  167672. * Exit: if return TRUE, have read and processed any parameters, and have
  167673. * updated the restart point to point after the parameters.
  167674. * If return FALSE, was forced to suspend before reaching end of
  167675. * marker parameters; restart point has not been moved. Same routine
  167676. * will be called again after application supplies more input data.
  167677. *
  167678. * This approach to suspension assumes that all of a marker's parameters
  167679. * can fit into a single input bufferload. This should hold for "normal"
  167680. * markers. Some COM/APPn markers might have large parameter segments
  167681. * that might not fit. If we are simply dropping such a marker, we use
  167682. * skip_input_data to get past it, and thereby put the problem on the
  167683. * source manager's shoulders. If we are saving the marker's contents
  167684. * into memory, we use a slightly different convention: when forced to
  167685. * suspend, the marker processor updates the restart point to the end of
  167686. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  167687. * On resumption, cinfo->unread_marker still contains the marker code,
  167688. * but the data source will point to the next chunk of marker data.
  167689. * The marker processor must retain internal state to deal with this.
  167690. *
  167691. * Note that we don't bother to avoid duplicate trace messages if a
  167692. * suspension occurs within marker parameters. Other side effects
  167693. * require more care.
  167694. */
  167695. LOCAL(boolean)
  167696. get_soi (j_decompress_ptr cinfo)
  167697. /* Process an SOI marker */
  167698. {
  167699. int i;
  167700. TRACEMS(cinfo, 1, JTRC_SOI);
  167701. if (cinfo->marker->saw_SOI)
  167702. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  167703. /* Reset all parameters that are defined to be reset by SOI */
  167704. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  167705. cinfo->arith_dc_L[i] = 0;
  167706. cinfo->arith_dc_U[i] = 1;
  167707. cinfo->arith_ac_K[i] = 5;
  167708. }
  167709. cinfo->restart_interval = 0;
  167710. /* Set initial assumptions for colorspace etc */
  167711. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167712. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  167713. cinfo->saw_JFIF_marker = FALSE;
  167714. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  167715. cinfo->JFIF_minor_version = 1;
  167716. cinfo->density_unit = 0;
  167717. cinfo->X_density = 1;
  167718. cinfo->Y_density = 1;
  167719. cinfo->saw_Adobe_marker = FALSE;
  167720. cinfo->Adobe_transform = 0;
  167721. cinfo->marker->saw_SOI = TRUE;
  167722. return TRUE;
  167723. }
  167724. LOCAL(boolean)
  167725. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  167726. /* Process a SOFn marker */
  167727. {
  167728. INT32 length;
  167729. int c, ci;
  167730. jpeg_component_info * compptr;
  167731. INPUT_VARS(cinfo);
  167732. cinfo->progressive_mode = is_prog;
  167733. cinfo->arith_code = is_arith;
  167734. INPUT_2BYTES(cinfo, length, return FALSE);
  167735. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  167736. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  167737. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  167738. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  167739. length -= 8;
  167740. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  167741. (int) cinfo->image_width, (int) cinfo->image_height,
  167742. cinfo->num_components);
  167743. if (cinfo->marker->saw_SOF)
  167744. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  167745. /* We don't support files in which the image height is initially specified */
  167746. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  167747. /* might as well have a general sanity check. */
  167748. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  167749. || cinfo->num_components <= 0)
  167750. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  167751. if (length != (cinfo->num_components * 3))
  167752. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167753. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  167754. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  167755. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167756. cinfo->num_components * SIZEOF(jpeg_component_info));
  167757. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167758. ci++, compptr++) {
  167759. compptr->component_index = ci;
  167760. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  167761. INPUT_BYTE(cinfo, c, return FALSE);
  167762. compptr->h_samp_factor = (c >> 4) & 15;
  167763. compptr->v_samp_factor = (c ) & 15;
  167764. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  167765. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  167766. compptr->component_id, compptr->h_samp_factor,
  167767. compptr->v_samp_factor, compptr->quant_tbl_no);
  167768. }
  167769. cinfo->marker->saw_SOF = TRUE;
  167770. INPUT_SYNC(cinfo);
  167771. return TRUE;
  167772. }
  167773. LOCAL(boolean)
  167774. get_sos (j_decompress_ptr cinfo)
  167775. /* Process a SOS marker */
  167776. {
  167777. INT32 length;
  167778. int i, ci, n, c, cc;
  167779. jpeg_component_info * compptr;
  167780. INPUT_VARS(cinfo);
  167781. if (! cinfo->marker->saw_SOF)
  167782. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  167783. INPUT_2BYTES(cinfo, length, return FALSE);
  167784. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  167785. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  167786. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  167787. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167788. cinfo->comps_in_scan = n;
  167789. /* Collect the component-spec parameters */
  167790. for (i = 0; i < n; i++) {
  167791. INPUT_BYTE(cinfo, cc, return FALSE);
  167792. INPUT_BYTE(cinfo, c, return FALSE);
  167793. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167794. ci++, compptr++) {
  167795. if (cc == compptr->component_id)
  167796. goto id_found;
  167797. }
  167798. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  167799. id_found:
  167800. cinfo->cur_comp_info[i] = compptr;
  167801. compptr->dc_tbl_no = (c >> 4) & 15;
  167802. compptr->ac_tbl_no = (c ) & 15;
  167803. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  167804. compptr->dc_tbl_no, compptr->ac_tbl_no);
  167805. }
  167806. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  167807. INPUT_BYTE(cinfo, c, return FALSE);
  167808. cinfo->Ss = c;
  167809. INPUT_BYTE(cinfo, c, return FALSE);
  167810. cinfo->Se = c;
  167811. INPUT_BYTE(cinfo, c, return FALSE);
  167812. cinfo->Ah = (c >> 4) & 15;
  167813. cinfo->Al = (c ) & 15;
  167814. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  167815. cinfo->Ah, cinfo->Al);
  167816. /* Prepare to scan data & restart markers */
  167817. cinfo->marker->next_restart_num = 0;
  167818. /* Count another SOS marker */
  167819. cinfo->input_scan_number++;
  167820. INPUT_SYNC(cinfo);
  167821. return TRUE;
  167822. }
  167823. #ifdef D_ARITH_CODING_SUPPORTED
  167824. LOCAL(boolean)
  167825. get_dac (j_decompress_ptr cinfo)
  167826. /* Process a DAC marker */
  167827. {
  167828. INT32 length;
  167829. int index, val;
  167830. INPUT_VARS(cinfo);
  167831. INPUT_2BYTES(cinfo, length, return FALSE);
  167832. length -= 2;
  167833. while (length > 0) {
  167834. INPUT_BYTE(cinfo, index, return FALSE);
  167835. INPUT_BYTE(cinfo, val, return FALSE);
  167836. length -= 2;
  167837. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  167838. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  167839. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  167840. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  167841. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  167842. } else { /* define DC table */
  167843. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  167844. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  167845. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  167846. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  167847. }
  167848. }
  167849. if (length != 0)
  167850. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167851. INPUT_SYNC(cinfo);
  167852. return TRUE;
  167853. }
  167854. #else /* ! D_ARITH_CODING_SUPPORTED */
  167855. #define get_dac(cinfo) skip_variable(cinfo)
  167856. #endif /* D_ARITH_CODING_SUPPORTED */
  167857. LOCAL(boolean)
  167858. get_dht (j_decompress_ptr cinfo)
  167859. /* Process a DHT marker */
  167860. {
  167861. INT32 length;
  167862. UINT8 bits[17];
  167863. UINT8 huffval[256];
  167864. int i, index, count;
  167865. JHUFF_TBL **htblptr;
  167866. INPUT_VARS(cinfo);
  167867. INPUT_2BYTES(cinfo, length, return FALSE);
  167868. length -= 2;
  167869. while (length > 16) {
  167870. INPUT_BYTE(cinfo, index, return FALSE);
  167871. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  167872. bits[0] = 0;
  167873. count = 0;
  167874. for (i = 1; i <= 16; i++) {
  167875. INPUT_BYTE(cinfo, bits[i], return FALSE);
  167876. count += bits[i];
  167877. }
  167878. length -= 1 + 16;
  167879. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167880. bits[1], bits[2], bits[3], bits[4],
  167881. bits[5], bits[6], bits[7], bits[8]);
  167882. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167883. bits[9], bits[10], bits[11], bits[12],
  167884. bits[13], bits[14], bits[15], bits[16]);
  167885. /* Here we just do minimal validation of the counts to avoid walking
  167886. * off the end of our table space. jdhuff.c will check more carefully.
  167887. */
  167888. if (count > 256 || ((INT32) count) > length)
  167889. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167890. for (i = 0; i < count; i++)
  167891. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  167892. length -= count;
  167893. if (index & 0x10) { /* AC table definition */
  167894. index -= 0x10;
  167895. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  167896. } else { /* DC table definition */
  167897. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  167898. }
  167899. if (index < 0 || index >= NUM_HUFF_TBLS)
  167900. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  167901. if (*htblptr == NULL)
  167902. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  167903. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  167904. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  167905. }
  167906. if (length != 0)
  167907. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167908. INPUT_SYNC(cinfo);
  167909. return TRUE;
  167910. }
  167911. LOCAL(boolean)
  167912. get_dqt (j_decompress_ptr cinfo)
  167913. /* Process a DQT marker */
  167914. {
  167915. INT32 length;
  167916. int n, i, prec;
  167917. unsigned int tmp;
  167918. JQUANT_TBL *quant_ptr;
  167919. INPUT_VARS(cinfo);
  167920. INPUT_2BYTES(cinfo, length, return FALSE);
  167921. length -= 2;
  167922. while (length > 0) {
  167923. INPUT_BYTE(cinfo, n, return FALSE);
  167924. prec = n >> 4;
  167925. n &= 0x0F;
  167926. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  167927. if (n >= NUM_QUANT_TBLS)
  167928. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  167929. if (cinfo->quant_tbl_ptrs[n] == NULL)
  167930. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  167931. quant_ptr = cinfo->quant_tbl_ptrs[n];
  167932. for (i = 0; i < DCTSIZE2; i++) {
  167933. if (prec)
  167934. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167935. else
  167936. INPUT_BYTE(cinfo, tmp, return FALSE);
  167937. /* We convert the zigzag-order table to natural array order. */
  167938. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  167939. }
  167940. if (cinfo->err->trace_level >= 2) {
  167941. for (i = 0; i < DCTSIZE2; i += 8) {
  167942. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  167943. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  167944. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  167945. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  167946. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  167947. }
  167948. }
  167949. length -= DCTSIZE2+1;
  167950. if (prec) length -= DCTSIZE2;
  167951. }
  167952. if (length != 0)
  167953. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167954. INPUT_SYNC(cinfo);
  167955. return TRUE;
  167956. }
  167957. LOCAL(boolean)
  167958. get_dri (j_decompress_ptr cinfo)
  167959. /* Process a DRI marker */
  167960. {
  167961. INT32 length;
  167962. unsigned int tmp;
  167963. INPUT_VARS(cinfo);
  167964. INPUT_2BYTES(cinfo, length, return FALSE);
  167965. if (length != 4)
  167966. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167967. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167968. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  167969. cinfo->restart_interval = tmp;
  167970. INPUT_SYNC(cinfo);
  167971. return TRUE;
  167972. }
  167973. /*
  167974. * Routines for processing APPn and COM markers.
  167975. * These are either saved in memory or discarded, per application request.
  167976. * APP0 and APP14 are specially checked to see if they are
  167977. * JFIF and Adobe markers, respectively.
  167978. */
  167979. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  167980. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  167981. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  167982. LOCAL(void)
  167983. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167984. unsigned int datalen, INT32 remaining)
  167985. /* Examine first few bytes from an APP0.
  167986. * Take appropriate action if it is a JFIF marker.
  167987. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167988. */
  167989. {
  167990. INT32 totallen = (INT32) datalen + remaining;
  167991. if (datalen >= APP0_DATA_LEN &&
  167992. GETJOCTET(data[0]) == 0x4A &&
  167993. GETJOCTET(data[1]) == 0x46 &&
  167994. GETJOCTET(data[2]) == 0x49 &&
  167995. GETJOCTET(data[3]) == 0x46 &&
  167996. GETJOCTET(data[4]) == 0) {
  167997. /* Found JFIF APP0 marker: save info */
  167998. cinfo->saw_JFIF_marker = TRUE;
  167999. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  168000. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  168001. cinfo->density_unit = GETJOCTET(data[7]);
  168002. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  168003. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  168004. /* Check version.
  168005. * Major version must be 1, anything else signals an incompatible change.
  168006. * (We used to treat this as an error, but now it's a nonfatal warning,
  168007. * because some bozo at Hijaak couldn't read the spec.)
  168008. * Minor version should be 0..2, but process anyway if newer.
  168009. */
  168010. if (cinfo->JFIF_major_version != 1)
  168011. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  168012. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  168013. /* Generate trace messages */
  168014. TRACEMS5(cinfo, 1, JTRC_JFIF,
  168015. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  168016. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  168017. /* Validate thumbnail dimensions and issue appropriate messages */
  168018. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  168019. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  168020. GETJOCTET(data[12]), GETJOCTET(data[13]));
  168021. totallen -= APP0_DATA_LEN;
  168022. if (totallen !=
  168023. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  168024. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  168025. } else if (datalen >= 6 &&
  168026. GETJOCTET(data[0]) == 0x4A &&
  168027. GETJOCTET(data[1]) == 0x46 &&
  168028. GETJOCTET(data[2]) == 0x58 &&
  168029. GETJOCTET(data[3]) == 0x58 &&
  168030. GETJOCTET(data[4]) == 0) {
  168031. /* Found JFIF "JFXX" extension APP0 marker */
  168032. /* The library doesn't actually do anything with these,
  168033. * but we try to produce a helpful trace message.
  168034. */
  168035. switch (GETJOCTET(data[5])) {
  168036. case 0x10:
  168037. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  168038. break;
  168039. case 0x11:
  168040. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  168041. break;
  168042. case 0x13:
  168043. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  168044. break;
  168045. default:
  168046. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  168047. GETJOCTET(data[5]), (int) totallen);
  168048. break;
  168049. }
  168050. } else {
  168051. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  168052. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  168053. }
  168054. }
  168055. LOCAL(void)
  168056. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  168057. unsigned int datalen, INT32 remaining)
  168058. /* Examine first few bytes from an APP14.
  168059. * Take appropriate action if it is an Adobe marker.
  168060. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  168061. */
  168062. {
  168063. unsigned int version, flags0, flags1, transform;
  168064. if (datalen >= APP14_DATA_LEN &&
  168065. GETJOCTET(data[0]) == 0x41 &&
  168066. GETJOCTET(data[1]) == 0x64 &&
  168067. GETJOCTET(data[2]) == 0x6F &&
  168068. GETJOCTET(data[3]) == 0x62 &&
  168069. GETJOCTET(data[4]) == 0x65) {
  168070. /* Found Adobe APP14 marker */
  168071. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  168072. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  168073. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  168074. transform = GETJOCTET(data[11]);
  168075. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  168076. cinfo->saw_Adobe_marker = TRUE;
  168077. cinfo->Adobe_transform = (UINT8) transform;
  168078. } else {
  168079. /* Start of APP14 does not match "Adobe", or too short */
  168080. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  168081. }
  168082. }
  168083. METHODDEF(boolean)
  168084. get_interesting_appn (j_decompress_ptr cinfo)
  168085. /* Process an APP0 or APP14 marker without saving it */
  168086. {
  168087. INT32 length;
  168088. JOCTET b[APPN_DATA_LEN];
  168089. unsigned int i, numtoread;
  168090. INPUT_VARS(cinfo);
  168091. INPUT_2BYTES(cinfo, length, return FALSE);
  168092. length -= 2;
  168093. /* get the interesting part of the marker data */
  168094. if (length >= APPN_DATA_LEN)
  168095. numtoread = APPN_DATA_LEN;
  168096. else if (length > 0)
  168097. numtoread = (unsigned int) length;
  168098. else
  168099. numtoread = 0;
  168100. for (i = 0; i < numtoread; i++)
  168101. INPUT_BYTE(cinfo, b[i], return FALSE);
  168102. length -= numtoread;
  168103. /* process it */
  168104. switch (cinfo->unread_marker) {
  168105. case M_APP0:
  168106. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  168107. break;
  168108. case M_APP14:
  168109. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  168110. break;
  168111. default:
  168112. /* can't get here unless jpeg_save_markers chooses wrong processor */
  168113. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168114. break;
  168115. }
  168116. /* skip any remaining data -- could be lots */
  168117. INPUT_SYNC(cinfo);
  168118. if (length > 0)
  168119. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168120. return TRUE;
  168121. }
  168122. #ifdef SAVE_MARKERS_SUPPORTED
  168123. METHODDEF(boolean)
  168124. save_marker (j_decompress_ptr cinfo)
  168125. /* Save an APPn or COM marker into the marker list */
  168126. {
  168127. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168128. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  168129. unsigned int bytes_read, data_length;
  168130. JOCTET FAR * data;
  168131. INT32 length = 0;
  168132. INPUT_VARS(cinfo);
  168133. if (cur_marker == NULL) {
  168134. /* begin reading a marker */
  168135. INPUT_2BYTES(cinfo, length, return FALSE);
  168136. length -= 2;
  168137. if (length >= 0) { /* watch out for bogus length word */
  168138. /* figure out how much we want to save */
  168139. unsigned int limit;
  168140. if (cinfo->unread_marker == (int) M_COM)
  168141. limit = marker->length_limit_COM;
  168142. else
  168143. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  168144. if ((unsigned int) length < limit)
  168145. limit = (unsigned int) length;
  168146. /* allocate and initialize the marker item */
  168147. cur_marker = (jpeg_saved_marker_ptr)
  168148. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168149. SIZEOF(struct jpeg_marker_struct) + limit);
  168150. cur_marker->next = NULL;
  168151. cur_marker->marker = (UINT8) cinfo->unread_marker;
  168152. cur_marker->original_length = (unsigned int) length;
  168153. cur_marker->data_length = limit;
  168154. /* data area is just beyond the jpeg_marker_struct */
  168155. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  168156. marker->cur_marker = cur_marker;
  168157. marker->bytes_read = 0;
  168158. bytes_read = 0;
  168159. data_length = limit;
  168160. } else {
  168161. /* deal with bogus length word */
  168162. bytes_read = data_length = 0;
  168163. data = NULL;
  168164. }
  168165. } else {
  168166. /* resume reading a marker */
  168167. bytes_read = marker->bytes_read;
  168168. data_length = cur_marker->data_length;
  168169. data = cur_marker->data + bytes_read;
  168170. }
  168171. while (bytes_read < data_length) {
  168172. INPUT_SYNC(cinfo); /* move the restart point to here */
  168173. marker->bytes_read = bytes_read;
  168174. /* If there's not at least one byte in buffer, suspend */
  168175. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  168176. /* Copy bytes with reasonable rapidity */
  168177. while (bytes_read < data_length && bytes_in_buffer > 0) {
  168178. *data++ = *next_input_byte++;
  168179. bytes_in_buffer--;
  168180. bytes_read++;
  168181. }
  168182. }
  168183. /* Done reading what we want to read */
  168184. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  168185. /* Add new marker to end of list */
  168186. if (cinfo->marker_list == NULL) {
  168187. cinfo->marker_list = cur_marker;
  168188. } else {
  168189. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  168190. while (prev->next != NULL)
  168191. prev = prev->next;
  168192. prev->next = cur_marker;
  168193. }
  168194. /* Reset pointer & calc remaining data length */
  168195. data = cur_marker->data;
  168196. length = cur_marker->original_length - data_length;
  168197. }
  168198. /* Reset to initial state for next marker */
  168199. marker->cur_marker = NULL;
  168200. /* Process the marker if interesting; else just make a generic trace msg */
  168201. switch (cinfo->unread_marker) {
  168202. case M_APP0:
  168203. examine_app0(cinfo, data, data_length, length);
  168204. break;
  168205. case M_APP14:
  168206. examine_app14(cinfo, data, data_length, length);
  168207. break;
  168208. default:
  168209. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  168210. (int) (data_length + length));
  168211. break;
  168212. }
  168213. /* skip any remaining data -- could be lots */
  168214. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168215. if (length > 0)
  168216. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168217. return TRUE;
  168218. }
  168219. #endif /* SAVE_MARKERS_SUPPORTED */
  168220. METHODDEF(boolean)
  168221. skip_variable (j_decompress_ptr cinfo)
  168222. /* Skip over an unknown or uninteresting variable-length marker */
  168223. {
  168224. INT32 length;
  168225. INPUT_VARS(cinfo);
  168226. INPUT_2BYTES(cinfo, length, return FALSE);
  168227. length -= 2;
  168228. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  168229. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168230. if (length > 0)
  168231. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168232. return TRUE;
  168233. }
  168234. /*
  168235. * Find the next JPEG marker, save it in cinfo->unread_marker.
  168236. * Returns FALSE if had to suspend before reaching a marker;
  168237. * in that case cinfo->unread_marker is unchanged.
  168238. *
  168239. * Note that the result might not be a valid marker code,
  168240. * but it will never be 0 or FF.
  168241. */
  168242. LOCAL(boolean)
  168243. next_marker (j_decompress_ptr cinfo)
  168244. {
  168245. int c;
  168246. INPUT_VARS(cinfo);
  168247. for (;;) {
  168248. INPUT_BYTE(cinfo, c, return FALSE);
  168249. /* Skip any non-FF bytes.
  168250. * This may look a bit inefficient, but it will not occur in a valid file.
  168251. * We sync after each discarded byte so that a suspending data source
  168252. * can discard the byte from its buffer.
  168253. */
  168254. while (c != 0xFF) {
  168255. cinfo->marker->discarded_bytes++;
  168256. INPUT_SYNC(cinfo);
  168257. INPUT_BYTE(cinfo, c, return FALSE);
  168258. }
  168259. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  168260. * pad bytes, so don't count them in discarded_bytes. We assume there
  168261. * will not be so many consecutive FF bytes as to overflow a suspending
  168262. * data source's input buffer.
  168263. */
  168264. do {
  168265. INPUT_BYTE(cinfo, c, return FALSE);
  168266. } while (c == 0xFF);
  168267. if (c != 0)
  168268. break; /* found a valid marker, exit loop */
  168269. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  168270. * Discard it and loop back to try again.
  168271. */
  168272. cinfo->marker->discarded_bytes += 2;
  168273. INPUT_SYNC(cinfo);
  168274. }
  168275. if (cinfo->marker->discarded_bytes != 0) {
  168276. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  168277. cinfo->marker->discarded_bytes = 0;
  168278. }
  168279. cinfo->unread_marker = c;
  168280. INPUT_SYNC(cinfo);
  168281. return TRUE;
  168282. }
  168283. LOCAL(boolean)
  168284. first_marker (j_decompress_ptr cinfo)
  168285. /* Like next_marker, but used to obtain the initial SOI marker. */
  168286. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  168287. * we might well scan an entire input file before realizing it ain't JPEG.
  168288. * If an application wants to process non-JFIF files, it must seek to the
  168289. * SOI before calling the JPEG library.
  168290. */
  168291. {
  168292. int c, c2;
  168293. INPUT_VARS(cinfo);
  168294. INPUT_BYTE(cinfo, c, return FALSE);
  168295. INPUT_BYTE(cinfo, c2, return FALSE);
  168296. if (c != 0xFF || c2 != (int) M_SOI)
  168297. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  168298. cinfo->unread_marker = c2;
  168299. INPUT_SYNC(cinfo);
  168300. return TRUE;
  168301. }
  168302. /*
  168303. * Read markers until SOS or EOI.
  168304. *
  168305. * Returns same codes as are defined for jpeg_consume_input:
  168306. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  168307. */
  168308. METHODDEF(int)
  168309. read_markers (j_decompress_ptr cinfo)
  168310. {
  168311. /* Outer loop repeats once for each marker. */
  168312. for (;;) {
  168313. /* Collect the marker proper, unless we already did. */
  168314. /* NB: first_marker() enforces the requirement that SOI appear first. */
  168315. if (cinfo->unread_marker == 0) {
  168316. if (! cinfo->marker->saw_SOI) {
  168317. if (! first_marker(cinfo))
  168318. return JPEG_SUSPENDED;
  168319. } else {
  168320. if (! next_marker(cinfo))
  168321. return JPEG_SUSPENDED;
  168322. }
  168323. }
  168324. /* At this point cinfo->unread_marker contains the marker code and the
  168325. * input point is just past the marker proper, but before any parameters.
  168326. * A suspension will cause us to return with this state still true.
  168327. */
  168328. switch (cinfo->unread_marker) {
  168329. case M_SOI:
  168330. if (! get_soi(cinfo))
  168331. return JPEG_SUSPENDED;
  168332. break;
  168333. case M_SOF0: /* Baseline */
  168334. case M_SOF1: /* Extended sequential, Huffman */
  168335. if (! get_sof(cinfo, FALSE, FALSE))
  168336. return JPEG_SUSPENDED;
  168337. break;
  168338. case M_SOF2: /* Progressive, Huffman */
  168339. if (! get_sof(cinfo, TRUE, FALSE))
  168340. return JPEG_SUSPENDED;
  168341. break;
  168342. case M_SOF9: /* Extended sequential, arithmetic */
  168343. if (! get_sof(cinfo, FALSE, TRUE))
  168344. return JPEG_SUSPENDED;
  168345. break;
  168346. case M_SOF10: /* Progressive, arithmetic */
  168347. if (! get_sof(cinfo, TRUE, TRUE))
  168348. return JPEG_SUSPENDED;
  168349. break;
  168350. /* Currently unsupported SOFn types */
  168351. case M_SOF3: /* Lossless, Huffman */
  168352. case M_SOF5: /* Differential sequential, Huffman */
  168353. case M_SOF6: /* Differential progressive, Huffman */
  168354. case M_SOF7: /* Differential lossless, Huffman */
  168355. case M_JPG: /* Reserved for JPEG extensions */
  168356. case M_SOF11: /* Lossless, arithmetic */
  168357. case M_SOF13: /* Differential sequential, arithmetic */
  168358. case M_SOF14: /* Differential progressive, arithmetic */
  168359. case M_SOF15: /* Differential lossless, arithmetic */
  168360. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  168361. break;
  168362. case M_SOS:
  168363. if (! get_sos(cinfo))
  168364. return JPEG_SUSPENDED;
  168365. cinfo->unread_marker = 0; /* processed the marker */
  168366. return JPEG_REACHED_SOS;
  168367. case M_EOI:
  168368. TRACEMS(cinfo, 1, JTRC_EOI);
  168369. cinfo->unread_marker = 0; /* processed the marker */
  168370. return JPEG_REACHED_EOI;
  168371. case M_DAC:
  168372. if (! get_dac(cinfo))
  168373. return JPEG_SUSPENDED;
  168374. break;
  168375. case M_DHT:
  168376. if (! get_dht(cinfo))
  168377. return JPEG_SUSPENDED;
  168378. break;
  168379. case M_DQT:
  168380. if (! get_dqt(cinfo))
  168381. return JPEG_SUSPENDED;
  168382. break;
  168383. case M_DRI:
  168384. if (! get_dri(cinfo))
  168385. return JPEG_SUSPENDED;
  168386. break;
  168387. case M_APP0:
  168388. case M_APP1:
  168389. case M_APP2:
  168390. case M_APP3:
  168391. case M_APP4:
  168392. case M_APP5:
  168393. case M_APP6:
  168394. case M_APP7:
  168395. case M_APP8:
  168396. case M_APP9:
  168397. case M_APP10:
  168398. case M_APP11:
  168399. case M_APP12:
  168400. case M_APP13:
  168401. case M_APP14:
  168402. case M_APP15:
  168403. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  168404. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  168405. return JPEG_SUSPENDED;
  168406. break;
  168407. case M_COM:
  168408. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  168409. return JPEG_SUSPENDED;
  168410. break;
  168411. case M_RST0: /* these are all parameterless */
  168412. case M_RST1:
  168413. case M_RST2:
  168414. case M_RST3:
  168415. case M_RST4:
  168416. case M_RST5:
  168417. case M_RST6:
  168418. case M_RST7:
  168419. case M_TEM:
  168420. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  168421. break;
  168422. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  168423. if (! skip_variable(cinfo))
  168424. return JPEG_SUSPENDED;
  168425. break;
  168426. default: /* must be DHP, EXP, JPGn, or RESn */
  168427. /* For now, we treat the reserved markers as fatal errors since they are
  168428. * likely to be used to signal incompatible JPEG Part 3 extensions.
  168429. * Once the JPEG 3 version-number marker is well defined, this code
  168430. * ought to change!
  168431. */
  168432. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168433. break;
  168434. }
  168435. /* Successfully processed marker, so reset state variable */
  168436. cinfo->unread_marker = 0;
  168437. } /* end loop */
  168438. }
  168439. /*
  168440. * Read a restart marker, which is expected to appear next in the datastream;
  168441. * if the marker is not there, take appropriate recovery action.
  168442. * Returns FALSE if suspension is required.
  168443. *
  168444. * This is called by the entropy decoder after it has read an appropriate
  168445. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  168446. * has already read a marker from the data source. Under normal conditions
  168447. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  168448. * it holds a marker which the decoder will be unable to read past.
  168449. */
  168450. METHODDEF(boolean)
  168451. read_restart_marker (j_decompress_ptr cinfo)
  168452. {
  168453. /* Obtain a marker unless we already did. */
  168454. /* Note that next_marker will complain if it skips any data. */
  168455. if (cinfo->unread_marker == 0) {
  168456. if (! next_marker(cinfo))
  168457. return FALSE;
  168458. }
  168459. if (cinfo->unread_marker ==
  168460. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  168461. /* Normal case --- swallow the marker and let entropy decoder continue */
  168462. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  168463. cinfo->unread_marker = 0;
  168464. } else {
  168465. /* Uh-oh, the restart markers have been messed up. */
  168466. /* Let the data source manager determine how to resync. */
  168467. if (! (*cinfo->src->resync_to_restart) (cinfo,
  168468. cinfo->marker->next_restart_num))
  168469. return FALSE;
  168470. }
  168471. /* Update next-restart state */
  168472. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  168473. return TRUE;
  168474. }
  168475. /*
  168476. * This is the default resync_to_restart method for data source managers
  168477. * to use if they don't have any better approach. Some data source managers
  168478. * may be able to back up, or may have additional knowledge about the data
  168479. * which permits a more intelligent recovery strategy; such managers would
  168480. * presumably supply their own resync method.
  168481. *
  168482. * read_restart_marker calls resync_to_restart if it finds a marker other than
  168483. * the restart marker it was expecting. (This code is *not* used unless
  168484. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  168485. * the marker code actually found (might be anything, except 0 or FF).
  168486. * The desired restart marker number (0..7) is passed as a parameter.
  168487. * This routine is supposed to apply whatever error recovery strategy seems
  168488. * appropriate in order to position the input stream to the next data segment.
  168489. * Note that cinfo->unread_marker is treated as a marker appearing before
  168490. * the current data-source input point; usually it should be reset to zero
  168491. * before returning.
  168492. * Returns FALSE if suspension is required.
  168493. *
  168494. * This implementation is substantially constrained by wanting to treat the
  168495. * input as a data stream; this means we can't back up. Therefore, we have
  168496. * only the following actions to work with:
  168497. * 1. Simply discard the marker and let the entropy decoder resume at next
  168498. * byte of file.
  168499. * 2. Read forward until we find another marker, discarding intervening
  168500. * data. (In theory we could look ahead within the current bufferload,
  168501. * without having to discard data if we don't find the desired marker.
  168502. * This idea is not implemented here, in part because it makes behavior
  168503. * dependent on buffer size and chance buffer-boundary positions.)
  168504. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  168505. * This will cause the entropy decoder to process an empty data segment,
  168506. * inserting dummy zeroes, and then we will reprocess the marker.
  168507. *
  168508. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  168509. * appropriate if the found marker is a future restart marker (indicating
  168510. * that we have missed the desired restart marker, probably because it got
  168511. * corrupted).
  168512. * We apply #2 or #3 if the found marker is a restart marker no more than
  168513. * two counts behind or ahead of the expected one. We also apply #2 if the
  168514. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  168515. * If the found marker is a restart marker more than 2 counts away, we do #1
  168516. * (too much risk that the marker is erroneous; with luck we will be able to
  168517. * resync at some future point).
  168518. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  168519. * overrunning the end of a scan. An implementation limited to single-scan
  168520. * files might find it better to apply #2 for markers other than EOI, since
  168521. * any other marker would have to be bogus data in that case.
  168522. */
  168523. GLOBAL(boolean)
  168524. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  168525. {
  168526. int marker = cinfo->unread_marker;
  168527. int action = 1;
  168528. /* Always put up a warning. */
  168529. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  168530. /* Outer loop handles repeated decision after scanning forward. */
  168531. for (;;) {
  168532. if (marker < (int) M_SOF0)
  168533. action = 2; /* invalid marker */
  168534. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  168535. action = 3; /* valid non-restart marker */
  168536. else {
  168537. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  168538. marker == ((int) M_RST0 + ((desired+2) & 7)))
  168539. action = 3; /* one of the next two expected restarts */
  168540. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  168541. marker == ((int) M_RST0 + ((desired-2) & 7)))
  168542. action = 2; /* a prior restart, so advance */
  168543. else
  168544. action = 1; /* desired restart or too far away */
  168545. }
  168546. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  168547. switch (action) {
  168548. case 1:
  168549. /* Discard marker and let entropy decoder resume processing. */
  168550. cinfo->unread_marker = 0;
  168551. return TRUE;
  168552. case 2:
  168553. /* Scan to the next marker, and repeat the decision loop. */
  168554. if (! next_marker(cinfo))
  168555. return FALSE;
  168556. marker = cinfo->unread_marker;
  168557. break;
  168558. case 3:
  168559. /* Return without advancing past this marker. */
  168560. /* Entropy decoder will be forced to process an empty segment. */
  168561. return TRUE;
  168562. }
  168563. } /* end loop */
  168564. }
  168565. /*
  168566. * Reset marker processing state to begin a fresh datastream.
  168567. */
  168568. METHODDEF(void)
  168569. reset_marker_reader (j_decompress_ptr cinfo)
  168570. {
  168571. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168572. cinfo->comp_info = NULL; /* until allocated by get_sof */
  168573. cinfo->input_scan_number = 0; /* no SOS seen yet */
  168574. cinfo->unread_marker = 0; /* no pending marker */
  168575. marker->pub.saw_SOI = FALSE; /* set internal state too */
  168576. marker->pub.saw_SOF = FALSE;
  168577. marker->pub.discarded_bytes = 0;
  168578. marker->cur_marker = NULL;
  168579. }
  168580. /*
  168581. * Initialize the marker reader module.
  168582. * This is called only once, when the decompression object is created.
  168583. */
  168584. GLOBAL(void)
  168585. jinit_marker_reader (j_decompress_ptr cinfo)
  168586. {
  168587. my_marker_ptr2 marker;
  168588. int i;
  168589. /* Create subobject in permanent pool */
  168590. marker = (my_marker_ptr2)
  168591. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168592. SIZEOF(my_marker_reader));
  168593. cinfo->marker = (struct jpeg_marker_reader *) marker;
  168594. /* Initialize public method pointers */
  168595. marker->pub.reset_marker_reader = reset_marker_reader;
  168596. marker->pub.read_markers = read_markers;
  168597. marker->pub.read_restart_marker = read_restart_marker;
  168598. /* Initialize COM/APPn processing.
  168599. * By default, we examine and then discard APP0 and APP14,
  168600. * but simply discard COM and all other APPn.
  168601. */
  168602. marker->process_COM = skip_variable;
  168603. marker->length_limit_COM = 0;
  168604. for (i = 0; i < 16; i++) {
  168605. marker->process_APPn[i] = skip_variable;
  168606. marker->length_limit_APPn[i] = 0;
  168607. }
  168608. marker->process_APPn[0] = get_interesting_appn;
  168609. marker->process_APPn[14] = get_interesting_appn;
  168610. /* Reset marker processing state */
  168611. reset_marker_reader(cinfo);
  168612. }
  168613. /*
  168614. * Control saving of COM and APPn markers into marker_list.
  168615. */
  168616. #ifdef SAVE_MARKERS_SUPPORTED
  168617. GLOBAL(void)
  168618. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  168619. unsigned int length_limit)
  168620. {
  168621. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168622. long maxlength;
  168623. jpeg_marker_parser_method processor;
  168624. /* Length limit mustn't be larger than what we can allocate
  168625. * (should only be a concern in a 16-bit environment).
  168626. */
  168627. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  168628. if (((long) length_limit) > maxlength)
  168629. length_limit = (unsigned int) maxlength;
  168630. /* Choose processor routine to use.
  168631. * APP0/APP14 have special requirements.
  168632. */
  168633. if (length_limit) {
  168634. processor = save_marker;
  168635. /* If saving APP0/APP14, save at least enough for our internal use. */
  168636. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  168637. length_limit = APP0_DATA_LEN;
  168638. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  168639. length_limit = APP14_DATA_LEN;
  168640. } else {
  168641. processor = skip_variable;
  168642. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  168643. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  168644. processor = get_interesting_appn;
  168645. }
  168646. if (marker_code == (int) M_COM) {
  168647. marker->process_COM = processor;
  168648. marker->length_limit_COM = length_limit;
  168649. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  168650. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  168651. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  168652. } else
  168653. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  168654. }
  168655. #endif /* SAVE_MARKERS_SUPPORTED */
  168656. /*
  168657. * Install a special processing method for COM or APPn markers.
  168658. */
  168659. GLOBAL(void)
  168660. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  168661. jpeg_marker_parser_method routine)
  168662. {
  168663. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168664. if (marker_code == (int) M_COM)
  168665. marker->process_COM = routine;
  168666. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  168667. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  168668. else
  168669. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  168670. }
  168671. /*** End of inlined file: jdmarker.c ***/
  168672. /*** Start of inlined file: jdmaster.c ***/
  168673. #define JPEG_INTERNALS
  168674. /* Private state */
  168675. typedef struct {
  168676. struct jpeg_decomp_master pub; /* public fields */
  168677. int pass_number; /* # of passes completed */
  168678. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  168679. /* Saved references to initialized quantizer modules,
  168680. * in case we need to switch modes.
  168681. */
  168682. struct jpeg_color_quantizer * quantizer_1pass;
  168683. struct jpeg_color_quantizer * quantizer_2pass;
  168684. } my_decomp_master;
  168685. typedef my_decomp_master * my_master_ptr6;
  168686. /*
  168687. * Determine whether merged upsample/color conversion should be used.
  168688. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  168689. */
  168690. LOCAL(boolean)
  168691. use_merged_upsample (j_decompress_ptr cinfo)
  168692. {
  168693. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168694. /* Merging is the equivalent of plain box-filter upsampling */
  168695. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  168696. return FALSE;
  168697. /* jdmerge.c only supports YCC=>RGB color conversion */
  168698. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  168699. cinfo->out_color_space != JCS_RGB ||
  168700. cinfo->out_color_components != RGB_PIXELSIZE)
  168701. return FALSE;
  168702. /* and it only handles 2h1v or 2h2v sampling ratios */
  168703. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  168704. cinfo->comp_info[1].h_samp_factor != 1 ||
  168705. cinfo->comp_info[2].h_samp_factor != 1 ||
  168706. cinfo->comp_info[0].v_samp_factor > 2 ||
  168707. cinfo->comp_info[1].v_samp_factor != 1 ||
  168708. cinfo->comp_info[2].v_samp_factor != 1)
  168709. return FALSE;
  168710. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  168711. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  168712. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  168713. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  168714. return FALSE;
  168715. /* ??? also need to test for upsample-time rescaling, when & if supported */
  168716. return TRUE; /* by golly, it'll work... */
  168717. #else
  168718. return FALSE;
  168719. #endif
  168720. }
  168721. /*
  168722. * Compute output image dimensions and related values.
  168723. * NOTE: this is exported for possible use by application.
  168724. * Hence it mustn't do anything that can't be done twice.
  168725. * Also note that it may be called before the master module is initialized!
  168726. */
  168727. GLOBAL(void)
  168728. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  168729. /* Do computations that are needed before master selection phase */
  168730. {
  168731. #ifdef IDCT_SCALING_SUPPORTED
  168732. int ci;
  168733. jpeg_component_info *compptr;
  168734. #endif
  168735. /* Prevent application from calling me at wrong times */
  168736. if (cinfo->global_state != DSTATE_READY)
  168737. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168738. #ifdef IDCT_SCALING_SUPPORTED
  168739. /* Compute actual output image dimensions and DCT scaling choices. */
  168740. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  168741. /* Provide 1/8 scaling */
  168742. cinfo->output_width = (JDIMENSION)
  168743. jdiv_round_up((long) cinfo->image_width, 8L);
  168744. cinfo->output_height = (JDIMENSION)
  168745. jdiv_round_up((long) cinfo->image_height, 8L);
  168746. cinfo->min_DCT_scaled_size = 1;
  168747. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  168748. /* Provide 1/4 scaling */
  168749. cinfo->output_width = (JDIMENSION)
  168750. jdiv_round_up((long) cinfo->image_width, 4L);
  168751. cinfo->output_height = (JDIMENSION)
  168752. jdiv_round_up((long) cinfo->image_height, 4L);
  168753. cinfo->min_DCT_scaled_size = 2;
  168754. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  168755. /* Provide 1/2 scaling */
  168756. cinfo->output_width = (JDIMENSION)
  168757. jdiv_round_up((long) cinfo->image_width, 2L);
  168758. cinfo->output_height = (JDIMENSION)
  168759. jdiv_round_up((long) cinfo->image_height, 2L);
  168760. cinfo->min_DCT_scaled_size = 4;
  168761. } else {
  168762. /* Provide 1/1 scaling */
  168763. cinfo->output_width = cinfo->image_width;
  168764. cinfo->output_height = cinfo->image_height;
  168765. cinfo->min_DCT_scaled_size = DCTSIZE;
  168766. }
  168767. /* In selecting the actual DCT scaling for each component, we try to
  168768. * scale up the chroma components via IDCT scaling rather than upsampling.
  168769. * This saves time if the upsampler gets to use 1:1 scaling.
  168770. * Note this code assumes that the supported DCT scalings are powers of 2.
  168771. */
  168772. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168773. ci++, compptr++) {
  168774. int ssize = cinfo->min_DCT_scaled_size;
  168775. while (ssize < DCTSIZE &&
  168776. (compptr->h_samp_factor * ssize * 2 <=
  168777. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  168778. (compptr->v_samp_factor * ssize * 2 <=
  168779. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  168780. ssize = ssize * 2;
  168781. }
  168782. compptr->DCT_scaled_size = ssize;
  168783. }
  168784. /* Recompute downsampled dimensions of components;
  168785. * application needs to know these if using raw downsampled data.
  168786. */
  168787. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168788. ci++, compptr++) {
  168789. /* Size in samples, after IDCT scaling */
  168790. compptr->downsampled_width = (JDIMENSION)
  168791. jdiv_round_up((long) cinfo->image_width *
  168792. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  168793. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  168794. compptr->downsampled_height = (JDIMENSION)
  168795. jdiv_round_up((long) cinfo->image_height *
  168796. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  168797. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  168798. }
  168799. #else /* !IDCT_SCALING_SUPPORTED */
  168800. /* Hardwire it to "no scaling" */
  168801. cinfo->output_width = cinfo->image_width;
  168802. cinfo->output_height = cinfo->image_height;
  168803. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  168804. * and has computed unscaled downsampled_width and downsampled_height.
  168805. */
  168806. #endif /* IDCT_SCALING_SUPPORTED */
  168807. /* Report number of components in selected colorspace. */
  168808. /* Probably this should be in the color conversion module... */
  168809. switch (cinfo->out_color_space) {
  168810. case JCS_GRAYSCALE:
  168811. cinfo->out_color_components = 1;
  168812. break;
  168813. case JCS_RGB:
  168814. #if RGB_PIXELSIZE != 3
  168815. cinfo->out_color_components = RGB_PIXELSIZE;
  168816. break;
  168817. #endif /* else share code with YCbCr */
  168818. case JCS_YCbCr:
  168819. cinfo->out_color_components = 3;
  168820. break;
  168821. case JCS_CMYK:
  168822. case JCS_YCCK:
  168823. cinfo->out_color_components = 4;
  168824. break;
  168825. default: /* else must be same colorspace as in file */
  168826. cinfo->out_color_components = cinfo->num_components;
  168827. break;
  168828. }
  168829. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  168830. cinfo->out_color_components);
  168831. /* See if upsampler will want to emit more than one row at a time */
  168832. if (use_merged_upsample(cinfo))
  168833. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  168834. else
  168835. cinfo->rec_outbuf_height = 1;
  168836. }
  168837. /*
  168838. * Several decompression processes need to range-limit values to the range
  168839. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  168840. * due to noise introduced by quantization, roundoff error, etc. These
  168841. * processes are inner loops and need to be as fast as possible. On most
  168842. * machines, particularly CPUs with pipelines or instruction prefetch,
  168843. * a (subscript-check-less) C table lookup
  168844. * x = sample_range_limit[x];
  168845. * is faster than explicit tests
  168846. * if (x < 0) x = 0;
  168847. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  168848. * These processes all use a common table prepared by the routine below.
  168849. *
  168850. * For most steps we can mathematically guarantee that the initial value
  168851. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  168852. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  168853. * limiting step (just after the IDCT), a wildly out-of-range value is
  168854. * possible if the input data is corrupt. To avoid any chance of indexing
  168855. * off the end of memory and getting a bad-pointer trap, we perform the
  168856. * post-IDCT limiting thus:
  168857. * x = range_limit[x & MASK];
  168858. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  168859. * samples. Under normal circumstances this is more than enough range and
  168860. * a correct output will be generated; with bogus input data the mask will
  168861. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  168862. * For the post-IDCT step, we want to convert the data from signed to unsigned
  168863. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  168864. * So the post-IDCT limiting table ends up looking like this:
  168865. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  168866. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168867. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168868. * 0,1,...,CENTERJSAMPLE-1
  168869. * Negative inputs select values from the upper half of the table after
  168870. * masking.
  168871. *
  168872. * We can save some space by overlapping the start of the post-IDCT table
  168873. * with the simpler range limiting table. The post-IDCT table begins at
  168874. * sample_range_limit + CENTERJSAMPLE.
  168875. *
  168876. * Note that the table is allocated in near data space on PCs; it's small
  168877. * enough and used often enough to justify this.
  168878. */
  168879. LOCAL(void)
  168880. prepare_range_limit_table (j_decompress_ptr cinfo)
  168881. /* Allocate and fill in the sample_range_limit table */
  168882. {
  168883. JSAMPLE * table;
  168884. int i;
  168885. table = (JSAMPLE *)
  168886. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168887. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168888. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  168889. cinfo->sample_range_limit = table;
  168890. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  168891. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  168892. /* Main part of "simple" table: limit[x] = x */
  168893. for (i = 0; i <= MAXJSAMPLE; i++)
  168894. table[i] = (JSAMPLE) i;
  168895. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  168896. /* End of simple table, rest of first half of post-IDCT table */
  168897. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  168898. table[i] = MAXJSAMPLE;
  168899. /* Second half of post-IDCT table */
  168900. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  168901. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168902. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  168903. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  168904. }
  168905. /*
  168906. * Master selection of decompression modules.
  168907. * This is done once at jpeg_start_decompress time. We determine
  168908. * which modules will be used and give them appropriate initialization calls.
  168909. * We also initialize the decompressor input side to begin consuming data.
  168910. *
  168911. * Since jpeg_read_header has finished, we know what is in the SOF
  168912. * and (first) SOS markers. We also have all the application parameter
  168913. * settings.
  168914. */
  168915. LOCAL(void)
  168916. master_selection (j_decompress_ptr cinfo)
  168917. {
  168918. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168919. boolean use_c_buffer;
  168920. long samplesperrow;
  168921. JDIMENSION jd_samplesperrow;
  168922. /* Initialize dimensions and other stuff */
  168923. jpeg_calc_output_dimensions(cinfo);
  168924. prepare_range_limit_table(cinfo);
  168925. /* Width of an output scanline must be representable as JDIMENSION. */
  168926. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  168927. jd_samplesperrow = (JDIMENSION) samplesperrow;
  168928. if ((long) jd_samplesperrow != samplesperrow)
  168929. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  168930. /* Initialize my private state */
  168931. master->pass_number = 0;
  168932. master->using_merged_upsample = use_merged_upsample(cinfo);
  168933. /* Color quantizer selection */
  168934. master->quantizer_1pass = NULL;
  168935. master->quantizer_2pass = NULL;
  168936. /* No mode changes if not using buffered-image mode. */
  168937. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  168938. cinfo->enable_1pass_quant = FALSE;
  168939. cinfo->enable_external_quant = FALSE;
  168940. cinfo->enable_2pass_quant = FALSE;
  168941. }
  168942. if (cinfo->quantize_colors) {
  168943. if (cinfo->raw_data_out)
  168944. ERREXIT(cinfo, JERR_NOTIMPL);
  168945. /* 2-pass quantizer only works in 3-component color space. */
  168946. if (cinfo->out_color_components != 3) {
  168947. cinfo->enable_1pass_quant = TRUE;
  168948. cinfo->enable_external_quant = FALSE;
  168949. cinfo->enable_2pass_quant = FALSE;
  168950. cinfo->colormap = NULL;
  168951. } else if (cinfo->colormap != NULL) {
  168952. cinfo->enable_external_quant = TRUE;
  168953. } else if (cinfo->two_pass_quantize) {
  168954. cinfo->enable_2pass_quant = TRUE;
  168955. } else {
  168956. cinfo->enable_1pass_quant = TRUE;
  168957. }
  168958. if (cinfo->enable_1pass_quant) {
  168959. #ifdef QUANT_1PASS_SUPPORTED
  168960. jinit_1pass_quantizer(cinfo);
  168961. master->quantizer_1pass = cinfo->cquantize;
  168962. #else
  168963. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168964. #endif
  168965. }
  168966. /* We use the 2-pass code to map to external colormaps. */
  168967. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  168968. #ifdef QUANT_2PASS_SUPPORTED
  168969. jinit_2pass_quantizer(cinfo);
  168970. master->quantizer_2pass = cinfo->cquantize;
  168971. #else
  168972. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168973. #endif
  168974. }
  168975. /* If both quantizers are initialized, the 2-pass one is left active;
  168976. * this is necessary for starting with quantization to an external map.
  168977. */
  168978. }
  168979. /* Post-processing: in particular, color conversion first */
  168980. if (! cinfo->raw_data_out) {
  168981. if (master->using_merged_upsample) {
  168982. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168983. jinit_merged_upsampler(cinfo); /* does color conversion too */
  168984. #else
  168985. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168986. #endif
  168987. } else {
  168988. jinit_color_deconverter(cinfo);
  168989. jinit_upsampler(cinfo);
  168990. }
  168991. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  168992. }
  168993. /* Inverse DCT */
  168994. jinit_inverse_dct(cinfo);
  168995. /* Entropy decoding: either Huffman or arithmetic coding. */
  168996. if (cinfo->arith_code) {
  168997. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168998. } else {
  168999. if (cinfo->progressive_mode) {
  169000. #ifdef D_PROGRESSIVE_SUPPORTED
  169001. jinit_phuff_decoder(cinfo);
  169002. #else
  169003. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169004. #endif
  169005. } else
  169006. jinit_huff_decoder(cinfo);
  169007. }
  169008. /* Initialize principal buffer controllers. */
  169009. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  169010. jinit_d_coef_controller(cinfo, use_c_buffer);
  169011. if (! cinfo->raw_data_out)
  169012. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  169013. /* We can now tell the memory manager to allocate virtual arrays. */
  169014. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169015. /* Initialize input side of decompressor to consume first scan. */
  169016. (*cinfo->inputctl->start_input_pass) (cinfo);
  169017. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169018. /* If jpeg_start_decompress will read the whole file, initialize
  169019. * progress monitoring appropriately. The input step is counted
  169020. * as one pass.
  169021. */
  169022. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  169023. cinfo->inputctl->has_multiple_scans) {
  169024. int nscans;
  169025. /* Estimate number of scans to set pass_limit. */
  169026. if (cinfo->progressive_mode) {
  169027. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169028. nscans = 2 + 3 * cinfo->num_components;
  169029. } else {
  169030. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169031. nscans = cinfo->num_components;
  169032. }
  169033. cinfo->progress->pass_counter = 0L;
  169034. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169035. cinfo->progress->completed_passes = 0;
  169036. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  169037. /* Count the input pass as done */
  169038. master->pass_number++;
  169039. }
  169040. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169041. }
  169042. /*
  169043. * Per-pass setup.
  169044. * This is called at the beginning of each output pass. We determine which
  169045. * modules will be active during this pass and give them appropriate
  169046. * start_pass calls. We also set is_dummy_pass to indicate whether this
  169047. * is a "real" output pass or a dummy pass for color quantization.
  169048. * (In the latter case, jdapistd.c will crank the pass to completion.)
  169049. */
  169050. METHODDEF(void)
  169051. prepare_for_output_pass (j_decompress_ptr cinfo)
  169052. {
  169053. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169054. if (master->pub.is_dummy_pass) {
  169055. #ifdef QUANT_2PASS_SUPPORTED
  169056. /* Final pass of 2-pass quantization */
  169057. master->pub.is_dummy_pass = FALSE;
  169058. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  169059. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  169060. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  169061. #else
  169062. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169063. #endif /* QUANT_2PASS_SUPPORTED */
  169064. } else {
  169065. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  169066. /* Select new quantization method */
  169067. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  169068. cinfo->cquantize = master->quantizer_2pass;
  169069. master->pub.is_dummy_pass = TRUE;
  169070. } else if (cinfo->enable_1pass_quant) {
  169071. cinfo->cquantize = master->quantizer_1pass;
  169072. } else {
  169073. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169074. }
  169075. }
  169076. (*cinfo->idct->start_pass) (cinfo);
  169077. (*cinfo->coef->start_output_pass) (cinfo);
  169078. if (! cinfo->raw_data_out) {
  169079. if (! master->using_merged_upsample)
  169080. (*cinfo->cconvert->start_pass) (cinfo);
  169081. (*cinfo->upsample->start_pass) (cinfo);
  169082. if (cinfo->quantize_colors)
  169083. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  169084. (*cinfo->post->start_pass) (cinfo,
  169085. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  169086. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  169087. }
  169088. }
  169089. /* Set up progress monitor's pass info if present */
  169090. if (cinfo->progress != NULL) {
  169091. cinfo->progress->completed_passes = master->pass_number;
  169092. cinfo->progress->total_passes = master->pass_number +
  169093. (master->pub.is_dummy_pass ? 2 : 1);
  169094. /* In buffered-image mode, we assume one more output pass if EOI not
  169095. * yet reached, but no more passes if EOI has been reached.
  169096. */
  169097. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  169098. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  169099. }
  169100. }
  169101. }
  169102. /*
  169103. * Finish up at end of an output pass.
  169104. */
  169105. METHODDEF(void)
  169106. finish_output_pass (j_decompress_ptr cinfo)
  169107. {
  169108. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169109. if (cinfo->quantize_colors)
  169110. (*cinfo->cquantize->finish_pass) (cinfo);
  169111. master->pass_number++;
  169112. }
  169113. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169114. /*
  169115. * Switch to a new external colormap between output passes.
  169116. */
  169117. GLOBAL(void)
  169118. jpeg_new_colormap (j_decompress_ptr cinfo)
  169119. {
  169120. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169121. /* Prevent application from calling me at wrong times */
  169122. if (cinfo->global_state != DSTATE_BUFIMAGE)
  169123. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169124. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  169125. cinfo->colormap != NULL) {
  169126. /* Select 2-pass quantizer for external colormap use */
  169127. cinfo->cquantize = master->quantizer_2pass;
  169128. /* Notify quantizer of colormap change */
  169129. (*cinfo->cquantize->new_color_map) (cinfo);
  169130. master->pub.is_dummy_pass = FALSE; /* just in case */
  169131. } else
  169132. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169133. }
  169134. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169135. /*
  169136. * Initialize master decompression control and select active modules.
  169137. * This is performed at the start of jpeg_start_decompress.
  169138. */
  169139. GLOBAL(void)
  169140. jinit_master_decompress (j_decompress_ptr cinfo)
  169141. {
  169142. my_master_ptr6 master;
  169143. master = (my_master_ptr6)
  169144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169145. SIZEOF(my_decomp_master));
  169146. cinfo->master = (struct jpeg_decomp_master *) master;
  169147. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  169148. master->pub.finish_output_pass = finish_output_pass;
  169149. master->pub.is_dummy_pass = FALSE;
  169150. master_selection(cinfo);
  169151. }
  169152. /*** End of inlined file: jdmaster.c ***/
  169153. #undef FIX
  169154. /*** Start of inlined file: jdmerge.c ***/
  169155. #define JPEG_INTERNALS
  169156. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169157. /* Private subobject */
  169158. typedef struct {
  169159. struct jpeg_upsampler pub; /* public fields */
  169160. /* Pointer to routine to do actual upsampling/conversion of one row group */
  169161. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  169162. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169163. JSAMPARRAY output_buf));
  169164. /* Private state for YCC->RGB conversion */
  169165. int * Cr_r_tab; /* => table for Cr to R conversion */
  169166. int * Cb_b_tab; /* => table for Cb to B conversion */
  169167. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169168. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169169. /* For 2:1 vertical sampling, we produce two output rows at a time.
  169170. * We need a "spare" row buffer to hold the second output row if the
  169171. * application provides just a one-row buffer; we also use the spare
  169172. * to discard the dummy last row if the image height is odd.
  169173. */
  169174. JSAMPROW spare_row;
  169175. boolean spare_full; /* T if spare buffer is occupied */
  169176. JDIMENSION out_row_width; /* samples per output row */
  169177. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169178. } my_upsampler;
  169179. typedef my_upsampler * my_upsample_ptr;
  169180. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169181. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169182. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169183. /*
  169184. * Initialize tables for YCC->RGB colorspace conversion.
  169185. * This is taken directly from jdcolor.c; see that file for more info.
  169186. */
  169187. LOCAL(void)
  169188. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  169189. {
  169190. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169191. int i;
  169192. INT32 x;
  169193. SHIFT_TEMPS
  169194. upsample->Cr_r_tab = (int *)
  169195. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169196. (MAXJSAMPLE+1) * SIZEOF(int));
  169197. upsample->Cb_b_tab = (int *)
  169198. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169199. (MAXJSAMPLE+1) * SIZEOF(int));
  169200. upsample->Cr_g_tab = (INT32 *)
  169201. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169202. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169203. upsample->Cb_g_tab = (INT32 *)
  169204. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169205. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169206. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169207. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169208. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169209. /* Cr=>R value is nearest int to 1.40200 * x */
  169210. upsample->Cr_r_tab[i] = (int)
  169211. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169212. /* Cb=>B value is nearest int to 1.77200 * x */
  169213. upsample->Cb_b_tab[i] = (int)
  169214. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169215. /* Cr=>G value is scaled-up -0.71414 * x */
  169216. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169217. /* Cb=>G value is scaled-up -0.34414 * x */
  169218. /* We also add in ONE_HALF so that need not do it in inner loop */
  169219. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169220. }
  169221. }
  169222. /*
  169223. * Initialize for an upsampling pass.
  169224. */
  169225. METHODDEF(void)
  169226. start_pass_merged_upsample (j_decompress_ptr cinfo)
  169227. {
  169228. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169229. /* Mark the spare buffer empty */
  169230. upsample->spare_full = FALSE;
  169231. /* Initialize total-height counter for detecting bottom of image */
  169232. upsample->rows_to_go = cinfo->output_height;
  169233. }
  169234. /*
  169235. * Control routine to do upsampling (and color conversion).
  169236. *
  169237. * The control routine just handles the row buffering considerations.
  169238. */
  169239. METHODDEF(void)
  169240. merged_2v_upsample (j_decompress_ptr cinfo,
  169241. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169242. JDIMENSION,
  169243. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169244. JDIMENSION out_rows_avail)
  169245. /* 2:1 vertical sampling case: may need a spare row. */
  169246. {
  169247. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169248. JSAMPROW work_ptrs[2];
  169249. JDIMENSION num_rows; /* number of rows returned to caller */
  169250. if (upsample->spare_full) {
  169251. /* If we have a spare row saved from a previous cycle, just return it. */
  169252. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  169253. 1, upsample->out_row_width);
  169254. num_rows = 1;
  169255. upsample->spare_full = FALSE;
  169256. } else {
  169257. /* Figure number of rows to return to caller. */
  169258. num_rows = 2;
  169259. /* Not more than the distance to the end of the image. */
  169260. if (num_rows > upsample->rows_to_go)
  169261. num_rows = upsample->rows_to_go;
  169262. /* And not more than what the client can accept: */
  169263. out_rows_avail -= *out_row_ctr;
  169264. if (num_rows > out_rows_avail)
  169265. num_rows = out_rows_avail;
  169266. /* Create output pointer array for upsampler. */
  169267. work_ptrs[0] = output_buf[*out_row_ctr];
  169268. if (num_rows > 1) {
  169269. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  169270. } else {
  169271. work_ptrs[1] = upsample->spare_row;
  169272. upsample->spare_full = TRUE;
  169273. }
  169274. /* Now do the upsampling. */
  169275. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  169276. }
  169277. /* Adjust counts */
  169278. *out_row_ctr += num_rows;
  169279. upsample->rows_to_go -= num_rows;
  169280. /* When the buffer is emptied, declare this input row group consumed */
  169281. if (! upsample->spare_full)
  169282. (*in_row_group_ctr)++;
  169283. }
  169284. METHODDEF(void)
  169285. merged_1v_upsample (j_decompress_ptr cinfo,
  169286. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169287. JDIMENSION,
  169288. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169289. JDIMENSION)
  169290. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  169291. {
  169292. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169293. /* Just do the upsampling. */
  169294. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  169295. output_buf + *out_row_ctr);
  169296. /* Adjust counts */
  169297. (*out_row_ctr)++;
  169298. (*in_row_group_ctr)++;
  169299. }
  169300. /*
  169301. * These are the routines invoked by the control routines to do
  169302. * the actual upsampling/conversion. One row group is processed per call.
  169303. *
  169304. * Note: since we may be writing directly into application-supplied buffers,
  169305. * we have to be honest about the output width; we can't assume the buffer
  169306. * has been rounded up to an even width.
  169307. */
  169308. /*
  169309. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  169310. */
  169311. METHODDEF(void)
  169312. h2v1_merged_upsample (j_decompress_ptr cinfo,
  169313. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169314. JSAMPARRAY output_buf)
  169315. {
  169316. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169317. register int y, cred, cgreen, cblue;
  169318. int cb, cr;
  169319. register JSAMPROW outptr;
  169320. JSAMPROW inptr0, inptr1, inptr2;
  169321. JDIMENSION col;
  169322. /* copy these pointers into registers if possible */
  169323. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169324. int * Crrtab = upsample->Cr_r_tab;
  169325. int * Cbbtab = upsample->Cb_b_tab;
  169326. INT32 * Crgtab = upsample->Cr_g_tab;
  169327. INT32 * Cbgtab = upsample->Cb_g_tab;
  169328. SHIFT_TEMPS
  169329. inptr0 = input_buf[0][in_row_group_ctr];
  169330. inptr1 = input_buf[1][in_row_group_ctr];
  169331. inptr2 = input_buf[2][in_row_group_ctr];
  169332. outptr = output_buf[0];
  169333. /* Loop for each pair of output pixels */
  169334. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169335. /* Do the chroma part of the calculation */
  169336. cb = GETJSAMPLE(*inptr1++);
  169337. cr = GETJSAMPLE(*inptr2++);
  169338. cred = Crrtab[cr];
  169339. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169340. cblue = Cbbtab[cb];
  169341. /* Fetch 2 Y values and emit 2 pixels */
  169342. y = GETJSAMPLE(*inptr0++);
  169343. outptr[RGB_RED] = range_limit[y + cred];
  169344. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169345. outptr[RGB_BLUE] = range_limit[y + cblue];
  169346. outptr += RGB_PIXELSIZE;
  169347. y = GETJSAMPLE(*inptr0++);
  169348. outptr[RGB_RED] = range_limit[y + cred];
  169349. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169350. outptr[RGB_BLUE] = range_limit[y + cblue];
  169351. outptr += RGB_PIXELSIZE;
  169352. }
  169353. /* If image width is odd, do the last output column separately */
  169354. if (cinfo->output_width & 1) {
  169355. cb = GETJSAMPLE(*inptr1);
  169356. cr = GETJSAMPLE(*inptr2);
  169357. cred = Crrtab[cr];
  169358. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169359. cblue = Cbbtab[cb];
  169360. y = GETJSAMPLE(*inptr0);
  169361. outptr[RGB_RED] = range_limit[y + cred];
  169362. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169363. outptr[RGB_BLUE] = range_limit[y + cblue];
  169364. }
  169365. }
  169366. /*
  169367. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  169368. */
  169369. METHODDEF(void)
  169370. h2v2_merged_upsample (j_decompress_ptr cinfo,
  169371. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169372. JSAMPARRAY output_buf)
  169373. {
  169374. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169375. register int y, cred, cgreen, cblue;
  169376. int cb, cr;
  169377. register JSAMPROW outptr0, outptr1;
  169378. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  169379. JDIMENSION col;
  169380. /* copy these pointers into registers if possible */
  169381. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169382. int * Crrtab = upsample->Cr_r_tab;
  169383. int * Cbbtab = upsample->Cb_b_tab;
  169384. INT32 * Crgtab = upsample->Cr_g_tab;
  169385. INT32 * Cbgtab = upsample->Cb_g_tab;
  169386. SHIFT_TEMPS
  169387. inptr00 = input_buf[0][in_row_group_ctr*2];
  169388. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  169389. inptr1 = input_buf[1][in_row_group_ctr];
  169390. inptr2 = input_buf[2][in_row_group_ctr];
  169391. outptr0 = output_buf[0];
  169392. outptr1 = output_buf[1];
  169393. /* Loop for each group of output pixels */
  169394. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169395. /* Do the chroma part of the calculation */
  169396. cb = GETJSAMPLE(*inptr1++);
  169397. cr = GETJSAMPLE(*inptr2++);
  169398. cred = Crrtab[cr];
  169399. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169400. cblue = Cbbtab[cb];
  169401. /* Fetch 4 Y values and emit 4 pixels */
  169402. y = GETJSAMPLE(*inptr00++);
  169403. outptr0[RGB_RED] = range_limit[y + cred];
  169404. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169405. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169406. outptr0 += RGB_PIXELSIZE;
  169407. y = GETJSAMPLE(*inptr00++);
  169408. outptr0[RGB_RED] = range_limit[y + cred];
  169409. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169410. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169411. outptr0 += RGB_PIXELSIZE;
  169412. y = GETJSAMPLE(*inptr01++);
  169413. outptr1[RGB_RED] = range_limit[y + cred];
  169414. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169415. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169416. outptr1 += RGB_PIXELSIZE;
  169417. y = GETJSAMPLE(*inptr01++);
  169418. outptr1[RGB_RED] = range_limit[y + cred];
  169419. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169420. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169421. outptr1 += RGB_PIXELSIZE;
  169422. }
  169423. /* If image width is odd, do the last output column separately */
  169424. if (cinfo->output_width & 1) {
  169425. cb = GETJSAMPLE(*inptr1);
  169426. cr = GETJSAMPLE(*inptr2);
  169427. cred = Crrtab[cr];
  169428. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169429. cblue = Cbbtab[cb];
  169430. y = GETJSAMPLE(*inptr00);
  169431. outptr0[RGB_RED] = range_limit[y + cred];
  169432. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169433. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169434. y = GETJSAMPLE(*inptr01);
  169435. outptr1[RGB_RED] = range_limit[y + cred];
  169436. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169437. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169438. }
  169439. }
  169440. /*
  169441. * Module initialization routine for merged upsampling/color conversion.
  169442. *
  169443. * NB: this is called under the conditions determined by use_merged_upsample()
  169444. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  169445. * of this module; no safety checks are made here.
  169446. */
  169447. GLOBAL(void)
  169448. jinit_merged_upsampler (j_decompress_ptr cinfo)
  169449. {
  169450. my_upsample_ptr upsample;
  169451. upsample = (my_upsample_ptr)
  169452. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169453. SIZEOF(my_upsampler));
  169454. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169455. upsample->pub.start_pass = start_pass_merged_upsample;
  169456. upsample->pub.need_context_rows = FALSE;
  169457. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  169458. if (cinfo->max_v_samp_factor == 2) {
  169459. upsample->pub.upsample = merged_2v_upsample;
  169460. upsample->upmethod = h2v2_merged_upsample;
  169461. /* Allocate a spare row buffer */
  169462. upsample->spare_row = (JSAMPROW)
  169463. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169464. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  169465. } else {
  169466. upsample->pub.upsample = merged_1v_upsample;
  169467. upsample->upmethod = h2v1_merged_upsample;
  169468. /* No spare row needed */
  169469. upsample->spare_row = NULL;
  169470. }
  169471. build_ycc_rgb_table2(cinfo);
  169472. }
  169473. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  169474. /*** End of inlined file: jdmerge.c ***/
  169475. #undef ASSIGN_STATE
  169476. /*** Start of inlined file: jdphuff.c ***/
  169477. #define JPEG_INTERNALS
  169478. #ifdef D_PROGRESSIVE_SUPPORTED
  169479. /*
  169480. * Expanded entropy decoder object for progressive Huffman decoding.
  169481. *
  169482. * The savable_state subrecord contains fields that change within an MCU,
  169483. * but must not be updated permanently until we complete the MCU.
  169484. */
  169485. typedef struct {
  169486. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  169487. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169488. } savable_state3;
  169489. /* This macro is to work around compilers with missing or broken
  169490. * structure assignment. You'll need to fix this code if you have
  169491. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169492. */
  169493. #ifndef NO_STRUCT_ASSIGN
  169494. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169495. #else
  169496. #if MAX_COMPS_IN_SCAN == 4
  169497. #define ASSIGN_STATE(dest,src) \
  169498. ((dest).EOBRUN = (src).EOBRUN, \
  169499. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  169500. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169501. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169502. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169503. #endif
  169504. #endif
  169505. typedef struct {
  169506. struct jpeg_entropy_decoder pub; /* public fields */
  169507. /* These fields are loaded into local variables at start of each MCU.
  169508. * In case of suspension, we exit WITHOUT updating them.
  169509. */
  169510. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169511. savable_state3 saved; /* Other state at start of MCU */
  169512. /* These fields are NOT loaded into local working state. */
  169513. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169514. /* Pointers to derived tables (these workspaces have image lifespan) */
  169515. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  169516. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  169517. } phuff_entropy_decoder;
  169518. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  169519. /* Forward declarations */
  169520. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  169521. JBLOCKROW *MCU_data));
  169522. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  169523. JBLOCKROW *MCU_data));
  169524. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  169525. JBLOCKROW *MCU_data));
  169526. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  169527. JBLOCKROW *MCU_data));
  169528. /*
  169529. * Initialize for a Huffman-compressed scan.
  169530. */
  169531. METHODDEF(void)
  169532. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  169533. {
  169534. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169535. boolean is_DC_band, bad;
  169536. int ci, coefi, tbl;
  169537. int *coef_bit_ptr;
  169538. jpeg_component_info * compptr;
  169539. is_DC_band = (cinfo->Ss == 0);
  169540. /* Validate scan parameters */
  169541. bad = FALSE;
  169542. if (is_DC_band) {
  169543. if (cinfo->Se != 0)
  169544. bad = TRUE;
  169545. } else {
  169546. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  169547. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  169548. bad = TRUE;
  169549. /* AC scans may have only one component */
  169550. if (cinfo->comps_in_scan != 1)
  169551. bad = TRUE;
  169552. }
  169553. if (cinfo->Ah != 0) {
  169554. /* Successive approximation refinement scan: must have Al = Ah-1. */
  169555. if (cinfo->Al != cinfo->Ah-1)
  169556. bad = TRUE;
  169557. }
  169558. if (cinfo->Al > 13) /* need not check for < 0 */
  169559. bad = TRUE;
  169560. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  169561. * but the spec doesn't say so, and we try to be liberal about what we
  169562. * accept. Note: large Al values could result in out-of-range DC
  169563. * coefficients during early scans, leading to bizarre displays due to
  169564. * overflows in the IDCT math. But we won't crash.
  169565. */
  169566. if (bad)
  169567. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  169568. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  169569. /* Update progression status, and verify that scan order is legal.
  169570. * Note that inter-scan inconsistencies are treated as warnings
  169571. * not fatal errors ... not clear if this is right way to behave.
  169572. */
  169573. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169574. int cindex = cinfo->cur_comp_info[ci]->component_index;
  169575. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  169576. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  169577. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  169578. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  169579. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  169580. if (cinfo->Ah != expected)
  169581. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  169582. coef_bit_ptr[coefi] = cinfo->Al;
  169583. }
  169584. }
  169585. /* Select MCU decoding routine */
  169586. if (cinfo->Ah == 0) {
  169587. if (is_DC_band)
  169588. entropy->pub.decode_mcu = decode_mcu_DC_first;
  169589. else
  169590. entropy->pub.decode_mcu = decode_mcu_AC_first;
  169591. } else {
  169592. if (is_DC_band)
  169593. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  169594. else
  169595. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  169596. }
  169597. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169598. compptr = cinfo->cur_comp_info[ci];
  169599. /* Make sure requested tables are present, and compute derived tables.
  169600. * We may build same derived table more than once, but it's not expensive.
  169601. */
  169602. if (is_DC_band) {
  169603. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  169604. tbl = compptr->dc_tbl_no;
  169605. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  169606. & entropy->derived_tbls[tbl]);
  169607. }
  169608. } else {
  169609. tbl = compptr->ac_tbl_no;
  169610. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  169611. & entropy->derived_tbls[tbl]);
  169612. /* remember the single active table */
  169613. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  169614. }
  169615. /* Initialize DC predictions to 0 */
  169616. entropy->saved.last_dc_val[ci] = 0;
  169617. }
  169618. /* Initialize bitread state variables */
  169619. entropy->bitstate.bits_left = 0;
  169620. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169621. entropy->pub.insufficient_data = FALSE;
  169622. /* Initialize private state variables */
  169623. entropy->saved.EOBRUN = 0;
  169624. /* Initialize restart counter */
  169625. entropy->restarts_to_go = cinfo->restart_interval;
  169626. }
  169627. /*
  169628. * Check for a restart marker & resynchronize decoder.
  169629. * Returns FALSE if must suspend.
  169630. */
  169631. LOCAL(boolean)
  169632. process_restartp (j_decompress_ptr cinfo)
  169633. {
  169634. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169635. int ci;
  169636. /* Throw away any unused bits remaining in bit buffer; */
  169637. /* include any full bytes in next_marker's count of discarded bytes */
  169638. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169639. entropy->bitstate.bits_left = 0;
  169640. /* Advance past the RSTn marker */
  169641. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169642. return FALSE;
  169643. /* Re-initialize DC predictions to 0 */
  169644. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169645. entropy->saved.last_dc_val[ci] = 0;
  169646. /* Re-init EOB run count, too */
  169647. entropy->saved.EOBRUN = 0;
  169648. /* Reset restart counter */
  169649. entropy->restarts_to_go = cinfo->restart_interval;
  169650. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169651. * against a marker. In that case we will end up treating the next data
  169652. * segment as empty, and we can avoid producing bogus output pixels by
  169653. * leaving the flag set.
  169654. */
  169655. if (cinfo->unread_marker == 0)
  169656. entropy->pub.insufficient_data = FALSE;
  169657. return TRUE;
  169658. }
  169659. /*
  169660. * Huffman MCU decoding.
  169661. * Each of these routines decodes and returns one MCU's worth of
  169662. * Huffman-compressed coefficients.
  169663. * The coefficients are reordered from zigzag order into natural array order,
  169664. * but are not dequantized.
  169665. *
  169666. * The i'th block of the MCU is stored into the block pointed to by
  169667. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  169668. *
  169669. * We return FALSE if data source requested suspension. In that case no
  169670. * changes have been made to permanent state. (Exception: some output
  169671. * coefficients may already have been assigned. This is harmless for
  169672. * spectral selection, since we'll just re-assign them on the next call.
  169673. * Successive approximation AC refinement has to be more careful, however.)
  169674. */
  169675. /*
  169676. * MCU decoding for DC initial scan (either spectral selection,
  169677. * or first pass of successive approximation).
  169678. */
  169679. METHODDEF(boolean)
  169680. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169681. {
  169682. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169683. int Al = cinfo->Al;
  169684. register int s, r;
  169685. int blkn, ci;
  169686. JBLOCKROW block;
  169687. BITREAD_STATE_VARS;
  169688. savable_state3 state;
  169689. d_derived_tbl * tbl;
  169690. jpeg_component_info * compptr;
  169691. /* Process restart marker if needed; may have to suspend */
  169692. if (cinfo->restart_interval) {
  169693. if (entropy->restarts_to_go == 0)
  169694. if (! process_restartp(cinfo))
  169695. return FALSE;
  169696. }
  169697. /* If we've run out of data, just leave the MCU set to zeroes.
  169698. * This way, we return uniform gray for the remainder of the segment.
  169699. */
  169700. if (! entropy->pub.insufficient_data) {
  169701. /* Load up working state */
  169702. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169703. ASSIGN_STATE(state, entropy->saved);
  169704. /* Outer loop handles each block in the MCU */
  169705. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169706. block = MCU_data[blkn];
  169707. ci = cinfo->MCU_membership[blkn];
  169708. compptr = cinfo->cur_comp_info[ci];
  169709. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  169710. /* Decode a single block's worth of coefficients */
  169711. /* Section F.2.2.1: decode the DC coefficient difference */
  169712. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  169713. if (s) {
  169714. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169715. r = GET_BITS(s);
  169716. s = HUFF_EXTEND(r, s);
  169717. }
  169718. /* Convert DC difference to actual value, update last_dc_val */
  169719. s += state.last_dc_val[ci];
  169720. state.last_dc_val[ci] = s;
  169721. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  169722. (*block)[0] = (JCOEF) (s << Al);
  169723. }
  169724. /* Completed MCU, so update state */
  169725. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169726. ASSIGN_STATE(entropy->saved, state);
  169727. }
  169728. /* Account for restart interval (no-op if not using restarts) */
  169729. entropy->restarts_to_go--;
  169730. return TRUE;
  169731. }
  169732. /*
  169733. * MCU decoding for AC initial scan (either spectral selection,
  169734. * or first pass of successive approximation).
  169735. */
  169736. METHODDEF(boolean)
  169737. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169738. {
  169739. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169740. int Se = cinfo->Se;
  169741. int Al = cinfo->Al;
  169742. register int s, k, r;
  169743. unsigned int EOBRUN;
  169744. JBLOCKROW block;
  169745. BITREAD_STATE_VARS;
  169746. d_derived_tbl * tbl;
  169747. /* Process restart marker if needed; may have to suspend */
  169748. if (cinfo->restart_interval) {
  169749. if (entropy->restarts_to_go == 0)
  169750. if (! process_restartp(cinfo))
  169751. return FALSE;
  169752. }
  169753. /* If we've run out of data, just leave the MCU set to zeroes.
  169754. * This way, we return uniform gray for the remainder of the segment.
  169755. */
  169756. if (! entropy->pub.insufficient_data) {
  169757. /* Load up working state.
  169758. * We can avoid loading/saving bitread state if in an EOB run.
  169759. */
  169760. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169761. /* There is always only one block per MCU */
  169762. if (EOBRUN > 0) /* if it's a band of zeroes... */
  169763. EOBRUN--; /* ...process it now (we do nothing) */
  169764. else {
  169765. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169766. block = MCU_data[0];
  169767. tbl = entropy->ac_derived_tbl;
  169768. for (k = cinfo->Ss; k <= Se; k++) {
  169769. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  169770. r = s >> 4;
  169771. s &= 15;
  169772. if (s) {
  169773. k += r;
  169774. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169775. r = GET_BITS(s);
  169776. s = HUFF_EXTEND(r, s);
  169777. /* Scale and output coefficient in natural (dezigzagged) order */
  169778. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  169779. } else {
  169780. if (r == 15) { /* ZRL */
  169781. k += 15; /* skip 15 zeroes in band */
  169782. } else { /* EOBr, run length is 2^r + appended bits */
  169783. EOBRUN = 1 << r;
  169784. if (r) { /* EOBr, r > 0 */
  169785. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  169786. r = GET_BITS(r);
  169787. EOBRUN += r;
  169788. }
  169789. EOBRUN--; /* this band is processed at this moment */
  169790. break; /* force end-of-band */
  169791. }
  169792. }
  169793. }
  169794. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169795. }
  169796. /* Completed MCU, so update state */
  169797. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169798. }
  169799. /* Account for restart interval (no-op if not using restarts) */
  169800. entropy->restarts_to_go--;
  169801. return TRUE;
  169802. }
  169803. /*
  169804. * MCU decoding for DC successive approximation refinement scan.
  169805. * Note: we assume such scans can be multi-component, although the spec
  169806. * is not very clear on the point.
  169807. */
  169808. METHODDEF(boolean)
  169809. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169810. {
  169811. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169812. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169813. int blkn;
  169814. JBLOCKROW block;
  169815. BITREAD_STATE_VARS;
  169816. /* Process restart marker if needed; may have to suspend */
  169817. if (cinfo->restart_interval) {
  169818. if (entropy->restarts_to_go == 0)
  169819. if (! process_restartp(cinfo))
  169820. return FALSE;
  169821. }
  169822. /* Not worth the cycles to check insufficient_data here,
  169823. * since we will not change the data anyway if we read zeroes.
  169824. */
  169825. /* Load up working state */
  169826. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169827. /* Outer loop handles each block in the MCU */
  169828. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169829. block = MCU_data[blkn];
  169830. /* Encoded data is simply the next bit of the two's-complement DC value */
  169831. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  169832. if (GET_BITS(1))
  169833. (*block)[0] |= p1;
  169834. /* Note: since we use |=, repeating the assignment later is safe */
  169835. }
  169836. /* Completed MCU, so update state */
  169837. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169838. /* Account for restart interval (no-op if not using restarts) */
  169839. entropy->restarts_to_go--;
  169840. return TRUE;
  169841. }
  169842. /*
  169843. * MCU decoding for AC successive approximation refinement scan.
  169844. */
  169845. METHODDEF(boolean)
  169846. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169847. {
  169848. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169849. int Se = cinfo->Se;
  169850. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169851. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  169852. register int s, k, r;
  169853. unsigned int EOBRUN;
  169854. JBLOCKROW block;
  169855. JCOEFPTR thiscoef;
  169856. BITREAD_STATE_VARS;
  169857. d_derived_tbl * tbl;
  169858. int num_newnz;
  169859. int newnz_pos[DCTSIZE2];
  169860. /* Process restart marker if needed; may have to suspend */
  169861. if (cinfo->restart_interval) {
  169862. if (entropy->restarts_to_go == 0)
  169863. if (! process_restartp(cinfo))
  169864. return FALSE;
  169865. }
  169866. /* If we've run out of data, don't modify the MCU.
  169867. */
  169868. if (! entropy->pub.insufficient_data) {
  169869. /* Load up working state */
  169870. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169871. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169872. /* There is always only one block per MCU */
  169873. block = MCU_data[0];
  169874. tbl = entropy->ac_derived_tbl;
  169875. /* If we are forced to suspend, we must undo the assignments to any newly
  169876. * nonzero coefficients in the block, because otherwise we'd get confused
  169877. * next time about which coefficients were already nonzero.
  169878. * But we need not undo addition of bits to already-nonzero coefficients;
  169879. * instead, we can test the current bit to see if we already did it.
  169880. */
  169881. num_newnz = 0;
  169882. /* initialize coefficient loop counter to start of band */
  169883. k = cinfo->Ss;
  169884. if (EOBRUN == 0) {
  169885. for (; k <= Se; k++) {
  169886. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  169887. r = s >> 4;
  169888. s &= 15;
  169889. if (s) {
  169890. if (s != 1) /* size of new coef should always be 1 */
  169891. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  169892. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169893. if (GET_BITS(1))
  169894. s = p1; /* newly nonzero coef is positive */
  169895. else
  169896. s = m1; /* newly nonzero coef is negative */
  169897. } else {
  169898. if (r != 15) {
  169899. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  169900. if (r) {
  169901. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  169902. r = GET_BITS(r);
  169903. EOBRUN += r;
  169904. }
  169905. break; /* rest of block is handled by EOB logic */
  169906. }
  169907. /* note s = 0 for processing ZRL */
  169908. }
  169909. /* Advance over already-nonzero coefs and r still-zero coefs,
  169910. * appending correction bits to the nonzeroes. A correction bit is 1
  169911. * if the absolute value of the coefficient must be increased.
  169912. */
  169913. do {
  169914. thiscoef = *block + jpeg_natural_order[k];
  169915. if (*thiscoef != 0) {
  169916. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169917. if (GET_BITS(1)) {
  169918. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  169919. if (*thiscoef >= 0)
  169920. *thiscoef += p1;
  169921. else
  169922. *thiscoef += m1;
  169923. }
  169924. }
  169925. } else {
  169926. if (--r < 0)
  169927. break; /* reached target zero coefficient */
  169928. }
  169929. k++;
  169930. } while (k <= Se);
  169931. if (s) {
  169932. int pos = jpeg_natural_order[k];
  169933. /* Output newly nonzero coefficient */
  169934. (*block)[pos] = (JCOEF) s;
  169935. /* Remember its position in case we have to suspend */
  169936. newnz_pos[num_newnz++] = pos;
  169937. }
  169938. }
  169939. }
  169940. if (EOBRUN > 0) {
  169941. /* Scan any remaining coefficient positions after the end-of-band
  169942. * (the last newly nonzero coefficient, if any). Append a correction
  169943. * bit to each already-nonzero coefficient. A correction bit is 1
  169944. * if the absolute value of the coefficient must be increased.
  169945. */
  169946. for (; k <= Se; k++) {
  169947. thiscoef = *block + jpeg_natural_order[k];
  169948. if (*thiscoef != 0) {
  169949. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169950. if (GET_BITS(1)) {
  169951. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  169952. if (*thiscoef >= 0)
  169953. *thiscoef += p1;
  169954. else
  169955. *thiscoef += m1;
  169956. }
  169957. }
  169958. }
  169959. }
  169960. /* Count one block completed in EOB run */
  169961. EOBRUN--;
  169962. }
  169963. /* Completed MCU, so update state */
  169964. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169965. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169966. }
  169967. /* Account for restart interval (no-op if not using restarts) */
  169968. entropy->restarts_to_go--;
  169969. return TRUE;
  169970. undoit:
  169971. /* Re-zero any output coefficients that we made newly nonzero */
  169972. while (num_newnz > 0)
  169973. (*block)[newnz_pos[--num_newnz]] = 0;
  169974. return FALSE;
  169975. }
  169976. /*
  169977. * Module initialization routine for progressive Huffman entropy decoding.
  169978. */
  169979. GLOBAL(void)
  169980. jinit_phuff_decoder (j_decompress_ptr cinfo)
  169981. {
  169982. phuff_entropy_ptr2 entropy;
  169983. int *coef_bit_ptr;
  169984. int ci, i;
  169985. entropy = (phuff_entropy_ptr2)
  169986. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169987. SIZEOF(phuff_entropy_decoder));
  169988. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169989. entropy->pub.start_pass = start_pass_phuff_decoder;
  169990. /* Mark derived tables unallocated */
  169991. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169992. entropy->derived_tbls[i] = NULL;
  169993. }
  169994. /* Create progression status table */
  169995. cinfo->coef_bits = (int (*)[DCTSIZE2])
  169996. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169997. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  169998. coef_bit_ptr = & cinfo->coef_bits[0][0];
  169999. for (ci = 0; ci < cinfo->num_components; ci++)
  170000. for (i = 0; i < DCTSIZE2; i++)
  170001. *coef_bit_ptr++ = -1;
  170002. }
  170003. #endif /* D_PROGRESSIVE_SUPPORTED */
  170004. /*** End of inlined file: jdphuff.c ***/
  170005. /*** Start of inlined file: jdpostct.c ***/
  170006. #define JPEG_INTERNALS
  170007. /* Private buffer controller object */
  170008. typedef struct {
  170009. struct jpeg_d_post_controller pub; /* public fields */
  170010. /* Color quantization source buffer: this holds output data from
  170011. * the upsample/color conversion step to be passed to the quantizer.
  170012. * For two-pass color quantization, we need a full-image buffer;
  170013. * for one-pass operation, a strip buffer is sufficient.
  170014. */
  170015. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  170016. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  170017. JDIMENSION strip_height; /* buffer size in rows */
  170018. /* for two-pass mode only: */
  170019. JDIMENSION starting_row; /* row # of first row in current strip */
  170020. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  170021. } my_post_controller;
  170022. typedef my_post_controller * my_post_ptr;
  170023. /* Forward declarations */
  170024. METHODDEF(void) post_process_1pass
  170025. JPP((j_decompress_ptr cinfo,
  170026. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170027. JDIMENSION in_row_groups_avail,
  170028. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170029. JDIMENSION out_rows_avail));
  170030. #ifdef QUANT_2PASS_SUPPORTED
  170031. METHODDEF(void) post_process_prepass
  170032. JPP((j_decompress_ptr cinfo,
  170033. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170034. JDIMENSION in_row_groups_avail,
  170035. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170036. JDIMENSION out_rows_avail));
  170037. METHODDEF(void) post_process_2pass
  170038. JPP((j_decompress_ptr cinfo,
  170039. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170040. JDIMENSION in_row_groups_avail,
  170041. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170042. JDIMENSION out_rows_avail));
  170043. #endif
  170044. /*
  170045. * Initialize for a processing pass.
  170046. */
  170047. METHODDEF(void)
  170048. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170049. {
  170050. my_post_ptr post = (my_post_ptr) cinfo->post;
  170051. switch (pass_mode) {
  170052. case JBUF_PASS_THRU:
  170053. if (cinfo->quantize_colors) {
  170054. /* Single-pass processing with color quantization. */
  170055. post->pub.post_process_data = post_process_1pass;
  170056. /* We could be doing buffered-image output before starting a 2-pass
  170057. * color quantization; in that case, jinit_d_post_controller did not
  170058. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  170059. */
  170060. if (post->buffer == NULL) {
  170061. post->buffer = (*cinfo->mem->access_virt_sarray)
  170062. ((j_common_ptr) cinfo, post->whole_image,
  170063. (JDIMENSION) 0, post->strip_height, TRUE);
  170064. }
  170065. } else {
  170066. /* For single-pass processing without color quantization,
  170067. * I have no work to do; just call the upsampler directly.
  170068. */
  170069. post->pub.post_process_data = cinfo->upsample->upsample;
  170070. }
  170071. break;
  170072. #ifdef QUANT_2PASS_SUPPORTED
  170073. case JBUF_SAVE_AND_PASS:
  170074. /* First pass of 2-pass quantization */
  170075. if (post->whole_image == NULL)
  170076. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170077. post->pub.post_process_data = post_process_prepass;
  170078. break;
  170079. case JBUF_CRANK_DEST:
  170080. /* Second pass of 2-pass quantization */
  170081. if (post->whole_image == NULL)
  170082. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170083. post->pub.post_process_data = post_process_2pass;
  170084. break;
  170085. #endif /* QUANT_2PASS_SUPPORTED */
  170086. default:
  170087. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170088. break;
  170089. }
  170090. post->starting_row = post->next_row = 0;
  170091. }
  170092. /*
  170093. * Process some data in the one-pass (strip buffer) case.
  170094. * This is used for color precision reduction as well as one-pass quantization.
  170095. */
  170096. METHODDEF(void)
  170097. post_process_1pass (j_decompress_ptr cinfo,
  170098. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170099. JDIMENSION in_row_groups_avail,
  170100. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170101. JDIMENSION out_rows_avail)
  170102. {
  170103. my_post_ptr post = (my_post_ptr) cinfo->post;
  170104. JDIMENSION num_rows, max_rows;
  170105. /* Fill the buffer, but not more than what we can dump out in one go. */
  170106. /* Note we rely on the upsampler to detect bottom of image. */
  170107. max_rows = out_rows_avail - *out_row_ctr;
  170108. if (max_rows > post->strip_height)
  170109. max_rows = post->strip_height;
  170110. num_rows = 0;
  170111. (*cinfo->upsample->upsample) (cinfo,
  170112. input_buf, in_row_group_ctr, in_row_groups_avail,
  170113. post->buffer, &num_rows, max_rows);
  170114. /* Quantize and emit data. */
  170115. (*cinfo->cquantize->color_quantize) (cinfo,
  170116. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  170117. *out_row_ctr += num_rows;
  170118. }
  170119. #ifdef QUANT_2PASS_SUPPORTED
  170120. /*
  170121. * Process some data in the first pass of 2-pass quantization.
  170122. */
  170123. METHODDEF(void)
  170124. post_process_prepass (j_decompress_ptr cinfo,
  170125. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170126. JDIMENSION in_row_groups_avail,
  170127. JSAMPARRAY, JDIMENSION *out_row_ctr,
  170128. JDIMENSION)
  170129. {
  170130. my_post_ptr post = (my_post_ptr) cinfo->post;
  170131. JDIMENSION old_next_row, num_rows;
  170132. /* Reposition virtual buffer if at start of strip. */
  170133. if (post->next_row == 0) {
  170134. post->buffer = (*cinfo->mem->access_virt_sarray)
  170135. ((j_common_ptr) cinfo, post->whole_image,
  170136. post->starting_row, post->strip_height, TRUE);
  170137. }
  170138. /* Upsample some data (up to a strip height's worth). */
  170139. old_next_row = post->next_row;
  170140. (*cinfo->upsample->upsample) (cinfo,
  170141. input_buf, in_row_group_ctr, in_row_groups_avail,
  170142. post->buffer, &post->next_row, post->strip_height);
  170143. /* Allow quantizer to scan new data. No data is emitted, */
  170144. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  170145. if (post->next_row > old_next_row) {
  170146. num_rows = post->next_row - old_next_row;
  170147. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  170148. (JSAMPARRAY) NULL, (int) num_rows);
  170149. *out_row_ctr += num_rows;
  170150. }
  170151. /* Advance if we filled the strip. */
  170152. if (post->next_row >= post->strip_height) {
  170153. post->starting_row += post->strip_height;
  170154. post->next_row = 0;
  170155. }
  170156. }
  170157. /*
  170158. * Process some data in the second pass of 2-pass quantization.
  170159. */
  170160. METHODDEF(void)
  170161. post_process_2pass (j_decompress_ptr cinfo,
  170162. JSAMPIMAGE, JDIMENSION *,
  170163. JDIMENSION,
  170164. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170165. JDIMENSION out_rows_avail)
  170166. {
  170167. my_post_ptr post = (my_post_ptr) cinfo->post;
  170168. JDIMENSION num_rows, max_rows;
  170169. /* Reposition virtual buffer if at start of strip. */
  170170. if (post->next_row == 0) {
  170171. post->buffer = (*cinfo->mem->access_virt_sarray)
  170172. ((j_common_ptr) cinfo, post->whole_image,
  170173. post->starting_row, post->strip_height, FALSE);
  170174. }
  170175. /* Determine number of rows to emit. */
  170176. num_rows = post->strip_height - post->next_row; /* available in strip */
  170177. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  170178. if (num_rows > max_rows)
  170179. num_rows = max_rows;
  170180. /* We have to check bottom of image here, can't depend on upsampler. */
  170181. max_rows = cinfo->output_height - post->starting_row;
  170182. if (num_rows > max_rows)
  170183. num_rows = max_rows;
  170184. /* Quantize and emit data. */
  170185. (*cinfo->cquantize->color_quantize) (cinfo,
  170186. post->buffer + post->next_row, output_buf + *out_row_ctr,
  170187. (int) num_rows);
  170188. *out_row_ctr += num_rows;
  170189. /* Advance if we filled the strip. */
  170190. post->next_row += num_rows;
  170191. if (post->next_row >= post->strip_height) {
  170192. post->starting_row += post->strip_height;
  170193. post->next_row = 0;
  170194. }
  170195. }
  170196. #endif /* QUANT_2PASS_SUPPORTED */
  170197. /*
  170198. * Initialize postprocessing controller.
  170199. */
  170200. GLOBAL(void)
  170201. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170202. {
  170203. my_post_ptr post;
  170204. post = (my_post_ptr)
  170205. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170206. SIZEOF(my_post_controller));
  170207. cinfo->post = (struct jpeg_d_post_controller *) post;
  170208. post->pub.start_pass = start_pass_dpost;
  170209. post->whole_image = NULL; /* flag for no virtual arrays */
  170210. post->buffer = NULL; /* flag for no strip buffer */
  170211. /* Create the quantization buffer, if needed */
  170212. if (cinfo->quantize_colors) {
  170213. /* The buffer strip height is max_v_samp_factor, which is typically
  170214. * an efficient number of rows for upsampling to return.
  170215. * (In the presence of output rescaling, we might want to be smarter?)
  170216. */
  170217. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  170218. if (need_full_buffer) {
  170219. /* Two-pass color quantization: need full-image storage. */
  170220. /* We round up the number of rows to a multiple of the strip height. */
  170221. #ifdef QUANT_2PASS_SUPPORTED
  170222. post->whole_image = (*cinfo->mem->request_virt_sarray)
  170223. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  170224. cinfo->output_width * cinfo->out_color_components,
  170225. (JDIMENSION) jround_up((long) cinfo->output_height,
  170226. (long) post->strip_height),
  170227. post->strip_height);
  170228. #else
  170229. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170230. #endif /* QUANT_2PASS_SUPPORTED */
  170231. } else {
  170232. /* One-pass color quantization: just make a strip buffer. */
  170233. post->buffer = (*cinfo->mem->alloc_sarray)
  170234. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170235. cinfo->output_width * cinfo->out_color_components,
  170236. post->strip_height);
  170237. }
  170238. }
  170239. }
  170240. /*** End of inlined file: jdpostct.c ***/
  170241. #undef FIX
  170242. /*** Start of inlined file: jdsample.c ***/
  170243. #define JPEG_INTERNALS
  170244. /* Pointer to routine to upsample a single component */
  170245. typedef JMETHOD(void, upsample1_ptr,
  170246. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170247. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  170248. /* Private subobject */
  170249. typedef struct {
  170250. struct jpeg_upsampler pub; /* public fields */
  170251. /* Color conversion buffer. When using separate upsampling and color
  170252. * conversion steps, this buffer holds one upsampled row group until it
  170253. * has been color converted and output.
  170254. * Note: we do not allocate any storage for component(s) which are full-size,
  170255. * ie do not need rescaling. The corresponding entry of color_buf[] is
  170256. * simply set to point to the input data array, thereby avoiding copying.
  170257. */
  170258. JSAMPARRAY color_buf[MAX_COMPONENTS];
  170259. /* Per-component upsampling method pointers */
  170260. upsample1_ptr methods[MAX_COMPONENTS];
  170261. int next_row_out; /* counts rows emitted from color_buf */
  170262. JDIMENSION rows_to_go; /* counts rows remaining in image */
  170263. /* Height of an input row group for each component. */
  170264. int rowgroup_height[MAX_COMPONENTS];
  170265. /* These arrays save pixel expansion factors so that int_expand need not
  170266. * recompute them each time. They are unused for other upsampling methods.
  170267. */
  170268. UINT8 h_expand[MAX_COMPONENTS];
  170269. UINT8 v_expand[MAX_COMPONENTS];
  170270. } my_upsampler2;
  170271. typedef my_upsampler2 * my_upsample_ptr2;
  170272. /*
  170273. * Initialize for an upsampling pass.
  170274. */
  170275. METHODDEF(void)
  170276. start_pass_upsample (j_decompress_ptr cinfo)
  170277. {
  170278. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170279. /* Mark the conversion buffer empty */
  170280. upsample->next_row_out = cinfo->max_v_samp_factor;
  170281. /* Initialize total-height counter for detecting bottom of image */
  170282. upsample->rows_to_go = cinfo->output_height;
  170283. }
  170284. /*
  170285. * Control routine to do upsampling (and color conversion).
  170286. *
  170287. * In this version we upsample each component independently.
  170288. * We upsample one row group into the conversion buffer, then apply
  170289. * color conversion a row at a time.
  170290. */
  170291. METHODDEF(void)
  170292. sep_upsample (j_decompress_ptr cinfo,
  170293. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170294. JDIMENSION,
  170295. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170296. JDIMENSION out_rows_avail)
  170297. {
  170298. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170299. int ci;
  170300. jpeg_component_info * compptr;
  170301. JDIMENSION num_rows;
  170302. /* Fill the conversion buffer, if it's empty */
  170303. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  170304. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170305. ci++, compptr++) {
  170306. /* Invoke per-component upsample method. Notice we pass a POINTER
  170307. * to color_buf[ci], so that fullsize_upsample can change it.
  170308. */
  170309. (*upsample->methods[ci]) (cinfo, compptr,
  170310. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  170311. upsample->color_buf + ci);
  170312. }
  170313. upsample->next_row_out = 0;
  170314. }
  170315. /* Color-convert and emit rows */
  170316. /* How many we have in the buffer: */
  170317. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  170318. /* Not more than the distance to the end of the image. Need this test
  170319. * in case the image height is not a multiple of max_v_samp_factor:
  170320. */
  170321. if (num_rows > upsample->rows_to_go)
  170322. num_rows = upsample->rows_to_go;
  170323. /* And not more than what the client can accept: */
  170324. out_rows_avail -= *out_row_ctr;
  170325. if (num_rows > out_rows_avail)
  170326. num_rows = out_rows_avail;
  170327. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  170328. (JDIMENSION) upsample->next_row_out,
  170329. output_buf + *out_row_ctr,
  170330. (int) num_rows);
  170331. /* Adjust counts */
  170332. *out_row_ctr += num_rows;
  170333. upsample->rows_to_go -= num_rows;
  170334. upsample->next_row_out += num_rows;
  170335. /* When the buffer is emptied, declare this input row group consumed */
  170336. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  170337. (*in_row_group_ctr)++;
  170338. }
  170339. /*
  170340. * These are the routines invoked by sep_upsample to upsample pixel values
  170341. * of a single component. One row group is processed per call.
  170342. */
  170343. /*
  170344. * For full-size components, we just make color_buf[ci] point at the
  170345. * input buffer, and thus avoid copying any data. Note that this is
  170346. * safe only because sep_upsample doesn't declare the input row group
  170347. * "consumed" until we are done color converting and emitting it.
  170348. */
  170349. METHODDEF(void)
  170350. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  170351. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170352. {
  170353. *output_data_ptr = input_data;
  170354. }
  170355. /*
  170356. * This is a no-op version used for "uninteresting" components.
  170357. * These components will not be referenced by color conversion.
  170358. */
  170359. METHODDEF(void)
  170360. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  170361. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  170362. {
  170363. *output_data_ptr = NULL; /* safety check */
  170364. }
  170365. /*
  170366. * This version handles any integral sampling ratios.
  170367. * This is not used for typical JPEG files, so it need not be fast.
  170368. * Nor, for that matter, is it particularly accurate: the algorithm is
  170369. * simple replication of the input pixel onto the corresponding output
  170370. * pixels. The hi-falutin sampling literature refers to this as a
  170371. * "box filter". A box filter tends to introduce visible artifacts,
  170372. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  170373. * you would be well advised to improve this code.
  170374. */
  170375. METHODDEF(void)
  170376. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170377. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170378. {
  170379. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170380. JSAMPARRAY output_data = *output_data_ptr;
  170381. register JSAMPROW inptr, outptr;
  170382. register JSAMPLE invalue;
  170383. register int h;
  170384. JSAMPROW outend;
  170385. int h_expand, v_expand;
  170386. int inrow, outrow;
  170387. h_expand = upsample->h_expand[compptr->component_index];
  170388. v_expand = upsample->v_expand[compptr->component_index];
  170389. inrow = outrow = 0;
  170390. while (outrow < cinfo->max_v_samp_factor) {
  170391. /* Generate one output row with proper horizontal expansion */
  170392. inptr = input_data[inrow];
  170393. outptr = output_data[outrow];
  170394. outend = outptr + cinfo->output_width;
  170395. while (outptr < outend) {
  170396. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170397. for (h = h_expand; h > 0; h--) {
  170398. *outptr++ = invalue;
  170399. }
  170400. }
  170401. /* Generate any additional output rows by duplicating the first one */
  170402. if (v_expand > 1) {
  170403. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  170404. v_expand-1, cinfo->output_width);
  170405. }
  170406. inrow++;
  170407. outrow += v_expand;
  170408. }
  170409. }
  170410. /*
  170411. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  170412. * It's still a box filter.
  170413. */
  170414. METHODDEF(void)
  170415. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  170416. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170417. {
  170418. JSAMPARRAY output_data = *output_data_ptr;
  170419. register JSAMPROW inptr, outptr;
  170420. register JSAMPLE invalue;
  170421. JSAMPROW outend;
  170422. int inrow;
  170423. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  170424. inptr = input_data[inrow];
  170425. outptr = output_data[inrow];
  170426. outend = outptr + cinfo->output_width;
  170427. while (outptr < outend) {
  170428. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170429. *outptr++ = invalue;
  170430. *outptr++ = invalue;
  170431. }
  170432. }
  170433. }
  170434. /*
  170435. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  170436. * It's still a box filter.
  170437. */
  170438. METHODDEF(void)
  170439. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  170440. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170441. {
  170442. JSAMPARRAY output_data = *output_data_ptr;
  170443. register JSAMPROW inptr, outptr;
  170444. register JSAMPLE invalue;
  170445. JSAMPROW outend;
  170446. int inrow, outrow;
  170447. inrow = outrow = 0;
  170448. while (outrow < cinfo->max_v_samp_factor) {
  170449. inptr = input_data[inrow];
  170450. outptr = output_data[outrow];
  170451. outend = outptr + cinfo->output_width;
  170452. while (outptr < outend) {
  170453. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170454. *outptr++ = invalue;
  170455. *outptr++ = invalue;
  170456. }
  170457. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  170458. 1, cinfo->output_width);
  170459. inrow++;
  170460. outrow += 2;
  170461. }
  170462. }
  170463. /*
  170464. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  170465. *
  170466. * The upsampling algorithm is linear interpolation between pixel centers,
  170467. * also known as a "triangle filter". This is a good compromise between
  170468. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  170469. * of the way between input pixel centers.
  170470. *
  170471. * A note about the "bias" calculations: when rounding fractional values to
  170472. * integer, we do not want to always round 0.5 up to the next integer.
  170473. * If we did that, we'd introduce a noticeable bias towards larger values.
  170474. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  170475. * alternate pixel locations (a simple ordered dither pattern).
  170476. */
  170477. METHODDEF(void)
  170478. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170479. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170480. {
  170481. JSAMPARRAY output_data = *output_data_ptr;
  170482. register JSAMPROW inptr, outptr;
  170483. register int invalue;
  170484. register JDIMENSION colctr;
  170485. int inrow;
  170486. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  170487. inptr = input_data[inrow];
  170488. outptr = output_data[inrow];
  170489. /* Special case for first column */
  170490. invalue = GETJSAMPLE(*inptr++);
  170491. *outptr++ = (JSAMPLE) invalue;
  170492. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  170493. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  170494. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  170495. invalue = GETJSAMPLE(*inptr++) * 3;
  170496. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  170497. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  170498. }
  170499. /* Special case for last column */
  170500. invalue = GETJSAMPLE(*inptr);
  170501. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  170502. *outptr++ = (JSAMPLE) invalue;
  170503. }
  170504. }
  170505. /*
  170506. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  170507. * Again a triangle filter; see comments for h2v1 case, above.
  170508. *
  170509. * It is OK for us to reference the adjacent input rows because we demanded
  170510. * context from the main buffer controller (see initialization code).
  170511. */
  170512. METHODDEF(void)
  170513. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170514. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170515. {
  170516. JSAMPARRAY output_data = *output_data_ptr;
  170517. register JSAMPROW inptr0, inptr1, outptr;
  170518. #if BITS_IN_JSAMPLE == 8
  170519. register int thiscolsum, lastcolsum, nextcolsum;
  170520. #else
  170521. register INT32 thiscolsum, lastcolsum, nextcolsum;
  170522. #endif
  170523. register JDIMENSION colctr;
  170524. int inrow, outrow, v;
  170525. inrow = outrow = 0;
  170526. while (outrow < cinfo->max_v_samp_factor) {
  170527. for (v = 0; v < 2; v++) {
  170528. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  170529. inptr0 = input_data[inrow];
  170530. if (v == 0) /* next nearest is row above */
  170531. inptr1 = input_data[inrow-1];
  170532. else /* next nearest is row below */
  170533. inptr1 = input_data[inrow+1];
  170534. outptr = output_data[outrow++];
  170535. /* Special case for first column */
  170536. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  170537. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  170538. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  170539. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  170540. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  170541. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  170542. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  170543. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  170544. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  170545. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  170546. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  170547. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  170548. }
  170549. /* Special case for last column */
  170550. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  170551. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  170552. }
  170553. inrow++;
  170554. }
  170555. }
  170556. /*
  170557. * Module initialization routine for upsampling.
  170558. */
  170559. GLOBAL(void)
  170560. jinit_upsampler (j_decompress_ptr cinfo)
  170561. {
  170562. my_upsample_ptr2 upsample;
  170563. int ci;
  170564. jpeg_component_info * compptr;
  170565. boolean need_buffer, do_fancy;
  170566. int h_in_group, v_in_group, h_out_group, v_out_group;
  170567. upsample = (my_upsample_ptr2)
  170568. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170569. SIZEOF(my_upsampler2));
  170570. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  170571. upsample->pub.start_pass = start_pass_upsample;
  170572. upsample->pub.upsample = sep_upsample;
  170573. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  170574. if (cinfo->CCIR601_sampling) /* this isn't supported */
  170575. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  170576. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  170577. * so don't ask for it.
  170578. */
  170579. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  170580. /* Verify we can handle the sampling factors, select per-component methods,
  170581. * and create storage as needed.
  170582. */
  170583. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170584. ci++, compptr++) {
  170585. /* Compute size of an "input group" after IDCT scaling. This many samples
  170586. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  170587. */
  170588. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  170589. cinfo->min_DCT_scaled_size;
  170590. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170591. cinfo->min_DCT_scaled_size;
  170592. h_out_group = cinfo->max_h_samp_factor;
  170593. v_out_group = cinfo->max_v_samp_factor;
  170594. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  170595. need_buffer = TRUE;
  170596. if (! compptr->component_needed) {
  170597. /* Don't bother to upsample an uninteresting component. */
  170598. upsample->methods[ci] = noop_upsample;
  170599. need_buffer = FALSE;
  170600. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  170601. /* Fullsize components can be processed without any work. */
  170602. upsample->methods[ci] = fullsize_upsample;
  170603. need_buffer = FALSE;
  170604. } else if (h_in_group * 2 == h_out_group &&
  170605. v_in_group == v_out_group) {
  170606. /* Special cases for 2h1v upsampling */
  170607. if (do_fancy && compptr->downsampled_width > 2)
  170608. upsample->methods[ci] = h2v1_fancy_upsample;
  170609. else
  170610. upsample->methods[ci] = h2v1_upsample;
  170611. } else if (h_in_group * 2 == h_out_group &&
  170612. v_in_group * 2 == v_out_group) {
  170613. /* Special cases for 2h2v upsampling */
  170614. if (do_fancy && compptr->downsampled_width > 2) {
  170615. upsample->methods[ci] = h2v2_fancy_upsample;
  170616. upsample->pub.need_context_rows = TRUE;
  170617. } else
  170618. upsample->methods[ci] = h2v2_upsample;
  170619. } else if ((h_out_group % h_in_group) == 0 &&
  170620. (v_out_group % v_in_group) == 0) {
  170621. /* Generic integral-factors upsampling method */
  170622. upsample->methods[ci] = int_upsample;
  170623. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  170624. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  170625. } else
  170626. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  170627. if (need_buffer) {
  170628. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  170629. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170630. (JDIMENSION) jround_up((long) cinfo->output_width,
  170631. (long) cinfo->max_h_samp_factor),
  170632. (JDIMENSION) cinfo->max_v_samp_factor);
  170633. }
  170634. }
  170635. }
  170636. /*** End of inlined file: jdsample.c ***/
  170637. /*** Start of inlined file: jdtrans.c ***/
  170638. #define JPEG_INTERNALS
  170639. /* Forward declarations */
  170640. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  170641. /*
  170642. * Read the coefficient arrays from a JPEG file.
  170643. * jpeg_read_header must be completed before calling this.
  170644. *
  170645. * The entire image is read into a set of virtual coefficient-block arrays,
  170646. * one per component. The return value is a pointer to the array of
  170647. * virtual-array descriptors. These can be manipulated directly via the
  170648. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  170649. * To release the memory occupied by the virtual arrays, call
  170650. * jpeg_finish_decompress() when done with the data.
  170651. *
  170652. * An alternative usage is to simply obtain access to the coefficient arrays
  170653. * during a buffered-image-mode decompression operation. This is allowed
  170654. * after any jpeg_finish_output() call. The arrays can be accessed until
  170655. * jpeg_finish_decompress() is called. (Note that any call to the library
  170656. * may reposition the arrays, so don't rely on access_virt_barray() results
  170657. * to stay valid across library calls.)
  170658. *
  170659. * Returns NULL if suspended. This case need be checked only if
  170660. * a suspending data source is used.
  170661. */
  170662. GLOBAL(jvirt_barray_ptr *)
  170663. jpeg_read_coefficients (j_decompress_ptr cinfo)
  170664. {
  170665. if (cinfo->global_state == DSTATE_READY) {
  170666. /* First call: initialize active modules */
  170667. transdecode_master_selection(cinfo);
  170668. cinfo->global_state = DSTATE_RDCOEFS;
  170669. }
  170670. if (cinfo->global_state == DSTATE_RDCOEFS) {
  170671. /* Absorb whole file into the coef buffer */
  170672. for (;;) {
  170673. int retcode;
  170674. /* Call progress monitor hook if present */
  170675. if (cinfo->progress != NULL)
  170676. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  170677. /* Absorb some more input */
  170678. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  170679. if (retcode == JPEG_SUSPENDED)
  170680. return NULL;
  170681. if (retcode == JPEG_REACHED_EOI)
  170682. break;
  170683. /* Advance progress counter if appropriate */
  170684. if (cinfo->progress != NULL &&
  170685. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  170686. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  170687. /* startup underestimated number of scans; ratchet up one scan */
  170688. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  170689. }
  170690. }
  170691. }
  170692. /* Set state so that jpeg_finish_decompress does the right thing */
  170693. cinfo->global_state = DSTATE_STOPPING;
  170694. }
  170695. /* At this point we should be in state DSTATE_STOPPING if being used
  170696. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  170697. * to the coefficients during a full buffered-image-mode decompression.
  170698. */
  170699. if ((cinfo->global_state == DSTATE_STOPPING ||
  170700. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  170701. return cinfo->coef->coef_arrays;
  170702. }
  170703. /* Oops, improper usage */
  170704. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  170705. return NULL; /* keep compiler happy */
  170706. }
  170707. /*
  170708. * Master selection of decompression modules for transcoding.
  170709. * This substitutes for jdmaster.c's initialization of the full decompressor.
  170710. */
  170711. LOCAL(void)
  170712. transdecode_master_selection (j_decompress_ptr cinfo)
  170713. {
  170714. /* This is effectively a buffered-image operation. */
  170715. cinfo->buffered_image = TRUE;
  170716. /* Entropy decoding: either Huffman or arithmetic coding. */
  170717. if (cinfo->arith_code) {
  170718. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  170719. } else {
  170720. if (cinfo->progressive_mode) {
  170721. #ifdef D_PROGRESSIVE_SUPPORTED
  170722. jinit_phuff_decoder(cinfo);
  170723. #else
  170724. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170725. #endif
  170726. } else
  170727. jinit_huff_decoder(cinfo);
  170728. }
  170729. /* Always get a full-image coefficient buffer. */
  170730. jinit_d_coef_controller(cinfo, TRUE);
  170731. /* We can now tell the memory manager to allocate virtual arrays. */
  170732. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  170733. /* Initialize input side of decompressor to consume first scan. */
  170734. (*cinfo->inputctl->start_input_pass) (cinfo);
  170735. /* Initialize progress monitoring. */
  170736. if (cinfo->progress != NULL) {
  170737. int nscans;
  170738. /* Estimate number of scans to set pass_limit. */
  170739. if (cinfo->progressive_mode) {
  170740. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  170741. nscans = 2 + 3 * cinfo->num_components;
  170742. } else if (cinfo->inputctl->has_multiple_scans) {
  170743. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  170744. nscans = cinfo->num_components;
  170745. } else {
  170746. nscans = 1;
  170747. }
  170748. cinfo->progress->pass_counter = 0L;
  170749. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  170750. cinfo->progress->completed_passes = 0;
  170751. cinfo->progress->total_passes = 1;
  170752. }
  170753. }
  170754. /*** End of inlined file: jdtrans.c ***/
  170755. /*** Start of inlined file: jfdctflt.c ***/
  170756. #define JPEG_INTERNALS
  170757. #ifdef DCT_FLOAT_SUPPORTED
  170758. /*
  170759. * This module is specialized to the case DCTSIZE = 8.
  170760. */
  170761. #if DCTSIZE != 8
  170762. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170763. #endif
  170764. /*
  170765. * Perform the forward DCT on one block of samples.
  170766. */
  170767. GLOBAL(void)
  170768. jpeg_fdct_float (FAST_FLOAT * data)
  170769. {
  170770. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170771. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170772. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  170773. FAST_FLOAT *dataptr;
  170774. int ctr;
  170775. /* Pass 1: process rows. */
  170776. dataptr = data;
  170777. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170778. tmp0 = dataptr[0] + dataptr[7];
  170779. tmp7 = dataptr[0] - dataptr[7];
  170780. tmp1 = dataptr[1] + dataptr[6];
  170781. tmp6 = dataptr[1] - dataptr[6];
  170782. tmp2 = dataptr[2] + dataptr[5];
  170783. tmp5 = dataptr[2] - dataptr[5];
  170784. tmp3 = dataptr[3] + dataptr[4];
  170785. tmp4 = dataptr[3] - dataptr[4];
  170786. /* Even part */
  170787. tmp10 = tmp0 + tmp3; /* phase 2 */
  170788. tmp13 = tmp0 - tmp3;
  170789. tmp11 = tmp1 + tmp2;
  170790. tmp12 = tmp1 - tmp2;
  170791. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170792. dataptr[4] = tmp10 - tmp11;
  170793. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170794. dataptr[2] = tmp13 + z1; /* phase 5 */
  170795. dataptr[6] = tmp13 - z1;
  170796. /* Odd part */
  170797. tmp10 = tmp4 + tmp5; /* phase 2 */
  170798. tmp11 = tmp5 + tmp6;
  170799. tmp12 = tmp6 + tmp7;
  170800. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170801. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170802. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170803. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170804. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170805. z11 = tmp7 + z3; /* phase 5 */
  170806. z13 = tmp7 - z3;
  170807. dataptr[5] = z13 + z2; /* phase 6 */
  170808. dataptr[3] = z13 - z2;
  170809. dataptr[1] = z11 + z4;
  170810. dataptr[7] = z11 - z4;
  170811. dataptr += DCTSIZE; /* advance pointer to next row */
  170812. }
  170813. /* Pass 2: process columns. */
  170814. dataptr = data;
  170815. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170816. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170817. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170818. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170819. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170820. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170821. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170822. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170823. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170824. /* Even part */
  170825. tmp10 = tmp0 + tmp3; /* phase 2 */
  170826. tmp13 = tmp0 - tmp3;
  170827. tmp11 = tmp1 + tmp2;
  170828. tmp12 = tmp1 - tmp2;
  170829. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170830. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170831. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170832. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170833. dataptr[DCTSIZE*6] = tmp13 - z1;
  170834. /* Odd part */
  170835. tmp10 = tmp4 + tmp5; /* phase 2 */
  170836. tmp11 = tmp5 + tmp6;
  170837. tmp12 = tmp6 + tmp7;
  170838. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170839. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170840. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170841. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170842. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170843. z11 = tmp7 + z3; /* phase 5 */
  170844. z13 = tmp7 - z3;
  170845. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170846. dataptr[DCTSIZE*3] = z13 - z2;
  170847. dataptr[DCTSIZE*1] = z11 + z4;
  170848. dataptr[DCTSIZE*7] = z11 - z4;
  170849. dataptr++; /* advance pointer to next column */
  170850. }
  170851. }
  170852. #endif /* DCT_FLOAT_SUPPORTED */
  170853. /*** End of inlined file: jfdctflt.c ***/
  170854. /*** Start of inlined file: jfdctint.c ***/
  170855. #define JPEG_INTERNALS
  170856. #ifdef DCT_ISLOW_SUPPORTED
  170857. /*
  170858. * This module is specialized to the case DCTSIZE = 8.
  170859. */
  170860. #if DCTSIZE != 8
  170861. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170862. #endif
  170863. /*
  170864. * The poop on this scaling stuff is as follows:
  170865. *
  170866. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  170867. * larger than the true DCT outputs. The final outputs are therefore
  170868. * a factor of N larger than desired; since N=8 this can be cured by
  170869. * a simple right shift at the end of the algorithm. The advantage of
  170870. * this arrangement is that we save two multiplications per 1-D DCT,
  170871. * because the y0 and y4 outputs need not be divided by sqrt(N).
  170872. * In the IJG code, this factor of 8 is removed by the quantization step
  170873. * (in jcdctmgr.c), NOT in this module.
  170874. *
  170875. * We have to do addition and subtraction of the integer inputs, which
  170876. * is no problem, and multiplication by fractional constants, which is
  170877. * a problem to do in integer arithmetic. We multiply all the constants
  170878. * by CONST_SCALE and convert them to integer constants (thus retaining
  170879. * CONST_BITS bits of precision in the constants). After doing a
  170880. * multiplication we have to divide the product by CONST_SCALE, with proper
  170881. * rounding, to produce the correct output. This division can be done
  170882. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170883. * as long as possible so that partial sums can be added together with
  170884. * full fractional precision.
  170885. *
  170886. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170887. * they are represented to better-than-integral precision. These outputs
  170888. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170889. * with the recommended scaling. (For 12-bit sample data, the intermediate
  170890. * array is INT32 anyway.)
  170891. *
  170892. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170893. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170894. * shows that the values given below are the most effective.
  170895. */
  170896. #if BITS_IN_JSAMPLE == 8
  170897. #define CONST_BITS 13
  170898. #define PASS1_BITS 2
  170899. #else
  170900. #define CONST_BITS 13
  170901. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170902. #endif
  170903. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170904. * causing a lot of useless floating-point operations at run time.
  170905. * To get around this we use the following pre-calculated constants.
  170906. * If you change CONST_BITS you may want to add appropriate values.
  170907. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170908. */
  170909. #if CONST_BITS == 13
  170910. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170911. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170912. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170913. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170914. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170915. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170916. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170917. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170918. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170919. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170920. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170921. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170922. #else
  170923. #define FIX_0_298631336 FIX(0.298631336)
  170924. #define FIX_0_390180644 FIX(0.390180644)
  170925. #define FIX_0_541196100 FIX(0.541196100)
  170926. #define FIX_0_765366865 FIX(0.765366865)
  170927. #define FIX_0_899976223 FIX(0.899976223)
  170928. #define FIX_1_175875602 FIX(1.175875602)
  170929. #define FIX_1_501321110 FIX(1.501321110)
  170930. #define FIX_1_847759065 FIX(1.847759065)
  170931. #define FIX_1_961570560 FIX(1.961570560)
  170932. #define FIX_2_053119869 FIX(2.053119869)
  170933. #define FIX_2_562915447 FIX(2.562915447)
  170934. #define FIX_3_072711026 FIX(3.072711026)
  170935. #endif
  170936. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170937. * For 8-bit samples with the recommended scaling, all the variable
  170938. * and constant values involved are no more than 16 bits wide, so a
  170939. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170940. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170941. */
  170942. #if BITS_IN_JSAMPLE == 8
  170943. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170944. #else
  170945. #define MULTIPLY(var,const) ((var) * (const))
  170946. #endif
  170947. /*
  170948. * Perform the forward DCT on one block of samples.
  170949. */
  170950. GLOBAL(void)
  170951. jpeg_fdct_islow (DCTELEM * data)
  170952. {
  170953. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170954. INT32 tmp10, tmp11, tmp12, tmp13;
  170955. INT32 z1, z2, z3, z4, z5;
  170956. DCTELEM *dataptr;
  170957. int ctr;
  170958. SHIFT_TEMPS
  170959. /* Pass 1: process rows. */
  170960. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  170961. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170962. dataptr = data;
  170963. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170964. tmp0 = dataptr[0] + dataptr[7];
  170965. tmp7 = dataptr[0] - dataptr[7];
  170966. tmp1 = dataptr[1] + dataptr[6];
  170967. tmp6 = dataptr[1] - dataptr[6];
  170968. tmp2 = dataptr[2] + dataptr[5];
  170969. tmp5 = dataptr[2] - dataptr[5];
  170970. tmp3 = dataptr[3] + dataptr[4];
  170971. tmp4 = dataptr[3] - dataptr[4];
  170972. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170973. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170974. */
  170975. tmp10 = tmp0 + tmp3;
  170976. tmp13 = tmp0 - tmp3;
  170977. tmp11 = tmp1 + tmp2;
  170978. tmp12 = tmp1 - tmp2;
  170979. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  170980. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  170981. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170982. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170983. CONST_BITS-PASS1_BITS);
  170984. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170985. CONST_BITS-PASS1_BITS);
  170986. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170987. * cK represents cos(K*pi/16).
  170988. * i0..i3 in the paper are tmp4..tmp7 here.
  170989. */
  170990. z1 = tmp4 + tmp7;
  170991. z2 = tmp5 + tmp6;
  170992. z3 = tmp4 + tmp6;
  170993. z4 = tmp5 + tmp7;
  170994. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170995. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170996. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170997. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170998. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170999. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171000. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171001. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171002. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171003. z3 += z5;
  171004. z4 += z5;
  171005. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  171006. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  171007. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  171008. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  171009. dataptr += DCTSIZE; /* advance pointer to next row */
  171010. }
  171011. /* Pass 2: process columns.
  171012. * We remove the PASS1_BITS scaling, but leave the results scaled up
  171013. * by an overall factor of 8.
  171014. */
  171015. dataptr = data;
  171016. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171017. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171018. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171019. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171020. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171021. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171022. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171023. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171024. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171025. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  171026. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  171027. */
  171028. tmp10 = tmp0 + tmp3;
  171029. tmp13 = tmp0 - tmp3;
  171030. tmp11 = tmp1 + tmp2;
  171031. tmp12 = tmp1 - tmp2;
  171032. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  171033. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  171034. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  171035. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  171036. CONST_BITS+PASS1_BITS);
  171037. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  171038. CONST_BITS+PASS1_BITS);
  171039. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  171040. * cK represents cos(K*pi/16).
  171041. * i0..i3 in the paper are tmp4..tmp7 here.
  171042. */
  171043. z1 = tmp4 + tmp7;
  171044. z2 = tmp5 + tmp6;
  171045. z3 = tmp4 + tmp6;
  171046. z4 = tmp5 + tmp7;
  171047. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171048. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171049. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171050. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171051. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171052. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171053. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171054. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171055. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171056. z3 += z5;
  171057. z4 += z5;
  171058. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  171059. CONST_BITS+PASS1_BITS);
  171060. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  171061. CONST_BITS+PASS1_BITS);
  171062. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  171063. CONST_BITS+PASS1_BITS);
  171064. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  171065. CONST_BITS+PASS1_BITS);
  171066. dataptr++; /* advance pointer to next column */
  171067. }
  171068. }
  171069. #endif /* DCT_ISLOW_SUPPORTED */
  171070. /*** End of inlined file: jfdctint.c ***/
  171071. #undef CONST_BITS
  171072. #undef MULTIPLY
  171073. #undef FIX_0_541196100
  171074. /*** Start of inlined file: jfdctfst.c ***/
  171075. #define JPEG_INTERNALS
  171076. #ifdef DCT_IFAST_SUPPORTED
  171077. /*
  171078. * This module is specialized to the case DCTSIZE = 8.
  171079. */
  171080. #if DCTSIZE != 8
  171081. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171082. #endif
  171083. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171084. * see jfdctint.c for more details. However, we choose to descale
  171085. * (right shift) multiplication products as soon as they are formed,
  171086. * rather than carrying additional fractional bits into subsequent additions.
  171087. * This compromises accuracy slightly, but it lets us save a few shifts.
  171088. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171089. * everywhere except in the multiplications proper; this saves a good deal
  171090. * of work on 16-bit-int machines.
  171091. *
  171092. * Again to save a few shifts, the intermediate results between pass 1 and
  171093. * pass 2 are not upscaled, but are represented only to integral precision.
  171094. *
  171095. * A final compromise is to represent the multiplicative constants to only
  171096. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171097. * machines, and may also reduce the cost of multiplication (since there
  171098. * are fewer one-bits in the constants).
  171099. */
  171100. #define CONST_BITS 8
  171101. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171102. * causing a lot of useless floating-point operations at run time.
  171103. * To get around this we use the following pre-calculated constants.
  171104. * If you change CONST_BITS you may want to add appropriate values.
  171105. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171106. */
  171107. #if CONST_BITS == 8
  171108. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  171109. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  171110. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  171111. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  171112. #else
  171113. #define FIX_0_382683433 FIX(0.382683433)
  171114. #define FIX_0_541196100 FIX(0.541196100)
  171115. #define FIX_0_707106781 FIX(0.707106781)
  171116. #define FIX_1_306562965 FIX(1.306562965)
  171117. #endif
  171118. /* We can gain a little more speed, with a further compromise in accuracy,
  171119. * by omitting the addition in a descaling shift. This yields an incorrectly
  171120. * rounded result half the time...
  171121. */
  171122. #ifndef USE_ACCURATE_ROUNDING
  171123. #undef DESCALE
  171124. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171125. #endif
  171126. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171127. * descale to yield a DCTELEM result.
  171128. */
  171129. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171130. /*
  171131. * Perform the forward DCT on one block of samples.
  171132. */
  171133. GLOBAL(void)
  171134. jpeg_fdct_ifast (DCTELEM * data)
  171135. {
  171136. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171137. DCTELEM tmp10, tmp11, tmp12, tmp13;
  171138. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  171139. DCTELEM *dataptr;
  171140. int ctr;
  171141. SHIFT_TEMPS
  171142. /* Pass 1: process rows. */
  171143. dataptr = data;
  171144. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171145. tmp0 = dataptr[0] + dataptr[7];
  171146. tmp7 = dataptr[0] - dataptr[7];
  171147. tmp1 = dataptr[1] + dataptr[6];
  171148. tmp6 = dataptr[1] - dataptr[6];
  171149. tmp2 = dataptr[2] + dataptr[5];
  171150. tmp5 = dataptr[2] - dataptr[5];
  171151. tmp3 = dataptr[3] + dataptr[4];
  171152. tmp4 = dataptr[3] - dataptr[4];
  171153. /* Even part */
  171154. tmp10 = tmp0 + tmp3; /* phase 2 */
  171155. tmp13 = tmp0 - tmp3;
  171156. tmp11 = tmp1 + tmp2;
  171157. tmp12 = tmp1 - tmp2;
  171158. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  171159. dataptr[4] = tmp10 - tmp11;
  171160. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171161. dataptr[2] = tmp13 + z1; /* phase 5 */
  171162. dataptr[6] = tmp13 - z1;
  171163. /* Odd part */
  171164. tmp10 = tmp4 + tmp5; /* phase 2 */
  171165. tmp11 = tmp5 + tmp6;
  171166. tmp12 = tmp6 + tmp7;
  171167. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171168. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171169. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171170. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171171. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171172. z11 = tmp7 + z3; /* phase 5 */
  171173. z13 = tmp7 - z3;
  171174. dataptr[5] = z13 + z2; /* phase 6 */
  171175. dataptr[3] = z13 - z2;
  171176. dataptr[1] = z11 + z4;
  171177. dataptr[7] = z11 - z4;
  171178. dataptr += DCTSIZE; /* advance pointer to next row */
  171179. }
  171180. /* Pass 2: process columns. */
  171181. dataptr = data;
  171182. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171183. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171184. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171185. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171186. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171187. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171188. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171189. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171190. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171191. /* Even part */
  171192. tmp10 = tmp0 + tmp3; /* phase 2 */
  171193. tmp13 = tmp0 - tmp3;
  171194. tmp11 = tmp1 + tmp2;
  171195. tmp12 = tmp1 - tmp2;
  171196. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  171197. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  171198. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171199. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  171200. dataptr[DCTSIZE*6] = tmp13 - z1;
  171201. /* Odd part */
  171202. tmp10 = tmp4 + tmp5; /* phase 2 */
  171203. tmp11 = tmp5 + tmp6;
  171204. tmp12 = tmp6 + tmp7;
  171205. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171206. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171207. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171208. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171209. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171210. z11 = tmp7 + z3; /* phase 5 */
  171211. z13 = tmp7 - z3;
  171212. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  171213. dataptr[DCTSIZE*3] = z13 - z2;
  171214. dataptr[DCTSIZE*1] = z11 + z4;
  171215. dataptr[DCTSIZE*7] = z11 - z4;
  171216. dataptr++; /* advance pointer to next column */
  171217. }
  171218. }
  171219. #endif /* DCT_IFAST_SUPPORTED */
  171220. /*** End of inlined file: jfdctfst.c ***/
  171221. #undef FIX_0_541196100
  171222. /*** Start of inlined file: jidctflt.c ***/
  171223. #define JPEG_INTERNALS
  171224. #ifdef DCT_FLOAT_SUPPORTED
  171225. /*
  171226. * This module is specialized to the case DCTSIZE = 8.
  171227. */
  171228. #if DCTSIZE != 8
  171229. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171230. #endif
  171231. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171232. * entry; produce a float result.
  171233. */
  171234. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  171235. /*
  171236. * Perform dequantization and inverse DCT on one block of coefficients.
  171237. */
  171238. GLOBAL(void)
  171239. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171240. JCOEFPTR coef_block,
  171241. JSAMPARRAY output_buf, JDIMENSION output_col)
  171242. {
  171243. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171244. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  171245. FAST_FLOAT z5, z10, z11, z12, z13;
  171246. JCOEFPTR inptr;
  171247. FLOAT_MULT_TYPE * quantptr;
  171248. FAST_FLOAT * wsptr;
  171249. JSAMPROW outptr;
  171250. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171251. int ctr;
  171252. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  171253. SHIFT_TEMPS
  171254. /* Pass 1: process columns from input, store into work array. */
  171255. inptr = coef_block;
  171256. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  171257. wsptr = workspace;
  171258. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171259. /* Due to quantization, we will usually find that many of the input
  171260. * coefficients are zero, especially the AC terms. We can exploit this
  171261. * by short-circuiting the IDCT calculation for any column in which all
  171262. * the AC terms are zero. In that case each output is equal to the
  171263. * DC coefficient (with scale factor as needed).
  171264. * With typical images and quantization tables, half or more of the
  171265. * column DCT calculations can be simplified this way.
  171266. */
  171267. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171268. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171269. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171270. inptr[DCTSIZE*7] == 0) {
  171271. /* AC terms all zero */
  171272. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171273. wsptr[DCTSIZE*0] = dcval;
  171274. wsptr[DCTSIZE*1] = dcval;
  171275. wsptr[DCTSIZE*2] = dcval;
  171276. wsptr[DCTSIZE*3] = dcval;
  171277. wsptr[DCTSIZE*4] = dcval;
  171278. wsptr[DCTSIZE*5] = dcval;
  171279. wsptr[DCTSIZE*6] = dcval;
  171280. wsptr[DCTSIZE*7] = dcval;
  171281. inptr++; /* advance pointers to next column */
  171282. quantptr++;
  171283. wsptr++;
  171284. continue;
  171285. }
  171286. /* Even part */
  171287. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171288. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171289. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171290. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171291. tmp10 = tmp0 + tmp2; /* phase 3 */
  171292. tmp11 = tmp0 - tmp2;
  171293. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  171294. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  171295. tmp0 = tmp10 + tmp13; /* phase 2 */
  171296. tmp3 = tmp10 - tmp13;
  171297. tmp1 = tmp11 + tmp12;
  171298. tmp2 = tmp11 - tmp12;
  171299. /* Odd part */
  171300. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171301. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171302. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171303. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171304. z13 = tmp6 + tmp5; /* phase 6 */
  171305. z10 = tmp6 - tmp5;
  171306. z11 = tmp4 + tmp7;
  171307. z12 = tmp4 - tmp7;
  171308. tmp7 = z11 + z13; /* phase 5 */
  171309. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  171310. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171311. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171312. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171313. tmp6 = tmp12 - tmp7; /* phase 2 */
  171314. tmp5 = tmp11 - tmp6;
  171315. tmp4 = tmp10 + tmp5;
  171316. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  171317. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  171318. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  171319. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  171320. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  171321. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  171322. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  171323. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  171324. inptr++; /* advance pointers to next column */
  171325. quantptr++;
  171326. wsptr++;
  171327. }
  171328. /* Pass 2: process rows from work array, store into output array. */
  171329. /* Note that we must descale the results by a factor of 8 == 2**3. */
  171330. wsptr = workspace;
  171331. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171332. outptr = output_buf[ctr] + output_col;
  171333. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171334. * However, the column calculation has created many nonzero AC terms, so
  171335. * the simplification applies less often (typically 5% to 10% of the time).
  171336. * And testing floats for zero is relatively expensive, so we don't bother.
  171337. */
  171338. /* Even part */
  171339. tmp10 = wsptr[0] + wsptr[4];
  171340. tmp11 = wsptr[0] - wsptr[4];
  171341. tmp13 = wsptr[2] + wsptr[6];
  171342. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  171343. tmp0 = tmp10 + tmp13;
  171344. tmp3 = tmp10 - tmp13;
  171345. tmp1 = tmp11 + tmp12;
  171346. tmp2 = tmp11 - tmp12;
  171347. /* Odd part */
  171348. z13 = wsptr[5] + wsptr[3];
  171349. z10 = wsptr[5] - wsptr[3];
  171350. z11 = wsptr[1] + wsptr[7];
  171351. z12 = wsptr[1] - wsptr[7];
  171352. tmp7 = z11 + z13;
  171353. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  171354. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171355. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171356. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171357. tmp6 = tmp12 - tmp7;
  171358. tmp5 = tmp11 - tmp6;
  171359. tmp4 = tmp10 + tmp5;
  171360. /* Final output stage: scale down by a factor of 8 and range-limit */
  171361. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  171362. & RANGE_MASK];
  171363. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  171364. & RANGE_MASK];
  171365. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  171366. & RANGE_MASK];
  171367. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  171368. & RANGE_MASK];
  171369. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  171370. & RANGE_MASK];
  171371. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  171372. & RANGE_MASK];
  171373. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  171374. & RANGE_MASK];
  171375. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  171376. & RANGE_MASK];
  171377. wsptr += DCTSIZE; /* advance pointer to next row */
  171378. }
  171379. }
  171380. #endif /* DCT_FLOAT_SUPPORTED */
  171381. /*** End of inlined file: jidctflt.c ***/
  171382. #undef CONST_BITS
  171383. #undef FIX_1_847759065
  171384. #undef MULTIPLY
  171385. #undef DEQUANTIZE
  171386. #undef DESCALE
  171387. /*** Start of inlined file: jidctfst.c ***/
  171388. #define JPEG_INTERNALS
  171389. #ifdef DCT_IFAST_SUPPORTED
  171390. /*
  171391. * This module is specialized to the case DCTSIZE = 8.
  171392. */
  171393. #if DCTSIZE != 8
  171394. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171395. #endif
  171396. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171397. * see jidctint.c for more details. However, we choose to descale
  171398. * (right shift) multiplication products as soon as they are formed,
  171399. * rather than carrying additional fractional bits into subsequent additions.
  171400. * This compromises accuracy slightly, but it lets us save a few shifts.
  171401. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171402. * everywhere except in the multiplications proper; this saves a good deal
  171403. * of work on 16-bit-int machines.
  171404. *
  171405. * The dequantized coefficients are not integers because the AA&N scaling
  171406. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  171407. * so that the first and second IDCT rounds have the same input scaling.
  171408. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  171409. * avoid a descaling shift; this compromises accuracy rather drastically
  171410. * for small quantization table entries, but it saves a lot of shifts.
  171411. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  171412. * so we use a much larger scaling factor to preserve accuracy.
  171413. *
  171414. * A final compromise is to represent the multiplicative constants to only
  171415. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171416. * machines, and may also reduce the cost of multiplication (since there
  171417. * are fewer one-bits in the constants).
  171418. */
  171419. #if BITS_IN_JSAMPLE == 8
  171420. #define CONST_BITS 8
  171421. #define PASS1_BITS 2
  171422. #else
  171423. #define CONST_BITS 8
  171424. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171425. #endif
  171426. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171427. * causing a lot of useless floating-point operations at run time.
  171428. * To get around this we use the following pre-calculated constants.
  171429. * If you change CONST_BITS you may want to add appropriate values.
  171430. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171431. */
  171432. #if CONST_BITS == 8
  171433. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  171434. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  171435. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  171436. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  171437. #else
  171438. #define FIX_1_082392200 FIX(1.082392200)
  171439. #define FIX_1_414213562 FIX(1.414213562)
  171440. #define FIX_1_847759065 FIX(1.847759065)
  171441. #define FIX_2_613125930 FIX(2.613125930)
  171442. #endif
  171443. /* We can gain a little more speed, with a further compromise in accuracy,
  171444. * by omitting the addition in a descaling shift. This yields an incorrectly
  171445. * rounded result half the time...
  171446. */
  171447. #ifndef USE_ACCURATE_ROUNDING
  171448. #undef DESCALE
  171449. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171450. #endif
  171451. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171452. * descale to yield a DCTELEM result.
  171453. */
  171454. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171455. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171456. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  171457. * multiplication will do. For 12-bit data, the multiplier table is
  171458. * declared INT32, so a 32-bit multiply will be used.
  171459. */
  171460. #if BITS_IN_JSAMPLE == 8
  171461. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  171462. #else
  171463. #define DEQUANTIZE(coef,quantval) \
  171464. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  171465. #endif
  171466. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  171467. * We assume that int right shift is unsigned if INT32 right shift is.
  171468. */
  171469. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  171470. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  171471. #if BITS_IN_JSAMPLE == 8
  171472. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  171473. #else
  171474. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  171475. #endif
  171476. #define IRIGHT_SHIFT(x,shft) \
  171477. ((ishift_temp = (x)) < 0 ? \
  171478. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  171479. (ishift_temp >> (shft)))
  171480. #else
  171481. #define ISHIFT_TEMPS
  171482. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  171483. #endif
  171484. #ifdef USE_ACCURATE_ROUNDING
  171485. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  171486. #else
  171487. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  171488. #endif
  171489. /*
  171490. * Perform dequantization and inverse DCT on one block of coefficients.
  171491. */
  171492. GLOBAL(void)
  171493. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171494. JCOEFPTR coef_block,
  171495. JSAMPARRAY output_buf, JDIMENSION output_col)
  171496. {
  171497. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171498. DCTELEM tmp10, tmp11, tmp12, tmp13;
  171499. DCTELEM z5, z10, z11, z12, z13;
  171500. JCOEFPTR inptr;
  171501. IFAST_MULT_TYPE * quantptr;
  171502. int * wsptr;
  171503. JSAMPROW outptr;
  171504. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171505. int ctr;
  171506. int workspace[DCTSIZE2]; /* buffers data between passes */
  171507. SHIFT_TEMPS /* for DESCALE */
  171508. ISHIFT_TEMPS /* for IDESCALE */
  171509. /* Pass 1: process columns from input, store into work array. */
  171510. inptr = coef_block;
  171511. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  171512. wsptr = workspace;
  171513. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171514. /* Due to quantization, we will usually find that many of the input
  171515. * coefficients are zero, especially the AC terms. We can exploit this
  171516. * by short-circuiting the IDCT calculation for any column in which all
  171517. * the AC terms are zero. In that case each output is equal to the
  171518. * DC coefficient (with scale factor as needed).
  171519. * With typical images and quantization tables, half or more of the
  171520. * column DCT calculations can be simplified this way.
  171521. */
  171522. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171523. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171524. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171525. inptr[DCTSIZE*7] == 0) {
  171526. /* AC terms all zero */
  171527. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171528. wsptr[DCTSIZE*0] = dcval;
  171529. wsptr[DCTSIZE*1] = dcval;
  171530. wsptr[DCTSIZE*2] = dcval;
  171531. wsptr[DCTSIZE*3] = dcval;
  171532. wsptr[DCTSIZE*4] = dcval;
  171533. wsptr[DCTSIZE*5] = dcval;
  171534. wsptr[DCTSIZE*6] = dcval;
  171535. wsptr[DCTSIZE*7] = dcval;
  171536. inptr++; /* advance pointers to next column */
  171537. quantptr++;
  171538. wsptr++;
  171539. continue;
  171540. }
  171541. /* Even part */
  171542. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171543. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171544. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171545. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171546. tmp10 = tmp0 + tmp2; /* phase 3 */
  171547. tmp11 = tmp0 - tmp2;
  171548. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  171549. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  171550. tmp0 = tmp10 + tmp13; /* phase 2 */
  171551. tmp3 = tmp10 - tmp13;
  171552. tmp1 = tmp11 + tmp12;
  171553. tmp2 = tmp11 - tmp12;
  171554. /* Odd part */
  171555. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171556. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171557. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171558. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171559. z13 = tmp6 + tmp5; /* phase 6 */
  171560. z10 = tmp6 - tmp5;
  171561. z11 = tmp4 + tmp7;
  171562. z12 = tmp4 - tmp7;
  171563. tmp7 = z11 + z13; /* phase 5 */
  171564. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  171565. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  171566. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  171567. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  171568. tmp6 = tmp12 - tmp7; /* phase 2 */
  171569. tmp5 = tmp11 - tmp6;
  171570. tmp4 = tmp10 + tmp5;
  171571. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  171572. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  171573. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  171574. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  171575. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  171576. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  171577. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  171578. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  171579. inptr++; /* advance pointers to next column */
  171580. quantptr++;
  171581. wsptr++;
  171582. }
  171583. /* Pass 2: process rows from work array, store into output array. */
  171584. /* Note that we must descale the results by a factor of 8 == 2**3, */
  171585. /* and also undo the PASS1_BITS scaling. */
  171586. wsptr = workspace;
  171587. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171588. outptr = output_buf[ctr] + output_col;
  171589. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171590. * However, the column calculation has created many nonzero AC terms, so
  171591. * the simplification applies less often (typically 5% to 10% of the time).
  171592. * On machines with very fast multiplication, it's possible that the
  171593. * test takes more time than it's worth. In that case this section
  171594. * may be commented out.
  171595. */
  171596. #ifndef NO_ZERO_ROW_TEST
  171597. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  171598. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171599. /* AC terms all zero */
  171600. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  171601. & RANGE_MASK];
  171602. outptr[0] = dcval;
  171603. outptr[1] = dcval;
  171604. outptr[2] = dcval;
  171605. outptr[3] = dcval;
  171606. outptr[4] = dcval;
  171607. outptr[5] = dcval;
  171608. outptr[6] = dcval;
  171609. outptr[7] = dcval;
  171610. wsptr += DCTSIZE; /* advance pointer to next row */
  171611. continue;
  171612. }
  171613. #endif
  171614. /* Even part */
  171615. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  171616. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  171617. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  171618. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  171619. - tmp13;
  171620. tmp0 = tmp10 + tmp13;
  171621. tmp3 = tmp10 - tmp13;
  171622. tmp1 = tmp11 + tmp12;
  171623. tmp2 = tmp11 - tmp12;
  171624. /* Odd part */
  171625. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  171626. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  171627. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  171628. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  171629. tmp7 = z11 + z13; /* phase 5 */
  171630. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  171631. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  171632. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  171633. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  171634. tmp6 = tmp12 - tmp7; /* phase 2 */
  171635. tmp5 = tmp11 - tmp6;
  171636. tmp4 = tmp10 + tmp5;
  171637. /* Final output stage: scale down by a factor of 8 and range-limit */
  171638. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  171639. & RANGE_MASK];
  171640. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  171641. & RANGE_MASK];
  171642. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  171643. & RANGE_MASK];
  171644. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  171645. & RANGE_MASK];
  171646. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  171647. & RANGE_MASK];
  171648. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  171649. & RANGE_MASK];
  171650. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  171651. & RANGE_MASK];
  171652. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  171653. & RANGE_MASK];
  171654. wsptr += DCTSIZE; /* advance pointer to next row */
  171655. }
  171656. }
  171657. #endif /* DCT_IFAST_SUPPORTED */
  171658. /*** End of inlined file: jidctfst.c ***/
  171659. #undef CONST_BITS
  171660. #undef FIX_1_847759065
  171661. #undef MULTIPLY
  171662. #undef DEQUANTIZE
  171663. /*** Start of inlined file: jidctint.c ***/
  171664. #define JPEG_INTERNALS
  171665. #ifdef DCT_ISLOW_SUPPORTED
  171666. /*
  171667. * This module is specialized to the case DCTSIZE = 8.
  171668. */
  171669. #if DCTSIZE != 8
  171670. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171671. #endif
  171672. /*
  171673. * The poop on this scaling stuff is as follows:
  171674. *
  171675. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  171676. * larger than the true IDCT outputs. The final outputs are therefore
  171677. * a factor of N larger than desired; since N=8 this can be cured by
  171678. * a simple right shift at the end of the algorithm. The advantage of
  171679. * this arrangement is that we save two multiplications per 1-D IDCT,
  171680. * because the y0 and y4 inputs need not be divided by sqrt(N).
  171681. *
  171682. * We have to do addition and subtraction of the integer inputs, which
  171683. * is no problem, and multiplication by fractional constants, which is
  171684. * a problem to do in integer arithmetic. We multiply all the constants
  171685. * by CONST_SCALE and convert them to integer constants (thus retaining
  171686. * CONST_BITS bits of precision in the constants). After doing a
  171687. * multiplication we have to divide the product by CONST_SCALE, with proper
  171688. * rounding, to produce the correct output. This division can be done
  171689. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  171690. * as long as possible so that partial sums can be added together with
  171691. * full fractional precision.
  171692. *
  171693. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  171694. * they are represented to better-than-integral precision. These outputs
  171695. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  171696. * with the recommended scaling. (To scale up 12-bit sample data further, an
  171697. * intermediate INT32 array would be needed.)
  171698. *
  171699. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  171700. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  171701. * shows that the values given below are the most effective.
  171702. */
  171703. #if BITS_IN_JSAMPLE == 8
  171704. #define CONST_BITS 13
  171705. #define PASS1_BITS 2
  171706. #else
  171707. #define CONST_BITS 13
  171708. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171709. #endif
  171710. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171711. * causing a lot of useless floating-point operations at run time.
  171712. * To get around this we use the following pre-calculated constants.
  171713. * If you change CONST_BITS you may want to add appropriate values.
  171714. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171715. */
  171716. #if CONST_BITS == 13
  171717. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  171718. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  171719. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  171720. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171721. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171722. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  171723. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  171724. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171725. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  171726. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  171727. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171728. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  171729. #else
  171730. #define FIX_0_298631336 FIX(0.298631336)
  171731. #define FIX_0_390180644 FIX(0.390180644)
  171732. #define FIX_0_541196100 FIX(0.541196100)
  171733. #define FIX_0_765366865 FIX(0.765366865)
  171734. #define FIX_0_899976223 FIX(0.899976223)
  171735. #define FIX_1_175875602 FIX(1.175875602)
  171736. #define FIX_1_501321110 FIX(1.501321110)
  171737. #define FIX_1_847759065 FIX(1.847759065)
  171738. #define FIX_1_961570560 FIX(1.961570560)
  171739. #define FIX_2_053119869 FIX(2.053119869)
  171740. #define FIX_2_562915447 FIX(2.562915447)
  171741. #define FIX_3_072711026 FIX(3.072711026)
  171742. #endif
  171743. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171744. * For 8-bit samples with the recommended scaling, all the variable
  171745. * and constant values involved are no more than 16 bits wide, so a
  171746. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171747. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171748. */
  171749. #if BITS_IN_JSAMPLE == 8
  171750. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171751. #else
  171752. #define MULTIPLY(var,const) ((var) * (const))
  171753. #endif
  171754. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171755. * entry; produce an int result. In this module, both inputs and result
  171756. * are 16 bits or less, so either int or short multiply will work.
  171757. */
  171758. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171759. /*
  171760. * Perform dequantization and inverse DCT on one block of coefficients.
  171761. */
  171762. GLOBAL(void)
  171763. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171764. JCOEFPTR coef_block,
  171765. JSAMPARRAY output_buf, JDIMENSION output_col)
  171766. {
  171767. INT32 tmp0, tmp1, tmp2, tmp3;
  171768. INT32 tmp10, tmp11, tmp12, tmp13;
  171769. INT32 z1, z2, z3, z4, z5;
  171770. JCOEFPTR inptr;
  171771. ISLOW_MULT_TYPE * quantptr;
  171772. int * wsptr;
  171773. JSAMPROW outptr;
  171774. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171775. int ctr;
  171776. int workspace[DCTSIZE2]; /* buffers data between passes */
  171777. SHIFT_TEMPS
  171778. /* Pass 1: process columns from input, store into work array. */
  171779. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  171780. /* furthermore, we scale the results by 2**PASS1_BITS. */
  171781. inptr = coef_block;
  171782. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171783. wsptr = workspace;
  171784. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171785. /* Due to quantization, we will usually find that many of the input
  171786. * coefficients are zero, especially the AC terms. We can exploit this
  171787. * by short-circuiting the IDCT calculation for any column in which all
  171788. * the AC terms are zero. In that case each output is equal to the
  171789. * DC coefficient (with scale factor as needed).
  171790. * With typical images and quantization tables, half or more of the
  171791. * column DCT calculations can be simplified this way.
  171792. */
  171793. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171794. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171795. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171796. inptr[DCTSIZE*7] == 0) {
  171797. /* AC terms all zero */
  171798. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171799. wsptr[DCTSIZE*0] = dcval;
  171800. wsptr[DCTSIZE*1] = dcval;
  171801. wsptr[DCTSIZE*2] = dcval;
  171802. wsptr[DCTSIZE*3] = dcval;
  171803. wsptr[DCTSIZE*4] = dcval;
  171804. wsptr[DCTSIZE*5] = dcval;
  171805. wsptr[DCTSIZE*6] = dcval;
  171806. wsptr[DCTSIZE*7] = dcval;
  171807. inptr++; /* advance pointers to next column */
  171808. quantptr++;
  171809. wsptr++;
  171810. continue;
  171811. }
  171812. /* Even part: reverse the even part of the forward DCT. */
  171813. /* The rotator is sqrt(2)*c(-6). */
  171814. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171815. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171816. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171817. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171818. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171819. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171820. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171821. tmp0 = (z2 + z3) << CONST_BITS;
  171822. tmp1 = (z2 - z3) << CONST_BITS;
  171823. tmp10 = tmp0 + tmp3;
  171824. tmp13 = tmp0 - tmp3;
  171825. tmp11 = tmp1 + tmp2;
  171826. tmp12 = tmp1 - tmp2;
  171827. /* Odd part per figure 8; the matrix is unitary and hence its
  171828. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171829. */
  171830. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171831. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171832. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171833. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171834. z1 = tmp0 + tmp3;
  171835. z2 = tmp1 + tmp2;
  171836. z3 = tmp0 + tmp2;
  171837. z4 = tmp1 + tmp3;
  171838. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171839. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171840. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171841. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171842. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171843. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171844. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171845. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171846. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171847. z3 += z5;
  171848. z4 += z5;
  171849. tmp0 += z1 + z3;
  171850. tmp1 += z2 + z4;
  171851. tmp2 += z2 + z3;
  171852. tmp3 += z1 + z4;
  171853. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171854. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  171855. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  171856. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  171857. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  171858. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  171859. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  171860. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  171861. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  171862. inptr++; /* advance pointers to next column */
  171863. quantptr++;
  171864. wsptr++;
  171865. }
  171866. /* Pass 2: process rows from work array, store into output array. */
  171867. /* Note that we must descale the results by a factor of 8 == 2**3, */
  171868. /* and also undo the PASS1_BITS scaling. */
  171869. wsptr = workspace;
  171870. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171871. outptr = output_buf[ctr] + output_col;
  171872. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171873. * However, the column calculation has created many nonzero AC terms, so
  171874. * the simplification applies less often (typically 5% to 10% of the time).
  171875. * On machines with very fast multiplication, it's possible that the
  171876. * test takes more time than it's worth. In that case this section
  171877. * may be commented out.
  171878. */
  171879. #ifndef NO_ZERO_ROW_TEST
  171880. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  171881. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171882. /* AC terms all zero */
  171883. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171884. & RANGE_MASK];
  171885. outptr[0] = dcval;
  171886. outptr[1] = dcval;
  171887. outptr[2] = dcval;
  171888. outptr[3] = dcval;
  171889. outptr[4] = dcval;
  171890. outptr[5] = dcval;
  171891. outptr[6] = dcval;
  171892. outptr[7] = dcval;
  171893. wsptr += DCTSIZE; /* advance pointer to next row */
  171894. continue;
  171895. }
  171896. #endif
  171897. /* Even part: reverse the even part of the forward DCT. */
  171898. /* The rotator is sqrt(2)*c(-6). */
  171899. z2 = (INT32) wsptr[2];
  171900. z3 = (INT32) wsptr[6];
  171901. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171902. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171903. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171904. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  171905. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  171906. tmp10 = tmp0 + tmp3;
  171907. tmp13 = tmp0 - tmp3;
  171908. tmp11 = tmp1 + tmp2;
  171909. tmp12 = tmp1 - tmp2;
  171910. /* Odd part per figure 8; the matrix is unitary and hence its
  171911. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171912. */
  171913. tmp0 = (INT32) wsptr[7];
  171914. tmp1 = (INT32) wsptr[5];
  171915. tmp2 = (INT32) wsptr[3];
  171916. tmp3 = (INT32) wsptr[1];
  171917. z1 = tmp0 + tmp3;
  171918. z2 = tmp1 + tmp2;
  171919. z3 = tmp0 + tmp2;
  171920. z4 = tmp1 + tmp3;
  171921. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171922. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171923. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171924. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171925. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171926. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171927. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171928. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171929. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171930. z3 += z5;
  171931. z4 += z5;
  171932. tmp0 += z1 + z3;
  171933. tmp1 += z2 + z4;
  171934. tmp2 += z2 + z3;
  171935. tmp3 += z1 + z4;
  171936. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171937. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  171938. CONST_BITS+PASS1_BITS+3)
  171939. & RANGE_MASK];
  171940. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  171941. CONST_BITS+PASS1_BITS+3)
  171942. & RANGE_MASK];
  171943. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  171944. CONST_BITS+PASS1_BITS+3)
  171945. & RANGE_MASK];
  171946. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  171947. CONST_BITS+PASS1_BITS+3)
  171948. & RANGE_MASK];
  171949. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  171950. CONST_BITS+PASS1_BITS+3)
  171951. & RANGE_MASK];
  171952. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  171953. CONST_BITS+PASS1_BITS+3)
  171954. & RANGE_MASK];
  171955. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  171956. CONST_BITS+PASS1_BITS+3)
  171957. & RANGE_MASK];
  171958. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  171959. CONST_BITS+PASS1_BITS+3)
  171960. & RANGE_MASK];
  171961. wsptr += DCTSIZE; /* advance pointer to next row */
  171962. }
  171963. }
  171964. #endif /* DCT_ISLOW_SUPPORTED */
  171965. /*** End of inlined file: jidctint.c ***/
  171966. /*** Start of inlined file: jidctred.c ***/
  171967. #define JPEG_INTERNALS
  171968. #ifdef IDCT_SCALING_SUPPORTED
  171969. /*
  171970. * This module is specialized to the case DCTSIZE = 8.
  171971. */
  171972. #if DCTSIZE != 8
  171973. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171974. #endif
  171975. /* Scaling is the same as in jidctint.c. */
  171976. #if BITS_IN_JSAMPLE == 8
  171977. #define CONST_BITS 13
  171978. #define PASS1_BITS 2
  171979. #else
  171980. #define CONST_BITS 13
  171981. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171982. #endif
  171983. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171984. * causing a lot of useless floating-point operations at run time.
  171985. * To get around this we use the following pre-calculated constants.
  171986. * If you change CONST_BITS you may want to add appropriate values.
  171987. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171988. */
  171989. #if CONST_BITS == 13
  171990. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  171991. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  171992. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  171993. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  171994. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171995. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  171996. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171997. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  171998. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  171999. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  172000. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  172001. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  172002. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  172003. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  172004. #else
  172005. #define FIX_0_211164243 FIX(0.211164243)
  172006. #define FIX_0_509795579 FIX(0.509795579)
  172007. #define FIX_0_601344887 FIX(0.601344887)
  172008. #define FIX_0_720959822 FIX(0.720959822)
  172009. #define FIX_0_765366865 FIX(0.765366865)
  172010. #define FIX_0_850430095 FIX(0.850430095)
  172011. #define FIX_0_899976223 FIX(0.899976223)
  172012. #define FIX_1_061594337 FIX(1.061594337)
  172013. #define FIX_1_272758580 FIX(1.272758580)
  172014. #define FIX_1_451774981 FIX(1.451774981)
  172015. #define FIX_1_847759065 FIX(1.847759065)
  172016. #define FIX_2_172734803 FIX(2.172734803)
  172017. #define FIX_2_562915447 FIX(2.562915447)
  172018. #define FIX_3_624509785 FIX(3.624509785)
  172019. #endif
  172020. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  172021. * For 8-bit samples with the recommended scaling, all the variable
  172022. * and constant values involved are no more than 16 bits wide, so a
  172023. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  172024. * For 12-bit samples, a full 32-bit multiplication will be needed.
  172025. */
  172026. #if BITS_IN_JSAMPLE == 8
  172027. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  172028. #else
  172029. #define MULTIPLY(var,const) ((var) * (const))
  172030. #endif
  172031. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172032. * entry; produce an int result. In this module, both inputs and result
  172033. * are 16 bits or less, so either int or short multiply will work.
  172034. */
  172035. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  172036. /*
  172037. * Perform dequantization and inverse DCT on one block of coefficients,
  172038. * producing a reduced-size 4x4 output block.
  172039. */
  172040. GLOBAL(void)
  172041. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172042. JCOEFPTR coef_block,
  172043. JSAMPARRAY output_buf, JDIMENSION output_col)
  172044. {
  172045. INT32 tmp0, tmp2, tmp10, tmp12;
  172046. INT32 z1, z2, z3, z4;
  172047. JCOEFPTR inptr;
  172048. ISLOW_MULT_TYPE * quantptr;
  172049. int * wsptr;
  172050. JSAMPROW outptr;
  172051. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172052. int ctr;
  172053. int workspace[DCTSIZE*4]; /* buffers data between passes */
  172054. SHIFT_TEMPS
  172055. /* Pass 1: process columns from input, store into work array. */
  172056. inptr = coef_block;
  172057. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172058. wsptr = workspace;
  172059. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172060. /* Don't bother to process column 4, because second pass won't use it */
  172061. if (ctr == DCTSIZE-4)
  172062. continue;
  172063. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172064. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  172065. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  172066. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  172067. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172068. wsptr[DCTSIZE*0] = dcval;
  172069. wsptr[DCTSIZE*1] = dcval;
  172070. wsptr[DCTSIZE*2] = dcval;
  172071. wsptr[DCTSIZE*3] = dcval;
  172072. continue;
  172073. }
  172074. /* Even part */
  172075. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172076. tmp0 <<= (CONST_BITS+1);
  172077. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172078. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172079. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  172080. tmp10 = tmp0 + tmp2;
  172081. tmp12 = tmp0 - tmp2;
  172082. /* Odd part */
  172083. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172084. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172085. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172086. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172087. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172088. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172089. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172090. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172091. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172092. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172093. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172094. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172095. /* Final output stage */
  172096. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  172097. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  172098. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  172099. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  172100. }
  172101. /* Pass 2: process 4 rows from work array, store into output array. */
  172102. wsptr = workspace;
  172103. for (ctr = 0; ctr < 4; ctr++) {
  172104. outptr = output_buf[ctr] + output_col;
  172105. /* It's not clear whether a zero row test is worthwhile here ... */
  172106. #ifndef NO_ZERO_ROW_TEST
  172107. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  172108. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172109. /* AC terms all zero */
  172110. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172111. & RANGE_MASK];
  172112. outptr[0] = dcval;
  172113. outptr[1] = dcval;
  172114. outptr[2] = dcval;
  172115. outptr[3] = dcval;
  172116. wsptr += DCTSIZE; /* advance pointer to next row */
  172117. continue;
  172118. }
  172119. #endif
  172120. /* Even part */
  172121. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  172122. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  172123. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  172124. tmp10 = tmp0 + tmp2;
  172125. tmp12 = tmp0 - tmp2;
  172126. /* Odd part */
  172127. z1 = (INT32) wsptr[7];
  172128. z2 = (INT32) wsptr[5];
  172129. z3 = (INT32) wsptr[3];
  172130. z4 = (INT32) wsptr[1];
  172131. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172132. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172133. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172134. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172135. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172136. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172137. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172138. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172139. /* Final output stage */
  172140. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  172141. CONST_BITS+PASS1_BITS+3+1)
  172142. & RANGE_MASK];
  172143. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  172144. CONST_BITS+PASS1_BITS+3+1)
  172145. & RANGE_MASK];
  172146. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  172147. CONST_BITS+PASS1_BITS+3+1)
  172148. & RANGE_MASK];
  172149. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  172150. CONST_BITS+PASS1_BITS+3+1)
  172151. & RANGE_MASK];
  172152. wsptr += DCTSIZE; /* advance pointer to next row */
  172153. }
  172154. }
  172155. /*
  172156. * Perform dequantization and inverse DCT on one block of coefficients,
  172157. * producing a reduced-size 2x2 output block.
  172158. */
  172159. GLOBAL(void)
  172160. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172161. JCOEFPTR coef_block,
  172162. JSAMPARRAY output_buf, JDIMENSION output_col)
  172163. {
  172164. INT32 tmp0, tmp10, z1;
  172165. JCOEFPTR inptr;
  172166. ISLOW_MULT_TYPE * quantptr;
  172167. int * wsptr;
  172168. JSAMPROW outptr;
  172169. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172170. int ctr;
  172171. int workspace[DCTSIZE*2]; /* buffers data between passes */
  172172. SHIFT_TEMPS
  172173. /* Pass 1: process columns from input, store into work array. */
  172174. inptr = coef_block;
  172175. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172176. wsptr = workspace;
  172177. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172178. /* Don't bother to process columns 2,4,6 */
  172179. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  172180. continue;
  172181. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  172182. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  172183. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  172184. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172185. wsptr[DCTSIZE*0] = dcval;
  172186. wsptr[DCTSIZE*1] = dcval;
  172187. continue;
  172188. }
  172189. /* Even part */
  172190. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172191. tmp10 = z1 << (CONST_BITS+2);
  172192. /* Odd part */
  172193. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172194. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  172195. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172196. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  172197. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172198. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  172199. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172200. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172201. /* Final output stage */
  172202. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  172203. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  172204. }
  172205. /* Pass 2: process 2 rows from work array, store into output array. */
  172206. wsptr = workspace;
  172207. for (ctr = 0; ctr < 2; ctr++) {
  172208. outptr = output_buf[ctr] + output_col;
  172209. /* It's not clear whether a zero row test is worthwhile here ... */
  172210. #ifndef NO_ZERO_ROW_TEST
  172211. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  172212. /* AC terms all zero */
  172213. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172214. & RANGE_MASK];
  172215. outptr[0] = dcval;
  172216. outptr[1] = dcval;
  172217. wsptr += DCTSIZE; /* advance pointer to next row */
  172218. continue;
  172219. }
  172220. #endif
  172221. /* Even part */
  172222. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  172223. /* Odd part */
  172224. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  172225. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  172226. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  172227. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172228. /* Final output stage */
  172229. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  172230. CONST_BITS+PASS1_BITS+3+2)
  172231. & RANGE_MASK];
  172232. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  172233. CONST_BITS+PASS1_BITS+3+2)
  172234. & RANGE_MASK];
  172235. wsptr += DCTSIZE; /* advance pointer to next row */
  172236. }
  172237. }
  172238. /*
  172239. * Perform dequantization and inverse DCT on one block of coefficients,
  172240. * producing a reduced-size 1x1 output block.
  172241. */
  172242. GLOBAL(void)
  172243. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172244. JCOEFPTR coef_block,
  172245. JSAMPARRAY output_buf, JDIMENSION output_col)
  172246. {
  172247. int dcval;
  172248. ISLOW_MULT_TYPE * quantptr;
  172249. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172250. SHIFT_TEMPS
  172251. /* We hardly need an inverse DCT routine for this: just take the
  172252. * average pixel value, which is one-eighth of the DC coefficient.
  172253. */
  172254. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172255. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  172256. dcval = (int) DESCALE((INT32) dcval, 3);
  172257. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  172258. }
  172259. #endif /* IDCT_SCALING_SUPPORTED */
  172260. /*** End of inlined file: jidctred.c ***/
  172261. /*** Start of inlined file: jmemmgr.c ***/
  172262. #define JPEG_INTERNALS
  172263. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  172264. /*** Start of inlined file: jmemsys.h ***/
  172265. #ifndef __jmemsys_h__
  172266. #define __jmemsys_h__
  172267. /* Short forms of external names for systems with brain-damaged linkers. */
  172268. #ifdef NEED_SHORT_EXTERNAL_NAMES
  172269. #define jpeg_get_small jGetSmall
  172270. #define jpeg_free_small jFreeSmall
  172271. #define jpeg_get_large jGetLarge
  172272. #define jpeg_free_large jFreeLarge
  172273. #define jpeg_mem_available jMemAvail
  172274. #define jpeg_open_backing_store jOpenBackStore
  172275. #define jpeg_mem_init jMemInit
  172276. #define jpeg_mem_term jMemTerm
  172277. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  172278. /*
  172279. * These two functions are used to allocate and release small chunks of
  172280. * memory. (Typically the total amount requested through jpeg_get_small is
  172281. * no more than 20K or so; this will be requested in chunks of a few K each.)
  172282. * Behavior should be the same as for the standard library functions malloc
  172283. * and free; in particular, jpeg_get_small must return NULL on failure.
  172284. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  172285. * size of the object being freed, just in case it's needed.
  172286. * On an 80x86 machine using small-data memory model, these manage near heap.
  172287. */
  172288. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  172289. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  172290. size_t sizeofobject));
  172291. /*
  172292. * These two functions are used to allocate and release large chunks of
  172293. * memory (up to the total free space designated by jpeg_mem_available).
  172294. * The interface is the same as above, except that on an 80x86 machine,
  172295. * far pointers are used. On most other machines these are identical to
  172296. * the jpeg_get/free_small routines; but we keep them separate anyway,
  172297. * in case a different allocation strategy is desirable for large chunks.
  172298. */
  172299. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  172300. size_t sizeofobject));
  172301. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  172302. size_t sizeofobject));
  172303. /*
  172304. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  172305. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  172306. * matter, but that case should never come into play). This macro is needed
  172307. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  172308. * On those machines, we expect that jconfig.h will provide a proper value.
  172309. * On machines with 32-bit flat address spaces, any large constant may be used.
  172310. *
  172311. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  172312. * size_t and will be a multiple of sizeof(align_type).
  172313. */
  172314. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  172315. #define MAX_ALLOC_CHUNK 1000000000L
  172316. #endif
  172317. /*
  172318. * This routine computes the total space still available for allocation by
  172319. * jpeg_get_large. If more space than this is needed, backing store will be
  172320. * used. NOTE: any memory already allocated must not be counted.
  172321. *
  172322. * There is a minimum space requirement, corresponding to the minimum
  172323. * feasible buffer sizes; jmemmgr.c will request that much space even if
  172324. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  172325. * all working storage in memory, is also passed in case it is useful.
  172326. * Finally, the total space already allocated is passed. If no better
  172327. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  172328. * is often a suitable calculation.
  172329. *
  172330. * It is OK for jpeg_mem_available to underestimate the space available
  172331. * (that'll just lead to more backing-store access than is really necessary).
  172332. * However, an overestimate will lead to failure. Hence it's wise to subtract
  172333. * a slop factor from the true available space. 5% should be enough.
  172334. *
  172335. * On machines with lots of virtual memory, any large constant may be returned.
  172336. * Conversely, zero may be returned to always use the minimum amount of memory.
  172337. */
  172338. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  172339. long min_bytes_needed,
  172340. long max_bytes_needed,
  172341. long already_allocated));
  172342. /*
  172343. * This structure holds whatever state is needed to access a single
  172344. * backing-store object. The read/write/close method pointers are called
  172345. * by jmemmgr.c to manipulate the backing-store object; all other fields
  172346. * are private to the system-dependent backing store routines.
  172347. */
  172348. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  172349. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  172350. typedef unsigned short XMSH; /* type of extended-memory handles */
  172351. typedef unsigned short EMSH; /* type of expanded-memory handles */
  172352. typedef union {
  172353. short file_handle; /* DOS file handle if it's a temp file */
  172354. XMSH xms_handle; /* handle if it's a chunk of XMS */
  172355. EMSH ems_handle; /* handle if it's a chunk of EMS */
  172356. } handle_union;
  172357. #endif /* USE_MSDOS_MEMMGR */
  172358. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  172359. #include <Files.h>
  172360. #endif /* USE_MAC_MEMMGR */
  172361. //typedef struct backing_store_struct * backing_store_ptr;
  172362. typedef struct backing_store_struct {
  172363. /* Methods for reading/writing/closing this backing-store object */
  172364. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  172365. struct backing_store_struct *info,
  172366. void FAR * buffer_address,
  172367. long file_offset, long byte_count));
  172368. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  172369. struct backing_store_struct *info,
  172370. void FAR * buffer_address,
  172371. long file_offset, long byte_count));
  172372. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  172373. struct backing_store_struct *info));
  172374. /* Private fields for system-dependent backing-store management */
  172375. #ifdef USE_MSDOS_MEMMGR
  172376. /* For the MS-DOS manager (jmemdos.c), we need: */
  172377. handle_union handle; /* reference to backing-store storage object */
  172378. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  172379. #else
  172380. #ifdef USE_MAC_MEMMGR
  172381. /* For the Mac manager (jmemmac.c), we need: */
  172382. short temp_file; /* file reference number to temp file */
  172383. FSSpec tempSpec; /* the FSSpec for the temp file */
  172384. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  172385. #else
  172386. /* For a typical implementation with temp files, we need: */
  172387. FILE * temp_file; /* stdio reference to temp file */
  172388. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  172389. #endif
  172390. #endif
  172391. } backing_store_info;
  172392. /*
  172393. * Initial opening of a backing-store object. This must fill in the
  172394. * read/write/close pointers in the object. The read/write routines
  172395. * may take an error exit if the specified maximum file size is exceeded.
  172396. * (If jpeg_mem_available always returns a large value, this routine can
  172397. * just take an error exit.)
  172398. */
  172399. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  172400. struct backing_store_struct *info,
  172401. long total_bytes_needed));
  172402. /*
  172403. * These routines take care of any system-dependent initialization and
  172404. * cleanup required. jpeg_mem_init will be called before anything is
  172405. * allocated (and, therefore, nothing in cinfo is of use except the error
  172406. * manager pointer). It should return a suitable default value for
  172407. * max_memory_to_use; this may subsequently be overridden by the surrounding
  172408. * application. (Note that max_memory_to_use is only important if
  172409. * jpeg_mem_available chooses to consult it ... no one else will.)
  172410. * jpeg_mem_term may assume that all requested memory has been freed and that
  172411. * all opened backing-store objects have been closed.
  172412. */
  172413. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  172414. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  172415. #endif
  172416. /*** End of inlined file: jmemsys.h ***/
  172417. /* import the system-dependent declarations */
  172418. #ifndef NO_GETENV
  172419. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  172420. extern char * getenv JPP((const char * name));
  172421. #endif
  172422. #endif
  172423. /*
  172424. * Some important notes:
  172425. * The allocation routines provided here must never return NULL.
  172426. * They should exit to error_exit if unsuccessful.
  172427. *
  172428. * It's not a good idea to try to merge the sarray and barray routines,
  172429. * even though they are textually almost the same, because samples are
  172430. * usually stored as bytes while coefficients are shorts or ints. Thus,
  172431. * in machines where byte pointers have a different representation from
  172432. * word pointers, the resulting machine code could not be the same.
  172433. */
  172434. /*
  172435. * Many machines require storage alignment: longs must start on 4-byte
  172436. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  172437. * always returns pointers that are multiples of the worst-case alignment
  172438. * requirement, and we had better do so too.
  172439. * There isn't any really portable way to determine the worst-case alignment
  172440. * requirement. This module assumes that the alignment requirement is
  172441. * multiples of sizeof(ALIGN_TYPE).
  172442. * By default, we define ALIGN_TYPE as double. This is necessary on some
  172443. * workstations (where doubles really do need 8-byte alignment) and will work
  172444. * fine on nearly everything. If your machine has lesser alignment needs,
  172445. * you can save a few bytes by making ALIGN_TYPE smaller.
  172446. * The only place I know of where this will NOT work is certain Macintosh
  172447. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  172448. * Doing 10-byte alignment is counterproductive because longwords won't be
  172449. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  172450. * such a compiler.
  172451. */
  172452. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  172453. #define ALIGN_TYPE double
  172454. #endif
  172455. /*
  172456. * We allocate objects from "pools", where each pool is gotten with a single
  172457. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  172458. * overhead within a pool, except for alignment padding. Each pool has a
  172459. * header with a link to the next pool of the same class.
  172460. * Small and large pool headers are identical except that the latter's
  172461. * link pointer must be FAR on 80x86 machines.
  172462. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  172463. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  172464. * of the alignment requirement of ALIGN_TYPE.
  172465. */
  172466. typedef union small_pool_struct * small_pool_ptr;
  172467. typedef union small_pool_struct {
  172468. struct {
  172469. small_pool_ptr next; /* next in list of pools */
  172470. size_t bytes_used; /* how many bytes already used within pool */
  172471. size_t bytes_left; /* bytes still available in this pool */
  172472. } hdr;
  172473. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  172474. } small_pool_hdr;
  172475. typedef union large_pool_struct FAR * large_pool_ptr;
  172476. typedef union large_pool_struct {
  172477. struct {
  172478. large_pool_ptr next; /* next in list of pools */
  172479. size_t bytes_used; /* how many bytes already used within pool */
  172480. size_t bytes_left; /* bytes still available in this pool */
  172481. } hdr;
  172482. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  172483. } large_pool_hdr;
  172484. /*
  172485. * Here is the full definition of a memory manager object.
  172486. */
  172487. typedef struct {
  172488. struct jpeg_memory_mgr pub; /* public fields */
  172489. /* Each pool identifier (lifetime class) names a linked list of pools. */
  172490. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  172491. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  172492. /* Since we only have one lifetime class of virtual arrays, only one
  172493. * linked list is necessary (for each datatype). Note that the virtual
  172494. * array control blocks being linked together are actually stored somewhere
  172495. * in the small-pool list.
  172496. */
  172497. jvirt_sarray_ptr virt_sarray_list;
  172498. jvirt_barray_ptr virt_barray_list;
  172499. /* This counts total space obtained from jpeg_get_small/large */
  172500. long total_space_allocated;
  172501. /* alloc_sarray and alloc_barray set this value for use by virtual
  172502. * array routines.
  172503. */
  172504. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  172505. } my_memory_mgr;
  172506. typedef my_memory_mgr * my_mem_ptr;
  172507. /*
  172508. * The control blocks for virtual arrays.
  172509. * Note that these blocks are allocated in the "small" pool area.
  172510. * System-dependent info for the associated backing store (if any) is hidden
  172511. * inside the backing_store_info struct.
  172512. */
  172513. struct jvirt_sarray_control {
  172514. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  172515. JDIMENSION rows_in_array; /* total virtual array height */
  172516. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  172517. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  172518. JDIMENSION rows_in_mem; /* height of memory buffer */
  172519. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  172520. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  172521. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  172522. boolean pre_zero; /* pre-zero mode requested? */
  172523. boolean dirty; /* do current buffer contents need written? */
  172524. boolean b_s_open; /* is backing-store data valid? */
  172525. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  172526. backing_store_info b_s_info; /* System-dependent control info */
  172527. };
  172528. struct jvirt_barray_control {
  172529. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  172530. JDIMENSION rows_in_array; /* total virtual array height */
  172531. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  172532. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  172533. JDIMENSION rows_in_mem; /* height of memory buffer */
  172534. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  172535. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  172536. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  172537. boolean pre_zero; /* pre-zero mode requested? */
  172538. boolean dirty; /* do current buffer contents need written? */
  172539. boolean b_s_open; /* is backing-store data valid? */
  172540. jvirt_barray_ptr next; /* link to next virtual barray control block */
  172541. backing_store_info b_s_info; /* System-dependent control info */
  172542. };
  172543. #ifdef MEM_STATS /* optional extra stuff for statistics */
  172544. LOCAL(void)
  172545. print_mem_stats (j_common_ptr cinfo, int pool_id)
  172546. {
  172547. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172548. small_pool_ptr shdr_ptr;
  172549. large_pool_ptr lhdr_ptr;
  172550. /* Since this is only a debugging stub, we can cheat a little by using
  172551. * fprintf directly rather than going through the trace message code.
  172552. * This is helpful because message parm array can't handle longs.
  172553. */
  172554. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  172555. pool_id, mem->total_space_allocated);
  172556. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  172557. lhdr_ptr = lhdr_ptr->hdr.next) {
  172558. fprintf(stderr, " Large chunk used %ld\n",
  172559. (long) lhdr_ptr->hdr.bytes_used);
  172560. }
  172561. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  172562. shdr_ptr = shdr_ptr->hdr.next) {
  172563. fprintf(stderr, " Small chunk used %ld free %ld\n",
  172564. (long) shdr_ptr->hdr.bytes_used,
  172565. (long) shdr_ptr->hdr.bytes_left);
  172566. }
  172567. }
  172568. #endif /* MEM_STATS */
  172569. LOCAL(void)
  172570. out_of_memory (j_common_ptr cinfo, int which)
  172571. /* Report an out-of-memory error and stop execution */
  172572. /* If we compiled MEM_STATS support, report alloc requests before dying */
  172573. {
  172574. #ifdef MEM_STATS
  172575. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  172576. #endif
  172577. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  172578. }
  172579. /*
  172580. * Allocation of "small" objects.
  172581. *
  172582. * For these, we use pooled storage. When a new pool must be created,
  172583. * we try to get enough space for the current request plus a "slop" factor,
  172584. * where the slop will be the amount of leftover space in the new pool.
  172585. * The speed vs. space tradeoff is largely determined by the slop values.
  172586. * A different slop value is provided for each pool class (lifetime),
  172587. * and we also distinguish the first pool of a class from later ones.
  172588. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  172589. * machines, but may be too small if longs are 64 bits or more.
  172590. */
  172591. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  172592. {
  172593. 1600, /* first PERMANENT pool */
  172594. 16000 /* first IMAGE pool */
  172595. };
  172596. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  172597. {
  172598. 0, /* additional PERMANENT pools */
  172599. 5000 /* additional IMAGE pools */
  172600. };
  172601. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  172602. METHODDEF(void *)
  172603. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  172604. /* Allocate a "small" object */
  172605. {
  172606. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172607. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  172608. char * data_ptr;
  172609. size_t odd_bytes, min_request, slop;
  172610. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  172611. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  172612. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  172613. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  172614. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  172615. if (odd_bytes > 0)
  172616. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  172617. /* See if space is available in any existing pool */
  172618. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172619. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172620. prev_hdr_ptr = NULL;
  172621. hdr_ptr = mem->small_list[pool_id];
  172622. while (hdr_ptr != NULL) {
  172623. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  172624. break; /* found pool with enough space */
  172625. prev_hdr_ptr = hdr_ptr;
  172626. hdr_ptr = hdr_ptr->hdr.next;
  172627. }
  172628. /* Time to make a new pool? */
  172629. if (hdr_ptr == NULL) {
  172630. /* min_request is what we need now, slop is what will be leftover */
  172631. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  172632. if (prev_hdr_ptr == NULL) /* first pool in class? */
  172633. slop = first_pool_slop[pool_id];
  172634. else
  172635. slop = extra_pool_slop[pool_id];
  172636. /* Don't ask for more than MAX_ALLOC_CHUNK */
  172637. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  172638. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  172639. /* Try to get space, if fail reduce slop and try again */
  172640. for (;;) {
  172641. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  172642. if (hdr_ptr != NULL)
  172643. break;
  172644. slop /= 2;
  172645. if (slop < MIN_SLOP) /* give up when it gets real small */
  172646. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  172647. }
  172648. mem->total_space_allocated += min_request + slop;
  172649. /* Success, initialize the new pool header and add to end of list */
  172650. hdr_ptr->hdr.next = NULL;
  172651. hdr_ptr->hdr.bytes_used = 0;
  172652. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  172653. if (prev_hdr_ptr == NULL) /* first pool in class? */
  172654. mem->small_list[pool_id] = hdr_ptr;
  172655. else
  172656. prev_hdr_ptr->hdr.next = hdr_ptr;
  172657. }
  172658. /* OK, allocate the object from the current pool */
  172659. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  172660. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  172661. hdr_ptr->hdr.bytes_used += sizeofobject;
  172662. hdr_ptr->hdr.bytes_left -= sizeofobject;
  172663. return (void *) data_ptr;
  172664. }
  172665. /*
  172666. * Allocation of "large" objects.
  172667. *
  172668. * The external semantics of these are the same as "small" objects,
  172669. * except that FAR pointers are used on 80x86. However the pool
  172670. * management heuristics are quite different. We assume that each
  172671. * request is large enough that it may as well be passed directly to
  172672. * jpeg_get_large; the pool management just links everything together
  172673. * so that we can free it all on demand.
  172674. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  172675. * structures. The routines that create these structures (see below)
  172676. * deliberately bunch rows together to ensure a large request size.
  172677. */
  172678. METHODDEF(void FAR *)
  172679. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  172680. /* Allocate a "large" object */
  172681. {
  172682. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172683. large_pool_ptr hdr_ptr;
  172684. size_t odd_bytes;
  172685. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  172686. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  172687. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  172688. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  172689. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  172690. if (odd_bytes > 0)
  172691. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  172692. /* Always make a new pool */
  172693. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172694. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172695. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  172696. SIZEOF(large_pool_hdr));
  172697. if (hdr_ptr == NULL)
  172698. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  172699. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  172700. /* Success, initialize the new pool header and add to list */
  172701. hdr_ptr->hdr.next = mem->large_list[pool_id];
  172702. /* We maintain space counts in each pool header for statistical purposes,
  172703. * even though they are not needed for allocation.
  172704. */
  172705. hdr_ptr->hdr.bytes_used = sizeofobject;
  172706. hdr_ptr->hdr.bytes_left = 0;
  172707. mem->large_list[pool_id] = hdr_ptr;
  172708. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  172709. }
  172710. /*
  172711. * Creation of 2-D sample arrays.
  172712. * The pointers are in near heap, the samples themselves in FAR heap.
  172713. *
  172714. * To minimize allocation overhead and to allow I/O of large contiguous
  172715. * blocks, we allocate the sample rows in groups of as many rows as possible
  172716. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  172717. * NB: the virtual array control routines, later in this file, know about
  172718. * this chunking of rows. The rowsperchunk value is left in the mem manager
  172719. * object so that it can be saved away if this sarray is the workspace for
  172720. * a virtual array.
  172721. */
  172722. METHODDEF(JSAMPARRAY)
  172723. alloc_sarray (j_common_ptr cinfo, int pool_id,
  172724. JDIMENSION samplesperrow, JDIMENSION numrows)
  172725. /* Allocate a 2-D sample array */
  172726. {
  172727. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172728. JSAMPARRAY result;
  172729. JSAMPROW workspace;
  172730. JDIMENSION rowsperchunk, currow, i;
  172731. long ltemp;
  172732. /* Calculate max # of rows allowed in one allocation chunk */
  172733. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172734. ((long) samplesperrow * SIZEOF(JSAMPLE));
  172735. if (ltemp <= 0)
  172736. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172737. if (ltemp < (long) numrows)
  172738. rowsperchunk = (JDIMENSION) ltemp;
  172739. else
  172740. rowsperchunk = numrows;
  172741. mem->last_rowsperchunk = rowsperchunk;
  172742. /* Get space for row pointers (small object) */
  172743. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  172744. (size_t) (numrows * SIZEOF(JSAMPROW)));
  172745. /* Get the rows themselves (large objects) */
  172746. currow = 0;
  172747. while (currow < numrows) {
  172748. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172749. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  172750. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  172751. * SIZEOF(JSAMPLE)));
  172752. for (i = rowsperchunk; i > 0; i--) {
  172753. result[currow++] = workspace;
  172754. workspace += samplesperrow;
  172755. }
  172756. }
  172757. return result;
  172758. }
  172759. /*
  172760. * Creation of 2-D coefficient-block arrays.
  172761. * This is essentially the same as the code for sample arrays, above.
  172762. */
  172763. METHODDEF(JBLOCKARRAY)
  172764. alloc_barray (j_common_ptr cinfo, int pool_id,
  172765. JDIMENSION blocksperrow, JDIMENSION numrows)
  172766. /* Allocate a 2-D coefficient-block array */
  172767. {
  172768. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172769. JBLOCKARRAY result;
  172770. JBLOCKROW workspace;
  172771. JDIMENSION rowsperchunk, currow, i;
  172772. long ltemp;
  172773. /* Calculate max # of rows allowed in one allocation chunk */
  172774. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172775. ((long) blocksperrow * SIZEOF(JBLOCK));
  172776. if (ltemp <= 0)
  172777. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172778. if (ltemp < (long) numrows)
  172779. rowsperchunk = (JDIMENSION) ltemp;
  172780. else
  172781. rowsperchunk = numrows;
  172782. mem->last_rowsperchunk = rowsperchunk;
  172783. /* Get space for row pointers (small object) */
  172784. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  172785. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  172786. /* Get the rows themselves (large objects) */
  172787. currow = 0;
  172788. while (currow < numrows) {
  172789. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172790. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  172791. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  172792. * SIZEOF(JBLOCK)));
  172793. for (i = rowsperchunk; i > 0; i--) {
  172794. result[currow++] = workspace;
  172795. workspace += blocksperrow;
  172796. }
  172797. }
  172798. return result;
  172799. }
  172800. /*
  172801. * About virtual array management:
  172802. *
  172803. * The above "normal" array routines are only used to allocate strip buffers
  172804. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  172805. * are handled as "virtual" arrays. The array is still accessed a strip at a
  172806. * time, but the memory manager must save the whole array for repeated
  172807. * accesses. The intended implementation is that there is a strip buffer in
  172808. * memory (as high as is possible given the desired memory limit), plus a
  172809. * backing file that holds the rest of the array.
  172810. *
  172811. * The request_virt_array routines are told the total size of the image and
  172812. * the maximum number of rows that will be accessed at once. The in-memory
  172813. * buffer must be at least as large as the maxaccess value.
  172814. *
  172815. * The request routines create control blocks but not the in-memory buffers.
  172816. * That is postponed until realize_virt_arrays is called. At that time the
  172817. * total amount of space needed is known (approximately, anyway), so free
  172818. * memory can be divided up fairly.
  172819. *
  172820. * The access_virt_array routines are responsible for making a specific strip
  172821. * area accessible (after reading or writing the backing file, if necessary).
  172822. * Note that the access routines are told whether the caller intends to modify
  172823. * the accessed strip; during a read-only pass this saves having to rewrite
  172824. * data to disk. The access routines are also responsible for pre-zeroing
  172825. * any newly accessed rows, if pre-zeroing was requested.
  172826. *
  172827. * In current usage, the access requests are usually for nonoverlapping
  172828. * strips; that is, successive access start_row numbers differ by exactly
  172829. * num_rows = maxaccess. This means we can get good performance with simple
  172830. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  172831. * of the access height; then there will never be accesses across bufferload
  172832. * boundaries. The code will still work with overlapping access requests,
  172833. * but it doesn't handle bufferload overlaps very efficiently.
  172834. */
  172835. METHODDEF(jvirt_sarray_ptr)
  172836. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172837. JDIMENSION samplesperrow, JDIMENSION numrows,
  172838. JDIMENSION maxaccess)
  172839. /* Request a virtual 2-D sample array */
  172840. {
  172841. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172842. jvirt_sarray_ptr result;
  172843. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172844. if (pool_id != JPOOL_IMAGE)
  172845. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172846. /* get control block */
  172847. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  172848. SIZEOF(struct jvirt_sarray_control));
  172849. result->mem_buffer = NULL; /* marks array not yet realized */
  172850. result->rows_in_array = numrows;
  172851. result->samplesperrow = samplesperrow;
  172852. result->maxaccess = maxaccess;
  172853. result->pre_zero = pre_zero;
  172854. result->b_s_open = FALSE; /* no associated backing-store object */
  172855. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  172856. mem->virt_sarray_list = result;
  172857. return result;
  172858. }
  172859. METHODDEF(jvirt_barray_ptr)
  172860. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172861. JDIMENSION blocksperrow, JDIMENSION numrows,
  172862. JDIMENSION maxaccess)
  172863. /* Request a virtual 2-D coefficient-block array */
  172864. {
  172865. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172866. jvirt_barray_ptr result;
  172867. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172868. if (pool_id != JPOOL_IMAGE)
  172869. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172870. /* get control block */
  172871. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  172872. SIZEOF(struct jvirt_barray_control));
  172873. result->mem_buffer = NULL; /* marks array not yet realized */
  172874. result->rows_in_array = numrows;
  172875. result->blocksperrow = blocksperrow;
  172876. result->maxaccess = maxaccess;
  172877. result->pre_zero = pre_zero;
  172878. result->b_s_open = FALSE; /* no associated backing-store object */
  172879. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  172880. mem->virt_barray_list = result;
  172881. return result;
  172882. }
  172883. METHODDEF(void)
  172884. realize_virt_arrays (j_common_ptr cinfo)
  172885. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  172886. {
  172887. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172888. long space_per_minheight, maximum_space, avail_mem;
  172889. long minheights, max_minheights;
  172890. jvirt_sarray_ptr sptr;
  172891. jvirt_barray_ptr bptr;
  172892. /* Compute the minimum space needed (maxaccess rows in each buffer)
  172893. * and the maximum space needed (full image height in each buffer).
  172894. * These may be of use to the system-dependent jpeg_mem_available routine.
  172895. */
  172896. space_per_minheight = 0;
  172897. maximum_space = 0;
  172898. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172899. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172900. space_per_minheight += (long) sptr->maxaccess *
  172901. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172902. maximum_space += (long) sptr->rows_in_array *
  172903. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172904. }
  172905. }
  172906. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172907. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172908. space_per_minheight += (long) bptr->maxaccess *
  172909. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172910. maximum_space += (long) bptr->rows_in_array *
  172911. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172912. }
  172913. }
  172914. if (space_per_minheight <= 0)
  172915. return; /* no unrealized arrays, no work */
  172916. /* Determine amount of memory to actually use; this is system-dependent. */
  172917. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  172918. mem->total_space_allocated);
  172919. /* If the maximum space needed is available, make all the buffers full
  172920. * height; otherwise parcel it out with the same number of minheights
  172921. * in each buffer.
  172922. */
  172923. if (avail_mem >= maximum_space)
  172924. max_minheights = 1000000000L;
  172925. else {
  172926. max_minheights = avail_mem / space_per_minheight;
  172927. /* If there doesn't seem to be enough space, try to get the minimum
  172928. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  172929. */
  172930. if (max_minheights <= 0)
  172931. max_minheights = 1;
  172932. }
  172933. /* Allocate the in-memory buffers and initialize backing store as needed. */
  172934. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172935. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172936. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  172937. if (minheights <= max_minheights) {
  172938. /* This buffer fits in memory */
  172939. sptr->rows_in_mem = sptr->rows_in_array;
  172940. } else {
  172941. /* It doesn't fit in memory, create backing store. */
  172942. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  172943. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  172944. (long) sptr->rows_in_array *
  172945. (long) sptr->samplesperrow *
  172946. (long) SIZEOF(JSAMPLE));
  172947. sptr->b_s_open = TRUE;
  172948. }
  172949. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  172950. sptr->samplesperrow, sptr->rows_in_mem);
  172951. sptr->rowsperchunk = mem->last_rowsperchunk;
  172952. sptr->cur_start_row = 0;
  172953. sptr->first_undef_row = 0;
  172954. sptr->dirty = FALSE;
  172955. }
  172956. }
  172957. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172958. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172959. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  172960. if (minheights <= max_minheights) {
  172961. /* This buffer fits in memory */
  172962. bptr->rows_in_mem = bptr->rows_in_array;
  172963. } else {
  172964. /* It doesn't fit in memory, create backing store. */
  172965. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  172966. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  172967. (long) bptr->rows_in_array *
  172968. (long) bptr->blocksperrow *
  172969. (long) SIZEOF(JBLOCK));
  172970. bptr->b_s_open = TRUE;
  172971. }
  172972. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  172973. bptr->blocksperrow, bptr->rows_in_mem);
  172974. bptr->rowsperchunk = mem->last_rowsperchunk;
  172975. bptr->cur_start_row = 0;
  172976. bptr->first_undef_row = 0;
  172977. bptr->dirty = FALSE;
  172978. }
  172979. }
  172980. }
  172981. LOCAL(void)
  172982. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  172983. /* Do backing store read or write of a virtual sample array */
  172984. {
  172985. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172986. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172987. file_offset = ptr->cur_start_row * bytesperrow;
  172988. /* Loop to read or write each allocation chunk in mem_buffer */
  172989. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172990. /* One chunk, but check for short chunk at end of buffer */
  172991. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172992. /* Transfer no more than is currently defined */
  172993. thisrow = (long) ptr->cur_start_row + i;
  172994. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172995. /* Transfer no more than fits in file */
  172996. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172997. if (rows <= 0) /* this chunk might be past end of file! */
  172998. break;
  172999. byte_count = rows * bytesperrow;
  173000. if (writing)
  173001. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173002. (void FAR *) ptr->mem_buffer[i],
  173003. file_offset, byte_count);
  173004. else
  173005. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173006. (void FAR *) ptr->mem_buffer[i],
  173007. file_offset, byte_count);
  173008. file_offset += byte_count;
  173009. }
  173010. }
  173011. LOCAL(void)
  173012. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  173013. /* Do backing store read or write of a virtual coefficient-block array */
  173014. {
  173015. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  173016. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  173017. file_offset = ptr->cur_start_row * bytesperrow;
  173018. /* Loop to read or write each allocation chunk in mem_buffer */
  173019. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  173020. /* One chunk, but check for short chunk at end of buffer */
  173021. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  173022. /* Transfer no more than is currently defined */
  173023. thisrow = (long) ptr->cur_start_row + i;
  173024. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  173025. /* Transfer no more than fits in file */
  173026. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  173027. if (rows <= 0) /* this chunk might be past end of file! */
  173028. break;
  173029. byte_count = rows * bytesperrow;
  173030. if (writing)
  173031. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173032. (void FAR *) ptr->mem_buffer[i],
  173033. file_offset, byte_count);
  173034. else
  173035. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173036. (void FAR *) ptr->mem_buffer[i],
  173037. file_offset, byte_count);
  173038. file_offset += byte_count;
  173039. }
  173040. }
  173041. METHODDEF(JSAMPARRAY)
  173042. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  173043. JDIMENSION start_row, JDIMENSION num_rows,
  173044. boolean writable)
  173045. /* Access the part of a virtual sample array starting at start_row */
  173046. /* and extending for num_rows rows. writable is true if */
  173047. /* caller intends to modify the accessed area. */
  173048. {
  173049. JDIMENSION end_row = start_row + num_rows;
  173050. JDIMENSION undef_row;
  173051. /* debugging check */
  173052. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173053. ptr->mem_buffer == NULL)
  173054. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173055. /* Make the desired part of the virtual array accessible */
  173056. if (start_row < ptr->cur_start_row ||
  173057. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173058. if (! ptr->b_s_open)
  173059. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173060. /* Flush old buffer contents if necessary */
  173061. if (ptr->dirty) {
  173062. do_sarray_io(cinfo, ptr, TRUE);
  173063. ptr->dirty = FALSE;
  173064. }
  173065. /* Decide what part of virtual array to access.
  173066. * Algorithm: if target address > current window, assume forward scan,
  173067. * load starting at target address. If target address < current window,
  173068. * assume backward scan, load so that target area is top of window.
  173069. * Note that when switching from forward write to forward read, will have
  173070. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173071. */
  173072. if (start_row > ptr->cur_start_row) {
  173073. ptr->cur_start_row = start_row;
  173074. } else {
  173075. /* use long arithmetic here to avoid overflow & unsigned problems */
  173076. long ltemp;
  173077. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173078. if (ltemp < 0)
  173079. ltemp = 0; /* don't fall off front end of file */
  173080. ptr->cur_start_row = (JDIMENSION) ltemp;
  173081. }
  173082. /* Read in the selected part of the array.
  173083. * During the initial write pass, we will do no actual read
  173084. * because the selected part is all undefined.
  173085. */
  173086. do_sarray_io(cinfo, ptr, FALSE);
  173087. }
  173088. /* Ensure the accessed part of the array is defined; prezero if needed.
  173089. * To improve locality of access, we only prezero the part of the array
  173090. * that the caller is about to access, not the entire in-memory array.
  173091. */
  173092. if (ptr->first_undef_row < end_row) {
  173093. if (ptr->first_undef_row < start_row) {
  173094. if (writable) /* writer skipped over a section of array */
  173095. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173096. undef_row = start_row; /* but reader is allowed to read ahead */
  173097. } else {
  173098. undef_row = ptr->first_undef_row;
  173099. }
  173100. if (writable)
  173101. ptr->first_undef_row = end_row;
  173102. if (ptr->pre_zero) {
  173103. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  173104. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173105. end_row -= ptr->cur_start_row;
  173106. while (undef_row < end_row) {
  173107. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173108. undef_row++;
  173109. }
  173110. } else {
  173111. if (! writable) /* reader looking at undefined data */
  173112. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173113. }
  173114. }
  173115. /* Flag the buffer dirty if caller will write in it */
  173116. if (writable)
  173117. ptr->dirty = TRUE;
  173118. /* Return address of proper part of the buffer */
  173119. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173120. }
  173121. METHODDEF(JBLOCKARRAY)
  173122. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  173123. JDIMENSION start_row, JDIMENSION num_rows,
  173124. boolean writable)
  173125. /* Access the part of a virtual block array starting at start_row */
  173126. /* and extending for num_rows rows. writable is true if */
  173127. /* caller intends to modify the accessed area. */
  173128. {
  173129. JDIMENSION end_row = start_row + num_rows;
  173130. JDIMENSION undef_row;
  173131. /* debugging check */
  173132. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173133. ptr->mem_buffer == NULL)
  173134. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173135. /* Make the desired part of the virtual array accessible */
  173136. if (start_row < ptr->cur_start_row ||
  173137. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173138. if (! ptr->b_s_open)
  173139. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173140. /* Flush old buffer contents if necessary */
  173141. if (ptr->dirty) {
  173142. do_barray_io(cinfo, ptr, TRUE);
  173143. ptr->dirty = FALSE;
  173144. }
  173145. /* Decide what part of virtual array to access.
  173146. * Algorithm: if target address > current window, assume forward scan,
  173147. * load starting at target address. If target address < current window,
  173148. * assume backward scan, load so that target area is top of window.
  173149. * Note that when switching from forward write to forward read, will have
  173150. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173151. */
  173152. if (start_row > ptr->cur_start_row) {
  173153. ptr->cur_start_row = start_row;
  173154. } else {
  173155. /* use long arithmetic here to avoid overflow & unsigned problems */
  173156. long ltemp;
  173157. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173158. if (ltemp < 0)
  173159. ltemp = 0; /* don't fall off front end of file */
  173160. ptr->cur_start_row = (JDIMENSION) ltemp;
  173161. }
  173162. /* Read in the selected part of the array.
  173163. * During the initial write pass, we will do no actual read
  173164. * because the selected part is all undefined.
  173165. */
  173166. do_barray_io(cinfo, ptr, FALSE);
  173167. }
  173168. /* Ensure the accessed part of the array is defined; prezero if needed.
  173169. * To improve locality of access, we only prezero the part of the array
  173170. * that the caller is about to access, not the entire in-memory array.
  173171. */
  173172. if (ptr->first_undef_row < end_row) {
  173173. if (ptr->first_undef_row < start_row) {
  173174. if (writable) /* writer skipped over a section of array */
  173175. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173176. undef_row = start_row; /* but reader is allowed to read ahead */
  173177. } else {
  173178. undef_row = ptr->first_undef_row;
  173179. }
  173180. if (writable)
  173181. ptr->first_undef_row = end_row;
  173182. if (ptr->pre_zero) {
  173183. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  173184. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173185. end_row -= ptr->cur_start_row;
  173186. while (undef_row < end_row) {
  173187. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173188. undef_row++;
  173189. }
  173190. } else {
  173191. if (! writable) /* reader looking at undefined data */
  173192. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173193. }
  173194. }
  173195. /* Flag the buffer dirty if caller will write in it */
  173196. if (writable)
  173197. ptr->dirty = TRUE;
  173198. /* Return address of proper part of the buffer */
  173199. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173200. }
  173201. /*
  173202. * Release all objects belonging to a specified pool.
  173203. */
  173204. METHODDEF(void)
  173205. free_pool (j_common_ptr cinfo, int pool_id)
  173206. {
  173207. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173208. small_pool_ptr shdr_ptr;
  173209. large_pool_ptr lhdr_ptr;
  173210. size_t space_freed;
  173211. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173212. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173213. #ifdef MEM_STATS
  173214. if (cinfo->err->trace_level > 1)
  173215. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  173216. #endif
  173217. /* If freeing IMAGE pool, close any virtual arrays first */
  173218. if (pool_id == JPOOL_IMAGE) {
  173219. jvirt_sarray_ptr sptr;
  173220. jvirt_barray_ptr bptr;
  173221. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173222. if (sptr->b_s_open) { /* there may be no backing store */
  173223. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  173224. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  173225. }
  173226. }
  173227. mem->virt_sarray_list = NULL;
  173228. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173229. if (bptr->b_s_open) { /* there may be no backing store */
  173230. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  173231. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  173232. }
  173233. }
  173234. mem->virt_barray_list = NULL;
  173235. }
  173236. /* Release large objects */
  173237. lhdr_ptr = mem->large_list[pool_id];
  173238. mem->large_list[pool_id] = NULL;
  173239. while (lhdr_ptr != NULL) {
  173240. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  173241. space_freed = lhdr_ptr->hdr.bytes_used +
  173242. lhdr_ptr->hdr.bytes_left +
  173243. SIZEOF(large_pool_hdr);
  173244. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  173245. mem->total_space_allocated -= space_freed;
  173246. lhdr_ptr = next_lhdr_ptr;
  173247. }
  173248. /* Release small objects */
  173249. shdr_ptr = mem->small_list[pool_id];
  173250. mem->small_list[pool_id] = NULL;
  173251. while (shdr_ptr != NULL) {
  173252. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  173253. space_freed = shdr_ptr->hdr.bytes_used +
  173254. shdr_ptr->hdr.bytes_left +
  173255. SIZEOF(small_pool_hdr);
  173256. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  173257. mem->total_space_allocated -= space_freed;
  173258. shdr_ptr = next_shdr_ptr;
  173259. }
  173260. }
  173261. /*
  173262. * Close up shop entirely.
  173263. * Note that this cannot be called unless cinfo->mem is non-NULL.
  173264. */
  173265. METHODDEF(void)
  173266. self_destruct (j_common_ptr cinfo)
  173267. {
  173268. int pool;
  173269. /* Close all backing store, release all memory.
  173270. * Releasing pools in reverse order might help avoid fragmentation
  173271. * with some (brain-damaged) malloc libraries.
  173272. */
  173273. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173274. free_pool(cinfo, pool);
  173275. }
  173276. /* Release the memory manager control block too. */
  173277. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  173278. cinfo->mem = NULL; /* ensures I will be called only once */
  173279. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173280. }
  173281. /*
  173282. * Memory manager initialization.
  173283. * When this is called, only the error manager pointer is valid in cinfo!
  173284. */
  173285. GLOBAL(void)
  173286. jinit_memory_mgr (j_common_ptr cinfo)
  173287. {
  173288. my_mem_ptr mem;
  173289. long max_to_use;
  173290. int pool;
  173291. size_t test_mac;
  173292. cinfo->mem = NULL; /* for safety if init fails */
  173293. /* Check for configuration errors.
  173294. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  173295. * doesn't reflect any real hardware alignment requirement.
  173296. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  173297. * in common if and only if X is a power of 2, ie has only one one-bit.
  173298. * Some compilers may give an "unreachable code" warning here; ignore it.
  173299. */
  173300. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  173301. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  173302. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  173303. * a multiple of SIZEOF(ALIGN_TYPE).
  173304. * Again, an "unreachable code" warning may be ignored here.
  173305. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  173306. */
  173307. test_mac = (size_t) MAX_ALLOC_CHUNK;
  173308. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  173309. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  173310. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  173311. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  173312. /* Attempt to allocate memory manager's control block */
  173313. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  173314. if (mem == NULL) {
  173315. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173316. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  173317. }
  173318. /* OK, fill in the method pointers */
  173319. mem->pub.alloc_small = alloc_small;
  173320. mem->pub.alloc_large = alloc_large;
  173321. mem->pub.alloc_sarray = alloc_sarray;
  173322. mem->pub.alloc_barray = alloc_barray;
  173323. mem->pub.request_virt_sarray = request_virt_sarray;
  173324. mem->pub.request_virt_barray = request_virt_barray;
  173325. mem->pub.realize_virt_arrays = realize_virt_arrays;
  173326. mem->pub.access_virt_sarray = access_virt_sarray;
  173327. mem->pub.access_virt_barray = access_virt_barray;
  173328. mem->pub.free_pool = free_pool;
  173329. mem->pub.self_destruct = self_destruct;
  173330. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  173331. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  173332. /* Initialize working state */
  173333. mem->pub.max_memory_to_use = max_to_use;
  173334. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173335. mem->small_list[pool] = NULL;
  173336. mem->large_list[pool] = NULL;
  173337. }
  173338. mem->virt_sarray_list = NULL;
  173339. mem->virt_barray_list = NULL;
  173340. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  173341. /* Declare ourselves open for business */
  173342. cinfo->mem = & mem->pub;
  173343. /* Check for an environment variable JPEGMEM; if found, override the
  173344. * default max_memory setting from jpeg_mem_init. Note that the
  173345. * surrounding application may again override this value.
  173346. * If your system doesn't support getenv(), define NO_GETENV to disable
  173347. * this feature.
  173348. */
  173349. #ifndef NO_GETENV
  173350. { char * memenv;
  173351. if ((memenv = getenv("JPEGMEM")) != NULL) {
  173352. char ch = 'x';
  173353. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  173354. if (ch == 'm' || ch == 'M')
  173355. max_to_use *= 1000L;
  173356. mem->pub.max_memory_to_use = max_to_use * 1000L;
  173357. }
  173358. }
  173359. }
  173360. #endif
  173361. }
  173362. /*** End of inlined file: jmemmgr.c ***/
  173363. /*** Start of inlined file: jmemnobs.c ***/
  173364. #define JPEG_INTERNALS
  173365. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  173366. extern void * malloc JPP((size_t size));
  173367. extern void free JPP((void *ptr));
  173368. #endif
  173369. /*
  173370. * Memory allocation and freeing are controlled by the regular library
  173371. * routines malloc() and free().
  173372. */
  173373. GLOBAL(void *)
  173374. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  173375. {
  173376. return (void *) malloc(sizeofobject);
  173377. }
  173378. GLOBAL(void)
  173379. jpeg_free_small (j_common_ptr , void * object, size_t)
  173380. {
  173381. free(object);
  173382. }
  173383. /*
  173384. * "Large" objects are treated the same as "small" ones.
  173385. * NB: although we include FAR keywords in the routine declarations,
  173386. * this file won't actually work in 80x86 small/medium model; at least,
  173387. * you probably won't be able to process useful-size images in only 64KB.
  173388. */
  173389. GLOBAL(void FAR *)
  173390. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  173391. {
  173392. return (void FAR *) malloc(sizeofobject);
  173393. }
  173394. GLOBAL(void)
  173395. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  173396. {
  173397. free(object);
  173398. }
  173399. /*
  173400. * This routine computes the total memory space available for allocation.
  173401. * Here we always say, "we got all you want bud!"
  173402. */
  173403. GLOBAL(long)
  173404. jpeg_mem_available (j_common_ptr, long,
  173405. long max_bytes_needed, long)
  173406. {
  173407. return max_bytes_needed;
  173408. }
  173409. /*
  173410. * Backing store (temporary file) management.
  173411. * Since jpeg_mem_available always promised the moon,
  173412. * this should never be called and we can just error out.
  173413. */
  173414. GLOBAL(void)
  173415. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  173416. long )
  173417. {
  173418. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  173419. }
  173420. /*
  173421. * These routines take care of any system-dependent initialization and
  173422. * cleanup required. Here, there isn't any.
  173423. */
  173424. GLOBAL(long)
  173425. jpeg_mem_init (j_common_ptr)
  173426. {
  173427. return 0; /* just set max_memory_to_use to 0 */
  173428. }
  173429. GLOBAL(void)
  173430. jpeg_mem_term (j_common_ptr)
  173431. {
  173432. /* no work */
  173433. }
  173434. /*** End of inlined file: jmemnobs.c ***/
  173435. /*** Start of inlined file: jquant1.c ***/
  173436. #define JPEG_INTERNALS
  173437. #ifdef QUANT_1PASS_SUPPORTED
  173438. /*
  173439. * The main purpose of 1-pass quantization is to provide a fast, if not very
  173440. * high quality, colormapped output capability. A 2-pass quantizer usually
  173441. * gives better visual quality; however, for quantized grayscale output this
  173442. * quantizer is perfectly adequate. Dithering is highly recommended with this
  173443. * quantizer, though you can turn it off if you really want to.
  173444. *
  173445. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  173446. * image. We use a map consisting of all combinations of Ncolors[i] color
  173447. * values for the i'th component. The Ncolors[] values are chosen so that
  173448. * their product, the total number of colors, is no more than that requested.
  173449. * (In most cases, the product will be somewhat less.)
  173450. *
  173451. * Since the colormap is orthogonal, the representative value for each color
  173452. * component can be determined without considering the other components;
  173453. * then these indexes can be combined into a colormap index by a standard
  173454. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  173455. * can be precalculated and stored in the lookup table colorindex[].
  173456. * colorindex[i][j] maps pixel value j in component i to the nearest
  173457. * representative value (grid plane) for that component; this index is
  173458. * multiplied by the array stride for component i, so that the
  173459. * index of the colormap entry closest to a given pixel value is just
  173460. * sum( colorindex[component-number][pixel-component-value] )
  173461. * Aside from being fast, this scheme allows for variable spacing between
  173462. * representative values with no additional lookup cost.
  173463. *
  173464. * If gamma correction has been applied in color conversion, it might be wise
  173465. * to adjust the color grid spacing so that the representative colors are
  173466. * equidistant in linear space. At this writing, gamma correction is not
  173467. * implemented by jdcolor, so nothing is done here.
  173468. */
  173469. /* Declarations for ordered dithering.
  173470. *
  173471. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  173472. * dithering is described in many references, for instance Dale Schumacher's
  173473. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  173474. * In place of Schumacher's comparisons against a "threshold" value, we add a
  173475. * "dither" value to the input pixel and then round the result to the nearest
  173476. * output value. The dither value is equivalent to (0.5 - threshold) times
  173477. * the distance between output values. For ordered dithering, we assume that
  173478. * the output colors are equally spaced; if not, results will probably be
  173479. * worse, since the dither may be too much or too little at a given point.
  173480. *
  173481. * The normal calculation would be to form pixel value + dither, range-limit
  173482. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  173483. * We can skip the separate range-limiting step by extending the colorindex
  173484. * table in both directions.
  173485. */
  173486. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  173487. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  173488. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  173489. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  173490. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  173491. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  173492. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  173493. /* Bayer's order-4 dither array. Generated by the code given in
  173494. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  173495. * The values in this array must range from 0 to ODITHER_CELLS-1.
  173496. */
  173497. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  173498. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  173499. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  173500. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  173501. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  173502. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  173503. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  173504. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  173505. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  173506. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  173507. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  173508. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  173509. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  173510. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  173511. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  173512. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  173513. };
  173514. /* Declarations for Floyd-Steinberg dithering.
  173515. *
  173516. * Errors are accumulated into the array fserrors[], at a resolution of
  173517. * 1/16th of a pixel count. The error at a given pixel is propagated
  173518. * to its not-yet-processed neighbors using the standard F-S fractions,
  173519. * ... (here) 7/16
  173520. * 3/16 5/16 1/16
  173521. * We work left-to-right on even rows, right-to-left on odd rows.
  173522. *
  173523. * We can get away with a single array (holding one row's worth of errors)
  173524. * by using it to store the current row's errors at pixel columns not yet
  173525. * processed, but the next row's errors at columns already processed. We
  173526. * need only a few extra variables to hold the errors immediately around the
  173527. * current column. (If we are lucky, those variables are in registers, but
  173528. * even if not, they're probably cheaper to access than array elements are.)
  173529. *
  173530. * The fserrors[] array is indexed [component#][position].
  173531. * We provide (#columns + 2) entries per component; the extra entry at each
  173532. * end saves us from special-casing the first and last pixels.
  173533. *
  173534. * Note: on a wide image, we might not have enough room in a PC's near data
  173535. * segment to hold the error array; so it is allocated with alloc_large.
  173536. */
  173537. #if BITS_IN_JSAMPLE == 8
  173538. typedef INT16 FSERROR; /* 16 bits should be enough */
  173539. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  173540. #else
  173541. typedef INT32 FSERROR; /* may need more than 16 bits */
  173542. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  173543. #endif
  173544. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  173545. /* Private subobject */
  173546. #define MAX_Q_COMPS 4 /* max components I can handle */
  173547. typedef struct {
  173548. struct jpeg_color_quantizer pub; /* public fields */
  173549. /* Initially allocated colormap is saved here */
  173550. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  173551. int sv_actual; /* number of entries in use */
  173552. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  173553. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  173554. * premultiplied as described above. Since colormap indexes must fit into
  173555. * JSAMPLEs, the entries of this array will too.
  173556. */
  173557. boolean is_padded; /* is the colorindex padded for odither? */
  173558. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  173559. /* Variables for ordered dithering */
  173560. int row_index; /* cur row's vertical index in dither matrix */
  173561. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  173562. /* Variables for Floyd-Steinberg dithering */
  173563. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  173564. boolean on_odd_row; /* flag to remember which row we are on */
  173565. } my_cquantizer;
  173566. typedef my_cquantizer * my_cquantize_ptr;
  173567. /*
  173568. * Policy-making subroutines for create_colormap and create_colorindex.
  173569. * These routines determine the colormap to be used. The rest of the module
  173570. * only assumes that the colormap is orthogonal.
  173571. *
  173572. * * select_ncolors decides how to divvy up the available colors
  173573. * among the components.
  173574. * * output_value defines the set of representative values for a component.
  173575. * * largest_input_value defines the mapping from input values to
  173576. * representative values for a component.
  173577. * Note that the latter two routines may impose different policies for
  173578. * different components, though this is not currently done.
  173579. */
  173580. LOCAL(int)
  173581. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  173582. /* Determine allocation of desired colors to components, */
  173583. /* and fill in Ncolors[] array to indicate choice. */
  173584. /* Return value is total number of colors (product of Ncolors[] values). */
  173585. {
  173586. int nc = cinfo->out_color_components; /* number of color components */
  173587. int max_colors = cinfo->desired_number_of_colors;
  173588. int total_colors, iroot, i, j;
  173589. boolean changed;
  173590. long temp;
  173591. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  173592. /* We can allocate at least the nc'th root of max_colors per component. */
  173593. /* Compute floor(nc'th root of max_colors). */
  173594. iroot = 1;
  173595. do {
  173596. iroot++;
  173597. temp = iroot; /* set temp = iroot ** nc */
  173598. for (i = 1; i < nc; i++)
  173599. temp *= iroot;
  173600. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  173601. iroot--; /* now iroot = floor(root) */
  173602. /* Must have at least 2 color values per component */
  173603. if (iroot < 2)
  173604. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  173605. /* Initialize to iroot color values for each component */
  173606. total_colors = 1;
  173607. for (i = 0; i < nc; i++) {
  173608. Ncolors[i] = iroot;
  173609. total_colors *= iroot;
  173610. }
  173611. /* We may be able to increment the count for one or more components without
  173612. * exceeding max_colors, though we know not all can be incremented.
  173613. * Sometimes, the first component can be incremented more than once!
  173614. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  173615. * In RGB colorspace, try to increment G first, then R, then B.
  173616. */
  173617. do {
  173618. changed = FALSE;
  173619. for (i = 0; i < nc; i++) {
  173620. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  173621. /* calculate new total_colors if Ncolors[j] is incremented */
  173622. temp = total_colors / Ncolors[j];
  173623. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  173624. if (temp > (long) max_colors)
  173625. break; /* won't fit, done with this pass */
  173626. Ncolors[j]++; /* OK, apply the increment */
  173627. total_colors = (int) temp;
  173628. changed = TRUE;
  173629. }
  173630. } while (changed);
  173631. return total_colors;
  173632. }
  173633. LOCAL(int)
  173634. output_value (j_decompress_ptr, int, int j, int maxj)
  173635. /* Return j'th output value, where j will range from 0 to maxj */
  173636. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  173637. {
  173638. /* We always provide values 0 and MAXJSAMPLE for each component;
  173639. * any additional values are equally spaced between these limits.
  173640. * (Forcing the upper and lower values to the limits ensures that
  173641. * dithering can't produce a color outside the selected gamut.)
  173642. */
  173643. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  173644. }
  173645. LOCAL(int)
  173646. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  173647. /* Return largest input value that should map to j'th output value */
  173648. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  173649. {
  173650. /* Breakpoints are halfway between values returned by output_value */
  173651. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  173652. }
  173653. /*
  173654. * Create the colormap.
  173655. */
  173656. LOCAL(void)
  173657. create_colormap (j_decompress_ptr cinfo)
  173658. {
  173659. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173660. JSAMPARRAY colormap; /* Created colormap */
  173661. int total_colors; /* Number of distinct output colors */
  173662. int i,j,k, nci, blksize, blkdist, ptr, val;
  173663. /* Select number of colors for each component */
  173664. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  173665. /* Report selected color counts */
  173666. if (cinfo->out_color_components == 3)
  173667. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  173668. total_colors, cquantize->Ncolors[0],
  173669. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  173670. else
  173671. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  173672. /* Allocate and fill in the colormap. */
  173673. /* The colors are ordered in the map in standard row-major order, */
  173674. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  173675. colormap = (*cinfo->mem->alloc_sarray)
  173676. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173677. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  173678. /* blksize is number of adjacent repeated entries for a component */
  173679. /* blkdist is distance between groups of identical entries for a component */
  173680. blkdist = total_colors;
  173681. for (i = 0; i < cinfo->out_color_components; i++) {
  173682. /* fill in colormap entries for i'th color component */
  173683. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173684. blksize = blkdist / nci;
  173685. for (j = 0; j < nci; j++) {
  173686. /* Compute j'th output value (out of nci) for component */
  173687. val = output_value(cinfo, i, j, nci-1);
  173688. /* Fill in all colormap entries that have this value of this component */
  173689. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  173690. /* fill in blksize entries beginning at ptr */
  173691. for (k = 0; k < blksize; k++)
  173692. colormap[i][ptr+k] = (JSAMPLE) val;
  173693. }
  173694. }
  173695. blkdist = blksize; /* blksize of this color is blkdist of next */
  173696. }
  173697. /* Save the colormap in private storage,
  173698. * where it will survive color quantization mode changes.
  173699. */
  173700. cquantize->sv_colormap = colormap;
  173701. cquantize->sv_actual = total_colors;
  173702. }
  173703. /*
  173704. * Create the color index table.
  173705. */
  173706. LOCAL(void)
  173707. create_colorindex (j_decompress_ptr cinfo)
  173708. {
  173709. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173710. JSAMPROW indexptr;
  173711. int i,j,k, nci, blksize, val, pad;
  173712. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  173713. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  173714. * This is not necessary in the other dithering modes. However, we
  173715. * flag whether it was done in case user changes dithering mode.
  173716. */
  173717. if (cinfo->dither_mode == JDITHER_ORDERED) {
  173718. pad = MAXJSAMPLE*2;
  173719. cquantize->is_padded = TRUE;
  173720. } else {
  173721. pad = 0;
  173722. cquantize->is_padded = FALSE;
  173723. }
  173724. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  173725. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173726. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  173727. (JDIMENSION) cinfo->out_color_components);
  173728. /* blksize is number of adjacent repeated entries for a component */
  173729. blksize = cquantize->sv_actual;
  173730. for (i = 0; i < cinfo->out_color_components; i++) {
  173731. /* fill in colorindex entries for i'th color component */
  173732. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173733. blksize = blksize / nci;
  173734. /* adjust colorindex pointers to provide padding at negative indexes. */
  173735. if (pad)
  173736. cquantize->colorindex[i] += MAXJSAMPLE;
  173737. /* in loop, val = index of current output value, */
  173738. /* and k = largest j that maps to current val */
  173739. indexptr = cquantize->colorindex[i];
  173740. val = 0;
  173741. k = largest_input_value(cinfo, i, 0, nci-1);
  173742. for (j = 0; j <= MAXJSAMPLE; j++) {
  173743. while (j > k) /* advance val if past boundary */
  173744. k = largest_input_value(cinfo, i, ++val, nci-1);
  173745. /* premultiply so that no multiplication needed in main processing */
  173746. indexptr[j] = (JSAMPLE) (val * blksize);
  173747. }
  173748. /* Pad at both ends if necessary */
  173749. if (pad)
  173750. for (j = 1; j <= MAXJSAMPLE; j++) {
  173751. indexptr[-j] = indexptr[0];
  173752. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  173753. }
  173754. }
  173755. }
  173756. /*
  173757. * Create an ordered-dither array for a component having ncolors
  173758. * distinct output values.
  173759. */
  173760. LOCAL(ODITHER_MATRIX_PTR)
  173761. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  173762. {
  173763. ODITHER_MATRIX_PTR odither;
  173764. int j,k;
  173765. INT32 num,den;
  173766. odither = (ODITHER_MATRIX_PTR)
  173767. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173768. SIZEOF(ODITHER_MATRIX));
  173769. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  173770. * Hence the dither value for the matrix cell with fill order f
  173771. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  173772. * On 16-bit-int machine, be careful to avoid overflow.
  173773. */
  173774. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  173775. for (j = 0; j < ODITHER_SIZE; j++) {
  173776. for (k = 0; k < ODITHER_SIZE; k++) {
  173777. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  173778. * MAXJSAMPLE;
  173779. /* Ensure round towards zero despite C's lack of consistency
  173780. * about rounding negative values in integer division...
  173781. */
  173782. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  173783. }
  173784. }
  173785. return odither;
  173786. }
  173787. /*
  173788. * Create the ordered-dither tables.
  173789. * Components having the same number of representative colors may
  173790. * share a dither table.
  173791. */
  173792. LOCAL(void)
  173793. create_odither_tables (j_decompress_ptr cinfo)
  173794. {
  173795. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173796. ODITHER_MATRIX_PTR odither;
  173797. int i, j, nci;
  173798. for (i = 0; i < cinfo->out_color_components; i++) {
  173799. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173800. odither = NULL; /* search for matching prior component */
  173801. for (j = 0; j < i; j++) {
  173802. if (nci == cquantize->Ncolors[j]) {
  173803. odither = cquantize->odither[j];
  173804. break;
  173805. }
  173806. }
  173807. if (odither == NULL) /* need a new table? */
  173808. odither = make_odither_array(cinfo, nci);
  173809. cquantize->odither[i] = odither;
  173810. }
  173811. }
  173812. /*
  173813. * Map some rows of pixels to the output colormapped representation.
  173814. */
  173815. METHODDEF(void)
  173816. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173817. JSAMPARRAY output_buf, int num_rows)
  173818. /* General case, no dithering */
  173819. {
  173820. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173821. JSAMPARRAY colorindex = cquantize->colorindex;
  173822. register int pixcode, ci;
  173823. register JSAMPROW ptrin, ptrout;
  173824. int row;
  173825. JDIMENSION col;
  173826. JDIMENSION width = cinfo->output_width;
  173827. register int nc = cinfo->out_color_components;
  173828. for (row = 0; row < num_rows; row++) {
  173829. ptrin = input_buf[row];
  173830. ptrout = output_buf[row];
  173831. for (col = width; col > 0; col--) {
  173832. pixcode = 0;
  173833. for (ci = 0; ci < nc; ci++) {
  173834. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  173835. }
  173836. *ptrout++ = (JSAMPLE) pixcode;
  173837. }
  173838. }
  173839. }
  173840. METHODDEF(void)
  173841. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173842. JSAMPARRAY output_buf, int num_rows)
  173843. /* Fast path for out_color_components==3, no dithering */
  173844. {
  173845. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173846. register int pixcode;
  173847. register JSAMPROW ptrin, ptrout;
  173848. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173849. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173850. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173851. int row;
  173852. JDIMENSION col;
  173853. JDIMENSION width = cinfo->output_width;
  173854. for (row = 0; row < num_rows; row++) {
  173855. ptrin = input_buf[row];
  173856. ptrout = output_buf[row];
  173857. for (col = width; col > 0; col--) {
  173858. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  173859. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  173860. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  173861. *ptrout++ = (JSAMPLE) pixcode;
  173862. }
  173863. }
  173864. }
  173865. METHODDEF(void)
  173866. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173867. JSAMPARRAY output_buf, int num_rows)
  173868. /* General case, with ordered dithering */
  173869. {
  173870. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173871. register JSAMPROW input_ptr;
  173872. register JSAMPROW output_ptr;
  173873. JSAMPROW colorindex_ci;
  173874. int * dither; /* points to active row of dither matrix */
  173875. int row_index, col_index; /* current indexes into dither matrix */
  173876. int nc = cinfo->out_color_components;
  173877. int ci;
  173878. int row;
  173879. JDIMENSION col;
  173880. JDIMENSION width = cinfo->output_width;
  173881. for (row = 0; row < num_rows; row++) {
  173882. /* Initialize output values to 0 so can process components separately */
  173883. jzero_far((void FAR *) output_buf[row],
  173884. (size_t) (width * SIZEOF(JSAMPLE)));
  173885. row_index = cquantize->row_index;
  173886. for (ci = 0; ci < nc; ci++) {
  173887. input_ptr = input_buf[row] + ci;
  173888. output_ptr = output_buf[row];
  173889. colorindex_ci = cquantize->colorindex[ci];
  173890. dither = cquantize->odither[ci][row_index];
  173891. col_index = 0;
  173892. for (col = width; col > 0; col--) {
  173893. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  173894. * select output value, accumulate into output code for this pixel.
  173895. * Range-limiting need not be done explicitly, as we have extended
  173896. * the colorindex table to produce the right answers for out-of-range
  173897. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  173898. * required amount of padding.
  173899. */
  173900. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  173901. input_ptr += nc;
  173902. output_ptr++;
  173903. col_index = (col_index + 1) & ODITHER_MASK;
  173904. }
  173905. }
  173906. /* Advance row index for next row */
  173907. row_index = (row_index + 1) & ODITHER_MASK;
  173908. cquantize->row_index = row_index;
  173909. }
  173910. }
  173911. METHODDEF(void)
  173912. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173913. JSAMPARRAY output_buf, int num_rows)
  173914. /* Fast path for out_color_components==3, with ordered dithering */
  173915. {
  173916. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173917. register int pixcode;
  173918. register JSAMPROW input_ptr;
  173919. register JSAMPROW output_ptr;
  173920. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173921. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173922. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173923. int * dither0; /* points to active row of dither matrix */
  173924. int * dither1;
  173925. int * dither2;
  173926. int row_index, col_index; /* current indexes into dither matrix */
  173927. int row;
  173928. JDIMENSION col;
  173929. JDIMENSION width = cinfo->output_width;
  173930. for (row = 0; row < num_rows; row++) {
  173931. row_index = cquantize->row_index;
  173932. input_ptr = input_buf[row];
  173933. output_ptr = output_buf[row];
  173934. dither0 = cquantize->odither[0][row_index];
  173935. dither1 = cquantize->odither[1][row_index];
  173936. dither2 = cquantize->odither[2][row_index];
  173937. col_index = 0;
  173938. for (col = width; col > 0; col--) {
  173939. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  173940. dither0[col_index]]);
  173941. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  173942. dither1[col_index]]);
  173943. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  173944. dither2[col_index]]);
  173945. *output_ptr++ = (JSAMPLE) pixcode;
  173946. col_index = (col_index + 1) & ODITHER_MASK;
  173947. }
  173948. row_index = (row_index + 1) & ODITHER_MASK;
  173949. cquantize->row_index = row_index;
  173950. }
  173951. }
  173952. METHODDEF(void)
  173953. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173954. JSAMPARRAY output_buf, int num_rows)
  173955. /* General case, with Floyd-Steinberg dithering */
  173956. {
  173957. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173958. register LOCFSERROR cur; /* current error or pixel value */
  173959. LOCFSERROR belowerr; /* error for pixel below cur */
  173960. LOCFSERROR bpreverr; /* error for below/prev col */
  173961. LOCFSERROR bnexterr; /* error for below/next col */
  173962. LOCFSERROR delta;
  173963. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173964. register JSAMPROW input_ptr;
  173965. register JSAMPROW output_ptr;
  173966. JSAMPROW colorindex_ci;
  173967. JSAMPROW colormap_ci;
  173968. int pixcode;
  173969. int nc = cinfo->out_color_components;
  173970. int dir; /* 1 for left-to-right, -1 for right-to-left */
  173971. int dirnc; /* dir * nc */
  173972. int ci;
  173973. int row;
  173974. JDIMENSION col;
  173975. JDIMENSION width = cinfo->output_width;
  173976. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173977. SHIFT_TEMPS
  173978. for (row = 0; row < num_rows; row++) {
  173979. /* Initialize output values to 0 so can process components separately */
  173980. jzero_far((void FAR *) output_buf[row],
  173981. (size_t) (width * SIZEOF(JSAMPLE)));
  173982. for (ci = 0; ci < nc; ci++) {
  173983. input_ptr = input_buf[row] + ci;
  173984. output_ptr = output_buf[row];
  173985. if (cquantize->on_odd_row) {
  173986. /* work right to left in this row */
  173987. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  173988. output_ptr += width-1;
  173989. dir = -1;
  173990. dirnc = -nc;
  173991. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  173992. } else {
  173993. /* work left to right in this row */
  173994. dir = 1;
  173995. dirnc = nc;
  173996. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  173997. }
  173998. colorindex_ci = cquantize->colorindex[ci];
  173999. colormap_ci = cquantize->sv_colormap[ci];
  174000. /* Preset error values: no error propagated to first pixel from left */
  174001. cur = 0;
  174002. /* and no error propagated to row below yet */
  174003. belowerr = bpreverr = 0;
  174004. for (col = width; col > 0; col--) {
  174005. /* cur holds the error propagated from the previous pixel on the
  174006. * current line. Add the error propagated from the previous line
  174007. * to form the complete error correction term for this pixel, and
  174008. * round the error term (which is expressed * 16) to an integer.
  174009. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174010. * for either sign of the error value.
  174011. * Note: errorptr points to *previous* column's array entry.
  174012. */
  174013. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  174014. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174015. * The maximum error is +- MAXJSAMPLE; this sets the required size
  174016. * of the range_limit array.
  174017. */
  174018. cur += GETJSAMPLE(*input_ptr);
  174019. cur = GETJSAMPLE(range_limit[cur]);
  174020. /* Select output value, accumulate into output code for this pixel */
  174021. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  174022. *output_ptr += (JSAMPLE) pixcode;
  174023. /* Compute actual representation error at this pixel */
  174024. /* Note: we can do this even though we don't have the final */
  174025. /* pixel code, because the colormap is orthogonal. */
  174026. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  174027. /* Compute error fractions to be propagated to adjacent pixels.
  174028. * Add these into the running sums, and simultaneously shift the
  174029. * next-line error sums left by 1 column.
  174030. */
  174031. bnexterr = cur;
  174032. delta = cur * 2;
  174033. cur += delta; /* form error * 3 */
  174034. errorptr[0] = (FSERROR) (bpreverr + cur);
  174035. cur += delta; /* form error * 5 */
  174036. bpreverr = belowerr + cur;
  174037. belowerr = bnexterr;
  174038. cur += delta; /* form error * 7 */
  174039. /* At this point cur contains the 7/16 error value to be propagated
  174040. * to the next pixel on the current line, and all the errors for the
  174041. * next line have been shifted over. We are therefore ready to move on.
  174042. */
  174043. input_ptr += dirnc; /* advance input ptr to next column */
  174044. output_ptr += dir; /* advance output ptr to next column */
  174045. errorptr += dir; /* advance errorptr to current column */
  174046. }
  174047. /* Post-loop cleanup: we must unload the final error value into the
  174048. * final fserrors[] entry. Note we need not unload belowerr because
  174049. * it is for the dummy column before or after the actual array.
  174050. */
  174051. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  174052. }
  174053. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  174054. }
  174055. }
  174056. /*
  174057. * Allocate workspace for Floyd-Steinberg errors.
  174058. */
  174059. LOCAL(void)
  174060. alloc_fs_workspace (j_decompress_ptr cinfo)
  174061. {
  174062. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174063. size_t arraysize;
  174064. int i;
  174065. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174066. for (i = 0; i < cinfo->out_color_components; i++) {
  174067. cquantize->fserrors[i] = (FSERRPTR)
  174068. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174069. }
  174070. }
  174071. /*
  174072. * Initialize for one-pass color quantization.
  174073. */
  174074. METHODDEF(void)
  174075. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  174076. {
  174077. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174078. size_t arraysize;
  174079. int i;
  174080. /* Install my colormap. */
  174081. cinfo->colormap = cquantize->sv_colormap;
  174082. cinfo->actual_number_of_colors = cquantize->sv_actual;
  174083. /* Initialize for desired dithering mode. */
  174084. switch (cinfo->dither_mode) {
  174085. case JDITHER_NONE:
  174086. if (cinfo->out_color_components == 3)
  174087. cquantize->pub.color_quantize = color_quantize3;
  174088. else
  174089. cquantize->pub.color_quantize = color_quantize;
  174090. break;
  174091. case JDITHER_ORDERED:
  174092. if (cinfo->out_color_components == 3)
  174093. cquantize->pub.color_quantize = quantize3_ord_dither;
  174094. else
  174095. cquantize->pub.color_quantize = quantize_ord_dither;
  174096. cquantize->row_index = 0; /* initialize state for ordered dither */
  174097. /* If user changed to ordered dither from another mode,
  174098. * we must recreate the color index table with padding.
  174099. * This will cost extra space, but probably isn't very likely.
  174100. */
  174101. if (! cquantize->is_padded)
  174102. create_colorindex(cinfo);
  174103. /* Create ordered-dither tables if we didn't already. */
  174104. if (cquantize->odither[0] == NULL)
  174105. create_odither_tables(cinfo);
  174106. break;
  174107. case JDITHER_FS:
  174108. cquantize->pub.color_quantize = quantize_fs_dither;
  174109. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  174110. /* Allocate Floyd-Steinberg workspace if didn't already. */
  174111. if (cquantize->fserrors[0] == NULL)
  174112. alloc_fs_workspace(cinfo);
  174113. /* Initialize the propagated errors to zero. */
  174114. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174115. for (i = 0; i < cinfo->out_color_components; i++)
  174116. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  174117. break;
  174118. default:
  174119. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174120. break;
  174121. }
  174122. }
  174123. /*
  174124. * Finish up at the end of the pass.
  174125. */
  174126. METHODDEF(void)
  174127. finish_pass_1_quant (j_decompress_ptr)
  174128. {
  174129. /* no work in 1-pass case */
  174130. }
  174131. /*
  174132. * Switch to a new external colormap between output passes.
  174133. * Shouldn't get to this module!
  174134. */
  174135. METHODDEF(void)
  174136. new_color_map_1_quant (j_decompress_ptr cinfo)
  174137. {
  174138. ERREXIT(cinfo, JERR_MODE_CHANGE);
  174139. }
  174140. /*
  174141. * Module initialization routine for 1-pass color quantization.
  174142. */
  174143. GLOBAL(void)
  174144. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  174145. {
  174146. my_cquantize_ptr cquantize;
  174147. cquantize = (my_cquantize_ptr)
  174148. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174149. SIZEOF(my_cquantizer));
  174150. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174151. cquantize->pub.start_pass = start_pass_1_quant;
  174152. cquantize->pub.finish_pass = finish_pass_1_quant;
  174153. cquantize->pub.new_color_map = new_color_map_1_quant;
  174154. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  174155. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  174156. /* Make sure my internal arrays won't overflow */
  174157. if (cinfo->out_color_components > MAX_Q_COMPS)
  174158. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  174159. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174160. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  174161. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  174162. /* Create the colormap and color index table. */
  174163. create_colormap(cinfo);
  174164. create_colorindex(cinfo);
  174165. /* Allocate Floyd-Steinberg workspace now if requested.
  174166. * We do this now since it is FAR storage and may affect the memory
  174167. * manager's space calculations. If the user changes to FS dither
  174168. * mode in a later pass, we will allocate the space then, and will
  174169. * possibly overrun the max_memory_to_use setting.
  174170. */
  174171. if (cinfo->dither_mode == JDITHER_FS)
  174172. alloc_fs_workspace(cinfo);
  174173. }
  174174. #endif /* QUANT_1PASS_SUPPORTED */
  174175. /*** End of inlined file: jquant1.c ***/
  174176. /*** Start of inlined file: jquant2.c ***/
  174177. #define JPEG_INTERNALS
  174178. #ifdef QUANT_2PASS_SUPPORTED
  174179. /*
  174180. * This module implements the well-known Heckbert paradigm for color
  174181. * quantization. Most of the ideas used here can be traced back to
  174182. * Heckbert's seminal paper
  174183. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  174184. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  174185. *
  174186. * In the first pass over the image, we accumulate a histogram showing the
  174187. * usage count of each possible color. To keep the histogram to a reasonable
  174188. * size, we reduce the precision of the input; typical practice is to retain
  174189. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  174190. * in the same histogram cell.
  174191. *
  174192. * Next, the color-selection step begins with a box representing the whole
  174193. * color space, and repeatedly splits the "largest" remaining box until we
  174194. * have as many boxes as desired colors. Then the mean color in each
  174195. * remaining box becomes one of the possible output colors.
  174196. *
  174197. * The second pass over the image maps each input pixel to the closest output
  174198. * color (optionally after applying a Floyd-Steinberg dithering correction).
  174199. * This mapping is logically trivial, but making it go fast enough requires
  174200. * considerable care.
  174201. *
  174202. * Heckbert-style quantizers vary a good deal in their policies for choosing
  174203. * the "largest" box and deciding where to cut it. The particular policies
  174204. * used here have proved out well in experimental comparisons, but better ones
  174205. * may yet be found.
  174206. *
  174207. * In earlier versions of the IJG code, this module quantized in YCbCr color
  174208. * space, processing the raw upsampled data without a color conversion step.
  174209. * This allowed the color conversion math to be done only once per colormap
  174210. * entry, not once per pixel. However, that optimization precluded other
  174211. * useful optimizations (such as merging color conversion with upsampling)
  174212. * and it also interfered with desired capabilities such as quantizing to an
  174213. * externally-supplied colormap. We have therefore abandoned that approach.
  174214. * The present code works in the post-conversion color space, typically RGB.
  174215. *
  174216. * To improve the visual quality of the results, we actually work in scaled
  174217. * RGB space, giving G distances more weight than R, and R in turn more than
  174218. * B. To do everything in integer math, we must use integer scale factors.
  174219. * The 2/3/1 scale factors used here correspond loosely to the relative
  174220. * weights of the colors in the NTSC grayscale equation.
  174221. * If you want to use this code to quantize a non-RGB color space, you'll
  174222. * probably need to change these scale factors.
  174223. */
  174224. #define R_SCALE 2 /* scale R distances by this much */
  174225. #define G_SCALE 3 /* scale G distances by this much */
  174226. #define B_SCALE 1 /* and B by this much */
  174227. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  174228. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  174229. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  174230. * you'll get compile errors until you extend this logic. In that case
  174231. * you'll probably want to tweak the histogram sizes too.
  174232. */
  174233. #if RGB_RED == 0
  174234. #define C0_SCALE R_SCALE
  174235. #endif
  174236. #if RGB_BLUE == 0
  174237. #define C0_SCALE B_SCALE
  174238. #endif
  174239. #if RGB_GREEN == 1
  174240. #define C1_SCALE G_SCALE
  174241. #endif
  174242. #if RGB_RED == 2
  174243. #define C2_SCALE R_SCALE
  174244. #endif
  174245. #if RGB_BLUE == 2
  174246. #define C2_SCALE B_SCALE
  174247. #endif
  174248. /*
  174249. * First we have the histogram data structure and routines for creating it.
  174250. *
  174251. * The number of bits of precision can be adjusted by changing these symbols.
  174252. * We recommend keeping 6 bits for G and 5 each for R and B.
  174253. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  174254. * better results; if you are short of memory, 5 bits all around will save
  174255. * some space but degrade the results.
  174256. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  174257. * (preferably unsigned long) for each cell. In practice this is overkill;
  174258. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  174259. * and clamping those that do overflow to the maximum value will give close-
  174260. * enough results. This reduces the recommended histogram size from 256Kb
  174261. * to 128Kb, which is a useful savings on PC-class machines.
  174262. * (In the second pass the histogram space is re-used for pixel mapping data;
  174263. * in that capacity, each cell must be able to store zero to the number of
  174264. * desired colors. 16 bits/cell is plenty for that too.)
  174265. * Since the JPEG code is intended to run in small memory model on 80x86
  174266. * machines, we can't just allocate the histogram in one chunk. Instead
  174267. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  174268. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  174269. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  174270. * on 80x86 machines, the pointer row is in near memory but the actual
  174271. * arrays are in far memory (same arrangement as we use for image arrays).
  174272. */
  174273. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  174274. /* These will do the right thing for either R,G,B or B,G,R color order,
  174275. * but you may not like the results for other color orders.
  174276. */
  174277. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  174278. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  174279. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  174280. /* Number of elements along histogram axes. */
  174281. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  174282. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  174283. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  174284. /* These are the amounts to shift an input value to get a histogram index. */
  174285. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  174286. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  174287. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  174288. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  174289. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  174290. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  174291. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  174292. typedef hist2d * hist3d; /* type for top-level pointer */
  174293. /* Declarations for Floyd-Steinberg dithering.
  174294. *
  174295. * Errors are accumulated into the array fserrors[], at a resolution of
  174296. * 1/16th of a pixel count. The error at a given pixel is propagated
  174297. * to its not-yet-processed neighbors using the standard F-S fractions,
  174298. * ... (here) 7/16
  174299. * 3/16 5/16 1/16
  174300. * We work left-to-right on even rows, right-to-left on odd rows.
  174301. *
  174302. * We can get away with a single array (holding one row's worth of errors)
  174303. * by using it to store the current row's errors at pixel columns not yet
  174304. * processed, but the next row's errors at columns already processed. We
  174305. * need only a few extra variables to hold the errors immediately around the
  174306. * current column. (If we are lucky, those variables are in registers, but
  174307. * even if not, they're probably cheaper to access than array elements are.)
  174308. *
  174309. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  174310. * each end saves us from special-casing the first and last pixels.
  174311. * Each entry is three values long, one value for each color component.
  174312. *
  174313. * Note: on a wide image, we might not have enough room in a PC's near data
  174314. * segment to hold the error array; so it is allocated with alloc_large.
  174315. */
  174316. #if BITS_IN_JSAMPLE == 8
  174317. typedef INT16 FSERROR; /* 16 bits should be enough */
  174318. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  174319. #else
  174320. typedef INT32 FSERROR; /* may need more than 16 bits */
  174321. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  174322. #endif
  174323. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  174324. /* Private subobject */
  174325. typedef struct {
  174326. struct jpeg_color_quantizer pub; /* public fields */
  174327. /* Space for the eventually created colormap is stashed here */
  174328. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  174329. int desired; /* desired # of colors = size of colormap */
  174330. /* Variables for accumulating image statistics */
  174331. hist3d histogram; /* pointer to the histogram */
  174332. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  174333. /* Variables for Floyd-Steinberg dithering */
  174334. FSERRPTR fserrors; /* accumulated errors */
  174335. boolean on_odd_row; /* flag to remember which row we are on */
  174336. int * error_limiter; /* table for clamping the applied error */
  174337. } my_cquantizer2;
  174338. typedef my_cquantizer2 * my_cquantize_ptr2;
  174339. /*
  174340. * Prescan some rows of pixels.
  174341. * In this module the prescan simply updates the histogram, which has been
  174342. * initialized to zeroes by start_pass.
  174343. * An output_buf parameter is required by the method signature, but no data
  174344. * is actually output (in fact the buffer controller is probably passing a
  174345. * NULL pointer).
  174346. */
  174347. METHODDEF(void)
  174348. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174349. JSAMPARRAY, int num_rows)
  174350. {
  174351. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174352. register JSAMPROW ptr;
  174353. register histptr histp;
  174354. register hist3d histogram = cquantize->histogram;
  174355. int row;
  174356. JDIMENSION col;
  174357. JDIMENSION width = cinfo->output_width;
  174358. for (row = 0; row < num_rows; row++) {
  174359. ptr = input_buf[row];
  174360. for (col = width; col > 0; col--) {
  174361. /* get pixel value and index into the histogram */
  174362. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  174363. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  174364. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  174365. /* increment, check for overflow and undo increment if so. */
  174366. if (++(*histp) <= 0)
  174367. (*histp)--;
  174368. ptr += 3;
  174369. }
  174370. }
  174371. }
  174372. /*
  174373. * Next we have the really interesting routines: selection of a colormap
  174374. * given the completed histogram.
  174375. * These routines work with a list of "boxes", each representing a rectangular
  174376. * subset of the input color space (to histogram precision).
  174377. */
  174378. typedef struct {
  174379. /* The bounds of the box (inclusive); expressed as histogram indexes */
  174380. int c0min, c0max;
  174381. int c1min, c1max;
  174382. int c2min, c2max;
  174383. /* The volume (actually 2-norm) of the box */
  174384. INT32 volume;
  174385. /* The number of nonzero histogram cells within this box */
  174386. long colorcount;
  174387. } box;
  174388. typedef box * boxptr;
  174389. LOCAL(boxptr)
  174390. find_biggest_color_pop (boxptr boxlist, int numboxes)
  174391. /* Find the splittable box with the largest color population */
  174392. /* Returns NULL if no splittable boxes remain */
  174393. {
  174394. register boxptr boxp;
  174395. register int i;
  174396. register long maxc = 0;
  174397. boxptr which = NULL;
  174398. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  174399. if (boxp->colorcount > maxc && boxp->volume > 0) {
  174400. which = boxp;
  174401. maxc = boxp->colorcount;
  174402. }
  174403. }
  174404. return which;
  174405. }
  174406. LOCAL(boxptr)
  174407. find_biggest_volume (boxptr boxlist, int numboxes)
  174408. /* Find the splittable box with the largest (scaled) volume */
  174409. /* Returns NULL if no splittable boxes remain */
  174410. {
  174411. register boxptr boxp;
  174412. register int i;
  174413. register INT32 maxv = 0;
  174414. boxptr which = NULL;
  174415. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  174416. if (boxp->volume > maxv) {
  174417. which = boxp;
  174418. maxv = boxp->volume;
  174419. }
  174420. }
  174421. return which;
  174422. }
  174423. LOCAL(void)
  174424. update_box (j_decompress_ptr cinfo, boxptr boxp)
  174425. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  174426. /* and recompute its volume and population */
  174427. {
  174428. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174429. hist3d histogram = cquantize->histogram;
  174430. histptr histp;
  174431. int c0,c1,c2;
  174432. int c0min,c0max,c1min,c1max,c2min,c2max;
  174433. INT32 dist0,dist1,dist2;
  174434. long ccount;
  174435. c0min = boxp->c0min; c0max = boxp->c0max;
  174436. c1min = boxp->c1min; c1max = boxp->c1max;
  174437. c2min = boxp->c2min; c2max = boxp->c2max;
  174438. if (c0max > c0min)
  174439. for (c0 = c0min; c0 <= c0max; c0++)
  174440. for (c1 = c1min; c1 <= c1max; c1++) {
  174441. histp = & histogram[c0][c1][c2min];
  174442. for (c2 = c2min; c2 <= c2max; c2++)
  174443. if (*histp++ != 0) {
  174444. boxp->c0min = c0min = c0;
  174445. goto have_c0min;
  174446. }
  174447. }
  174448. have_c0min:
  174449. if (c0max > c0min)
  174450. for (c0 = c0max; c0 >= c0min; c0--)
  174451. for (c1 = c1min; c1 <= c1max; c1++) {
  174452. histp = & histogram[c0][c1][c2min];
  174453. for (c2 = c2min; c2 <= c2max; c2++)
  174454. if (*histp++ != 0) {
  174455. boxp->c0max = c0max = c0;
  174456. goto have_c0max;
  174457. }
  174458. }
  174459. have_c0max:
  174460. if (c1max > c1min)
  174461. for (c1 = c1min; c1 <= c1max; c1++)
  174462. for (c0 = c0min; c0 <= c0max; c0++) {
  174463. histp = & histogram[c0][c1][c2min];
  174464. for (c2 = c2min; c2 <= c2max; c2++)
  174465. if (*histp++ != 0) {
  174466. boxp->c1min = c1min = c1;
  174467. goto have_c1min;
  174468. }
  174469. }
  174470. have_c1min:
  174471. if (c1max > c1min)
  174472. for (c1 = c1max; c1 >= c1min; c1--)
  174473. for (c0 = c0min; c0 <= c0max; c0++) {
  174474. histp = & histogram[c0][c1][c2min];
  174475. for (c2 = c2min; c2 <= c2max; c2++)
  174476. if (*histp++ != 0) {
  174477. boxp->c1max = c1max = c1;
  174478. goto have_c1max;
  174479. }
  174480. }
  174481. have_c1max:
  174482. if (c2max > c2min)
  174483. for (c2 = c2min; c2 <= c2max; c2++)
  174484. for (c0 = c0min; c0 <= c0max; c0++) {
  174485. histp = & histogram[c0][c1min][c2];
  174486. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  174487. if (*histp != 0) {
  174488. boxp->c2min = c2min = c2;
  174489. goto have_c2min;
  174490. }
  174491. }
  174492. have_c2min:
  174493. if (c2max > c2min)
  174494. for (c2 = c2max; c2 >= c2min; c2--)
  174495. for (c0 = c0min; c0 <= c0max; c0++) {
  174496. histp = & histogram[c0][c1min][c2];
  174497. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  174498. if (*histp != 0) {
  174499. boxp->c2max = c2max = c2;
  174500. goto have_c2max;
  174501. }
  174502. }
  174503. have_c2max:
  174504. /* Update box volume.
  174505. * We use 2-norm rather than real volume here; this biases the method
  174506. * against making long narrow boxes, and it has the side benefit that
  174507. * a box is splittable iff norm > 0.
  174508. * Since the differences are expressed in histogram-cell units,
  174509. * we have to shift back to JSAMPLE units to get consistent distances;
  174510. * after which, we scale according to the selected distance scale factors.
  174511. */
  174512. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  174513. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  174514. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  174515. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  174516. /* Now scan remaining volume of box and compute population */
  174517. ccount = 0;
  174518. for (c0 = c0min; c0 <= c0max; c0++)
  174519. for (c1 = c1min; c1 <= c1max; c1++) {
  174520. histp = & histogram[c0][c1][c2min];
  174521. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  174522. if (*histp != 0) {
  174523. ccount++;
  174524. }
  174525. }
  174526. boxp->colorcount = ccount;
  174527. }
  174528. LOCAL(int)
  174529. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  174530. int desired_colors)
  174531. /* Repeatedly select and split the largest box until we have enough boxes */
  174532. {
  174533. int n,lb;
  174534. int c0,c1,c2,cmax;
  174535. register boxptr b1,b2;
  174536. while (numboxes < desired_colors) {
  174537. /* Select box to split.
  174538. * Current algorithm: by population for first half, then by volume.
  174539. */
  174540. if (numboxes*2 <= desired_colors) {
  174541. b1 = find_biggest_color_pop(boxlist, numboxes);
  174542. } else {
  174543. b1 = find_biggest_volume(boxlist, numboxes);
  174544. }
  174545. if (b1 == NULL) /* no splittable boxes left! */
  174546. break;
  174547. b2 = &boxlist[numboxes]; /* where new box will go */
  174548. /* Copy the color bounds to the new box. */
  174549. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  174550. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  174551. /* Choose which axis to split the box on.
  174552. * Current algorithm: longest scaled axis.
  174553. * See notes in update_box about scaling distances.
  174554. */
  174555. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  174556. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  174557. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  174558. /* We want to break any ties in favor of green, then red, blue last.
  174559. * This code does the right thing for R,G,B or B,G,R color orders only.
  174560. */
  174561. #if RGB_RED == 0
  174562. cmax = c1; n = 1;
  174563. if (c0 > cmax) { cmax = c0; n = 0; }
  174564. if (c2 > cmax) { n = 2; }
  174565. #else
  174566. cmax = c1; n = 1;
  174567. if (c2 > cmax) { cmax = c2; n = 2; }
  174568. if (c0 > cmax) { n = 0; }
  174569. #endif
  174570. /* Choose split point along selected axis, and update box bounds.
  174571. * Current algorithm: split at halfway point.
  174572. * (Since the box has been shrunk to minimum volume,
  174573. * any split will produce two nonempty subboxes.)
  174574. * Note that lb value is max for lower box, so must be < old max.
  174575. */
  174576. switch (n) {
  174577. case 0:
  174578. lb = (b1->c0max + b1->c0min) / 2;
  174579. b1->c0max = lb;
  174580. b2->c0min = lb+1;
  174581. break;
  174582. case 1:
  174583. lb = (b1->c1max + b1->c1min) / 2;
  174584. b1->c1max = lb;
  174585. b2->c1min = lb+1;
  174586. break;
  174587. case 2:
  174588. lb = (b1->c2max + b1->c2min) / 2;
  174589. b1->c2max = lb;
  174590. b2->c2min = lb+1;
  174591. break;
  174592. }
  174593. /* Update stats for boxes */
  174594. update_box(cinfo, b1);
  174595. update_box(cinfo, b2);
  174596. numboxes++;
  174597. }
  174598. return numboxes;
  174599. }
  174600. LOCAL(void)
  174601. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  174602. /* Compute representative color for a box, put it in colormap[icolor] */
  174603. {
  174604. /* Current algorithm: mean weighted by pixels (not colors) */
  174605. /* Note it is important to get the rounding correct! */
  174606. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174607. hist3d histogram = cquantize->histogram;
  174608. histptr histp;
  174609. int c0,c1,c2;
  174610. int c0min,c0max,c1min,c1max,c2min,c2max;
  174611. long count;
  174612. long total = 0;
  174613. long c0total = 0;
  174614. long c1total = 0;
  174615. long c2total = 0;
  174616. c0min = boxp->c0min; c0max = boxp->c0max;
  174617. c1min = boxp->c1min; c1max = boxp->c1max;
  174618. c2min = boxp->c2min; c2max = boxp->c2max;
  174619. for (c0 = c0min; c0 <= c0max; c0++)
  174620. for (c1 = c1min; c1 <= c1max; c1++) {
  174621. histp = & histogram[c0][c1][c2min];
  174622. for (c2 = c2min; c2 <= c2max; c2++) {
  174623. if ((count = *histp++) != 0) {
  174624. total += count;
  174625. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  174626. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  174627. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  174628. }
  174629. }
  174630. }
  174631. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  174632. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  174633. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  174634. }
  174635. LOCAL(void)
  174636. select_colors (j_decompress_ptr cinfo, int desired_colors)
  174637. /* Master routine for color selection */
  174638. {
  174639. boxptr boxlist;
  174640. int numboxes;
  174641. int i;
  174642. /* Allocate workspace for box list */
  174643. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  174644. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  174645. /* Initialize one box containing whole space */
  174646. numboxes = 1;
  174647. boxlist[0].c0min = 0;
  174648. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  174649. boxlist[0].c1min = 0;
  174650. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  174651. boxlist[0].c2min = 0;
  174652. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  174653. /* Shrink it to actually-used volume and set its statistics */
  174654. update_box(cinfo, & boxlist[0]);
  174655. /* Perform median-cut to produce final box list */
  174656. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  174657. /* Compute the representative color for each box, fill colormap */
  174658. for (i = 0; i < numboxes; i++)
  174659. compute_color(cinfo, & boxlist[i], i);
  174660. cinfo->actual_number_of_colors = numboxes;
  174661. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  174662. }
  174663. /*
  174664. * These routines are concerned with the time-critical task of mapping input
  174665. * colors to the nearest color in the selected colormap.
  174666. *
  174667. * We re-use the histogram space as an "inverse color map", essentially a
  174668. * cache for the results of nearest-color searches. All colors within a
  174669. * histogram cell will be mapped to the same colormap entry, namely the one
  174670. * closest to the cell's center. This may not be quite the closest entry to
  174671. * the actual input color, but it's almost as good. A zero in the cache
  174672. * indicates we haven't found the nearest color for that cell yet; the array
  174673. * is cleared to zeroes before starting the mapping pass. When we find the
  174674. * nearest color for a cell, its colormap index plus one is recorded in the
  174675. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  174676. * when they need to use an unfilled entry in the cache.
  174677. *
  174678. * Our method of efficiently finding nearest colors is based on the "locally
  174679. * sorted search" idea described by Heckbert and on the incremental distance
  174680. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  174681. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  174682. * the distances from a given colormap entry to each cell of the histogram can
  174683. * be computed quickly using an incremental method: the differences between
  174684. * distances to adjacent cells themselves differ by a constant. This allows a
  174685. * fairly fast implementation of the "brute force" approach of computing the
  174686. * distance from every colormap entry to every histogram cell. Unfortunately,
  174687. * it needs a work array to hold the best-distance-so-far for each histogram
  174688. * cell (because the inner loop has to be over cells, not colormap entries).
  174689. * The work array elements have to be INT32s, so the work array would need
  174690. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  174691. *
  174692. * To get around these problems, we apply Thomas' method to compute the
  174693. * nearest colors for only the cells within a small subbox of the histogram.
  174694. * The work array need be only as big as the subbox, so the memory usage
  174695. * problem is solved. Furthermore, we need not fill subboxes that are never
  174696. * referenced in pass2; many images use only part of the color gamut, so a
  174697. * fair amount of work is saved. An additional advantage of this
  174698. * approach is that we can apply Heckbert's locality criterion to quickly
  174699. * eliminate colormap entries that are far away from the subbox; typically
  174700. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  174701. * and we need not compute their distances to individual cells in the subbox.
  174702. * The speed of this approach is heavily influenced by the subbox size: too
  174703. * small means too much overhead, too big loses because Heckbert's criterion
  174704. * can't eliminate as many colormap entries. Empirically the best subbox
  174705. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  174706. *
  174707. * Thomas' article also describes a refined method which is asymptotically
  174708. * faster than the brute-force method, but it is also far more complex and
  174709. * cannot efficiently be applied to small subboxes. It is therefore not
  174710. * useful for programs intended to be portable to DOS machines. On machines
  174711. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  174712. * refined method might be faster than the present code --- but then again,
  174713. * it might not be any faster, and it's certainly more complicated.
  174714. */
  174715. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  174716. #define BOX_C0_LOG (HIST_C0_BITS-3)
  174717. #define BOX_C1_LOG (HIST_C1_BITS-3)
  174718. #define BOX_C2_LOG (HIST_C2_BITS-3)
  174719. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  174720. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  174721. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  174722. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  174723. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  174724. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  174725. /*
  174726. * The next three routines implement inverse colormap filling. They could
  174727. * all be folded into one big routine, but splitting them up this way saves
  174728. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  174729. * and may allow some compilers to produce better code by registerizing more
  174730. * inner-loop variables.
  174731. */
  174732. LOCAL(int)
  174733. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174734. JSAMPLE colorlist[])
  174735. /* Locate the colormap entries close enough to an update box to be candidates
  174736. * for the nearest entry to some cell(s) in the update box. The update box
  174737. * is specified by the center coordinates of its first cell. The number of
  174738. * candidate colormap entries is returned, and their colormap indexes are
  174739. * placed in colorlist[].
  174740. * This routine uses Heckbert's "locally sorted search" criterion to select
  174741. * the colors that need further consideration.
  174742. */
  174743. {
  174744. int numcolors = cinfo->actual_number_of_colors;
  174745. int maxc0, maxc1, maxc2;
  174746. int centerc0, centerc1, centerc2;
  174747. int i, x, ncolors;
  174748. INT32 minmaxdist, min_dist, max_dist, tdist;
  174749. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  174750. /* Compute true coordinates of update box's upper corner and center.
  174751. * Actually we compute the coordinates of the center of the upper-corner
  174752. * histogram cell, which are the upper bounds of the volume we care about.
  174753. * Note that since ">>" rounds down, the "center" values may be closer to
  174754. * min than to max; hence comparisons to them must be "<=", not "<".
  174755. */
  174756. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  174757. centerc0 = (minc0 + maxc0) >> 1;
  174758. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  174759. centerc1 = (minc1 + maxc1) >> 1;
  174760. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  174761. centerc2 = (minc2 + maxc2) >> 1;
  174762. /* For each color in colormap, find:
  174763. * 1. its minimum squared-distance to any point in the update box
  174764. * (zero if color is within update box);
  174765. * 2. its maximum squared-distance to any point in the update box.
  174766. * Both of these can be found by considering only the corners of the box.
  174767. * We save the minimum distance for each color in mindist[];
  174768. * only the smallest maximum distance is of interest.
  174769. */
  174770. minmaxdist = 0x7FFFFFFFL;
  174771. for (i = 0; i < numcolors; i++) {
  174772. /* We compute the squared-c0-distance term, then add in the other two. */
  174773. x = GETJSAMPLE(cinfo->colormap[0][i]);
  174774. if (x < minc0) {
  174775. tdist = (x - minc0) * C0_SCALE;
  174776. min_dist = tdist*tdist;
  174777. tdist = (x - maxc0) * C0_SCALE;
  174778. max_dist = tdist*tdist;
  174779. } else if (x > maxc0) {
  174780. tdist = (x - maxc0) * C0_SCALE;
  174781. min_dist = tdist*tdist;
  174782. tdist = (x - minc0) * C0_SCALE;
  174783. max_dist = tdist*tdist;
  174784. } else {
  174785. /* within cell range so no contribution to min_dist */
  174786. min_dist = 0;
  174787. if (x <= centerc0) {
  174788. tdist = (x - maxc0) * C0_SCALE;
  174789. max_dist = tdist*tdist;
  174790. } else {
  174791. tdist = (x - minc0) * C0_SCALE;
  174792. max_dist = tdist*tdist;
  174793. }
  174794. }
  174795. x = GETJSAMPLE(cinfo->colormap[1][i]);
  174796. if (x < minc1) {
  174797. tdist = (x - minc1) * C1_SCALE;
  174798. min_dist += tdist*tdist;
  174799. tdist = (x - maxc1) * C1_SCALE;
  174800. max_dist += tdist*tdist;
  174801. } else if (x > maxc1) {
  174802. tdist = (x - maxc1) * C1_SCALE;
  174803. min_dist += tdist*tdist;
  174804. tdist = (x - minc1) * C1_SCALE;
  174805. max_dist += tdist*tdist;
  174806. } else {
  174807. /* within cell range so no contribution to min_dist */
  174808. if (x <= centerc1) {
  174809. tdist = (x - maxc1) * C1_SCALE;
  174810. max_dist += tdist*tdist;
  174811. } else {
  174812. tdist = (x - minc1) * C1_SCALE;
  174813. max_dist += tdist*tdist;
  174814. }
  174815. }
  174816. x = GETJSAMPLE(cinfo->colormap[2][i]);
  174817. if (x < minc2) {
  174818. tdist = (x - minc2) * C2_SCALE;
  174819. min_dist += tdist*tdist;
  174820. tdist = (x - maxc2) * C2_SCALE;
  174821. max_dist += tdist*tdist;
  174822. } else if (x > maxc2) {
  174823. tdist = (x - maxc2) * C2_SCALE;
  174824. min_dist += tdist*tdist;
  174825. tdist = (x - minc2) * C2_SCALE;
  174826. max_dist += tdist*tdist;
  174827. } else {
  174828. /* within cell range so no contribution to min_dist */
  174829. if (x <= centerc2) {
  174830. tdist = (x - maxc2) * C2_SCALE;
  174831. max_dist += tdist*tdist;
  174832. } else {
  174833. tdist = (x - minc2) * C2_SCALE;
  174834. max_dist += tdist*tdist;
  174835. }
  174836. }
  174837. mindist[i] = min_dist; /* save away the results */
  174838. if (max_dist < minmaxdist)
  174839. minmaxdist = max_dist;
  174840. }
  174841. /* Now we know that no cell in the update box is more than minmaxdist
  174842. * away from some colormap entry. Therefore, only colors that are
  174843. * within minmaxdist of some part of the box need be considered.
  174844. */
  174845. ncolors = 0;
  174846. for (i = 0; i < numcolors; i++) {
  174847. if (mindist[i] <= minmaxdist)
  174848. colorlist[ncolors++] = (JSAMPLE) i;
  174849. }
  174850. return ncolors;
  174851. }
  174852. LOCAL(void)
  174853. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174854. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  174855. /* Find the closest colormap entry for each cell in the update box,
  174856. * given the list of candidate colors prepared by find_nearby_colors.
  174857. * Return the indexes of the closest entries in the bestcolor[] array.
  174858. * This routine uses Thomas' incremental distance calculation method to
  174859. * find the distance from a colormap entry to successive cells in the box.
  174860. */
  174861. {
  174862. int ic0, ic1, ic2;
  174863. int i, icolor;
  174864. register INT32 * bptr; /* pointer into bestdist[] array */
  174865. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174866. INT32 dist0, dist1; /* initial distance values */
  174867. register INT32 dist2; /* current distance in inner loop */
  174868. INT32 xx0, xx1; /* distance increments */
  174869. register INT32 xx2;
  174870. INT32 inc0, inc1, inc2; /* initial values for increments */
  174871. /* This array holds the distance to the nearest-so-far color for each cell */
  174872. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174873. /* Initialize best-distance for each cell of the update box */
  174874. bptr = bestdist;
  174875. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  174876. *bptr++ = 0x7FFFFFFFL;
  174877. /* For each color selected by find_nearby_colors,
  174878. * compute its distance to the center of each cell in the box.
  174879. * If that's less than best-so-far, update best distance and color number.
  174880. */
  174881. /* Nominal steps between cell centers ("x" in Thomas article) */
  174882. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  174883. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  174884. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  174885. for (i = 0; i < numcolors; i++) {
  174886. icolor = GETJSAMPLE(colorlist[i]);
  174887. /* Compute (square of) distance from minc0/c1/c2 to this color */
  174888. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  174889. dist0 = inc0*inc0;
  174890. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  174891. dist0 += inc1*inc1;
  174892. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  174893. dist0 += inc2*inc2;
  174894. /* Form the initial difference increments */
  174895. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  174896. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  174897. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  174898. /* Now loop over all cells in box, updating distance per Thomas method */
  174899. bptr = bestdist;
  174900. cptr = bestcolor;
  174901. xx0 = inc0;
  174902. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  174903. dist1 = dist0;
  174904. xx1 = inc1;
  174905. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  174906. dist2 = dist1;
  174907. xx2 = inc2;
  174908. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  174909. if (dist2 < *bptr) {
  174910. *bptr = dist2;
  174911. *cptr = (JSAMPLE) icolor;
  174912. }
  174913. dist2 += xx2;
  174914. xx2 += 2 * STEP_C2 * STEP_C2;
  174915. bptr++;
  174916. cptr++;
  174917. }
  174918. dist1 += xx1;
  174919. xx1 += 2 * STEP_C1 * STEP_C1;
  174920. }
  174921. dist0 += xx0;
  174922. xx0 += 2 * STEP_C0 * STEP_C0;
  174923. }
  174924. }
  174925. }
  174926. LOCAL(void)
  174927. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  174928. /* Fill the inverse-colormap entries in the update box that contains */
  174929. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  174930. /* we can fill as many others as we wish.) */
  174931. {
  174932. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174933. hist3d histogram = cquantize->histogram;
  174934. int minc0, minc1, minc2; /* lower left corner of update box */
  174935. int ic0, ic1, ic2;
  174936. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174937. register histptr cachep; /* pointer into main cache array */
  174938. /* This array lists the candidate colormap indexes. */
  174939. JSAMPLE colorlist[MAXNUMCOLORS];
  174940. int numcolors; /* number of candidate colors */
  174941. /* This array holds the actually closest colormap index for each cell. */
  174942. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174943. /* Convert cell coordinates to update box ID */
  174944. c0 >>= BOX_C0_LOG;
  174945. c1 >>= BOX_C1_LOG;
  174946. c2 >>= BOX_C2_LOG;
  174947. /* Compute true coordinates of update box's origin corner.
  174948. * Actually we compute the coordinates of the center of the corner
  174949. * histogram cell, which are the lower bounds of the volume we care about.
  174950. */
  174951. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  174952. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  174953. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  174954. /* Determine which colormap entries are close enough to be candidates
  174955. * for the nearest entry to some cell in the update box.
  174956. */
  174957. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  174958. /* Determine the actually nearest colors. */
  174959. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  174960. bestcolor);
  174961. /* Save the best color numbers (plus 1) in the main cache array */
  174962. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  174963. c1 <<= BOX_C1_LOG;
  174964. c2 <<= BOX_C2_LOG;
  174965. cptr = bestcolor;
  174966. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  174967. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  174968. cachep = & histogram[c0+ic0][c1+ic1][c2];
  174969. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  174970. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  174971. }
  174972. }
  174973. }
  174974. }
  174975. /*
  174976. * Map some rows of pixels to the output colormapped representation.
  174977. */
  174978. METHODDEF(void)
  174979. pass2_no_dither (j_decompress_ptr cinfo,
  174980. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174981. /* This version performs no dithering */
  174982. {
  174983. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174984. hist3d histogram = cquantize->histogram;
  174985. register JSAMPROW inptr, outptr;
  174986. register histptr cachep;
  174987. register int c0, c1, c2;
  174988. int row;
  174989. JDIMENSION col;
  174990. JDIMENSION width = cinfo->output_width;
  174991. for (row = 0; row < num_rows; row++) {
  174992. inptr = input_buf[row];
  174993. outptr = output_buf[row];
  174994. for (col = width; col > 0; col--) {
  174995. /* get pixel value and index into the cache */
  174996. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  174997. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  174998. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  174999. cachep = & histogram[c0][c1][c2];
  175000. /* If we have not seen this color before, find nearest colormap entry */
  175001. /* and update the cache */
  175002. if (*cachep == 0)
  175003. fill_inverse_cmap(cinfo, c0,c1,c2);
  175004. /* Now emit the colormap index for this cell */
  175005. *outptr++ = (JSAMPLE) (*cachep - 1);
  175006. }
  175007. }
  175008. }
  175009. METHODDEF(void)
  175010. pass2_fs_dither (j_decompress_ptr cinfo,
  175011. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  175012. /* This version performs Floyd-Steinberg dithering */
  175013. {
  175014. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175015. hist3d histogram = cquantize->histogram;
  175016. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  175017. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  175018. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  175019. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  175020. JSAMPROW inptr; /* => current input pixel */
  175021. JSAMPROW outptr; /* => current output pixel */
  175022. histptr cachep;
  175023. int dir; /* +1 or -1 depending on direction */
  175024. int dir3; /* 3*dir, for advancing inptr & errorptr */
  175025. int row;
  175026. JDIMENSION col;
  175027. JDIMENSION width = cinfo->output_width;
  175028. JSAMPLE *range_limit = cinfo->sample_range_limit;
  175029. int *error_limit = cquantize->error_limiter;
  175030. JSAMPROW colormap0 = cinfo->colormap[0];
  175031. JSAMPROW colormap1 = cinfo->colormap[1];
  175032. JSAMPROW colormap2 = cinfo->colormap[2];
  175033. SHIFT_TEMPS
  175034. for (row = 0; row < num_rows; row++) {
  175035. inptr = input_buf[row];
  175036. outptr = output_buf[row];
  175037. if (cquantize->on_odd_row) {
  175038. /* work right to left in this row */
  175039. inptr += (width-1) * 3; /* so point to rightmost pixel */
  175040. outptr += width-1;
  175041. dir = -1;
  175042. dir3 = -3;
  175043. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  175044. cquantize->on_odd_row = FALSE; /* flip for next time */
  175045. } else {
  175046. /* work left to right in this row */
  175047. dir = 1;
  175048. dir3 = 3;
  175049. errorptr = cquantize->fserrors; /* => entry before first real column */
  175050. cquantize->on_odd_row = TRUE; /* flip for next time */
  175051. }
  175052. /* Preset error values: no error propagated to first pixel from left */
  175053. cur0 = cur1 = cur2 = 0;
  175054. /* and no error propagated to row below yet */
  175055. belowerr0 = belowerr1 = belowerr2 = 0;
  175056. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  175057. for (col = width; col > 0; col--) {
  175058. /* curN holds the error propagated from the previous pixel on the
  175059. * current line. Add the error propagated from the previous line
  175060. * to form the complete error correction term for this pixel, and
  175061. * round the error term (which is expressed * 16) to an integer.
  175062. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  175063. * for either sign of the error value.
  175064. * Note: errorptr points to *previous* column's array entry.
  175065. */
  175066. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  175067. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  175068. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  175069. /* Limit the error using transfer function set by init_error_limit.
  175070. * See comments with init_error_limit for rationale.
  175071. */
  175072. cur0 = error_limit[cur0];
  175073. cur1 = error_limit[cur1];
  175074. cur2 = error_limit[cur2];
  175075. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  175076. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  175077. * this sets the required size of the range_limit array.
  175078. */
  175079. cur0 += GETJSAMPLE(inptr[0]);
  175080. cur1 += GETJSAMPLE(inptr[1]);
  175081. cur2 += GETJSAMPLE(inptr[2]);
  175082. cur0 = GETJSAMPLE(range_limit[cur0]);
  175083. cur1 = GETJSAMPLE(range_limit[cur1]);
  175084. cur2 = GETJSAMPLE(range_limit[cur2]);
  175085. /* Index into the cache with adjusted pixel value */
  175086. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  175087. /* If we have not seen this color before, find nearest colormap */
  175088. /* entry and update the cache */
  175089. if (*cachep == 0)
  175090. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  175091. /* Now emit the colormap index for this cell */
  175092. { register int pixcode = *cachep - 1;
  175093. *outptr = (JSAMPLE) pixcode;
  175094. /* Compute representation error for this pixel */
  175095. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  175096. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  175097. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  175098. }
  175099. /* Compute error fractions to be propagated to adjacent pixels.
  175100. * Add these into the running sums, and simultaneously shift the
  175101. * next-line error sums left by 1 column.
  175102. */
  175103. { register LOCFSERROR bnexterr, delta;
  175104. bnexterr = cur0; /* Process component 0 */
  175105. delta = cur0 * 2;
  175106. cur0 += delta; /* form error * 3 */
  175107. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  175108. cur0 += delta; /* form error * 5 */
  175109. bpreverr0 = belowerr0 + cur0;
  175110. belowerr0 = bnexterr;
  175111. cur0 += delta; /* form error * 7 */
  175112. bnexterr = cur1; /* Process component 1 */
  175113. delta = cur1 * 2;
  175114. cur1 += delta; /* form error * 3 */
  175115. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  175116. cur1 += delta; /* form error * 5 */
  175117. bpreverr1 = belowerr1 + cur1;
  175118. belowerr1 = bnexterr;
  175119. cur1 += delta; /* form error * 7 */
  175120. bnexterr = cur2; /* Process component 2 */
  175121. delta = cur2 * 2;
  175122. cur2 += delta; /* form error * 3 */
  175123. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  175124. cur2 += delta; /* form error * 5 */
  175125. bpreverr2 = belowerr2 + cur2;
  175126. belowerr2 = bnexterr;
  175127. cur2 += delta; /* form error * 7 */
  175128. }
  175129. /* At this point curN contains the 7/16 error value to be propagated
  175130. * to the next pixel on the current line, and all the errors for the
  175131. * next line have been shifted over. We are therefore ready to move on.
  175132. */
  175133. inptr += dir3; /* Advance pixel pointers to next column */
  175134. outptr += dir;
  175135. errorptr += dir3; /* advance errorptr to current column */
  175136. }
  175137. /* Post-loop cleanup: we must unload the final error values into the
  175138. * final fserrors[] entry. Note we need not unload belowerrN because
  175139. * it is for the dummy column before or after the actual array.
  175140. */
  175141. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  175142. errorptr[1] = (FSERROR) bpreverr1;
  175143. errorptr[2] = (FSERROR) bpreverr2;
  175144. }
  175145. }
  175146. /*
  175147. * Initialize the error-limiting transfer function (lookup table).
  175148. * The raw F-S error computation can potentially compute error values of up to
  175149. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  175150. * much less, otherwise obviously wrong pixels will be created. (Typical
  175151. * effects include weird fringes at color-area boundaries, isolated bright
  175152. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  175153. * is to ensure that the "corners" of the color cube are allocated as output
  175154. * colors; then repeated errors in the same direction cannot cause cascading
  175155. * error buildup. However, that only prevents the error from getting
  175156. * completely out of hand; Aaron Giles reports that error limiting improves
  175157. * the results even with corner colors allocated.
  175158. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  175159. * well, but the smoother transfer function used below is even better. Thanks
  175160. * to Aaron Giles for this idea.
  175161. */
  175162. LOCAL(void)
  175163. init_error_limit (j_decompress_ptr cinfo)
  175164. /* Allocate and fill in the error_limiter table */
  175165. {
  175166. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175167. int * table;
  175168. int in, out;
  175169. table = (int *) (*cinfo->mem->alloc_small)
  175170. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  175171. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  175172. cquantize->error_limiter = table;
  175173. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  175174. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  175175. out = 0;
  175176. for (in = 0; in < STEPSIZE; in++, out++) {
  175177. table[in] = out; table[-in] = -out;
  175178. }
  175179. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  175180. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  175181. table[in] = out; table[-in] = -out;
  175182. }
  175183. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  175184. for (; in <= MAXJSAMPLE; in++) {
  175185. table[in] = out; table[-in] = -out;
  175186. }
  175187. #undef STEPSIZE
  175188. }
  175189. /*
  175190. * Finish up at the end of each pass.
  175191. */
  175192. METHODDEF(void)
  175193. finish_pass1 (j_decompress_ptr cinfo)
  175194. {
  175195. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175196. /* Select the representative colors and fill in cinfo->colormap */
  175197. cinfo->colormap = cquantize->sv_colormap;
  175198. select_colors(cinfo, cquantize->desired);
  175199. /* Force next pass to zero the color index table */
  175200. cquantize->needs_zeroed = TRUE;
  175201. }
  175202. METHODDEF(void)
  175203. finish_pass2 (j_decompress_ptr)
  175204. {
  175205. /* no work */
  175206. }
  175207. /*
  175208. * Initialize for each processing pass.
  175209. */
  175210. METHODDEF(void)
  175211. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  175212. {
  175213. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175214. hist3d histogram = cquantize->histogram;
  175215. int i;
  175216. /* Only F-S dithering or no dithering is supported. */
  175217. /* If user asks for ordered dither, give him F-S. */
  175218. if (cinfo->dither_mode != JDITHER_NONE)
  175219. cinfo->dither_mode = JDITHER_FS;
  175220. if (is_pre_scan) {
  175221. /* Set up method pointers */
  175222. cquantize->pub.color_quantize = prescan_quantize;
  175223. cquantize->pub.finish_pass = finish_pass1;
  175224. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  175225. } else {
  175226. /* Set up method pointers */
  175227. if (cinfo->dither_mode == JDITHER_FS)
  175228. cquantize->pub.color_quantize = pass2_fs_dither;
  175229. else
  175230. cquantize->pub.color_quantize = pass2_no_dither;
  175231. cquantize->pub.finish_pass = finish_pass2;
  175232. /* Make sure color count is acceptable */
  175233. i = cinfo->actual_number_of_colors;
  175234. if (i < 1)
  175235. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  175236. if (i > MAXNUMCOLORS)
  175237. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175238. if (cinfo->dither_mode == JDITHER_FS) {
  175239. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  175240. (3 * SIZEOF(FSERROR)));
  175241. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  175242. if (cquantize->fserrors == NULL)
  175243. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175244. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  175245. /* Initialize the propagated errors to zero. */
  175246. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  175247. /* Make the error-limit table if we didn't already. */
  175248. if (cquantize->error_limiter == NULL)
  175249. init_error_limit(cinfo);
  175250. cquantize->on_odd_row = FALSE;
  175251. }
  175252. }
  175253. /* Zero the histogram or inverse color map, if necessary */
  175254. if (cquantize->needs_zeroed) {
  175255. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175256. jzero_far((void FAR *) histogram[i],
  175257. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175258. }
  175259. cquantize->needs_zeroed = FALSE;
  175260. }
  175261. }
  175262. /*
  175263. * Switch to a new external colormap between output passes.
  175264. */
  175265. METHODDEF(void)
  175266. new_color_map_2_quant (j_decompress_ptr cinfo)
  175267. {
  175268. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175269. /* Reset the inverse color map */
  175270. cquantize->needs_zeroed = TRUE;
  175271. }
  175272. /*
  175273. * Module initialization routine for 2-pass color quantization.
  175274. */
  175275. GLOBAL(void)
  175276. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  175277. {
  175278. my_cquantize_ptr2 cquantize;
  175279. int i;
  175280. cquantize = (my_cquantize_ptr2)
  175281. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175282. SIZEOF(my_cquantizer2));
  175283. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  175284. cquantize->pub.start_pass = start_pass_2_quant;
  175285. cquantize->pub.new_color_map = new_color_map_2_quant;
  175286. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  175287. cquantize->error_limiter = NULL;
  175288. /* Make sure jdmaster didn't give me a case I can't handle */
  175289. if (cinfo->out_color_components != 3)
  175290. ERREXIT(cinfo, JERR_NOTIMPL);
  175291. /* Allocate the histogram/inverse colormap storage */
  175292. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  175293. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  175294. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175295. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  175296. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175297. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175298. }
  175299. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  175300. /* Allocate storage for the completed colormap, if required.
  175301. * We do this now since it is FAR storage and may affect
  175302. * the memory manager's space calculations.
  175303. */
  175304. if (cinfo->enable_2pass_quant) {
  175305. /* Make sure color count is acceptable */
  175306. int desired = cinfo->desired_number_of_colors;
  175307. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  175308. if (desired < 8)
  175309. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  175310. /* Make sure colormap indexes can be represented by JSAMPLEs */
  175311. if (desired > MAXNUMCOLORS)
  175312. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175313. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  175314. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  175315. cquantize->desired = desired;
  175316. } else
  175317. cquantize->sv_colormap = NULL;
  175318. /* Only F-S dithering or no dithering is supported. */
  175319. /* If user asks for ordered dither, give him F-S. */
  175320. if (cinfo->dither_mode != JDITHER_NONE)
  175321. cinfo->dither_mode = JDITHER_FS;
  175322. /* Allocate Floyd-Steinberg workspace if necessary.
  175323. * This isn't really needed until pass 2, but again it is FAR storage.
  175324. * Although we will cope with a later change in dither_mode,
  175325. * we do not promise to honor max_memory_to_use if dither_mode changes.
  175326. */
  175327. if (cinfo->dither_mode == JDITHER_FS) {
  175328. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175329. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175330. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  175331. /* Might as well create the error-limiting table too. */
  175332. init_error_limit(cinfo);
  175333. }
  175334. }
  175335. #endif /* QUANT_2PASS_SUPPORTED */
  175336. /*** End of inlined file: jquant2.c ***/
  175337. /*** Start of inlined file: jutils.c ***/
  175338. #define JPEG_INTERNALS
  175339. /*
  175340. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  175341. * of a DCT block read in natural order (left to right, top to bottom).
  175342. */
  175343. #if 0 /* This table is not actually needed in v6a */
  175344. const int jpeg_zigzag_order[DCTSIZE2] = {
  175345. 0, 1, 5, 6, 14, 15, 27, 28,
  175346. 2, 4, 7, 13, 16, 26, 29, 42,
  175347. 3, 8, 12, 17, 25, 30, 41, 43,
  175348. 9, 11, 18, 24, 31, 40, 44, 53,
  175349. 10, 19, 23, 32, 39, 45, 52, 54,
  175350. 20, 22, 33, 38, 46, 51, 55, 60,
  175351. 21, 34, 37, 47, 50, 56, 59, 61,
  175352. 35, 36, 48, 49, 57, 58, 62, 63
  175353. };
  175354. #endif
  175355. /*
  175356. * jpeg_natural_order[i] is the natural-order position of the i'th element
  175357. * of zigzag order.
  175358. *
  175359. * When reading corrupted data, the Huffman decoders could attempt
  175360. * to reference an entry beyond the end of this array (if the decoded
  175361. * zero run length reaches past the end of the block). To prevent
  175362. * wild stores without adding an inner-loop test, we put some extra
  175363. * "63"s after the real entries. This will cause the extra coefficient
  175364. * to be stored in location 63 of the block, not somewhere random.
  175365. * The worst case would be a run-length of 15, which means we need 16
  175366. * fake entries.
  175367. */
  175368. const int jpeg_natural_order[DCTSIZE2+16] = {
  175369. 0, 1, 8, 16, 9, 2, 3, 10,
  175370. 17, 24, 32, 25, 18, 11, 4, 5,
  175371. 12, 19, 26, 33, 40, 48, 41, 34,
  175372. 27, 20, 13, 6, 7, 14, 21, 28,
  175373. 35, 42, 49, 56, 57, 50, 43, 36,
  175374. 29, 22, 15, 23, 30, 37, 44, 51,
  175375. 58, 59, 52, 45, 38, 31, 39, 46,
  175376. 53, 60, 61, 54, 47, 55, 62, 63,
  175377. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  175378. 63, 63, 63, 63, 63, 63, 63, 63
  175379. };
  175380. /*
  175381. * Arithmetic utilities
  175382. */
  175383. GLOBAL(long)
  175384. jdiv_round_up (long a, long b)
  175385. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  175386. /* Assumes a >= 0, b > 0 */
  175387. {
  175388. return (a + b - 1L) / b;
  175389. }
  175390. GLOBAL(long)
  175391. jround_up (long a, long b)
  175392. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  175393. /* Assumes a >= 0, b > 0 */
  175394. {
  175395. a += b - 1L;
  175396. return a - (a % b);
  175397. }
  175398. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  175399. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  175400. * are FAR and we're assuming a small-pointer memory model. However, some
  175401. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  175402. * in the small-model libraries. These will be used if USE_FMEM is defined.
  175403. * Otherwise, the routines below do it the hard way. (The performance cost
  175404. * is not all that great, because these routines aren't very heavily used.)
  175405. */
  175406. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  175407. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  175408. #define FMEMZERO(target,size) MEMZERO(target,size)
  175409. #else /* 80x86 case, define if we can */
  175410. #ifdef USE_FMEM
  175411. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  175412. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  175413. #endif
  175414. #endif
  175415. GLOBAL(void)
  175416. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  175417. JSAMPARRAY output_array, int dest_row,
  175418. int num_rows, JDIMENSION num_cols)
  175419. /* Copy some rows of samples from one place to another.
  175420. * num_rows rows are copied from input_array[source_row++]
  175421. * to output_array[dest_row++]; these areas may overlap for duplication.
  175422. * The source and destination arrays must be at least as wide as num_cols.
  175423. */
  175424. {
  175425. register JSAMPROW inptr, outptr;
  175426. #ifdef FMEMCOPY
  175427. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  175428. #else
  175429. register JDIMENSION count;
  175430. #endif
  175431. register int row;
  175432. input_array += source_row;
  175433. output_array += dest_row;
  175434. for (row = num_rows; row > 0; row--) {
  175435. inptr = *input_array++;
  175436. outptr = *output_array++;
  175437. #ifdef FMEMCOPY
  175438. FMEMCOPY(outptr, inptr, count);
  175439. #else
  175440. for (count = num_cols; count > 0; count--)
  175441. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  175442. #endif
  175443. }
  175444. }
  175445. GLOBAL(void)
  175446. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  175447. JDIMENSION num_blocks)
  175448. /* Copy a row of coefficient blocks from one place to another. */
  175449. {
  175450. #ifdef FMEMCOPY
  175451. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  175452. #else
  175453. register JCOEFPTR inptr, outptr;
  175454. register long count;
  175455. inptr = (JCOEFPTR) input_row;
  175456. outptr = (JCOEFPTR) output_row;
  175457. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  175458. *outptr++ = *inptr++;
  175459. }
  175460. #endif
  175461. }
  175462. GLOBAL(void)
  175463. jzero_far (void FAR * target, size_t bytestozero)
  175464. /* Zero out a chunk of FAR memory. */
  175465. /* This might be sample-array data, block-array data, or alloc_large data. */
  175466. {
  175467. #ifdef FMEMZERO
  175468. FMEMZERO(target, bytestozero);
  175469. #else
  175470. register char FAR * ptr = (char FAR *) target;
  175471. register size_t count;
  175472. for (count = bytestozero; count > 0; count--) {
  175473. *ptr++ = 0;
  175474. }
  175475. #endif
  175476. }
  175477. /*** End of inlined file: jutils.c ***/
  175478. /*** Start of inlined file: transupp.c ***/
  175479. /* Although this file really shouldn't have access to the library internals,
  175480. * it's helpful to let it call jround_up() and jcopy_block_row().
  175481. */
  175482. #define JPEG_INTERNALS
  175483. /*** Start of inlined file: transupp.h ***/
  175484. /* If you happen not to want the image transform support, disable it here */
  175485. #ifndef TRANSFORMS_SUPPORTED
  175486. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  175487. #endif
  175488. /* Short forms of external names for systems with brain-damaged linkers. */
  175489. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175490. #define jtransform_request_workspace jTrRequest
  175491. #define jtransform_adjust_parameters jTrAdjust
  175492. #define jtransform_execute_transformation jTrExec
  175493. #define jcopy_markers_setup jCMrkSetup
  175494. #define jcopy_markers_execute jCMrkExec
  175495. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175496. /*
  175497. * Codes for supported types of image transformations.
  175498. */
  175499. typedef enum {
  175500. JXFORM_NONE, /* no transformation */
  175501. JXFORM_FLIP_H, /* horizontal flip */
  175502. JXFORM_FLIP_V, /* vertical flip */
  175503. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  175504. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  175505. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  175506. JXFORM_ROT_180, /* 180-degree rotation */
  175507. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  175508. } JXFORM_CODE;
  175509. /*
  175510. * Although rotating and flipping data expressed as DCT coefficients is not
  175511. * hard, there is an asymmetry in the JPEG format specification for images
  175512. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  175513. * image edges are padded out to the next iMCU boundary with junk data; but
  175514. * no padding is possible at the top and left edges. If we were to flip
  175515. * the whole image including the pad data, then pad garbage would become
  175516. * visible at the top and/or left, and real pixels would disappear into the
  175517. * pad margins --- perhaps permanently, since encoders & decoders may not
  175518. * bother to preserve DCT blocks that appear to be completely outside the
  175519. * nominal image area. So, we have to exclude any partial iMCUs from the
  175520. * basic transformation.
  175521. *
  175522. * Transpose is the only transformation that can handle partial iMCUs at the
  175523. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  175524. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  175525. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  175526. * The other transforms are defined as combinations of these basic transforms
  175527. * and process edge blocks in a way that preserves the equivalence.
  175528. *
  175529. * The "trim" option causes untransformable partial iMCUs to be dropped;
  175530. * this is not strictly lossless, but it usually gives the best-looking
  175531. * result for odd-size images. Note that when this option is active,
  175532. * the expected mathematical equivalences between the transforms may not hold.
  175533. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  175534. * followed by -rot 180 -trim trims both edges.)
  175535. *
  175536. * We also offer a "force to grayscale" option, which simply discards the
  175537. * chrominance channels of a YCbCr image. This is lossless in the sense that
  175538. * the luminance channel is preserved exactly. It's not the same kind of
  175539. * thing as the rotate/flip transformations, but it's convenient to handle it
  175540. * as part of this package, mainly because the transformation routines have to
  175541. * be aware of the option to know how many components to work on.
  175542. */
  175543. typedef struct {
  175544. /* Options: set by caller */
  175545. JXFORM_CODE transform; /* image transform operator */
  175546. boolean trim; /* if TRUE, trim partial MCUs as needed */
  175547. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  175548. /* Internal workspace: caller should not touch these */
  175549. int num_components; /* # of components in workspace */
  175550. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  175551. } jpeg_transform_info;
  175552. #if TRANSFORMS_SUPPORTED
  175553. /* Request any required workspace */
  175554. EXTERN(void) jtransform_request_workspace
  175555. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  175556. /* Adjust output image parameters */
  175557. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  175558. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175559. jvirt_barray_ptr *src_coef_arrays,
  175560. jpeg_transform_info *info));
  175561. /* Execute the actual transformation, if any */
  175562. EXTERN(void) jtransform_execute_transformation
  175563. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175564. jvirt_barray_ptr *src_coef_arrays,
  175565. jpeg_transform_info *info));
  175566. #endif /* TRANSFORMS_SUPPORTED */
  175567. /*
  175568. * Support for copying optional markers from source to destination file.
  175569. */
  175570. typedef enum {
  175571. JCOPYOPT_NONE, /* copy no optional markers */
  175572. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  175573. JCOPYOPT_ALL /* copy all optional markers */
  175574. } JCOPY_OPTION;
  175575. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  175576. /* Setup decompression object to save desired markers in memory */
  175577. EXTERN(void) jcopy_markers_setup
  175578. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  175579. /* Copy markers saved in the given source object to the destination object */
  175580. EXTERN(void) jcopy_markers_execute
  175581. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175582. JCOPY_OPTION option));
  175583. /*** End of inlined file: transupp.h ***/
  175584. /* My own external interface */
  175585. #if TRANSFORMS_SUPPORTED
  175586. /*
  175587. * Lossless image transformation routines. These routines work on DCT
  175588. * coefficient arrays and thus do not require any lossy decompression
  175589. * or recompression of the image.
  175590. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  175591. *
  175592. * Horizontal flipping is done in-place, using a single top-to-bottom
  175593. * pass through the virtual source array. It will thus be much the
  175594. * fastest option for images larger than main memory.
  175595. *
  175596. * The other routines require a set of destination virtual arrays, so they
  175597. * need twice as much memory as jpegtran normally does. The destination
  175598. * arrays are always written in normal scan order (top to bottom) because
  175599. * the virtual array manager expects this. The source arrays will be scanned
  175600. * in the corresponding order, which means multiple passes through the source
  175601. * arrays for most of the transforms. That could result in much thrashing
  175602. * if the image is larger than main memory.
  175603. *
  175604. * Some notes about the operating environment of the individual transform
  175605. * routines:
  175606. * 1. Both the source and destination virtual arrays are allocated from the
  175607. * source JPEG object, and therefore should be manipulated by calling the
  175608. * source's memory manager.
  175609. * 2. The destination's component count should be used. It may be smaller
  175610. * than the source's when forcing to grayscale.
  175611. * 3. Likewise the destination's sampling factors should be used. When
  175612. * forcing to grayscale the destination's sampling factors will be all 1,
  175613. * and we may as well take that as the effective iMCU size.
  175614. * 4. When "trim" is in effect, the destination's dimensions will be the
  175615. * trimmed values but the source's will be untrimmed.
  175616. * 5. All the routines assume that the source and destination buffers are
  175617. * padded out to a full iMCU boundary. This is true, although for the
  175618. * source buffer it is an undocumented property of jdcoefct.c.
  175619. * Notes 2,3,4 boil down to this: generally we should use the destination's
  175620. * dimensions and ignore the source's.
  175621. */
  175622. LOCAL(void)
  175623. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175624. jvirt_barray_ptr *src_coef_arrays)
  175625. /* Horizontal flip; done in-place, so no separate dest array is required */
  175626. {
  175627. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  175628. int ci, k, offset_y;
  175629. JBLOCKARRAY buffer;
  175630. JCOEFPTR ptr1, ptr2;
  175631. JCOEF temp1, temp2;
  175632. jpeg_component_info *compptr;
  175633. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  175634. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  175635. * mirroring by changing the signs of odd-numbered columns.
  175636. * Partial iMCUs at the right edge are left untouched.
  175637. */
  175638. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175639. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175640. compptr = dstinfo->comp_info + ci;
  175641. comp_width = MCU_cols * compptr->h_samp_factor;
  175642. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  175643. blk_y += compptr->v_samp_factor) {
  175644. buffer = (*srcinfo->mem->access_virt_barray)
  175645. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  175646. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175647. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175648. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  175649. ptr1 = buffer[offset_y][blk_x];
  175650. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  175651. /* this unrolled loop doesn't need to know which row it's on... */
  175652. for (k = 0; k < DCTSIZE2; k += 2) {
  175653. temp1 = *ptr1; /* swap even column */
  175654. temp2 = *ptr2;
  175655. *ptr1++ = temp2;
  175656. *ptr2++ = temp1;
  175657. temp1 = *ptr1; /* swap odd column with sign change */
  175658. temp2 = *ptr2;
  175659. *ptr1++ = -temp2;
  175660. *ptr2++ = -temp1;
  175661. }
  175662. }
  175663. }
  175664. }
  175665. }
  175666. }
  175667. LOCAL(void)
  175668. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175669. jvirt_barray_ptr *src_coef_arrays,
  175670. jvirt_barray_ptr *dst_coef_arrays)
  175671. /* Vertical flip */
  175672. {
  175673. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  175674. int ci, i, j, offset_y;
  175675. JBLOCKARRAY src_buffer, dst_buffer;
  175676. JBLOCKROW src_row_ptr, dst_row_ptr;
  175677. JCOEFPTR src_ptr, dst_ptr;
  175678. jpeg_component_info *compptr;
  175679. /* We output into a separate array because we can't touch different
  175680. * rows of the source virtual array simultaneously. Otherwise, this
  175681. * is a pretty straightforward analog of horizontal flip.
  175682. * Within a DCT block, vertical mirroring is done by changing the signs
  175683. * of odd-numbered rows.
  175684. * Partial iMCUs at the bottom edge are copied verbatim.
  175685. */
  175686. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175687. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175688. compptr = dstinfo->comp_info + ci;
  175689. comp_height = MCU_rows * compptr->v_samp_factor;
  175690. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175691. dst_blk_y += compptr->v_samp_factor) {
  175692. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175693. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175694. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175695. if (dst_blk_y < comp_height) {
  175696. /* Row is within the mirrorable area. */
  175697. src_buffer = (*srcinfo->mem->access_virt_barray)
  175698. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175699. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175700. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175701. } else {
  175702. /* Bottom-edge blocks will be copied verbatim. */
  175703. src_buffer = (*srcinfo->mem->access_virt_barray)
  175704. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175705. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175706. }
  175707. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175708. if (dst_blk_y < comp_height) {
  175709. /* Row is within the mirrorable area. */
  175710. dst_row_ptr = dst_buffer[offset_y];
  175711. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175712. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175713. dst_blk_x++) {
  175714. dst_ptr = dst_row_ptr[dst_blk_x];
  175715. src_ptr = src_row_ptr[dst_blk_x];
  175716. for (i = 0; i < DCTSIZE; i += 2) {
  175717. /* copy even row */
  175718. for (j = 0; j < DCTSIZE; j++)
  175719. *dst_ptr++ = *src_ptr++;
  175720. /* copy odd row with sign change */
  175721. for (j = 0; j < DCTSIZE; j++)
  175722. *dst_ptr++ = - *src_ptr++;
  175723. }
  175724. }
  175725. } else {
  175726. /* Just copy row verbatim. */
  175727. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  175728. compptr->width_in_blocks);
  175729. }
  175730. }
  175731. }
  175732. }
  175733. }
  175734. LOCAL(void)
  175735. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175736. jvirt_barray_ptr *src_coef_arrays,
  175737. jvirt_barray_ptr *dst_coef_arrays)
  175738. /* Transpose source into destination */
  175739. {
  175740. JDIMENSION dst_blk_x, dst_blk_y;
  175741. int ci, i, j, offset_x, offset_y;
  175742. JBLOCKARRAY src_buffer, dst_buffer;
  175743. JCOEFPTR src_ptr, dst_ptr;
  175744. jpeg_component_info *compptr;
  175745. /* Transposing pixels within a block just requires transposing the
  175746. * DCT coefficients.
  175747. * Partial iMCUs at the edges require no special treatment; we simply
  175748. * process all the available DCT blocks for every component.
  175749. */
  175750. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175751. compptr = dstinfo->comp_info + ci;
  175752. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175753. dst_blk_y += compptr->v_samp_factor) {
  175754. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175755. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175756. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175757. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175758. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175759. dst_blk_x += compptr->h_samp_factor) {
  175760. src_buffer = (*srcinfo->mem->access_virt_barray)
  175761. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175762. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175763. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175764. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175765. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175766. for (i = 0; i < DCTSIZE; i++)
  175767. for (j = 0; j < DCTSIZE; j++)
  175768. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175769. }
  175770. }
  175771. }
  175772. }
  175773. }
  175774. }
  175775. LOCAL(void)
  175776. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175777. jvirt_barray_ptr *src_coef_arrays,
  175778. jvirt_barray_ptr *dst_coef_arrays)
  175779. /* 90 degree rotation is equivalent to
  175780. * 1. Transposing the image;
  175781. * 2. Horizontal mirroring.
  175782. * These two steps are merged into a single processing routine.
  175783. */
  175784. {
  175785. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  175786. int ci, i, j, offset_x, offset_y;
  175787. JBLOCKARRAY src_buffer, dst_buffer;
  175788. JCOEFPTR src_ptr, dst_ptr;
  175789. jpeg_component_info *compptr;
  175790. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175791. * at the (output) right edge properly. They just get transposed and
  175792. * not mirrored.
  175793. */
  175794. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175795. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175796. compptr = dstinfo->comp_info + ci;
  175797. comp_width = MCU_cols * compptr->h_samp_factor;
  175798. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175799. dst_blk_y += compptr->v_samp_factor) {
  175800. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175801. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175802. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175803. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175804. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175805. dst_blk_x += compptr->h_samp_factor) {
  175806. src_buffer = (*srcinfo->mem->access_virt_barray)
  175807. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175808. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175809. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175810. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175811. if (dst_blk_x < comp_width) {
  175812. /* Block is within the mirrorable area. */
  175813. dst_ptr = dst_buffer[offset_y]
  175814. [comp_width - dst_blk_x - offset_x - 1];
  175815. for (i = 0; i < DCTSIZE; i++) {
  175816. for (j = 0; j < DCTSIZE; j++)
  175817. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175818. i++;
  175819. for (j = 0; j < DCTSIZE; j++)
  175820. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175821. }
  175822. } else {
  175823. /* Edge blocks are transposed but not mirrored. */
  175824. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175825. for (i = 0; i < DCTSIZE; i++)
  175826. for (j = 0; j < DCTSIZE; j++)
  175827. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175828. }
  175829. }
  175830. }
  175831. }
  175832. }
  175833. }
  175834. }
  175835. LOCAL(void)
  175836. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175837. jvirt_barray_ptr *src_coef_arrays,
  175838. jvirt_barray_ptr *dst_coef_arrays)
  175839. /* 270 degree rotation is equivalent to
  175840. * 1. Horizontal mirroring;
  175841. * 2. Transposing the image.
  175842. * These two steps are merged into a single processing routine.
  175843. */
  175844. {
  175845. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  175846. int ci, i, j, offset_x, offset_y;
  175847. JBLOCKARRAY src_buffer, dst_buffer;
  175848. JCOEFPTR src_ptr, dst_ptr;
  175849. jpeg_component_info *compptr;
  175850. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175851. * at the (output) bottom edge properly. They just get transposed and
  175852. * not mirrored.
  175853. */
  175854. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175855. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175856. compptr = dstinfo->comp_info + ci;
  175857. comp_height = MCU_rows * compptr->v_samp_factor;
  175858. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175859. dst_blk_y += compptr->v_samp_factor) {
  175860. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175861. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175862. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175863. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175864. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175865. dst_blk_x += compptr->h_samp_factor) {
  175866. src_buffer = (*srcinfo->mem->access_virt_barray)
  175867. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175868. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175869. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175870. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175871. if (dst_blk_y < comp_height) {
  175872. /* Block is within the mirrorable area. */
  175873. src_ptr = src_buffer[offset_x]
  175874. [comp_height - dst_blk_y - offset_y - 1];
  175875. for (i = 0; i < DCTSIZE; i++) {
  175876. for (j = 0; j < DCTSIZE; j++) {
  175877. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175878. j++;
  175879. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175880. }
  175881. }
  175882. } else {
  175883. /* Edge blocks are transposed but not mirrored. */
  175884. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175885. for (i = 0; i < DCTSIZE; i++)
  175886. for (j = 0; j < DCTSIZE; j++)
  175887. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175888. }
  175889. }
  175890. }
  175891. }
  175892. }
  175893. }
  175894. }
  175895. LOCAL(void)
  175896. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175897. jvirt_barray_ptr *src_coef_arrays,
  175898. jvirt_barray_ptr *dst_coef_arrays)
  175899. /* 180 degree rotation is equivalent to
  175900. * 1. Vertical mirroring;
  175901. * 2. Horizontal mirroring.
  175902. * These two steps are merged into a single processing routine.
  175903. */
  175904. {
  175905. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175906. int ci, i, j, offset_y;
  175907. JBLOCKARRAY src_buffer, dst_buffer;
  175908. JBLOCKROW src_row_ptr, dst_row_ptr;
  175909. JCOEFPTR src_ptr, dst_ptr;
  175910. jpeg_component_info *compptr;
  175911. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175912. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175913. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175914. compptr = dstinfo->comp_info + ci;
  175915. comp_width = MCU_cols * compptr->h_samp_factor;
  175916. comp_height = MCU_rows * compptr->v_samp_factor;
  175917. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175918. dst_blk_y += compptr->v_samp_factor) {
  175919. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175920. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175921. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175922. if (dst_blk_y < comp_height) {
  175923. /* Row is within the vertically mirrorable area. */
  175924. src_buffer = (*srcinfo->mem->access_virt_barray)
  175925. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175926. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175927. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175928. } else {
  175929. /* Bottom-edge rows are only mirrored horizontally. */
  175930. src_buffer = (*srcinfo->mem->access_virt_barray)
  175931. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175932. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175933. }
  175934. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175935. if (dst_blk_y < comp_height) {
  175936. /* Row is within the mirrorable area. */
  175937. dst_row_ptr = dst_buffer[offset_y];
  175938. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175939. /* Process the blocks that can be mirrored both ways. */
  175940. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175941. dst_ptr = dst_row_ptr[dst_blk_x];
  175942. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175943. for (i = 0; i < DCTSIZE; i += 2) {
  175944. /* For even row, negate every odd column. */
  175945. for (j = 0; j < DCTSIZE; j += 2) {
  175946. *dst_ptr++ = *src_ptr++;
  175947. *dst_ptr++ = - *src_ptr++;
  175948. }
  175949. /* For odd row, negate every even column. */
  175950. for (j = 0; j < DCTSIZE; j += 2) {
  175951. *dst_ptr++ = - *src_ptr++;
  175952. *dst_ptr++ = *src_ptr++;
  175953. }
  175954. }
  175955. }
  175956. /* Any remaining right-edge blocks are only mirrored vertically. */
  175957. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175958. dst_ptr = dst_row_ptr[dst_blk_x];
  175959. src_ptr = src_row_ptr[dst_blk_x];
  175960. for (i = 0; i < DCTSIZE; i += 2) {
  175961. for (j = 0; j < DCTSIZE; j++)
  175962. *dst_ptr++ = *src_ptr++;
  175963. for (j = 0; j < DCTSIZE; j++)
  175964. *dst_ptr++ = - *src_ptr++;
  175965. }
  175966. }
  175967. } else {
  175968. /* Remaining rows are just mirrored horizontally. */
  175969. dst_row_ptr = dst_buffer[offset_y];
  175970. src_row_ptr = src_buffer[offset_y];
  175971. /* Process the blocks that can be mirrored. */
  175972. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175973. dst_ptr = dst_row_ptr[dst_blk_x];
  175974. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175975. for (i = 0; i < DCTSIZE2; i += 2) {
  175976. *dst_ptr++ = *src_ptr++;
  175977. *dst_ptr++ = - *src_ptr++;
  175978. }
  175979. }
  175980. /* Any remaining right-edge blocks are only copied. */
  175981. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175982. dst_ptr = dst_row_ptr[dst_blk_x];
  175983. src_ptr = src_row_ptr[dst_blk_x];
  175984. for (i = 0; i < DCTSIZE2; i++)
  175985. *dst_ptr++ = *src_ptr++;
  175986. }
  175987. }
  175988. }
  175989. }
  175990. }
  175991. }
  175992. LOCAL(void)
  175993. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175994. jvirt_barray_ptr *src_coef_arrays,
  175995. jvirt_barray_ptr *dst_coef_arrays)
  175996. /* Transverse transpose is equivalent to
  175997. * 1. 180 degree rotation;
  175998. * 2. Transposition;
  175999. * or
  176000. * 1. Horizontal mirroring;
  176001. * 2. Transposition;
  176002. * 3. Horizontal mirroring.
  176003. * These steps are merged into a single processing routine.
  176004. */
  176005. {
  176006. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  176007. int ci, i, j, offset_x, offset_y;
  176008. JBLOCKARRAY src_buffer, dst_buffer;
  176009. JCOEFPTR src_ptr, dst_ptr;
  176010. jpeg_component_info *compptr;
  176011. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176012. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176013. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176014. compptr = dstinfo->comp_info + ci;
  176015. comp_width = MCU_cols * compptr->h_samp_factor;
  176016. comp_height = MCU_rows * compptr->v_samp_factor;
  176017. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176018. dst_blk_y += compptr->v_samp_factor) {
  176019. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176020. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176021. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176022. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176023. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176024. dst_blk_x += compptr->h_samp_factor) {
  176025. src_buffer = (*srcinfo->mem->access_virt_barray)
  176026. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176027. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176028. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176029. if (dst_blk_y < comp_height) {
  176030. src_ptr = src_buffer[offset_x]
  176031. [comp_height - dst_blk_y - offset_y - 1];
  176032. if (dst_blk_x < comp_width) {
  176033. /* Block is within the mirrorable area. */
  176034. dst_ptr = dst_buffer[offset_y]
  176035. [comp_width - dst_blk_x - offset_x - 1];
  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. i++;
  176043. for (j = 0; j < DCTSIZE; j++) {
  176044. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176045. j++;
  176046. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176047. }
  176048. }
  176049. } else {
  176050. /* Right-edge blocks are mirrored in y only */
  176051. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176052. for (i = 0; i < DCTSIZE; i++) {
  176053. for (j = 0; j < DCTSIZE; j++) {
  176054. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176055. j++;
  176056. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176057. }
  176058. }
  176059. }
  176060. } else {
  176061. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176062. if (dst_blk_x < comp_width) {
  176063. /* Bottom-edge blocks are mirrored in x only */
  176064. dst_ptr = dst_buffer[offset_y]
  176065. [comp_width - dst_blk_x - offset_x - 1];
  176066. for (i = 0; i < DCTSIZE; i++) {
  176067. for (j = 0; j < DCTSIZE; j++)
  176068. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176069. i++;
  176070. for (j = 0; j < DCTSIZE; j++)
  176071. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176072. }
  176073. } else {
  176074. /* At lower right corner, just transpose, no mirroring */
  176075. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176076. for (i = 0; i < DCTSIZE; i++)
  176077. for (j = 0; j < DCTSIZE; j++)
  176078. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176079. }
  176080. }
  176081. }
  176082. }
  176083. }
  176084. }
  176085. }
  176086. }
  176087. /* Request any required workspace.
  176088. *
  176089. * We allocate the workspace virtual arrays from the source decompression
  176090. * object, so that all the arrays (both the original data and the workspace)
  176091. * will be taken into account while making memory management decisions.
  176092. * Hence, this routine must be called after jpeg_read_header (which reads
  176093. * the image dimensions) and before jpeg_read_coefficients (which realizes
  176094. * the source's virtual arrays).
  176095. */
  176096. GLOBAL(void)
  176097. jtransform_request_workspace (j_decompress_ptr srcinfo,
  176098. jpeg_transform_info *info)
  176099. {
  176100. jvirt_barray_ptr *coef_arrays = NULL;
  176101. jpeg_component_info *compptr;
  176102. int ci;
  176103. if (info->force_grayscale &&
  176104. srcinfo->jpeg_color_space == JCS_YCbCr &&
  176105. srcinfo->num_components == 3) {
  176106. /* We'll only process the first component */
  176107. info->num_components = 1;
  176108. } else {
  176109. /* Process all the components */
  176110. info->num_components = srcinfo->num_components;
  176111. }
  176112. switch (info->transform) {
  176113. case JXFORM_NONE:
  176114. case JXFORM_FLIP_H:
  176115. /* Don't need a workspace array */
  176116. break;
  176117. case JXFORM_FLIP_V:
  176118. case JXFORM_ROT_180:
  176119. /* Need workspace arrays having same dimensions as source image.
  176120. * Note that we allocate arrays padded out to the next iMCU boundary,
  176121. * so that transform routines need not worry about missing edge blocks.
  176122. */
  176123. coef_arrays = (jvirt_barray_ptr *)
  176124. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176125. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176126. for (ci = 0; ci < info->num_components; ci++) {
  176127. compptr = srcinfo->comp_info + ci;
  176128. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176129. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176130. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176131. (long) compptr->h_samp_factor),
  176132. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176133. (long) compptr->v_samp_factor),
  176134. (JDIMENSION) compptr->v_samp_factor);
  176135. }
  176136. break;
  176137. case JXFORM_TRANSPOSE:
  176138. case JXFORM_TRANSVERSE:
  176139. case JXFORM_ROT_90:
  176140. case JXFORM_ROT_270:
  176141. /* Need workspace arrays having transposed dimensions.
  176142. * Note that we allocate arrays padded out to the next iMCU boundary,
  176143. * so that transform routines need not worry about missing edge blocks.
  176144. */
  176145. coef_arrays = (jvirt_barray_ptr *)
  176146. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176147. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176148. for (ci = 0; ci < info->num_components; ci++) {
  176149. compptr = srcinfo->comp_info + ci;
  176150. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176151. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176152. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176153. (long) compptr->v_samp_factor),
  176154. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176155. (long) compptr->h_samp_factor),
  176156. (JDIMENSION) compptr->h_samp_factor);
  176157. }
  176158. break;
  176159. }
  176160. info->workspace_coef_arrays = coef_arrays;
  176161. }
  176162. /* Transpose destination image parameters */
  176163. LOCAL(void)
  176164. transpose_critical_parameters (j_compress_ptr dstinfo)
  176165. {
  176166. int tblno, i, j, ci, itemp;
  176167. jpeg_component_info *compptr;
  176168. JQUANT_TBL *qtblptr;
  176169. JDIMENSION dtemp;
  176170. UINT16 qtemp;
  176171. /* Transpose basic image dimensions */
  176172. dtemp = dstinfo->image_width;
  176173. dstinfo->image_width = dstinfo->image_height;
  176174. dstinfo->image_height = dtemp;
  176175. /* Transpose sampling factors */
  176176. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176177. compptr = dstinfo->comp_info + ci;
  176178. itemp = compptr->h_samp_factor;
  176179. compptr->h_samp_factor = compptr->v_samp_factor;
  176180. compptr->v_samp_factor = itemp;
  176181. }
  176182. /* Transpose quantization tables */
  176183. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  176184. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  176185. if (qtblptr != NULL) {
  176186. for (i = 0; i < DCTSIZE; i++) {
  176187. for (j = 0; j < i; j++) {
  176188. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  176189. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  176190. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  176191. }
  176192. }
  176193. }
  176194. }
  176195. }
  176196. /* Trim off any partial iMCUs on the indicated destination edge */
  176197. LOCAL(void)
  176198. trim_right_edge (j_compress_ptr dstinfo)
  176199. {
  176200. int ci, max_h_samp_factor;
  176201. JDIMENSION MCU_cols;
  176202. /* We have to compute max_h_samp_factor ourselves,
  176203. * because it hasn't been set yet in the destination
  176204. * (and we don't want to use the source's value).
  176205. */
  176206. max_h_samp_factor = 1;
  176207. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176208. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  176209. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  176210. }
  176211. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  176212. if (MCU_cols > 0) /* can't trim to 0 pixels */
  176213. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  176214. }
  176215. LOCAL(void)
  176216. trim_bottom_edge (j_compress_ptr dstinfo)
  176217. {
  176218. int ci, max_v_samp_factor;
  176219. JDIMENSION MCU_rows;
  176220. /* We have to compute max_v_samp_factor ourselves,
  176221. * because it hasn't been set yet in the destination
  176222. * (and we don't want to use the source's value).
  176223. */
  176224. max_v_samp_factor = 1;
  176225. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176226. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  176227. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  176228. }
  176229. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  176230. if (MCU_rows > 0) /* can't trim to 0 pixels */
  176231. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  176232. }
  176233. /* Adjust output image parameters as needed.
  176234. *
  176235. * This must be called after jpeg_copy_critical_parameters()
  176236. * and before jpeg_write_coefficients().
  176237. *
  176238. * The return value is the set of virtual coefficient arrays to be written
  176239. * (either the ones allocated by jtransform_request_workspace, or the
  176240. * original source data arrays). The caller will need to pass this value
  176241. * to jpeg_write_coefficients().
  176242. */
  176243. GLOBAL(jvirt_barray_ptr *)
  176244. jtransform_adjust_parameters (j_decompress_ptr,
  176245. j_compress_ptr dstinfo,
  176246. jvirt_barray_ptr *src_coef_arrays,
  176247. jpeg_transform_info *info)
  176248. {
  176249. /* If force-to-grayscale is requested, adjust destination parameters */
  176250. if (info->force_grayscale) {
  176251. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  176252. * properly. Among other things, the target h_samp_factor & v_samp_factor
  176253. * will get set to 1, which typically won't match the source.
  176254. * In fact we do this even if the source is already grayscale; that
  176255. * provides an easy way of coercing a grayscale JPEG with funny sampling
  176256. * factors to the customary 1,1. (Some decoders fail on other factors.)
  176257. */
  176258. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  176259. dstinfo->num_components == 3) ||
  176260. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  176261. dstinfo->num_components == 1)) {
  176262. /* We have to preserve the source's quantization table number. */
  176263. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  176264. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  176265. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  176266. } else {
  176267. /* Sorry, can't do it */
  176268. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  176269. }
  176270. }
  176271. /* Correct the destination's image dimensions etc if necessary */
  176272. switch (info->transform) {
  176273. case JXFORM_NONE:
  176274. /* Nothing to do */
  176275. break;
  176276. case JXFORM_FLIP_H:
  176277. if (info->trim)
  176278. trim_right_edge(dstinfo);
  176279. break;
  176280. case JXFORM_FLIP_V:
  176281. if (info->trim)
  176282. trim_bottom_edge(dstinfo);
  176283. break;
  176284. case JXFORM_TRANSPOSE:
  176285. transpose_critical_parameters(dstinfo);
  176286. /* transpose does NOT have to trim anything */
  176287. break;
  176288. case JXFORM_TRANSVERSE:
  176289. transpose_critical_parameters(dstinfo);
  176290. if (info->trim) {
  176291. trim_right_edge(dstinfo);
  176292. trim_bottom_edge(dstinfo);
  176293. }
  176294. break;
  176295. case JXFORM_ROT_90:
  176296. transpose_critical_parameters(dstinfo);
  176297. if (info->trim)
  176298. trim_right_edge(dstinfo);
  176299. break;
  176300. case JXFORM_ROT_180:
  176301. if (info->trim) {
  176302. trim_right_edge(dstinfo);
  176303. trim_bottom_edge(dstinfo);
  176304. }
  176305. break;
  176306. case JXFORM_ROT_270:
  176307. transpose_critical_parameters(dstinfo);
  176308. if (info->trim)
  176309. trim_bottom_edge(dstinfo);
  176310. break;
  176311. }
  176312. /* Return the appropriate output data set */
  176313. if (info->workspace_coef_arrays != NULL)
  176314. return info->workspace_coef_arrays;
  176315. return src_coef_arrays;
  176316. }
  176317. /* Execute the actual transformation, if any.
  176318. *
  176319. * This must be called *after* jpeg_write_coefficients, because it depends
  176320. * on jpeg_write_coefficients to have computed subsidiary values such as
  176321. * the per-component width and height fields in the destination object.
  176322. *
  176323. * Note that some transformations will modify the source data arrays!
  176324. */
  176325. GLOBAL(void)
  176326. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  176327. j_compress_ptr dstinfo,
  176328. jvirt_barray_ptr *src_coef_arrays,
  176329. jpeg_transform_info *info)
  176330. {
  176331. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  176332. switch (info->transform) {
  176333. case JXFORM_NONE:
  176334. break;
  176335. case JXFORM_FLIP_H:
  176336. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  176337. break;
  176338. case JXFORM_FLIP_V:
  176339. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176340. break;
  176341. case JXFORM_TRANSPOSE:
  176342. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176343. break;
  176344. case JXFORM_TRANSVERSE:
  176345. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176346. break;
  176347. case JXFORM_ROT_90:
  176348. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176349. break;
  176350. case JXFORM_ROT_180:
  176351. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176352. break;
  176353. case JXFORM_ROT_270:
  176354. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176355. break;
  176356. }
  176357. }
  176358. #endif /* TRANSFORMS_SUPPORTED */
  176359. /* Setup decompression object to save desired markers in memory.
  176360. * This must be called before jpeg_read_header() to have the desired effect.
  176361. */
  176362. GLOBAL(void)
  176363. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  176364. {
  176365. #ifdef SAVE_MARKERS_SUPPORTED
  176366. int m;
  176367. /* Save comments except under NONE option */
  176368. if (option != JCOPYOPT_NONE) {
  176369. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  176370. }
  176371. /* Save all types of APPn markers iff ALL option */
  176372. if (option == JCOPYOPT_ALL) {
  176373. for (m = 0; m < 16; m++)
  176374. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  176375. }
  176376. #endif /* SAVE_MARKERS_SUPPORTED */
  176377. }
  176378. /* Copy markers saved in the given source object to the destination object.
  176379. * This should be called just after jpeg_start_compress() or
  176380. * jpeg_write_coefficients().
  176381. * Note that those routines will have written the SOI, and also the
  176382. * JFIF APP0 or Adobe APP14 markers if selected.
  176383. */
  176384. GLOBAL(void)
  176385. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176386. JCOPY_OPTION)
  176387. {
  176388. jpeg_saved_marker_ptr marker;
  176389. /* In the current implementation, we don't actually need to examine the
  176390. * option flag here; we just copy everything that got saved.
  176391. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  176392. * if the encoder library already wrote one.
  176393. */
  176394. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  176395. if (dstinfo->write_JFIF_header &&
  176396. marker->marker == JPEG_APP0 &&
  176397. marker->data_length >= 5 &&
  176398. GETJOCTET(marker->data[0]) == 0x4A &&
  176399. GETJOCTET(marker->data[1]) == 0x46 &&
  176400. GETJOCTET(marker->data[2]) == 0x49 &&
  176401. GETJOCTET(marker->data[3]) == 0x46 &&
  176402. GETJOCTET(marker->data[4]) == 0)
  176403. continue; /* reject duplicate JFIF */
  176404. if (dstinfo->write_Adobe_marker &&
  176405. marker->marker == JPEG_APP0+14 &&
  176406. marker->data_length >= 5 &&
  176407. GETJOCTET(marker->data[0]) == 0x41 &&
  176408. GETJOCTET(marker->data[1]) == 0x64 &&
  176409. GETJOCTET(marker->data[2]) == 0x6F &&
  176410. GETJOCTET(marker->data[3]) == 0x62 &&
  176411. GETJOCTET(marker->data[4]) == 0x65)
  176412. continue; /* reject duplicate Adobe */
  176413. #ifdef NEED_FAR_POINTERS
  176414. /* We could use jpeg_write_marker if the data weren't FAR... */
  176415. {
  176416. unsigned int i;
  176417. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  176418. for (i = 0; i < marker->data_length; i++)
  176419. jpeg_write_m_byte(dstinfo, marker->data[i]);
  176420. }
  176421. #else
  176422. jpeg_write_marker(dstinfo, marker->marker,
  176423. marker->data, marker->data_length);
  176424. #endif
  176425. }
  176426. }
  176427. /*** End of inlined file: transupp.c ***/
  176428. }
  176429. #else
  176430. #define JPEG_INTERNALS
  176431. #undef FAR
  176432. #include <jpeglib.h>
  176433. #endif
  176434. }
  176435. #undef max
  176436. #undef min
  176437. #if JUCE_MSVC
  176438. #pragma warning (pop)
  176439. #endif
  176440. BEGIN_JUCE_NAMESPACE
  176441. namespace JPEGHelpers
  176442. {
  176443. using namespace jpeglibNamespace;
  176444. #if ! JUCE_MSVC
  176445. using jpeglibNamespace::boolean;
  176446. #endif
  176447. struct JPEGDecodingFailure {};
  176448. static void fatalErrorHandler (j_common_ptr)
  176449. {
  176450. throw JPEGDecodingFailure();
  176451. }
  176452. static void silentErrorCallback1 (j_common_ptr) {}
  176453. static void silentErrorCallback2 (j_common_ptr, int) {}
  176454. static void silentErrorCallback3 (j_common_ptr, char*) {}
  176455. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  176456. {
  176457. zerostruct (err);
  176458. err.error_exit = fatalErrorHandler;
  176459. err.emit_message = silentErrorCallback2;
  176460. err.output_message = silentErrorCallback1;
  176461. err.format_message = silentErrorCallback3;
  176462. err.reset_error_mgr = silentErrorCallback1;
  176463. }
  176464. static void dummyCallback1 (j_decompress_ptr)
  176465. {
  176466. }
  176467. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  176468. {
  176469. decompStruct->src->next_input_byte += num;
  176470. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  176471. decompStruct->src->bytes_in_buffer -= num;
  176472. }
  176473. static boolean jpegFill (j_decompress_ptr)
  176474. {
  176475. return 0;
  176476. }
  176477. static const int jpegBufferSize = 512;
  176478. struct JuceJpegDest : public jpeg_destination_mgr
  176479. {
  176480. OutputStream* output;
  176481. char* buffer;
  176482. };
  176483. static void jpegWriteInit (j_compress_ptr)
  176484. {
  176485. }
  176486. static void jpegWriteTerminate (j_compress_ptr cinfo)
  176487. {
  176488. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  176489. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  176490. dest->output->write (dest->buffer, (int) numToWrite);
  176491. }
  176492. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  176493. {
  176494. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  176495. const int numToWrite = jpegBufferSize;
  176496. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  176497. dest->free_in_buffer = jpegBufferSize;
  176498. return dest->output->write (dest->buffer, numToWrite);
  176499. }
  176500. }
  176501. JPEGImageFormat::JPEGImageFormat()
  176502. : quality (-1.0f)
  176503. {
  176504. }
  176505. JPEGImageFormat::~JPEGImageFormat() {}
  176506. void JPEGImageFormat::setQuality (const float newQuality)
  176507. {
  176508. quality = newQuality;
  176509. }
  176510. const String JPEGImageFormat::getFormatName()
  176511. {
  176512. return "JPEG";
  176513. }
  176514. bool JPEGImageFormat::canUnderstand (InputStream& in)
  176515. {
  176516. const int bytesNeeded = 10;
  176517. uint8 header [bytesNeeded];
  176518. if (in.read (header, bytesNeeded) == bytesNeeded)
  176519. {
  176520. return header[0] == 0xff
  176521. && header[1] == 0xd8
  176522. && header[2] == 0xff
  176523. && (header[3] == 0xe0 || header[3] == 0xe1);
  176524. }
  176525. return false;
  176526. }
  176527. Image* JPEGImageFormat::decodeImage (InputStream& in)
  176528. {
  176529. using namespace jpeglibNamespace;
  176530. using namespace JPEGHelpers;
  176531. MemoryBlock mb;
  176532. in.readIntoMemoryBlock (mb);
  176533. Image* image = 0;
  176534. if (mb.getSize() > 16)
  176535. {
  176536. struct jpeg_decompress_struct jpegDecompStruct;
  176537. struct jpeg_error_mgr jerr;
  176538. setupSilentErrorHandler (jerr);
  176539. jpegDecompStruct.err = &jerr;
  176540. jpeg_create_decompress (&jpegDecompStruct);
  176541. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  176542. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  176543. jpegDecompStruct.src->init_source = dummyCallback1;
  176544. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  176545. jpegDecompStruct.src->skip_input_data = jpegSkip;
  176546. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  176547. jpegDecompStruct.src->term_source = dummyCallback1;
  176548. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  176549. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  176550. try
  176551. {
  176552. jpeg_read_header (&jpegDecompStruct, TRUE);
  176553. jpeg_calc_output_dimensions (&jpegDecompStruct);
  176554. const int width = jpegDecompStruct.output_width;
  176555. const int height = jpegDecompStruct.output_height;
  176556. jpegDecompStruct.out_color_space = JCS_RGB;
  176557. JSAMPARRAY buffer
  176558. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  176559. JPOOL_IMAGE,
  176560. width * 3, 1);
  176561. if (jpeg_start_decompress (&jpegDecompStruct))
  176562. {
  176563. image = Image::createNativeImage (Image::RGB, width, height, false);
  176564. const bool hasAlphaChan = image->hasAlphaChannel();
  176565. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  176566. for (int y = 0; y < height; ++y)
  176567. {
  176568. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  176569. const uint8* src = *buffer;
  176570. uint8* dest = destData.getLinePointer (y);
  176571. if (hasAlphaChan)
  176572. {
  176573. for (int i = width; --i >= 0;)
  176574. {
  176575. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  176576. ((PixelARGB*) dest)->premultiply();
  176577. dest += destData.pixelStride;
  176578. src += 3;
  176579. }
  176580. }
  176581. else
  176582. {
  176583. for (int i = width; --i >= 0;)
  176584. {
  176585. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  176586. dest += destData.pixelStride;
  176587. src += 3;
  176588. }
  176589. }
  176590. }
  176591. jpeg_finish_decompress (&jpegDecompStruct);
  176592. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  176593. }
  176594. jpeg_destroy_decompress (&jpegDecompStruct);
  176595. }
  176596. catch (...)
  176597. {}
  176598. }
  176599. return image;
  176600. }
  176601. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  176602. {
  176603. using namespace jpeglibNamespace;
  176604. using namespace JPEGHelpers;
  176605. if (image.hasAlphaChannel())
  176606. {
  176607. // this method could fill the background in white and still save the image..
  176608. jassertfalse
  176609. return true;
  176610. }
  176611. struct jpeg_compress_struct jpegCompStruct;
  176612. struct jpeg_error_mgr jerr;
  176613. setupSilentErrorHandler (jerr);
  176614. jpegCompStruct.err = &jerr;
  176615. jpeg_create_compress (&jpegCompStruct);
  176616. JuceJpegDest dest;
  176617. jpegCompStruct.dest = &dest;
  176618. dest.output = &out;
  176619. HeapBlock <char> tempBuffer (jpegBufferSize);
  176620. dest.buffer = tempBuffer;
  176621. dest.next_output_byte = (JOCTET*) dest.buffer;
  176622. dest.free_in_buffer = jpegBufferSize;
  176623. dest.init_destination = jpegWriteInit;
  176624. dest.empty_output_buffer = jpegWriteFlush;
  176625. dest.term_destination = jpegWriteTerminate;
  176626. jpegCompStruct.image_width = image.getWidth();
  176627. jpegCompStruct.image_height = image.getHeight();
  176628. jpegCompStruct.input_components = 3;
  176629. jpegCompStruct.in_color_space = JCS_RGB;
  176630. jpegCompStruct.write_JFIF_header = 1;
  176631. jpegCompStruct.X_density = 72;
  176632. jpegCompStruct.Y_density = 72;
  176633. jpeg_set_defaults (&jpegCompStruct);
  176634. jpegCompStruct.dct_method = JDCT_FLOAT;
  176635. jpegCompStruct.optimize_coding = 1;
  176636. //jpegCompStruct.smoothing_factor = 10;
  176637. if (quality < 0.0f)
  176638. quality = 0.85f;
  176639. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  176640. jpeg_start_compress (&jpegCompStruct, TRUE);
  176641. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  176642. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  176643. JPOOL_IMAGE, strideBytes, 1);
  176644. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  176645. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  176646. {
  176647. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  176648. uint8* dst = *buffer;
  176649. for (int i = jpegCompStruct.image_width; --i >= 0;)
  176650. {
  176651. *dst++ = ((const PixelRGB*) src)->getRed();
  176652. *dst++ = ((const PixelRGB*) src)->getGreen();
  176653. *dst++ = ((const PixelRGB*) src)->getBlue();
  176654. src += srcData.pixelStride;
  176655. }
  176656. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  176657. }
  176658. jpeg_finish_compress (&jpegCompStruct);
  176659. jpeg_destroy_compress (&jpegCompStruct);
  176660. out.flush();
  176661. return true;
  176662. }
  176663. END_JUCE_NAMESPACE
  176664. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  176665. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  176666. #ifdef _MSC_VER
  176667. #pragma warning (push)
  176668. #pragma warning (disable: 4390 4611)
  176669. #endif
  176670. namespace zlibNamespace
  176671. {
  176672. #if JUCE_INCLUDE_ZLIB_CODE
  176673. #undef OS_CODE
  176674. #undef fdopen
  176675. #undef OS_CODE
  176676. #else
  176677. #include <zlib.h>
  176678. #endif
  176679. }
  176680. namespace pnglibNamespace
  176681. {
  176682. using namespace zlibNamespace;
  176683. #if JUCE_INCLUDE_PNGLIB_CODE
  176684. #if _MSC_VER != 1310
  176685. using ::calloc; // (causes conflict in VS.NET 2003)
  176686. using ::malloc;
  176687. using ::free;
  176688. #endif
  176689. extern "C"
  176690. {
  176691. using ::abs;
  176692. #define PNG_INTERNAL
  176693. #define NO_DUMMY_DECL
  176694. #define PNG_SETJMP_NOT_SUPPORTED
  176695. /*** Start of inlined file: png.h ***/
  176696. /* png.h - header file for PNG reference library
  176697. *
  176698. * libpng version 1.2.21 - October 4, 2007
  176699. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  176700. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  176701. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  176702. *
  176703. * Authors and maintainers:
  176704. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  176705. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  176706. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  176707. * See also "Contributing Authors", below.
  176708. *
  176709. * Note about libpng version numbers:
  176710. *
  176711. * Due to various miscommunications, unforeseen code incompatibilities
  176712. * and occasional factors outside the authors' control, version numbering
  176713. * on the library has not always been consistent and straightforward.
  176714. * The following table summarizes matters since version 0.89c, which was
  176715. * the first widely used release:
  176716. *
  176717. * source png.h png.h shared-lib
  176718. * version string int version
  176719. * ------- ------ ----- ----------
  176720. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  176721. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  176722. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  176723. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  176724. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  176725. * 0.97c 0.97 97 2.0.97
  176726. * 0.98 0.98 98 2.0.98
  176727. * 0.99 0.99 98 2.0.99
  176728. * 0.99a-m 0.99 99 2.0.99
  176729. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  176730. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  176731. * 1.0.1 png.h string is 10001 2.1.0
  176732. * 1.0.1a-e identical to the 10002 from here on, the shared library
  176733. * 1.0.2 source version) 10002 is 2.V where V is the source code
  176734. * 1.0.2a-b 10003 version, except as noted.
  176735. * 1.0.3 10003
  176736. * 1.0.3a-d 10004
  176737. * 1.0.4 10004
  176738. * 1.0.4a-f 10005
  176739. * 1.0.5 (+ 2 patches) 10005
  176740. * 1.0.5a-d 10006
  176741. * 1.0.5e-r 10100 (not source compatible)
  176742. * 1.0.5s-v 10006 (not binary compatible)
  176743. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  176744. * 1.0.6d-f 10007 (still binary incompatible)
  176745. * 1.0.6g 10007
  176746. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  176747. * 1.0.6i 10007 10.6i
  176748. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  176749. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  176750. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  176751. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  176752. * 1.0.7 1 10007 (still compatible)
  176753. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  176754. * 1.0.8rc1 1 10008 2.1.0.8rc1
  176755. * 1.0.8 1 10008 2.1.0.8
  176756. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  176757. * 1.0.9rc1 1 10009 2.1.0.9rc1
  176758. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  176759. * 1.0.9rc2 1 10009 2.1.0.9rc2
  176760. * 1.0.9 1 10009 2.1.0.9
  176761. * 1.0.10beta1 1 10010 2.1.0.10beta1
  176762. * 1.0.10rc1 1 10010 2.1.0.10rc1
  176763. * 1.0.10 1 10010 2.1.0.10
  176764. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  176765. * 1.0.11rc1 1 10011 2.1.0.11rc1
  176766. * 1.0.11 1 10011 2.1.0.11
  176767. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  176768. * 1.0.12rc1 2 10012 2.1.0.12rc1
  176769. * 1.0.12 2 10012 2.1.0.12
  176770. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  176771. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  176772. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  176773. * 1.2.0rc1 3 10200 3.1.2.0rc1
  176774. * 1.2.0 3 10200 3.1.2.0
  176775. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  176776. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  176777. * 1.2.1 3 10201 3.1.2.1
  176778. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  176779. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  176780. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  176781. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  176782. * 1.0.13 10 10013 10.so.0.1.0.13
  176783. * 1.2.2 12 10202 12.so.0.1.2.2
  176784. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  176785. * 1.2.3 12 10203 12.so.0.1.2.3
  176786. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  176787. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  176788. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  176789. * 1.0.14 10 10014 10.so.0.1.0.14
  176790. * 1.2.4 13 10204 12.so.0.1.2.4
  176791. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  176792. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  176793. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  176794. * 1.0.15 10 10015 10.so.0.1.0.15
  176795. * 1.2.5 13 10205 12.so.0.1.2.5
  176796. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  176797. * 1.0.16 10 10016 10.so.0.1.0.16
  176798. * 1.2.6 13 10206 12.so.0.1.2.6
  176799. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  176800. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  176801. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  176802. * 1.0.17 10 10017 10.so.0.1.0.17
  176803. * 1.2.7 13 10207 12.so.0.1.2.7
  176804. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  176805. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  176806. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  176807. * 1.0.18 10 10018 10.so.0.1.0.18
  176808. * 1.2.8 13 10208 12.so.0.1.2.8
  176809. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  176810. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  176811. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  176812. * 1.2.9 13 10209 12.so.0.9[.0]
  176813. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  176814. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  176815. * 1.2.10 13 10210 12.so.0.10[.0]
  176816. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  176817. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  176818. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  176819. * 1.0.19 10 10019 10.so.0.19[.0]
  176820. * 1.2.11 13 10211 12.so.0.11[.0]
  176821. * 1.0.20 10 10020 10.so.0.20[.0]
  176822. * 1.2.12 13 10212 12.so.0.12[.0]
  176823. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  176824. * 1.0.21 10 10021 10.so.0.21[.0]
  176825. * 1.2.13 13 10213 12.so.0.13[.0]
  176826. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  176827. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  176828. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  176829. * 1.0.22 10 10022 10.so.0.22[.0]
  176830. * 1.2.14 13 10214 12.so.0.14[.0]
  176831. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  176832. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  176833. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  176834. * 1.0.23 10 10023 10.so.0.23[.0]
  176835. * 1.2.15 13 10215 12.so.0.15[.0]
  176836. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  176837. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  176838. * 1.0.24 10 10024 10.so.0.24[.0]
  176839. * 1.2.16 13 10216 12.so.0.16[.0]
  176840. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  176841. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  176842. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  176843. * 1.0.25 10 10025 10.so.0.25[.0]
  176844. * 1.2.17 13 10217 12.so.0.17[.0]
  176845. * 1.0.26 10 10026 10.so.0.26[.0]
  176846. * 1.2.18 13 10218 12.so.0.18[.0]
  176847. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  176848. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  176849. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  176850. * 1.0.27 10 10027 10.so.0.27[.0]
  176851. * 1.2.19 13 10219 12.so.0.19[.0]
  176852. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  176853. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  176854. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  176855. * 1.0.28 10 10028 10.so.0.28[.0]
  176856. * 1.2.20 13 10220 12.so.0.20[.0]
  176857. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  176858. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  176859. * 1.0.29 10 10029 10.so.0.29[.0]
  176860. * 1.2.21 13 10221 12.so.0.21[.0]
  176861. *
  176862. * Henceforth the source version will match the shared-library major
  176863. * and minor numbers; the shared-library major version number will be
  176864. * used for changes in backward compatibility, as it is intended. The
  176865. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  176866. * for applications, is an unsigned integer of the form xyyzz corresponding
  176867. * to the source version x.y.z (leading zeros in y and z). Beta versions
  176868. * were given the previous public release number plus a letter, until
  176869. * version 1.0.6j; from then on they were given the upcoming public
  176870. * release number plus "betaNN" or "rcN".
  176871. *
  176872. * Binary incompatibility exists only when applications make direct access
  176873. * to the info_ptr or png_ptr members through png.h, and the compiled
  176874. * application is loaded with a different version of the library.
  176875. *
  176876. * DLLNUM will change each time there are forward or backward changes
  176877. * in binary compatibility (e.g., when a new feature is added).
  176878. *
  176879. * See libpng.txt or libpng.3 for more information. The PNG specification
  176880. * is available as a W3C Recommendation and as an ISO Specification,
  176881. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  176882. */
  176883. /*
  176884. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  176885. *
  176886. * If you modify libpng you may insert additional notices immediately following
  176887. * this sentence.
  176888. *
  176889. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  176890. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  176891. * distributed according to the same disclaimer and license as libpng-1.2.5
  176892. * with the following individual added to the list of Contributing Authors:
  176893. *
  176894. * Cosmin Truta
  176895. *
  176896. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  176897. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  176898. * distributed according to the same disclaimer and license as libpng-1.0.6
  176899. * with the following individuals added to the list of Contributing Authors:
  176900. *
  176901. * Simon-Pierre Cadieux
  176902. * Eric S. Raymond
  176903. * Gilles Vollant
  176904. *
  176905. * and with the following additions to the disclaimer:
  176906. *
  176907. * There is no warranty against interference with your enjoyment of the
  176908. * library or against infringement. There is no warranty that our
  176909. * efforts or the library will fulfill any of your particular purposes
  176910. * or needs. This library is provided with all faults, and the entire
  176911. * risk of satisfactory quality, performance, accuracy, and effort is with
  176912. * the user.
  176913. *
  176914. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  176915. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  176916. * distributed according to the same disclaimer and license as libpng-0.96,
  176917. * with the following individuals added to the list of Contributing Authors:
  176918. *
  176919. * Tom Lane
  176920. * Glenn Randers-Pehrson
  176921. * Willem van Schaik
  176922. *
  176923. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  176924. * Copyright (c) 1996, 1997 Andreas Dilger
  176925. * Distributed according to the same disclaimer and license as libpng-0.88,
  176926. * with the following individuals added to the list of Contributing Authors:
  176927. *
  176928. * John Bowler
  176929. * Kevin Bracey
  176930. * Sam Bushell
  176931. * Magnus Holmgren
  176932. * Greg Roelofs
  176933. * Tom Tanner
  176934. *
  176935. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  176936. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  176937. *
  176938. * For the purposes of this copyright and license, "Contributing Authors"
  176939. * is defined as the following set of individuals:
  176940. *
  176941. * Andreas Dilger
  176942. * Dave Martindale
  176943. * Guy Eric Schalnat
  176944. * Paul Schmidt
  176945. * Tim Wegner
  176946. *
  176947. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  176948. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  176949. * including, without limitation, the warranties of merchantability and of
  176950. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  176951. * assume no liability for direct, indirect, incidental, special, exemplary,
  176952. * or consequential damages, which may result from the use of the PNG
  176953. * Reference Library, even if advised of the possibility of such damage.
  176954. *
  176955. * Permission is hereby granted to use, copy, modify, and distribute this
  176956. * source code, or portions hereof, for any purpose, without fee, subject
  176957. * to the following restrictions:
  176958. *
  176959. * 1. The origin of this source code must not be misrepresented.
  176960. *
  176961. * 2. Altered versions must be plainly marked as such and
  176962. * must not be misrepresented as being the original source.
  176963. *
  176964. * 3. This Copyright notice may not be removed or altered from
  176965. * any source or altered source distribution.
  176966. *
  176967. * The Contributing Authors and Group 42, Inc. specifically permit, without
  176968. * fee, and encourage the use of this source code as a component to
  176969. * supporting the PNG file format in commercial products. If you use this
  176970. * source code in a product, acknowledgment is not required but would be
  176971. * appreciated.
  176972. */
  176973. /*
  176974. * A "png_get_copyright" function is available, for convenient use in "about"
  176975. * boxes and the like:
  176976. *
  176977. * printf("%s",png_get_copyright(NULL));
  176978. *
  176979. * Also, the PNG logo (in PNG format, of course) is supplied in the
  176980. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  176981. */
  176982. /*
  176983. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  176984. * certification mark of the Open Source Initiative.
  176985. */
  176986. /*
  176987. * The contributing authors would like to thank all those who helped
  176988. * with testing, bug fixes, and patience. This wouldn't have been
  176989. * possible without all of you.
  176990. *
  176991. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  176992. */
  176993. /*
  176994. * Y2K compliance in libpng:
  176995. * =========================
  176996. *
  176997. * October 4, 2007
  176998. *
  176999. * Since the PNG Development group is an ad-hoc body, we can't make
  177000. * an official declaration.
  177001. *
  177002. * This is your unofficial assurance that libpng from version 0.71 and
  177003. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  177004. * versions were also Y2K compliant.
  177005. *
  177006. * Libpng only has three year fields. One is a 2-byte unsigned integer
  177007. * that will hold years up to 65535. The other two hold the date in text
  177008. * format, and will hold years up to 9999.
  177009. *
  177010. * The integer is
  177011. * "png_uint_16 year" in png_time_struct.
  177012. *
  177013. * The strings are
  177014. * "png_charp time_buffer" in png_struct and
  177015. * "near_time_buffer", which is a local character string in png.c.
  177016. *
  177017. * There are seven time-related functions:
  177018. * png.c: png_convert_to_rfc_1123() in png.c
  177019. * (formerly png_convert_to_rfc_1152() in error)
  177020. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  177021. * png_convert_from_time_t() in pngwrite.c
  177022. * png_get_tIME() in pngget.c
  177023. * png_handle_tIME() in pngrutil.c, called in pngread.c
  177024. * png_set_tIME() in pngset.c
  177025. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  177026. *
  177027. * All handle dates properly in a Y2K environment. The
  177028. * png_convert_from_time_t() function calls gmtime() to convert from system
  177029. * clock time, which returns (year - 1900), which we properly convert to
  177030. * the full 4-digit year. There is a possibility that applications using
  177031. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  177032. * function, or that they are incorrectly passing only a 2-digit year
  177033. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  177034. * but this is not under our control. The libpng documentation has always
  177035. * stated that it works with 4-digit years, and the APIs have been
  177036. * documented as such.
  177037. *
  177038. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  177039. * integer to hold the year, and can hold years as large as 65535.
  177040. *
  177041. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  177042. * no date-related code.
  177043. *
  177044. * Glenn Randers-Pehrson
  177045. * libpng maintainer
  177046. * PNG Development Group
  177047. */
  177048. #ifndef PNG_H
  177049. #define PNG_H
  177050. /* This is not the place to learn how to use libpng. The file libpng.txt
  177051. * describes how to use libpng, and the file example.c summarizes it
  177052. * with some code on which to build. This file is useful for looking
  177053. * at the actual function definitions and structure components.
  177054. */
  177055. /* Version information for png.h - this should match the version in png.c */
  177056. #define PNG_LIBPNG_VER_STRING "1.2.21"
  177057. #define PNG_HEADER_VERSION_STRING \
  177058. " libpng version 1.2.21 - October 4, 2007\n"
  177059. #define PNG_LIBPNG_VER_SONUM 0
  177060. #define PNG_LIBPNG_VER_DLLNUM 13
  177061. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  177062. #define PNG_LIBPNG_VER_MAJOR 1
  177063. #define PNG_LIBPNG_VER_MINOR 2
  177064. #define PNG_LIBPNG_VER_RELEASE 21
  177065. /* This should match the numeric part of the final component of
  177066. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  177067. #define PNG_LIBPNG_VER_BUILD 0
  177068. /* Release Status */
  177069. #define PNG_LIBPNG_BUILD_ALPHA 1
  177070. #define PNG_LIBPNG_BUILD_BETA 2
  177071. #define PNG_LIBPNG_BUILD_RC 3
  177072. #define PNG_LIBPNG_BUILD_STABLE 4
  177073. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  177074. /* Release-Specific Flags */
  177075. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  177076. PNG_LIBPNG_BUILD_STABLE only */
  177077. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  177078. PNG_LIBPNG_BUILD_SPECIAL */
  177079. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  177080. PNG_LIBPNG_BUILD_PRIVATE */
  177081. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  177082. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  177083. * We must not include leading zeros.
  177084. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  177085. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  177086. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  177087. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  177088. #ifndef PNG_VERSION_INFO_ONLY
  177089. /* include the compression library's header */
  177090. #endif
  177091. /* include all user configurable info, including optional assembler routines */
  177092. /*** Start of inlined file: pngconf.h ***/
  177093. /* pngconf.h - machine configurable file for libpng
  177094. *
  177095. * libpng version 1.2.21 - October 4, 2007
  177096. * For conditions of distribution and use, see copyright notice in png.h
  177097. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177098. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177099. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177100. */
  177101. /* Any machine specific code is near the front of this file, so if you
  177102. * are configuring libpng for a machine, you may want to read the section
  177103. * starting here down to where it starts to typedef png_color, png_text,
  177104. * and png_info.
  177105. */
  177106. #ifndef PNGCONF_H
  177107. #define PNGCONF_H
  177108. #define PNG_1_2_X
  177109. // These are some Juce config settings that should remove any unnecessary code bloat..
  177110. #define PNG_NO_STDIO 1
  177111. #define PNG_DEBUG 0
  177112. #define PNG_NO_WARNINGS 1
  177113. #define PNG_NO_ERROR_TEXT 1
  177114. #define PNG_NO_ERROR_NUMBERS 1
  177115. #define PNG_NO_USER_MEM 1
  177116. #define PNG_NO_READ_iCCP 1
  177117. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  177118. #define PNG_NO_READ_USER_CHUNKS 1
  177119. #define PNG_NO_READ_iTXt 1
  177120. #define PNG_NO_READ_sCAL 1
  177121. #define PNG_NO_READ_sPLT 1
  177122. #define png_error(a, b) png_err(a)
  177123. #define png_warning(a, b)
  177124. #define png_chunk_error(a, b) png_err(a)
  177125. #define png_chunk_warning(a, b)
  177126. /*
  177127. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  177128. * includes the resource compiler for Windows DLL configurations.
  177129. */
  177130. #ifdef PNG_USER_CONFIG
  177131. # ifndef PNG_USER_PRIVATEBUILD
  177132. # define PNG_USER_PRIVATEBUILD
  177133. # endif
  177134. #include "pngusr.h"
  177135. #endif
  177136. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  177137. #ifdef PNG_CONFIGURE_LIBPNG
  177138. #ifdef HAVE_CONFIG_H
  177139. #include "config.h"
  177140. #endif
  177141. #endif
  177142. /*
  177143. * Added at libpng-1.2.8
  177144. *
  177145. * If you create a private DLL you need to define in "pngusr.h" the followings:
  177146. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  177147. * the DLL was built>
  177148. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  177149. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  177150. * distinguish your DLL from those of the official release. These
  177151. * correspond to the trailing letters that come after the version
  177152. * number and must match your private DLL name>
  177153. * e.g. // private DLL "libpng13gx.dll"
  177154. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  177155. *
  177156. * The following macros are also at your disposal if you want to complete the
  177157. * DLL VERSIONINFO structure.
  177158. * - PNG_USER_VERSIONINFO_COMMENTS
  177159. * - PNG_USER_VERSIONINFO_COMPANYNAME
  177160. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  177161. */
  177162. #ifdef __STDC__
  177163. #ifdef SPECIALBUILD
  177164. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  177165. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  177166. #endif
  177167. #ifdef PRIVATEBUILD
  177168. # pragma message("PRIVATEBUILD is deprecated.\
  177169. Use PNG_USER_PRIVATEBUILD instead.")
  177170. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  177171. #endif
  177172. #endif /* __STDC__ */
  177173. #ifndef PNG_VERSION_INFO_ONLY
  177174. /* End of material added to libpng-1.2.8 */
  177175. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  177176. Restored at libpng-1.2.21 */
  177177. # define PNG_WARN_UNINITIALIZED_ROW 1
  177178. /* End of material added at libpng-1.2.19/1.2.21 */
  177179. /* This is the size of the compression buffer, and thus the size of
  177180. * an IDAT chunk. Make this whatever size you feel is best for your
  177181. * machine. One of these will be allocated per png_struct. When this
  177182. * is full, it writes the data to the disk, and does some other
  177183. * calculations. Making this an extremely small size will slow
  177184. * the library down, but you may want to experiment to determine
  177185. * where it becomes significant, if you are concerned with memory
  177186. * usage. Note that zlib allocates at least 32Kb also. For readers,
  177187. * this describes the size of the buffer available to read the data in.
  177188. * Unless this gets smaller than the size of a row (compressed),
  177189. * it should not make much difference how big this is.
  177190. */
  177191. #ifndef PNG_ZBUF_SIZE
  177192. # define PNG_ZBUF_SIZE 8192
  177193. #endif
  177194. /* Enable if you want a write-only libpng */
  177195. #ifndef PNG_NO_READ_SUPPORTED
  177196. # define PNG_READ_SUPPORTED
  177197. #endif
  177198. /* Enable if you want a read-only libpng */
  177199. #ifndef PNG_NO_WRITE_SUPPORTED
  177200. # define PNG_WRITE_SUPPORTED
  177201. #endif
  177202. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  177203. support PNGs that are embedded in MNG datastreams */
  177204. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  177205. # ifndef PNG_MNG_FEATURES_SUPPORTED
  177206. # define PNG_MNG_FEATURES_SUPPORTED
  177207. # endif
  177208. #endif
  177209. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  177210. # ifndef PNG_FLOATING_POINT_SUPPORTED
  177211. # define PNG_FLOATING_POINT_SUPPORTED
  177212. # endif
  177213. #endif
  177214. /* If you are running on a machine where you cannot allocate more
  177215. * than 64K of memory at once, uncomment this. While libpng will not
  177216. * normally need that much memory in a chunk (unless you load up a very
  177217. * large file), zlib needs to know how big of a chunk it can use, and
  177218. * libpng thus makes sure to check any memory allocation to verify it
  177219. * will fit into memory.
  177220. #define PNG_MAX_MALLOC_64K
  177221. */
  177222. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  177223. # define PNG_MAX_MALLOC_64K
  177224. #endif
  177225. /* Special munging to support doing things the 'cygwin' way:
  177226. * 'Normal' png-on-win32 defines/defaults:
  177227. * PNG_BUILD_DLL -- building dll
  177228. * PNG_USE_DLL -- building an application, linking to dll
  177229. * (no define) -- building static library, or building an
  177230. * application and linking to the static lib
  177231. * 'Cygwin' defines/defaults:
  177232. * PNG_BUILD_DLL -- (ignored) building the dll
  177233. * (no define) -- (ignored) building an application, linking to the dll
  177234. * PNG_STATIC -- (ignored) building the static lib, or building an
  177235. * application that links to the static lib.
  177236. * ALL_STATIC -- (ignored) building various static libs, or building an
  177237. * application that links to the static libs.
  177238. * Thus,
  177239. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  177240. * this bit of #ifdefs will define the 'correct' config variables based on
  177241. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  177242. * unnecessary.
  177243. *
  177244. * Also, the precedence order is:
  177245. * ALL_STATIC (since we can't #undef something outside our namespace)
  177246. * PNG_BUILD_DLL
  177247. * PNG_STATIC
  177248. * (nothing) == PNG_USE_DLL
  177249. *
  177250. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  177251. * of auto-import in binutils, we no longer need to worry about
  177252. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  177253. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  177254. * to __declspec() stuff. However, we DO need to worry about
  177255. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  177256. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  177257. */
  177258. #if defined(__CYGWIN__)
  177259. # if defined(ALL_STATIC)
  177260. # if defined(PNG_BUILD_DLL)
  177261. # undef PNG_BUILD_DLL
  177262. # endif
  177263. # if defined(PNG_USE_DLL)
  177264. # undef PNG_USE_DLL
  177265. # endif
  177266. # if defined(PNG_DLL)
  177267. # undef PNG_DLL
  177268. # endif
  177269. # if !defined(PNG_STATIC)
  177270. # define PNG_STATIC
  177271. # endif
  177272. # else
  177273. # if defined (PNG_BUILD_DLL)
  177274. # if defined(PNG_STATIC)
  177275. # undef PNG_STATIC
  177276. # endif
  177277. # if defined(PNG_USE_DLL)
  177278. # undef PNG_USE_DLL
  177279. # endif
  177280. # if !defined(PNG_DLL)
  177281. # define PNG_DLL
  177282. # endif
  177283. # else
  177284. # if defined(PNG_STATIC)
  177285. # if defined(PNG_USE_DLL)
  177286. # undef PNG_USE_DLL
  177287. # endif
  177288. # if defined(PNG_DLL)
  177289. # undef PNG_DLL
  177290. # endif
  177291. # else
  177292. # if !defined(PNG_USE_DLL)
  177293. # define PNG_USE_DLL
  177294. # endif
  177295. # if !defined(PNG_DLL)
  177296. # define PNG_DLL
  177297. # endif
  177298. # endif
  177299. # endif
  177300. # endif
  177301. #endif
  177302. /* This protects us against compilers that run on a windowing system
  177303. * and thus don't have or would rather us not use the stdio types:
  177304. * stdin, stdout, and stderr. The only one currently used is stderr
  177305. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  177306. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  177307. * will also prevent these, plus will prevent the entire set of stdio
  177308. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  177309. * unless (PNG_DEBUG > 0) has been #defined.
  177310. *
  177311. * #define PNG_NO_CONSOLE_IO
  177312. * #define PNG_NO_STDIO
  177313. */
  177314. #if defined(_WIN32_WCE)
  177315. # include <windows.h>
  177316. /* Console I/O functions are not supported on WindowsCE */
  177317. # define PNG_NO_CONSOLE_IO
  177318. # ifdef PNG_DEBUG
  177319. # undef PNG_DEBUG
  177320. # endif
  177321. #endif
  177322. #ifdef PNG_BUILD_DLL
  177323. # ifndef PNG_CONSOLE_IO_SUPPORTED
  177324. # ifndef PNG_NO_CONSOLE_IO
  177325. # define PNG_NO_CONSOLE_IO
  177326. # endif
  177327. # endif
  177328. #endif
  177329. # ifdef PNG_NO_STDIO
  177330. # ifndef PNG_NO_CONSOLE_IO
  177331. # define PNG_NO_CONSOLE_IO
  177332. # endif
  177333. # ifdef PNG_DEBUG
  177334. # if (PNG_DEBUG > 0)
  177335. # include <stdio.h>
  177336. # endif
  177337. # endif
  177338. # else
  177339. # if !defined(_WIN32_WCE)
  177340. /* "stdio.h" functions are not supported on WindowsCE */
  177341. # include <stdio.h>
  177342. # endif
  177343. # endif
  177344. /* This macro protects us against machines that don't have function
  177345. * prototypes (ie K&R style headers). If your compiler does not handle
  177346. * function prototypes, define this macro and use the included ansi2knr.
  177347. * I've always been able to use _NO_PROTO as the indicator, but you may
  177348. * need to drag the empty declaration out in front of here, or change the
  177349. * ifdef to suit your own needs.
  177350. */
  177351. #ifndef PNGARG
  177352. #ifdef OF /* zlib prototype munger */
  177353. # define PNGARG(arglist) OF(arglist)
  177354. #else
  177355. #ifdef _NO_PROTO
  177356. # define PNGARG(arglist) ()
  177357. # ifndef PNG_TYPECAST_NULL
  177358. # define PNG_TYPECAST_NULL
  177359. # endif
  177360. #else
  177361. # define PNGARG(arglist) arglist
  177362. #endif /* _NO_PROTO */
  177363. #endif /* OF */
  177364. #endif /* PNGARG */
  177365. /* Try to determine if we are compiling on a Mac. Note that testing for
  177366. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  177367. * on non-Mac platforms.
  177368. */
  177369. #ifndef MACOS
  177370. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  177371. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  177372. # define MACOS
  177373. # endif
  177374. #endif
  177375. /* enough people need this for various reasons to include it here */
  177376. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  177377. # include <sys/types.h>
  177378. #endif
  177379. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  177380. # define PNG_SETJMP_SUPPORTED
  177381. #endif
  177382. #ifdef PNG_SETJMP_SUPPORTED
  177383. /* This is an attempt to force a single setjmp behaviour on Linux. If
  177384. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  177385. */
  177386. # ifdef __linux__
  177387. # ifdef _BSD_SOURCE
  177388. # define PNG_SAVE_BSD_SOURCE
  177389. # undef _BSD_SOURCE
  177390. # endif
  177391. # ifdef _SETJMP_H
  177392. /* If you encounter a compiler error here, see the explanation
  177393. * near the end of INSTALL.
  177394. */
  177395. __png.h__ already includes setjmp.h;
  177396. __dont__ include it again.;
  177397. # endif
  177398. # endif /* __linux__ */
  177399. /* include setjmp.h for error handling */
  177400. # include <setjmp.h>
  177401. # ifdef __linux__
  177402. # ifdef PNG_SAVE_BSD_SOURCE
  177403. # define _BSD_SOURCE
  177404. # undef PNG_SAVE_BSD_SOURCE
  177405. # endif
  177406. # endif /* __linux__ */
  177407. #endif /* PNG_SETJMP_SUPPORTED */
  177408. #ifdef BSD
  177409. #if ! JUCE_MAC
  177410. # include <strings.h>
  177411. #endif
  177412. #else
  177413. # include <string.h>
  177414. #endif
  177415. /* Other defines for things like memory and the like can go here. */
  177416. #ifdef PNG_INTERNAL
  177417. #include <stdlib.h>
  177418. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  177419. * aren't usually used outside the library (as far as I know), so it is
  177420. * debatable if they should be exported at all. In the future, when it is
  177421. * possible to have run-time registry of chunk-handling functions, some of
  177422. * these will be made available again.
  177423. #define PNG_EXTERN extern
  177424. */
  177425. #define PNG_EXTERN
  177426. /* Other defines specific to compilers can go here. Try to keep
  177427. * them inside an appropriate ifdef/endif pair for portability.
  177428. */
  177429. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  177430. # if defined(MACOS)
  177431. /* We need to check that <math.h> hasn't already been included earlier
  177432. * as it seems it doesn't agree with <fp.h>, yet we should really use
  177433. * <fp.h> if possible.
  177434. */
  177435. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  177436. # include <fp.h>
  177437. # endif
  177438. # else
  177439. # include <math.h>
  177440. # endif
  177441. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  177442. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  177443. * MATH=68881
  177444. */
  177445. # include <m68881.h>
  177446. # endif
  177447. #endif
  177448. /* Codewarrior on NT has linking problems without this. */
  177449. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  177450. # define PNG_ALWAYS_EXTERN
  177451. #endif
  177452. /* This provides the non-ANSI (far) memory allocation routines. */
  177453. #if defined(__TURBOC__) && defined(__MSDOS__)
  177454. # include <mem.h>
  177455. # include <alloc.h>
  177456. #endif
  177457. /* I have no idea why is this necessary... */
  177458. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  177459. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  177460. # include <malloc.h>
  177461. #endif
  177462. /* This controls how fine the dithering gets. As this allocates
  177463. * a largish chunk of memory (32K), those who are not as concerned
  177464. * with dithering quality can decrease some or all of these.
  177465. */
  177466. #ifndef PNG_DITHER_RED_BITS
  177467. # define PNG_DITHER_RED_BITS 5
  177468. #endif
  177469. #ifndef PNG_DITHER_GREEN_BITS
  177470. # define PNG_DITHER_GREEN_BITS 5
  177471. #endif
  177472. #ifndef PNG_DITHER_BLUE_BITS
  177473. # define PNG_DITHER_BLUE_BITS 5
  177474. #endif
  177475. /* This controls how fine the gamma correction becomes when you
  177476. * are only interested in 8 bits anyway. Increasing this value
  177477. * results in more memory being used, and more pow() functions
  177478. * being called to fill in the gamma tables. Don't set this value
  177479. * less then 8, and even that may not work (I haven't tested it).
  177480. */
  177481. #ifndef PNG_MAX_GAMMA_8
  177482. # define PNG_MAX_GAMMA_8 11
  177483. #endif
  177484. /* This controls how much a difference in gamma we can tolerate before
  177485. * we actually start doing gamma conversion.
  177486. */
  177487. #ifndef PNG_GAMMA_THRESHOLD
  177488. # define PNG_GAMMA_THRESHOLD 0.05
  177489. #endif
  177490. #endif /* PNG_INTERNAL */
  177491. /* The following uses const char * instead of char * for error
  177492. * and warning message functions, so some compilers won't complain.
  177493. * If you do not want to use const, define PNG_NO_CONST here.
  177494. */
  177495. #ifndef PNG_NO_CONST
  177496. # define PNG_CONST const
  177497. #else
  177498. # define PNG_CONST
  177499. #endif
  177500. /* The following defines give you the ability to remove code from the
  177501. * library that you will not be using. I wish I could figure out how to
  177502. * automate this, but I can't do that without making it seriously hard
  177503. * on the users. So if you are not using an ability, change the #define
  177504. * to and #undef, and that part of the library will not be compiled. If
  177505. * your linker can't find a function, you may want to make sure the
  177506. * ability is defined here. Some of these depend upon some others being
  177507. * defined. I haven't figured out all the interactions here, so you may
  177508. * have to experiment awhile to get everything to compile. If you are
  177509. * creating or using a shared library, you probably shouldn't touch this,
  177510. * as it will affect the size of the structures, and this will cause bad
  177511. * things to happen if the library and/or application ever change.
  177512. */
  177513. /* Any features you will not be using can be undef'ed here */
  177514. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  177515. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  177516. * on the compile line, then pick and choose which ones to define without
  177517. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  177518. * if you only want to have a png-compliant reader/writer but don't need
  177519. * any of the extra transformations. This saves about 80 kbytes in a
  177520. * typical installation of the library. (PNG_NO_* form added in version
  177521. * 1.0.1c, for consistency)
  177522. */
  177523. /* The size of the png_text structure changed in libpng-1.0.6 when
  177524. * iTXt support was added. iTXt support was turned off by default through
  177525. * libpng-1.2.x, to support old apps that malloc the png_text structure
  177526. * instead of calling png_set_text() and letting libpng malloc it. It
  177527. * was turned on by default in libpng-1.3.0.
  177528. */
  177529. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177530. # ifndef PNG_NO_iTXt_SUPPORTED
  177531. # define PNG_NO_iTXt_SUPPORTED
  177532. # endif
  177533. # ifndef PNG_NO_READ_iTXt
  177534. # define PNG_NO_READ_iTXt
  177535. # endif
  177536. # ifndef PNG_NO_WRITE_iTXt
  177537. # define PNG_NO_WRITE_iTXt
  177538. # endif
  177539. #endif
  177540. #if !defined(PNG_NO_iTXt_SUPPORTED)
  177541. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  177542. # define PNG_READ_iTXt
  177543. # endif
  177544. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  177545. # define PNG_WRITE_iTXt
  177546. # endif
  177547. #endif
  177548. /* The following support, added after version 1.0.0, can be turned off here en
  177549. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  177550. * with old applications that require the length of png_struct and png_info
  177551. * to remain unchanged.
  177552. */
  177553. #ifdef PNG_LEGACY_SUPPORTED
  177554. # define PNG_NO_FREE_ME
  177555. # define PNG_NO_READ_UNKNOWN_CHUNKS
  177556. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  177557. # define PNG_NO_READ_USER_CHUNKS
  177558. # define PNG_NO_READ_iCCP
  177559. # define PNG_NO_WRITE_iCCP
  177560. # define PNG_NO_READ_iTXt
  177561. # define PNG_NO_WRITE_iTXt
  177562. # define PNG_NO_READ_sCAL
  177563. # define PNG_NO_WRITE_sCAL
  177564. # define PNG_NO_READ_sPLT
  177565. # define PNG_NO_WRITE_sPLT
  177566. # define PNG_NO_INFO_IMAGE
  177567. # define PNG_NO_READ_RGB_TO_GRAY
  177568. # define PNG_NO_READ_USER_TRANSFORM
  177569. # define PNG_NO_WRITE_USER_TRANSFORM
  177570. # define PNG_NO_USER_MEM
  177571. # define PNG_NO_READ_EMPTY_PLTE
  177572. # define PNG_NO_MNG_FEATURES
  177573. # define PNG_NO_FIXED_POINT_SUPPORTED
  177574. #endif
  177575. /* Ignore attempt to turn off both floating and fixed point support */
  177576. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  177577. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  177578. # define PNG_FIXED_POINT_SUPPORTED
  177579. #endif
  177580. #ifndef PNG_NO_FREE_ME
  177581. # define PNG_FREE_ME_SUPPORTED
  177582. #endif
  177583. #if defined(PNG_READ_SUPPORTED)
  177584. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  177585. !defined(PNG_NO_READ_TRANSFORMS)
  177586. # define PNG_READ_TRANSFORMS_SUPPORTED
  177587. #endif
  177588. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  177589. # ifndef PNG_NO_READ_EXPAND
  177590. # define PNG_READ_EXPAND_SUPPORTED
  177591. # endif
  177592. # ifndef PNG_NO_READ_SHIFT
  177593. # define PNG_READ_SHIFT_SUPPORTED
  177594. # endif
  177595. # ifndef PNG_NO_READ_PACK
  177596. # define PNG_READ_PACK_SUPPORTED
  177597. # endif
  177598. # ifndef PNG_NO_READ_BGR
  177599. # define PNG_READ_BGR_SUPPORTED
  177600. # endif
  177601. # ifndef PNG_NO_READ_SWAP
  177602. # define PNG_READ_SWAP_SUPPORTED
  177603. # endif
  177604. # ifndef PNG_NO_READ_PACKSWAP
  177605. # define PNG_READ_PACKSWAP_SUPPORTED
  177606. # endif
  177607. # ifndef PNG_NO_READ_INVERT
  177608. # define PNG_READ_INVERT_SUPPORTED
  177609. # endif
  177610. # ifndef PNG_NO_READ_DITHER
  177611. # define PNG_READ_DITHER_SUPPORTED
  177612. # endif
  177613. # ifndef PNG_NO_READ_BACKGROUND
  177614. # define PNG_READ_BACKGROUND_SUPPORTED
  177615. # endif
  177616. # ifndef PNG_NO_READ_16_TO_8
  177617. # define PNG_READ_16_TO_8_SUPPORTED
  177618. # endif
  177619. # ifndef PNG_NO_READ_FILLER
  177620. # define PNG_READ_FILLER_SUPPORTED
  177621. # endif
  177622. # ifndef PNG_NO_READ_GAMMA
  177623. # define PNG_READ_GAMMA_SUPPORTED
  177624. # endif
  177625. # ifndef PNG_NO_READ_GRAY_TO_RGB
  177626. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  177627. # endif
  177628. # ifndef PNG_NO_READ_SWAP_ALPHA
  177629. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  177630. # endif
  177631. # ifndef PNG_NO_READ_INVERT_ALPHA
  177632. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  177633. # endif
  177634. # ifndef PNG_NO_READ_STRIP_ALPHA
  177635. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  177636. # endif
  177637. # ifndef PNG_NO_READ_USER_TRANSFORM
  177638. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  177639. # endif
  177640. # ifndef PNG_NO_READ_RGB_TO_GRAY
  177641. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  177642. # endif
  177643. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  177644. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  177645. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  177646. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  177647. #endif /* about interlacing capability! You'll */
  177648. /* still have interlacing unless you change the following line: */
  177649. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  177650. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  177651. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  177652. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  177653. # endif
  177654. #endif
  177655. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177656. /* Deprecated, will be removed from version 2.0.0.
  177657. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  177658. #ifndef PNG_NO_READ_EMPTY_PLTE
  177659. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  177660. #endif
  177661. #endif
  177662. #endif /* PNG_READ_SUPPORTED */
  177663. #if defined(PNG_WRITE_SUPPORTED)
  177664. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  177665. !defined(PNG_NO_WRITE_TRANSFORMS)
  177666. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  177667. #endif
  177668. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  177669. # ifndef PNG_NO_WRITE_SHIFT
  177670. # define PNG_WRITE_SHIFT_SUPPORTED
  177671. # endif
  177672. # ifndef PNG_NO_WRITE_PACK
  177673. # define PNG_WRITE_PACK_SUPPORTED
  177674. # endif
  177675. # ifndef PNG_NO_WRITE_BGR
  177676. # define PNG_WRITE_BGR_SUPPORTED
  177677. # endif
  177678. # ifndef PNG_NO_WRITE_SWAP
  177679. # define PNG_WRITE_SWAP_SUPPORTED
  177680. # endif
  177681. # ifndef PNG_NO_WRITE_PACKSWAP
  177682. # define PNG_WRITE_PACKSWAP_SUPPORTED
  177683. # endif
  177684. # ifndef PNG_NO_WRITE_INVERT
  177685. # define PNG_WRITE_INVERT_SUPPORTED
  177686. # endif
  177687. # ifndef PNG_NO_WRITE_FILLER
  177688. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  177689. # endif
  177690. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  177691. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  177692. # endif
  177693. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  177694. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  177695. # endif
  177696. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  177697. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  177698. # endif
  177699. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  177700. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  177701. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177702. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  177703. encoders, but can cause trouble
  177704. if left undefined */
  177705. #endif
  177706. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  177707. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  177708. defined(PNG_FLOATING_POINT_SUPPORTED)
  177709. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  177710. #endif
  177711. #ifndef PNG_NO_WRITE_FLUSH
  177712. # define PNG_WRITE_FLUSH_SUPPORTED
  177713. #endif
  177714. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177715. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  177716. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  177717. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  177718. #endif
  177719. #endif
  177720. #endif /* PNG_WRITE_SUPPORTED */
  177721. #ifndef PNG_1_0_X
  177722. # ifndef PNG_NO_ERROR_NUMBERS
  177723. # define PNG_ERROR_NUMBERS_SUPPORTED
  177724. # endif
  177725. #endif /* PNG_1_0_X */
  177726. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177727. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  177728. # ifndef PNG_NO_USER_TRANSFORM_PTR
  177729. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  177730. # endif
  177731. #endif
  177732. #ifndef PNG_NO_STDIO
  177733. # define PNG_TIME_RFC1123_SUPPORTED
  177734. #endif
  177735. /* This adds extra functions in pngget.c for accessing data from the
  177736. * info pointer (added in version 0.99)
  177737. * png_get_image_width()
  177738. * png_get_image_height()
  177739. * png_get_bit_depth()
  177740. * png_get_color_type()
  177741. * png_get_compression_type()
  177742. * png_get_filter_type()
  177743. * png_get_interlace_type()
  177744. * png_get_pixel_aspect_ratio()
  177745. * png_get_pixels_per_meter()
  177746. * png_get_x_offset_pixels()
  177747. * png_get_y_offset_pixels()
  177748. * png_get_x_offset_microns()
  177749. * png_get_y_offset_microns()
  177750. */
  177751. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  177752. # define PNG_EASY_ACCESS_SUPPORTED
  177753. #endif
  177754. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  177755. * and removed from version 1.2.20. The following will be removed
  177756. * from libpng-1.4.0
  177757. */
  177758. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  177759. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  177760. # define PNG_OPTIMIZED_CODE_SUPPORTED
  177761. # endif
  177762. #endif
  177763. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  177764. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  177765. # define PNG_ASSEMBLER_CODE_SUPPORTED
  177766. # endif
  177767. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  177768. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  177769. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177770. # define PNG_NO_MMX_CODE
  177771. # endif
  177772. # endif
  177773. # if defined(__APPLE__)
  177774. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177775. # define PNG_NO_MMX_CODE
  177776. # endif
  177777. # endif
  177778. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  177779. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177780. # define PNG_NO_MMX_CODE
  177781. # endif
  177782. # endif
  177783. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177784. # define PNG_MMX_CODE_SUPPORTED
  177785. # endif
  177786. #endif
  177787. /* end of obsolete code to be removed from libpng-1.4.0 */
  177788. #if !defined(PNG_1_0_X)
  177789. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  177790. # define PNG_USER_MEM_SUPPORTED
  177791. #endif
  177792. #endif /* PNG_1_0_X */
  177793. /* Added at libpng-1.2.6 */
  177794. #if !defined(PNG_1_0_X)
  177795. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  177796. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  177797. # define PNG_SET_USER_LIMITS_SUPPORTED
  177798. #endif
  177799. #endif
  177800. #endif /* PNG_1_0_X */
  177801. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  177802. * how large, set these limits to 0x7fffffffL
  177803. */
  177804. #ifndef PNG_USER_WIDTH_MAX
  177805. # define PNG_USER_WIDTH_MAX 1000000L
  177806. #endif
  177807. #ifndef PNG_USER_HEIGHT_MAX
  177808. # define PNG_USER_HEIGHT_MAX 1000000L
  177809. #endif
  177810. /* These are currently experimental features, define them if you want */
  177811. /* very little testing */
  177812. /*
  177813. #ifdef PNG_READ_SUPPORTED
  177814. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  177815. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  177816. # endif
  177817. #endif
  177818. */
  177819. /* This is only for PowerPC big-endian and 680x0 systems */
  177820. /* some testing */
  177821. /*
  177822. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  177823. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  177824. #endif
  177825. */
  177826. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  177827. /*
  177828. #define PNG_NO_POINTER_INDEXING
  177829. */
  177830. /* These functions are turned off by default, as they will be phased out. */
  177831. /*
  177832. #define PNG_USELESS_TESTS_SUPPORTED
  177833. #define PNG_CORRECT_PALETTE_SUPPORTED
  177834. */
  177835. /* Any chunks you are not interested in, you can undef here. The
  177836. * ones that allocate memory may be expecially important (hIST,
  177837. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  177838. * a bit smaller.
  177839. */
  177840. #if defined(PNG_READ_SUPPORTED) && \
  177841. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177842. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  177843. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177844. #endif
  177845. #if defined(PNG_WRITE_SUPPORTED) && \
  177846. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177847. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  177848. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177849. #endif
  177850. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177851. #ifdef PNG_NO_READ_TEXT
  177852. # define PNG_NO_READ_iTXt
  177853. # define PNG_NO_READ_tEXt
  177854. # define PNG_NO_READ_zTXt
  177855. #endif
  177856. #ifndef PNG_NO_READ_bKGD
  177857. # define PNG_READ_bKGD_SUPPORTED
  177858. # define PNG_bKGD_SUPPORTED
  177859. #endif
  177860. #ifndef PNG_NO_READ_cHRM
  177861. # define PNG_READ_cHRM_SUPPORTED
  177862. # define PNG_cHRM_SUPPORTED
  177863. #endif
  177864. #ifndef PNG_NO_READ_gAMA
  177865. # define PNG_READ_gAMA_SUPPORTED
  177866. # define PNG_gAMA_SUPPORTED
  177867. #endif
  177868. #ifndef PNG_NO_READ_hIST
  177869. # define PNG_READ_hIST_SUPPORTED
  177870. # define PNG_hIST_SUPPORTED
  177871. #endif
  177872. #ifndef PNG_NO_READ_iCCP
  177873. # define PNG_READ_iCCP_SUPPORTED
  177874. # define PNG_iCCP_SUPPORTED
  177875. #endif
  177876. #ifndef PNG_NO_READ_iTXt
  177877. # ifndef PNG_READ_iTXt_SUPPORTED
  177878. # define PNG_READ_iTXt_SUPPORTED
  177879. # endif
  177880. # ifndef PNG_iTXt_SUPPORTED
  177881. # define PNG_iTXt_SUPPORTED
  177882. # endif
  177883. #endif
  177884. #ifndef PNG_NO_READ_oFFs
  177885. # define PNG_READ_oFFs_SUPPORTED
  177886. # define PNG_oFFs_SUPPORTED
  177887. #endif
  177888. #ifndef PNG_NO_READ_pCAL
  177889. # define PNG_READ_pCAL_SUPPORTED
  177890. # define PNG_pCAL_SUPPORTED
  177891. #endif
  177892. #ifndef PNG_NO_READ_sCAL
  177893. # define PNG_READ_sCAL_SUPPORTED
  177894. # define PNG_sCAL_SUPPORTED
  177895. #endif
  177896. #ifndef PNG_NO_READ_pHYs
  177897. # define PNG_READ_pHYs_SUPPORTED
  177898. # define PNG_pHYs_SUPPORTED
  177899. #endif
  177900. #ifndef PNG_NO_READ_sBIT
  177901. # define PNG_READ_sBIT_SUPPORTED
  177902. # define PNG_sBIT_SUPPORTED
  177903. #endif
  177904. #ifndef PNG_NO_READ_sPLT
  177905. # define PNG_READ_sPLT_SUPPORTED
  177906. # define PNG_sPLT_SUPPORTED
  177907. #endif
  177908. #ifndef PNG_NO_READ_sRGB
  177909. # define PNG_READ_sRGB_SUPPORTED
  177910. # define PNG_sRGB_SUPPORTED
  177911. #endif
  177912. #ifndef PNG_NO_READ_tEXt
  177913. # define PNG_READ_tEXt_SUPPORTED
  177914. # define PNG_tEXt_SUPPORTED
  177915. #endif
  177916. #ifndef PNG_NO_READ_tIME
  177917. # define PNG_READ_tIME_SUPPORTED
  177918. # define PNG_tIME_SUPPORTED
  177919. #endif
  177920. #ifndef PNG_NO_READ_tRNS
  177921. # define PNG_READ_tRNS_SUPPORTED
  177922. # define PNG_tRNS_SUPPORTED
  177923. #endif
  177924. #ifndef PNG_NO_READ_zTXt
  177925. # define PNG_READ_zTXt_SUPPORTED
  177926. # define PNG_zTXt_SUPPORTED
  177927. #endif
  177928. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  177929. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  177930. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177931. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177932. # endif
  177933. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177934. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177935. # endif
  177936. #endif
  177937. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  177938. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  177939. # define PNG_READ_USER_CHUNKS_SUPPORTED
  177940. # define PNG_USER_CHUNKS_SUPPORTED
  177941. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  177942. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  177943. # endif
  177944. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  177945. # undef PNG_NO_HANDLE_AS_UNKNOWN
  177946. # endif
  177947. #endif
  177948. #ifndef PNG_NO_READ_OPT_PLTE
  177949. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  177950. #endif /* optional PLTE chunk in RGB and RGBA images */
  177951. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  177952. defined(PNG_READ_zTXt_SUPPORTED)
  177953. # define PNG_READ_TEXT_SUPPORTED
  177954. # define PNG_TEXT_SUPPORTED
  177955. #endif
  177956. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  177957. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177958. #ifdef PNG_NO_WRITE_TEXT
  177959. # define PNG_NO_WRITE_iTXt
  177960. # define PNG_NO_WRITE_tEXt
  177961. # define PNG_NO_WRITE_zTXt
  177962. #endif
  177963. #ifndef PNG_NO_WRITE_bKGD
  177964. # define PNG_WRITE_bKGD_SUPPORTED
  177965. # ifndef PNG_bKGD_SUPPORTED
  177966. # define PNG_bKGD_SUPPORTED
  177967. # endif
  177968. #endif
  177969. #ifndef PNG_NO_WRITE_cHRM
  177970. # define PNG_WRITE_cHRM_SUPPORTED
  177971. # ifndef PNG_cHRM_SUPPORTED
  177972. # define PNG_cHRM_SUPPORTED
  177973. # endif
  177974. #endif
  177975. #ifndef PNG_NO_WRITE_gAMA
  177976. # define PNG_WRITE_gAMA_SUPPORTED
  177977. # ifndef PNG_gAMA_SUPPORTED
  177978. # define PNG_gAMA_SUPPORTED
  177979. # endif
  177980. #endif
  177981. #ifndef PNG_NO_WRITE_hIST
  177982. # define PNG_WRITE_hIST_SUPPORTED
  177983. # ifndef PNG_hIST_SUPPORTED
  177984. # define PNG_hIST_SUPPORTED
  177985. # endif
  177986. #endif
  177987. #ifndef PNG_NO_WRITE_iCCP
  177988. # define PNG_WRITE_iCCP_SUPPORTED
  177989. # ifndef PNG_iCCP_SUPPORTED
  177990. # define PNG_iCCP_SUPPORTED
  177991. # endif
  177992. #endif
  177993. #ifndef PNG_NO_WRITE_iTXt
  177994. # ifndef PNG_WRITE_iTXt_SUPPORTED
  177995. # define PNG_WRITE_iTXt_SUPPORTED
  177996. # endif
  177997. # ifndef PNG_iTXt_SUPPORTED
  177998. # define PNG_iTXt_SUPPORTED
  177999. # endif
  178000. #endif
  178001. #ifndef PNG_NO_WRITE_oFFs
  178002. # define PNG_WRITE_oFFs_SUPPORTED
  178003. # ifndef PNG_oFFs_SUPPORTED
  178004. # define PNG_oFFs_SUPPORTED
  178005. # endif
  178006. #endif
  178007. #ifndef PNG_NO_WRITE_pCAL
  178008. # define PNG_WRITE_pCAL_SUPPORTED
  178009. # ifndef PNG_pCAL_SUPPORTED
  178010. # define PNG_pCAL_SUPPORTED
  178011. # endif
  178012. #endif
  178013. #ifndef PNG_NO_WRITE_sCAL
  178014. # define PNG_WRITE_sCAL_SUPPORTED
  178015. # ifndef PNG_sCAL_SUPPORTED
  178016. # define PNG_sCAL_SUPPORTED
  178017. # endif
  178018. #endif
  178019. #ifndef PNG_NO_WRITE_pHYs
  178020. # define PNG_WRITE_pHYs_SUPPORTED
  178021. # ifndef PNG_pHYs_SUPPORTED
  178022. # define PNG_pHYs_SUPPORTED
  178023. # endif
  178024. #endif
  178025. #ifndef PNG_NO_WRITE_sBIT
  178026. # define PNG_WRITE_sBIT_SUPPORTED
  178027. # ifndef PNG_sBIT_SUPPORTED
  178028. # define PNG_sBIT_SUPPORTED
  178029. # endif
  178030. #endif
  178031. #ifndef PNG_NO_WRITE_sPLT
  178032. # define PNG_WRITE_sPLT_SUPPORTED
  178033. # ifndef PNG_sPLT_SUPPORTED
  178034. # define PNG_sPLT_SUPPORTED
  178035. # endif
  178036. #endif
  178037. #ifndef PNG_NO_WRITE_sRGB
  178038. # define PNG_WRITE_sRGB_SUPPORTED
  178039. # ifndef PNG_sRGB_SUPPORTED
  178040. # define PNG_sRGB_SUPPORTED
  178041. # endif
  178042. #endif
  178043. #ifndef PNG_NO_WRITE_tEXt
  178044. # define PNG_WRITE_tEXt_SUPPORTED
  178045. # ifndef PNG_tEXt_SUPPORTED
  178046. # define PNG_tEXt_SUPPORTED
  178047. # endif
  178048. #endif
  178049. #ifndef PNG_NO_WRITE_tIME
  178050. # define PNG_WRITE_tIME_SUPPORTED
  178051. # ifndef PNG_tIME_SUPPORTED
  178052. # define PNG_tIME_SUPPORTED
  178053. # endif
  178054. #endif
  178055. #ifndef PNG_NO_WRITE_tRNS
  178056. # define PNG_WRITE_tRNS_SUPPORTED
  178057. # ifndef PNG_tRNS_SUPPORTED
  178058. # define PNG_tRNS_SUPPORTED
  178059. # endif
  178060. #endif
  178061. #ifndef PNG_NO_WRITE_zTXt
  178062. # define PNG_WRITE_zTXt_SUPPORTED
  178063. # ifndef PNG_zTXt_SUPPORTED
  178064. # define PNG_zTXt_SUPPORTED
  178065. # endif
  178066. #endif
  178067. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  178068. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  178069. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  178070. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  178071. # endif
  178072. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  178073. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178074. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178075. # endif
  178076. # endif
  178077. #endif
  178078. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  178079. defined(PNG_WRITE_zTXt_SUPPORTED)
  178080. # define PNG_WRITE_TEXT_SUPPORTED
  178081. # ifndef PNG_TEXT_SUPPORTED
  178082. # define PNG_TEXT_SUPPORTED
  178083. # endif
  178084. #endif
  178085. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  178086. /* Turn this off to disable png_read_png() and
  178087. * png_write_png() and leave the row_pointers member
  178088. * out of the info structure.
  178089. */
  178090. #ifndef PNG_NO_INFO_IMAGE
  178091. # define PNG_INFO_IMAGE_SUPPORTED
  178092. #endif
  178093. /* need the time information for reading tIME chunks */
  178094. #if defined(PNG_tIME_SUPPORTED)
  178095. # if !defined(_WIN32_WCE)
  178096. /* "time.h" functions are not supported on WindowsCE */
  178097. # include <time.h>
  178098. # endif
  178099. #endif
  178100. /* Some typedefs to get us started. These should be safe on most of the
  178101. * common platforms. The typedefs should be at least as large as the
  178102. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  178103. * don't have to be exactly that size. Some compilers dislike passing
  178104. * unsigned shorts as function parameters, so you may be better off using
  178105. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  178106. * want to have unsigned int for png_uint_32 instead of unsigned long.
  178107. */
  178108. typedef unsigned long png_uint_32;
  178109. typedef long png_int_32;
  178110. typedef unsigned short png_uint_16;
  178111. typedef short png_int_16;
  178112. typedef unsigned char png_byte;
  178113. /* This is usually size_t. It is typedef'ed just in case you need it to
  178114. change (I'm not sure if you will or not, so I thought I'd be safe) */
  178115. #ifdef PNG_SIZE_T
  178116. typedef PNG_SIZE_T png_size_t;
  178117. # define png_sizeof(x) png_convert_size(sizeof (x))
  178118. #else
  178119. typedef size_t png_size_t;
  178120. # define png_sizeof(x) sizeof (x)
  178121. #endif
  178122. /* The following is needed for medium model support. It cannot be in the
  178123. * PNG_INTERNAL section. Needs modification for other compilers besides
  178124. * MSC. Model independent support declares all arrays and pointers to be
  178125. * large using the far keyword. The zlib version used must also support
  178126. * model independent data. As of version zlib 1.0.4, the necessary changes
  178127. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  178128. * changes that are needed. (Tim Wegner)
  178129. */
  178130. /* Separate compiler dependencies (problem here is that zlib.h always
  178131. defines FAR. (SJT) */
  178132. #ifdef __BORLANDC__
  178133. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  178134. # define LDATA 1
  178135. # else
  178136. # define LDATA 0
  178137. # endif
  178138. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  178139. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  178140. # define PNG_MAX_MALLOC_64K
  178141. # if (LDATA != 1)
  178142. # ifndef FAR
  178143. # define FAR __far
  178144. # endif
  178145. # define USE_FAR_KEYWORD
  178146. # endif /* LDATA != 1 */
  178147. /* Possibly useful for moving data out of default segment.
  178148. * Uncomment it if you want. Could also define FARDATA as
  178149. * const if your compiler supports it. (SJT)
  178150. # define FARDATA FAR
  178151. */
  178152. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  178153. #endif /* __BORLANDC__ */
  178154. /* Suggest testing for specific compiler first before testing for
  178155. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  178156. * making reliance oncertain keywords suspect. (SJT)
  178157. */
  178158. /* MSC Medium model */
  178159. #if defined(FAR)
  178160. # if defined(M_I86MM)
  178161. # define USE_FAR_KEYWORD
  178162. # define FARDATA FAR
  178163. # include <dos.h>
  178164. # endif
  178165. #endif
  178166. /* SJT: default case */
  178167. #ifndef FAR
  178168. # define FAR
  178169. #endif
  178170. /* At this point FAR is always defined */
  178171. #ifndef FARDATA
  178172. # define FARDATA
  178173. #endif
  178174. /* Typedef for floating-point numbers that are converted
  178175. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  178176. typedef png_int_32 png_fixed_point;
  178177. /* Add typedefs for pointers */
  178178. typedef void FAR * png_voidp;
  178179. typedef png_byte FAR * png_bytep;
  178180. typedef png_uint_32 FAR * png_uint_32p;
  178181. typedef png_int_32 FAR * png_int_32p;
  178182. typedef png_uint_16 FAR * png_uint_16p;
  178183. typedef png_int_16 FAR * png_int_16p;
  178184. typedef PNG_CONST char FAR * png_const_charp;
  178185. typedef char FAR * png_charp;
  178186. typedef png_fixed_point FAR * png_fixed_point_p;
  178187. #ifndef PNG_NO_STDIO
  178188. #if defined(_WIN32_WCE)
  178189. typedef HANDLE png_FILE_p;
  178190. #else
  178191. typedef FILE * png_FILE_p;
  178192. #endif
  178193. #endif
  178194. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178195. typedef double FAR * png_doublep;
  178196. #endif
  178197. /* Pointers to pointers; i.e. arrays */
  178198. typedef png_byte FAR * FAR * png_bytepp;
  178199. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  178200. typedef png_int_32 FAR * FAR * png_int_32pp;
  178201. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  178202. typedef png_int_16 FAR * FAR * png_int_16pp;
  178203. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  178204. typedef char FAR * FAR * png_charpp;
  178205. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  178206. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178207. typedef double FAR * FAR * png_doublepp;
  178208. #endif
  178209. /* Pointers to pointers to pointers; i.e., pointer to array */
  178210. typedef char FAR * FAR * FAR * png_charppp;
  178211. #if 0
  178212. /* SPC - Is this stuff deprecated? */
  178213. /* It'll be removed as of libpng-1.3.0 - GR-P */
  178214. /* libpng typedefs for types in zlib. If zlib changes
  178215. * or another compression library is used, then change these.
  178216. * Eliminates need to change all the source files.
  178217. */
  178218. typedef charf * png_zcharp;
  178219. typedef charf * FAR * png_zcharpp;
  178220. typedef z_stream FAR * png_zstreamp;
  178221. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  178222. /*
  178223. * Define PNG_BUILD_DLL if the module being built is a Windows
  178224. * LIBPNG DLL.
  178225. *
  178226. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  178227. * It is equivalent to Microsoft predefined macro _DLL that is
  178228. * automatically defined when you compile using the share
  178229. * version of the CRT (C Run-Time library)
  178230. *
  178231. * The cygwin mods make this behavior a little different:
  178232. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  178233. * Define PNG_STATIC if you are building a static library for use with cygwin,
  178234. * -or- if you are building an application that you want to link to the
  178235. * static library.
  178236. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  178237. * the other flags is defined.
  178238. */
  178239. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  178240. # define PNG_DLL
  178241. #endif
  178242. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  178243. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  178244. * command-line override
  178245. */
  178246. #if defined(__CYGWIN__)
  178247. # if !defined(PNG_STATIC)
  178248. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178249. # undef PNG_USE_GLOBAL_ARRAYS
  178250. # endif
  178251. # if !defined(PNG_USE_LOCAL_ARRAYS)
  178252. # define PNG_USE_LOCAL_ARRAYS
  178253. # endif
  178254. # else
  178255. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  178256. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178257. # undef PNG_USE_GLOBAL_ARRAYS
  178258. # endif
  178259. # endif
  178260. # endif
  178261. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178262. # define PNG_USE_LOCAL_ARRAYS
  178263. # endif
  178264. #endif
  178265. /* Do not use global arrays (helps with building DLL's)
  178266. * They are no longer used in libpng itself, since version 1.0.5c,
  178267. * but might be required for some pre-1.0.5c applications.
  178268. */
  178269. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178270. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  178271. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  178272. # define PNG_USE_LOCAL_ARRAYS
  178273. # else
  178274. # define PNG_USE_GLOBAL_ARRAYS
  178275. # endif
  178276. #endif
  178277. #if defined(__CYGWIN__)
  178278. # undef PNGAPI
  178279. # define PNGAPI __cdecl
  178280. # undef PNG_IMPEXP
  178281. # define PNG_IMPEXP
  178282. #endif
  178283. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  178284. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  178285. * Don't ignore those warnings; you must also reset the default calling
  178286. * convention in your compiler to match your PNGAPI, and you must build
  178287. * zlib and your applications the same way you build libpng.
  178288. */
  178289. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  178290. # ifndef PNG_NO_MODULEDEF
  178291. # define PNG_NO_MODULEDEF
  178292. # endif
  178293. #endif
  178294. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  178295. # define PNG_IMPEXP
  178296. #endif
  178297. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  178298. (( defined(_Windows) || defined(_WINDOWS) || \
  178299. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  178300. # ifndef PNGAPI
  178301. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  178302. # define PNGAPI __cdecl
  178303. # else
  178304. # define PNGAPI _cdecl
  178305. # endif
  178306. # endif
  178307. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  178308. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  178309. # define PNG_IMPEXP
  178310. # endif
  178311. # if !defined(PNG_IMPEXP)
  178312. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178313. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  178314. /* Borland/Microsoft */
  178315. # if defined(_MSC_VER) || defined(__BORLANDC__)
  178316. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  178317. # define PNG_EXPORT PNG_EXPORT_TYPE1
  178318. # else
  178319. # define PNG_EXPORT PNG_EXPORT_TYPE2
  178320. # if defined(PNG_BUILD_DLL)
  178321. # define PNG_IMPEXP __export
  178322. # else
  178323. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  178324. VC++ */
  178325. # endif /* Exists in Borland C++ for
  178326. C++ classes (== huge) */
  178327. # endif
  178328. # endif
  178329. # if !defined(PNG_IMPEXP)
  178330. # if defined(PNG_BUILD_DLL)
  178331. # define PNG_IMPEXP __declspec(dllexport)
  178332. # else
  178333. # define PNG_IMPEXP __declspec(dllimport)
  178334. # endif
  178335. # endif
  178336. # endif /* PNG_IMPEXP */
  178337. #else /* !(DLL || non-cygwin WINDOWS) */
  178338. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  178339. # ifndef PNGAPI
  178340. # define PNGAPI _System
  178341. # endif
  178342. # else
  178343. # if 0 /* ... other platforms, with other meanings */
  178344. # endif
  178345. # endif
  178346. #endif
  178347. #ifndef PNGAPI
  178348. # define PNGAPI
  178349. #endif
  178350. #ifndef PNG_IMPEXP
  178351. # define PNG_IMPEXP
  178352. #endif
  178353. #ifdef PNG_BUILDSYMS
  178354. # ifndef PNG_EXPORT
  178355. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  178356. # endif
  178357. # ifdef PNG_USE_GLOBAL_ARRAYS
  178358. # ifndef PNG_EXPORT_VAR
  178359. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  178360. # endif
  178361. # endif
  178362. #endif
  178363. #ifndef PNG_EXPORT
  178364. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178365. #endif
  178366. #ifdef PNG_USE_GLOBAL_ARRAYS
  178367. # ifndef PNG_EXPORT_VAR
  178368. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  178369. # endif
  178370. #endif
  178371. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  178372. * functions that are passed far data must be model independent.
  178373. */
  178374. #ifndef PNG_ABORT
  178375. # define PNG_ABORT() abort()
  178376. #endif
  178377. #ifdef PNG_SETJMP_SUPPORTED
  178378. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  178379. #else
  178380. # define png_jmpbuf(png_ptr) \
  178381. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  178382. #endif
  178383. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  178384. /* use this to make far-to-near assignments */
  178385. # define CHECK 1
  178386. # define NOCHECK 0
  178387. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  178388. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  178389. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  178390. # define png_strcpy _fstrcpy
  178391. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  178392. # define png_strlen _fstrlen
  178393. # define png_memcmp _fmemcmp /* SJT: added */
  178394. # define png_memcpy _fmemcpy
  178395. # define png_memset _fmemset
  178396. #else /* use the usual functions */
  178397. # define CVT_PTR(ptr) (ptr)
  178398. # define CVT_PTR_NOCHECK(ptr) (ptr)
  178399. # ifndef PNG_NO_SNPRINTF
  178400. # ifdef _MSC_VER
  178401. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  178402. # define png_snprintf2 _snprintf
  178403. # define png_snprintf6 _snprintf
  178404. # else
  178405. # define png_snprintf snprintf /* Added to v 1.2.19 */
  178406. # define png_snprintf2 snprintf
  178407. # define png_snprintf6 snprintf
  178408. # endif
  178409. # else
  178410. /* You don't have or don't want to use snprintf(). Caution: Using
  178411. * sprintf instead of snprintf exposes your application to accidental
  178412. * or malevolent buffer overflows. If you don't have snprintf()
  178413. * as a general rule you should provide one (you can get one from
  178414. * Portable OpenSSH). */
  178415. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  178416. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  178417. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  178418. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  178419. # endif
  178420. # define png_strcpy strcpy
  178421. # define png_strncpy strncpy /* Added to v 1.2.6 */
  178422. # define png_strlen strlen
  178423. # define png_memcmp memcmp /* SJT: added */
  178424. # define png_memcpy memcpy
  178425. # define png_memset memset
  178426. #endif
  178427. /* End of memory model independent support */
  178428. /* Just a little check that someone hasn't tried to define something
  178429. * contradictory.
  178430. */
  178431. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  178432. # undef PNG_ZBUF_SIZE
  178433. # define PNG_ZBUF_SIZE 65536L
  178434. #endif
  178435. /* Added at libpng-1.2.8 */
  178436. #endif /* PNG_VERSION_INFO_ONLY */
  178437. #endif /* PNGCONF_H */
  178438. /*** End of inlined file: pngconf.h ***/
  178439. #ifdef _MSC_VER
  178440. #pragma warning (disable: 4996 4100)
  178441. #endif
  178442. /*
  178443. * Added at libpng-1.2.8 */
  178444. /* Ref MSDN: Private as priority over Special
  178445. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  178446. * procedures. If this value is given, the StringFileInfo block must
  178447. * contain a PrivateBuild string.
  178448. *
  178449. * VS_FF_SPECIALBUILD File *was* built by the original company using
  178450. * standard release procedures but is a variation of the standard
  178451. * file of the same version number. If this value is given, the
  178452. * StringFileInfo block must contain a SpecialBuild string.
  178453. */
  178454. #if defined(PNG_USER_PRIVATEBUILD)
  178455. # define PNG_LIBPNG_BUILD_TYPE \
  178456. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  178457. #else
  178458. # if defined(PNG_LIBPNG_SPECIALBUILD)
  178459. # define PNG_LIBPNG_BUILD_TYPE \
  178460. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  178461. # else
  178462. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  178463. # endif
  178464. #endif
  178465. #ifndef PNG_VERSION_INFO_ONLY
  178466. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  178467. #ifdef __cplusplus
  178468. extern "C" {
  178469. #endif /* __cplusplus */
  178470. /* This file is arranged in several sections. The first section contains
  178471. * structure and type definitions. The second section contains the external
  178472. * library functions, while the third has the internal library functions,
  178473. * which applications aren't expected to use directly.
  178474. */
  178475. #ifndef PNG_NO_TYPECAST_NULL
  178476. #define int_p_NULL (int *)NULL
  178477. #define png_bytep_NULL (png_bytep)NULL
  178478. #define png_bytepp_NULL (png_bytepp)NULL
  178479. #define png_doublep_NULL (png_doublep)NULL
  178480. #define png_error_ptr_NULL (png_error_ptr)NULL
  178481. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  178482. #define png_free_ptr_NULL (png_free_ptr)NULL
  178483. #define png_infopp_NULL (png_infopp)NULL
  178484. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  178485. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  178486. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  178487. #define png_structp_NULL (png_structp)NULL
  178488. #define png_uint_16p_NULL (png_uint_16p)NULL
  178489. #define png_voidp_NULL (png_voidp)NULL
  178490. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  178491. #else
  178492. #define int_p_NULL NULL
  178493. #define png_bytep_NULL NULL
  178494. #define png_bytepp_NULL NULL
  178495. #define png_doublep_NULL NULL
  178496. #define png_error_ptr_NULL NULL
  178497. #define png_flush_ptr_NULL NULL
  178498. #define png_free_ptr_NULL NULL
  178499. #define png_infopp_NULL NULL
  178500. #define png_malloc_ptr_NULL NULL
  178501. #define png_read_status_ptr_NULL NULL
  178502. #define png_rw_ptr_NULL NULL
  178503. #define png_structp_NULL NULL
  178504. #define png_uint_16p_NULL NULL
  178505. #define png_voidp_NULL NULL
  178506. #define png_write_status_ptr_NULL NULL
  178507. #endif
  178508. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  178509. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  178510. /* Version information for C files, stored in png.c. This had better match
  178511. * the version above.
  178512. */
  178513. #ifdef PNG_USE_GLOBAL_ARRAYS
  178514. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  178515. /* need room for 99.99.99beta99z */
  178516. #else
  178517. #define png_libpng_ver png_get_header_ver(NULL)
  178518. #endif
  178519. #ifdef PNG_USE_GLOBAL_ARRAYS
  178520. /* This was removed in version 1.0.5c */
  178521. /* Structures to facilitate easy interlacing. See png.c for more details */
  178522. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  178523. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  178524. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  178525. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  178526. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  178527. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  178528. /* This isn't currently used. If you need it, see png.c for more details.
  178529. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  178530. */
  178531. #endif
  178532. #endif /* PNG_NO_EXTERN */
  178533. /* Three color definitions. The order of the red, green, and blue, (and the
  178534. * exact size) is not important, although the size of the fields need to
  178535. * be png_byte or png_uint_16 (as defined below).
  178536. */
  178537. typedef struct png_color_struct
  178538. {
  178539. png_byte red;
  178540. png_byte green;
  178541. png_byte blue;
  178542. } png_color;
  178543. typedef png_color FAR * png_colorp;
  178544. typedef png_color FAR * FAR * png_colorpp;
  178545. typedef struct png_color_16_struct
  178546. {
  178547. png_byte index; /* used for palette files */
  178548. png_uint_16 red; /* for use in red green blue files */
  178549. png_uint_16 green;
  178550. png_uint_16 blue;
  178551. png_uint_16 gray; /* for use in grayscale files */
  178552. } png_color_16;
  178553. typedef png_color_16 FAR * png_color_16p;
  178554. typedef png_color_16 FAR * FAR * png_color_16pp;
  178555. typedef struct png_color_8_struct
  178556. {
  178557. png_byte red; /* for use in red green blue files */
  178558. png_byte green;
  178559. png_byte blue;
  178560. png_byte gray; /* for use in grayscale files */
  178561. png_byte alpha; /* for alpha channel files */
  178562. } png_color_8;
  178563. typedef png_color_8 FAR * png_color_8p;
  178564. typedef png_color_8 FAR * FAR * png_color_8pp;
  178565. /*
  178566. * The following two structures are used for the in-core representation
  178567. * of sPLT chunks.
  178568. */
  178569. typedef struct png_sPLT_entry_struct
  178570. {
  178571. png_uint_16 red;
  178572. png_uint_16 green;
  178573. png_uint_16 blue;
  178574. png_uint_16 alpha;
  178575. png_uint_16 frequency;
  178576. } png_sPLT_entry;
  178577. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  178578. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  178579. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  178580. * occupy the LSB of their respective members, and the MSB of each member
  178581. * is zero-filled. The frequency member always occupies the full 16 bits.
  178582. */
  178583. typedef struct png_sPLT_struct
  178584. {
  178585. png_charp name; /* palette name */
  178586. png_byte depth; /* depth of palette samples */
  178587. png_sPLT_entryp entries; /* palette entries */
  178588. png_int_32 nentries; /* number of palette entries */
  178589. } png_sPLT_t;
  178590. typedef png_sPLT_t FAR * png_sPLT_tp;
  178591. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  178592. #ifdef PNG_TEXT_SUPPORTED
  178593. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  178594. * and whether that contents is compressed or not. The "key" field
  178595. * points to a regular zero-terminated C string. The "text", "lang", and
  178596. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  178597. * However, the * structure returned by png_get_text() will always contain
  178598. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  178599. * so they can be safely used in printf() and other string-handling functions.
  178600. */
  178601. typedef struct png_text_struct
  178602. {
  178603. int compression; /* compression value:
  178604. -1: tEXt, none
  178605. 0: zTXt, deflate
  178606. 1: iTXt, none
  178607. 2: iTXt, deflate */
  178608. png_charp key; /* keyword, 1-79 character description of "text" */
  178609. png_charp text; /* comment, may be an empty string (ie "")
  178610. or a NULL pointer */
  178611. png_size_t text_length; /* length of the text string */
  178612. #ifdef PNG_iTXt_SUPPORTED
  178613. png_size_t itxt_length; /* length of the itxt string */
  178614. png_charp lang; /* language code, 0-79 characters
  178615. or a NULL pointer */
  178616. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  178617. chars or a NULL pointer */
  178618. #endif
  178619. } png_text;
  178620. typedef png_text FAR * png_textp;
  178621. typedef png_text FAR * FAR * png_textpp;
  178622. #endif
  178623. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  178624. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  178625. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  178626. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  178627. #define PNG_TEXT_COMPRESSION_NONE -1
  178628. #define PNG_TEXT_COMPRESSION_zTXt 0
  178629. #define PNG_ITXT_COMPRESSION_NONE 1
  178630. #define PNG_ITXT_COMPRESSION_zTXt 2
  178631. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  178632. /* png_time is a way to hold the time in an machine independent way.
  178633. * Two conversions are provided, both from time_t and struct tm. There
  178634. * is no portable way to convert to either of these structures, as far
  178635. * as I know. If you know of a portable way, send it to me. As a side
  178636. * note - PNG has always been Year 2000 compliant!
  178637. */
  178638. typedef struct png_time_struct
  178639. {
  178640. png_uint_16 year; /* full year, as in, 1995 */
  178641. png_byte month; /* month of year, 1 - 12 */
  178642. png_byte day; /* day of month, 1 - 31 */
  178643. png_byte hour; /* hour of day, 0 - 23 */
  178644. png_byte minute; /* minute of hour, 0 - 59 */
  178645. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  178646. } png_time;
  178647. typedef png_time FAR * png_timep;
  178648. typedef png_time FAR * FAR * png_timepp;
  178649. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178650. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  178651. * no specific support. The idea is that we can use this to queue
  178652. * up private chunks for output even though the library doesn't actually
  178653. * know about their semantics.
  178654. */
  178655. typedef struct png_unknown_chunk_t
  178656. {
  178657. png_byte name[5];
  178658. png_byte *data;
  178659. png_size_t size;
  178660. /* libpng-using applications should NOT directly modify this byte. */
  178661. png_byte location; /* mode of operation at read time */
  178662. }
  178663. png_unknown_chunk;
  178664. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  178665. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  178666. #endif
  178667. /* png_info is a structure that holds the information in a PNG file so
  178668. * that the application can find out the characteristics of the image.
  178669. * If you are reading the file, this structure will tell you what is
  178670. * in the PNG file. If you are writing the file, fill in the information
  178671. * you want to put into the PNG file, then call png_write_info().
  178672. * The names chosen should be very close to the PNG specification, so
  178673. * consult that document for information about the meaning of each field.
  178674. *
  178675. * With libpng < 0.95, it was only possible to directly set and read the
  178676. * the values in the png_info_struct, which meant that the contents and
  178677. * order of the values had to remain fixed. With libpng 0.95 and later,
  178678. * however, there are now functions that abstract the contents of
  178679. * png_info_struct from the application, so this makes it easier to use
  178680. * libpng with dynamic libraries, and even makes it possible to use
  178681. * libraries that don't have all of the libpng ancillary chunk-handing
  178682. * functionality.
  178683. *
  178684. * In any case, the order of the parameters in png_info_struct should NOT
  178685. * be changed for as long as possible to keep compatibility with applications
  178686. * that use the old direct-access method with png_info_struct.
  178687. *
  178688. * The following members may have allocated storage attached that should be
  178689. * cleaned up before the structure is discarded: palette, trans, text,
  178690. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  178691. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  178692. * are automatically freed when the info structure is deallocated, if they were
  178693. * allocated internally by libpng. This behavior can be changed by means
  178694. * of the png_data_freer() function.
  178695. *
  178696. * More allocation details: all the chunk-reading functions that
  178697. * change these members go through the corresponding png_set_*
  178698. * functions. A function to clear these members is available: see
  178699. * png_free_data(). The png_set_* functions do not depend on being
  178700. * able to point info structure members to any of the storage they are
  178701. * passed (they make their own copies), EXCEPT that the png_set_text
  178702. * functions use the same storage passed to them in the text_ptr or
  178703. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  178704. * functions do not make their own copies.
  178705. */
  178706. typedef struct png_info_struct
  178707. {
  178708. /* the following are necessary for every PNG file */
  178709. png_uint_32 width; /* width of image in pixels (from IHDR) */
  178710. png_uint_32 height; /* height of image in pixels (from IHDR) */
  178711. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  178712. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  178713. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  178714. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  178715. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  178716. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  178717. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  178718. /* The following three should have been named *_method not *_type */
  178719. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  178720. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  178721. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  178722. /* The following is informational only on read, and not used on writes. */
  178723. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  178724. png_byte pixel_depth; /* number of bits per pixel */
  178725. png_byte spare_byte; /* to align the data, and for future use */
  178726. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  178727. /* The rest of the data is optional. If you are reading, check the
  178728. * valid field to see if the information in these are valid. If you
  178729. * are writing, set the valid field to those chunks you want written,
  178730. * and initialize the appropriate fields below.
  178731. */
  178732. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  178733. /* The gAMA chunk describes the gamma characteristics of the system
  178734. * on which the image was created, normally in the range [1.0, 2.5].
  178735. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  178736. */
  178737. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  178738. #endif
  178739. #if defined(PNG_sRGB_SUPPORTED)
  178740. /* GR-P, 0.96a */
  178741. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  178742. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  178743. #endif
  178744. #if defined(PNG_TEXT_SUPPORTED)
  178745. /* The tEXt, and zTXt chunks contain human-readable textual data in
  178746. * uncompressed, compressed, and optionally compressed forms, respectively.
  178747. * The data in "text" is an array of pointers to uncompressed,
  178748. * null-terminated C strings. Each chunk has a keyword that describes the
  178749. * textual data contained in that chunk. Keywords are not required to be
  178750. * unique, and the text string may be empty. Any number of text chunks may
  178751. * be in an image.
  178752. */
  178753. int num_text; /* number of comments read/to write */
  178754. int max_text; /* current size of text array */
  178755. png_textp text; /* array of comments read/to write */
  178756. #endif /* PNG_TEXT_SUPPORTED */
  178757. #if defined(PNG_tIME_SUPPORTED)
  178758. /* The tIME chunk holds the last time the displayed image data was
  178759. * modified. See the png_time struct for the contents of this struct.
  178760. */
  178761. png_time mod_time;
  178762. #endif
  178763. #if defined(PNG_sBIT_SUPPORTED)
  178764. /* The sBIT chunk specifies the number of significant high-order bits
  178765. * in the pixel data. Values are in the range [1, bit_depth], and are
  178766. * only specified for the channels in the pixel data. The contents of
  178767. * the low-order bits is not specified. Data is valid if
  178768. * (valid & PNG_INFO_sBIT) is non-zero.
  178769. */
  178770. png_color_8 sig_bit; /* significant bits in color channels */
  178771. #endif
  178772. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  178773. defined(PNG_READ_BACKGROUND_SUPPORTED)
  178774. /* The tRNS chunk supplies transparency data for paletted images and
  178775. * other image types that don't need a full alpha channel. There are
  178776. * "num_trans" transparency values for a paletted image, stored in the
  178777. * same order as the palette colors, starting from index 0. Values
  178778. * for the data are in the range [0, 255], ranging from fully transparent
  178779. * to fully opaque, respectively. For non-paletted images, there is a
  178780. * single color specified that should be treated as fully transparent.
  178781. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  178782. */
  178783. png_bytep trans; /* transparent values for paletted image */
  178784. png_color_16 trans_values; /* transparent color for non-palette image */
  178785. #endif
  178786. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178787. /* The bKGD chunk gives the suggested image background color if the
  178788. * display program does not have its own background color and the image
  178789. * is needs to composited onto a background before display. The colors
  178790. * in "background" are normally in the same color space/depth as the
  178791. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  178792. */
  178793. png_color_16 background;
  178794. #endif
  178795. #if defined(PNG_oFFs_SUPPORTED)
  178796. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  178797. * and downwards from the top-left corner of the display, page, or other
  178798. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  178799. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  178800. */
  178801. png_int_32 x_offset; /* x offset on page */
  178802. png_int_32 y_offset; /* y offset on page */
  178803. png_byte offset_unit_type; /* offset units type */
  178804. #endif
  178805. #if defined(PNG_pHYs_SUPPORTED)
  178806. /* The pHYs chunk gives the physical pixel density of the image for
  178807. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  178808. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  178809. */
  178810. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  178811. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  178812. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  178813. #endif
  178814. #if defined(PNG_hIST_SUPPORTED)
  178815. /* The hIST chunk contains the relative frequency or importance of the
  178816. * various palette entries, so that a viewer can intelligently select a
  178817. * reduced-color palette, if required. Data is an array of "num_palette"
  178818. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  178819. * is non-zero.
  178820. */
  178821. png_uint_16p hist;
  178822. #endif
  178823. #ifdef PNG_cHRM_SUPPORTED
  178824. /* The cHRM chunk describes the CIE color characteristics of the monitor
  178825. * on which the PNG was created. This data allows the viewer to do gamut
  178826. * mapping of the input image to ensure that the viewer sees the same
  178827. * colors in the image as the creator. Values are in the range
  178828. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  178829. */
  178830. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178831. float x_white;
  178832. float y_white;
  178833. float x_red;
  178834. float y_red;
  178835. float x_green;
  178836. float y_green;
  178837. float x_blue;
  178838. float y_blue;
  178839. #endif
  178840. #endif
  178841. #if defined(PNG_pCAL_SUPPORTED)
  178842. /* The pCAL chunk describes a transformation between the stored pixel
  178843. * values and original physical data values used to create the image.
  178844. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  178845. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  178846. * (possibly non-linear) transformation function given by "pcal_type"
  178847. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  178848. * defines below, and the PNG-Group's PNG extensions document for a
  178849. * complete description of the transformations and how they should be
  178850. * implemented, and for a description of the ASCII parameter strings.
  178851. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  178852. */
  178853. png_charp pcal_purpose; /* pCAL chunk description string */
  178854. png_int_32 pcal_X0; /* minimum value */
  178855. png_int_32 pcal_X1; /* maximum value */
  178856. png_charp pcal_units; /* Latin-1 string giving physical units */
  178857. png_charpp pcal_params; /* ASCII strings containing parameter values */
  178858. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  178859. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  178860. #endif
  178861. /* New members added in libpng-1.0.6 */
  178862. #ifdef PNG_FREE_ME_SUPPORTED
  178863. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178864. #endif
  178865. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178866. /* storage for unknown chunks that the library doesn't recognize. */
  178867. png_unknown_chunkp unknown_chunks;
  178868. png_size_t unknown_chunks_num;
  178869. #endif
  178870. #if defined(PNG_iCCP_SUPPORTED)
  178871. /* iCCP chunk data. */
  178872. png_charp iccp_name; /* profile name */
  178873. png_charp iccp_profile; /* International Color Consortium profile data */
  178874. /* Note to maintainer: should be png_bytep */
  178875. png_uint_32 iccp_proflen; /* ICC profile data length */
  178876. png_byte iccp_compression; /* Always zero */
  178877. #endif
  178878. #if defined(PNG_sPLT_SUPPORTED)
  178879. /* data on sPLT chunks (there may be more than one). */
  178880. png_sPLT_tp splt_palettes;
  178881. png_uint_32 splt_palettes_num;
  178882. #endif
  178883. #if defined(PNG_sCAL_SUPPORTED)
  178884. /* The sCAL chunk describes the actual physical dimensions of the
  178885. * subject matter of the graphic. The chunk contains a unit specification
  178886. * a byte value, and two ASCII strings representing floating-point
  178887. * values. The values are width and height corresponsing to one pixel
  178888. * in the image. This external representation is converted to double
  178889. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  178890. */
  178891. png_byte scal_unit; /* unit of physical scale */
  178892. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178893. double scal_pixel_width; /* width of one pixel */
  178894. double scal_pixel_height; /* height of one pixel */
  178895. #endif
  178896. #ifdef PNG_FIXED_POINT_SUPPORTED
  178897. png_charp scal_s_width; /* string containing height */
  178898. png_charp scal_s_height; /* string containing width */
  178899. #endif
  178900. #endif
  178901. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178902. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  178903. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  178904. png_bytepp row_pointers; /* the image bits */
  178905. #endif
  178906. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  178907. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  178908. #endif
  178909. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  178910. png_fixed_point int_x_white;
  178911. png_fixed_point int_y_white;
  178912. png_fixed_point int_x_red;
  178913. png_fixed_point int_y_red;
  178914. png_fixed_point int_x_green;
  178915. png_fixed_point int_y_green;
  178916. png_fixed_point int_x_blue;
  178917. png_fixed_point int_y_blue;
  178918. #endif
  178919. } png_info;
  178920. typedef png_info FAR * png_infop;
  178921. typedef png_info FAR * FAR * png_infopp;
  178922. /* Maximum positive integer used in PNG is (2^31)-1 */
  178923. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  178924. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  178925. #define PNG_SIZE_MAX ((png_size_t)(-1))
  178926. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178927. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  178928. #define PNG_MAX_UINT PNG_UINT_31_MAX
  178929. #endif
  178930. /* These describe the color_type field in png_info. */
  178931. /* color type masks */
  178932. #define PNG_COLOR_MASK_PALETTE 1
  178933. #define PNG_COLOR_MASK_COLOR 2
  178934. #define PNG_COLOR_MASK_ALPHA 4
  178935. /* color types. Note that not all combinations are legal */
  178936. #define PNG_COLOR_TYPE_GRAY 0
  178937. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  178938. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  178939. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  178940. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  178941. /* aliases */
  178942. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  178943. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  178944. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  178945. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  178946. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  178947. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  178948. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  178949. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  178950. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  178951. /* These are for the interlacing type. These values should NOT be changed. */
  178952. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  178953. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  178954. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  178955. /* These are for the oFFs chunk. These values should NOT be changed. */
  178956. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  178957. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  178958. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  178959. /* These are for the pCAL chunk. These values should NOT be changed. */
  178960. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  178961. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  178962. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  178963. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  178964. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  178965. /* These are for the sCAL chunk. These values should NOT be changed. */
  178966. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  178967. #define PNG_SCALE_METER 1 /* meters per pixel */
  178968. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  178969. #define PNG_SCALE_LAST 3 /* Not a valid value */
  178970. /* These are for the pHYs chunk. These values should NOT be changed. */
  178971. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  178972. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  178973. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  178974. /* These are for the sRGB chunk. These values should NOT be changed. */
  178975. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  178976. #define PNG_sRGB_INTENT_RELATIVE 1
  178977. #define PNG_sRGB_INTENT_SATURATION 2
  178978. #define PNG_sRGB_INTENT_ABSOLUTE 3
  178979. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  178980. /* This is for text chunks */
  178981. #define PNG_KEYWORD_MAX_LENGTH 79
  178982. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  178983. #define PNG_MAX_PALETTE_LENGTH 256
  178984. /* These determine if an ancillary chunk's data has been successfully read
  178985. * from the PNG header, or if the application has filled in the corresponding
  178986. * data in the info_struct to be written into the output file. The values
  178987. * of the PNG_INFO_<chunk> defines should NOT be changed.
  178988. */
  178989. #define PNG_INFO_gAMA 0x0001
  178990. #define PNG_INFO_sBIT 0x0002
  178991. #define PNG_INFO_cHRM 0x0004
  178992. #define PNG_INFO_PLTE 0x0008
  178993. #define PNG_INFO_tRNS 0x0010
  178994. #define PNG_INFO_bKGD 0x0020
  178995. #define PNG_INFO_hIST 0x0040
  178996. #define PNG_INFO_pHYs 0x0080
  178997. #define PNG_INFO_oFFs 0x0100
  178998. #define PNG_INFO_tIME 0x0200
  178999. #define PNG_INFO_pCAL 0x0400
  179000. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  179001. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  179002. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  179003. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  179004. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  179005. /* This is used for the transformation routines, as some of them
  179006. * change these values for the row. It also should enable using
  179007. * the routines for other purposes.
  179008. */
  179009. typedef struct png_row_info_struct
  179010. {
  179011. png_uint_32 width; /* width of row */
  179012. png_uint_32 rowbytes; /* number of bytes in row */
  179013. png_byte color_type; /* color type of row */
  179014. png_byte bit_depth; /* bit depth of row */
  179015. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  179016. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  179017. } png_row_info;
  179018. typedef png_row_info FAR * png_row_infop;
  179019. typedef png_row_info FAR * FAR * png_row_infopp;
  179020. /* These are the function types for the I/O functions and for the functions
  179021. * that allow the user to override the default I/O functions with his or her
  179022. * own. The png_error_ptr type should match that of user-supplied warning
  179023. * and error functions, while the png_rw_ptr type should match that of the
  179024. * user read/write data functions.
  179025. */
  179026. typedef struct png_struct_def png_struct;
  179027. typedef png_struct FAR * png_structp;
  179028. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  179029. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  179030. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  179031. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  179032. int));
  179033. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  179034. int));
  179035. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179036. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  179037. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  179038. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  179039. png_uint_32, int));
  179040. #endif
  179041. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179042. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179043. defined(PNG_LEGACY_SUPPORTED)
  179044. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  179045. png_row_infop, png_bytep));
  179046. #endif
  179047. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179048. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  179049. #endif
  179050. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179051. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  179052. #endif
  179053. /* Transform masks for the high-level interface */
  179054. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  179055. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  179056. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  179057. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  179058. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  179059. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  179060. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  179061. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  179062. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  179063. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  179064. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  179065. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  179066. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  179067. /* Flags for MNG supported features */
  179068. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  179069. #define PNG_FLAG_MNG_FILTER_64 0x04
  179070. #define PNG_ALL_MNG_FEATURES 0x05
  179071. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  179072. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  179073. /* The structure that holds the information to read and write PNG files.
  179074. * The only people who need to care about what is inside of this are the
  179075. * people who will be modifying the library for their own special needs.
  179076. * It should NOT be accessed directly by an application, except to store
  179077. * the jmp_buf.
  179078. */
  179079. struct png_struct_def
  179080. {
  179081. #ifdef PNG_SETJMP_SUPPORTED
  179082. jmp_buf jmpbuf; /* used in png_error */
  179083. #endif
  179084. png_error_ptr error_fn; /* function for printing errors and aborting */
  179085. png_error_ptr warning_fn; /* function for printing warnings */
  179086. png_voidp error_ptr; /* user supplied struct for error functions */
  179087. png_rw_ptr write_data_fn; /* function for writing output data */
  179088. png_rw_ptr read_data_fn; /* function for reading input data */
  179089. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  179090. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  179091. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  179092. #endif
  179093. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179094. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  179095. #endif
  179096. /* These were added in libpng-1.0.2 */
  179097. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  179098. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179099. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179100. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  179101. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  179102. png_byte user_transform_channels; /* channels in user transformed pixels */
  179103. #endif
  179104. #endif
  179105. png_uint_32 mode; /* tells us where we are in the PNG file */
  179106. png_uint_32 flags; /* flags indicating various things to libpng */
  179107. png_uint_32 transformations; /* which transformations to perform */
  179108. z_stream zstream; /* pointer to decompression structure (below) */
  179109. png_bytep zbuf; /* buffer for zlib */
  179110. png_size_t zbuf_size; /* size of zbuf */
  179111. int zlib_level; /* holds zlib compression level */
  179112. int zlib_method; /* holds zlib compression method */
  179113. int zlib_window_bits; /* holds zlib compression window bits */
  179114. int zlib_mem_level; /* holds zlib compression memory level */
  179115. int zlib_strategy; /* holds zlib compression strategy */
  179116. png_uint_32 width; /* width of image in pixels */
  179117. png_uint_32 height; /* height of image in pixels */
  179118. png_uint_32 num_rows; /* number of rows in current pass */
  179119. png_uint_32 usr_width; /* width of row at start of write */
  179120. png_uint_32 rowbytes; /* size of row in bytes */
  179121. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  179122. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  179123. png_uint_32 row_number; /* current row in interlace pass */
  179124. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  179125. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  179126. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  179127. png_bytep up_row; /* buffer to save "up" row when filtering */
  179128. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  179129. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  179130. png_row_info row_info; /* used for transformation routines */
  179131. png_uint_32 idat_size; /* current IDAT size for read */
  179132. png_uint_32 crc; /* current chunk CRC value */
  179133. png_colorp palette; /* palette from the input file */
  179134. png_uint_16 num_palette; /* number of color entries in palette */
  179135. png_uint_16 num_trans; /* number of transparency values */
  179136. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  179137. png_byte compression; /* file compression type (always 0) */
  179138. png_byte filter; /* file filter type (always 0) */
  179139. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  179140. png_byte pass; /* current interlace pass (0 - 6) */
  179141. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  179142. png_byte color_type; /* color type of file */
  179143. png_byte bit_depth; /* bit depth of file */
  179144. png_byte usr_bit_depth; /* bit depth of users row */
  179145. png_byte pixel_depth; /* number of bits per pixel */
  179146. png_byte channels; /* number of channels in file */
  179147. png_byte usr_channels; /* channels at start of write */
  179148. png_byte sig_bytes; /* magic bytes read/written from start of file */
  179149. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179150. #ifdef PNG_LEGACY_SUPPORTED
  179151. png_byte filler; /* filler byte for pixel expansion */
  179152. #else
  179153. png_uint_16 filler; /* filler bytes for pixel expansion */
  179154. #endif
  179155. #endif
  179156. #if defined(PNG_bKGD_SUPPORTED)
  179157. png_byte background_gamma_type;
  179158. # ifdef PNG_FLOATING_POINT_SUPPORTED
  179159. float background_gamma;
  179160. # endif
  179161. png_color_16 background; /* background color in screen gamma space */
  179162. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179163. png_color_16 background_1; /* background normalized to gamma 1.0 */
  179164. #endif
  179165. #endif /* PNG_bKGD_SUPPORTED */
  179166. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179167. png_flush_ptr output_flush_fn;/* Function for flushing output */
  179168. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  179169. png_uint_32 flush_rows; /* number of rows written since last flush */
  179170. #endif
  179171. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179172. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  179173. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179174. float gamma; /* file gamma value */
  179175. float screen_gamma; /* screen gamma value (display_exponent) */
  179176. #endif
  179177. #endif
  179178. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179179. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  179180. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  179181. png_bytep gamma_to_1; /* converts from file to 1.0 */
  179182. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  179183. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  179184. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  179185. #endif
  179186. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  179187. png_color_8 sig_bit; /* significant bits in each available channel */
  179188. #endif
  179189. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  179190. png_color_8 shift; /* shift for significant bit tranformation */
  179191. #endif
  179192. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  179193. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179194. png_bytep trans; /* transparency values for paletted files */
  179195. png_color_16 trans_values; /* transparency values for non-paletted files */
  179196. #endif
  179197. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  179198. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  179199. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179200. png_progressive_info_ptr info_fn; /* called after header data fully read */
  179201. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  179202. png_progressive_end_ptr end_fn; /* called after image is complete */
  179203. png_bytep save_buffer_ptr; /* current location in save_buffer */
  179204. png_bytep save_buffer; /* buffer for previously read data */
  179205. png_bytep current_buffer_ptr; /* current location in current_buffer */
  179206. png_bytep current_buffer; /* buffer for recently used data */
  179207. png_uint_32 push_length; /* size of current input chunk */
  179208. png_uint_32 skip_length; /* bytes to skip in input data */
  179209. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  179210. png_size_t save_buffer_max; /* total size of save_buffer */
  179211. png_size_t buffer_size; /* total amount of available input data */
  179212. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  179213. int process_mode; /* what push library is currently doing */
  179214. int cur_palette; /* current push library palette index */
  179215. # if defined(PNG_TEXT_SUPPORTED)
  179216. png_size_t current_text_size; /* current size of text input data */
  179217. png_size_t current_text_left; /* how much text left to read in input */
  179218. png_charp current_text; /* current text chunk buffer */
  179219. png_charp current_text_ptr; /* current location in current_text */
  179220. # endif /* PNG_TEXT_SUPPORTED */
  179221. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179222. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  179223. /* for the Borland special 64K segment handler */
  179224. png_bytepp offset_table_ptr;
  179225. png_bytep offset_table;
  179226. png_uint_16 offset_table_number;
  179227. png_uint_16 offset_table_count;
  179228. png_uint_16 offset_table_count_free;
  179229. #endif
  179230. #if defined(PNG_READ_DITHER_SUPPORTED)
  179231. png_bytep palette_lookup; /* lookup table for dithering */
  179232. png_bytep dither_index; /* index translation for palette files */
  179233. #endif
  179234. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  179235. png_uint_16p hist; /* histogram */
  179236. #endif
  179237. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  179238. png_byte heuristic_method; /* heuristic for row filter selection */
  179239. png_byte num_prev_filters; /* number of weights for previous rows */
  179240. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  179241. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  179242. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  179243. png_uint_16p filter_costs; /* relative filter calculation cost */
  179244. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  179245. #endif
  179246. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179247. png_charp time_buffer; /* String to hold RFC 1123 time text */
  179248. #endif
  179249. /* New members added in libpng-1.0.6 */
  179250. #ifdef PNG_FREE_ME_SUPPORTED
  179251. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  179252. #endif
  179253. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179254. png_voidp user_chunk_ptr;
  179255. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  179256. #endif
  179257. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179258. int num_chunk_list;
  179259. png_bytep chunk_list;
  179260. #endif
  179261. /* New members added in libpng-1.0.3 */
  179262. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179263. png_byte rgb_to_gray_status;
  179264. /* These were changed from png_byte in libpng-1.0.6 */
  179265. png_uint_16 rgb_to_gray_red_coeff;
  179266. png_uint_16 rgb_to_gray_green_coeff;
  179267. png_uint_16 rgb_to_gray_blue_coeff;
  179268. #endif
  179269. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  179270. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  179271. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  179272. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  179273. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  179274. #ifdef PNG_1_0_X
  179275. png_byte mng_features_permitted;
  179276. #else
  179277. png_uint_32 mng_features_permitted;
  179278. #endif /* PNG_1_0_X */
  179279. #endif
  179280. /* New member added in libpng-1.0.7 */
  179281. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179282. png_fixed_point int_gamma;
  179283. #endif
  179284. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  179285. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  179286. png_byte filter_type;
  179287. #endif
  179288. #if defined(PNG_1_0_X)
  179289. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  179290. png_uint_32 row_buf_size;
  179291. #endif
  179292. /* New members added in libpng-1.2.0 */
  179293. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179294. # if !defined(PNG_1_0_X)
  179295. # if defined(PNG_MMX_CODE_SUPPORTED)
  179296. png_byte mmx_bitdepth_threshold;
  179297. png_uint_32 mmx_rowbytes_threshold;
  179298. # endif
  179299. png_uint_32 asm_flags;
  179300. # endif
  179301. #endif
  179302. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  179303. #ifdef PNG_USER_MEM_SUPPORTED
  179304. png_voidp mem_ptr; /* user supplied struct for mem functions */
  179305. png_malloc_ptr malloc_fn; /* function for allocating memory */
  179306. png_free_ptr free_fn; /* function for freeing memory */
  179307. #endif
  179308. /* New member added in libpng-1.0.13 and 1.2.0 */
  179309. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  179310. #if defined(PNG_READ_DITHER_SUPPORTED)
  179311. /* The following three members were added at version 1.0.14 and 1.2.4 */
  179312. png_bytep dither_sort; /* working sort array */
  179313. png_bytep index_to_palette; /* where the original index currently is */
  179314. /* in the palette */
  179315. png_bytep palette_to_index; /* which original index points to this */
  179316. /* palette color */
  179317. #endif
  179318. /* New members added in libpng-1.0.16 and 1.2.6 */
  179319. png_byte compression_type;
  179320. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179321. png_uint_32 user_width_max;
  179322. png_uint_32 user_height_max;
  179323. #endif
  179324. /* New member added in libpng-1.0.25 and 1.2.17 */
  179325. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179326. /* storage for unknown chunk that the library doesn't recognize. */
  179327. png_unknown_chunk unknown_chunk;
  179328. #endif
  179329. };
  179330. /* This triggers a compiler error in png.c, if png.c and png.h
  179331. * do not agree upon the version number.
  179332. */
  179333. typedef png_structp version_1_2_21;
  179334. typedef png_struct FAR * FAR * png_structpp;
  179335. /* Here are the function definitions most commonly used. This is not
  179336. * the place to find out how to use libpng. See libpng.txt for the
  179337. * full explanation, see example.c for the summary. This just provides
  179338. * a simple one line description of the use of each function.
  179339. */
  179340. /* Returns the version number of the library */
  179341. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  179342. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  179343. * Handling more than 8 bytes from the beginning of the file is an error.
  179344. */
  179345. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  179346. int num_bytes));
  179347. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  179348. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  179349. * signature, and non-zero otherwise. Having num_to_check == 0 or
  179350. * start > 7 will always fail (ie return non-zero).
  179351. */
  179352. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  179353. png_size_t num_to_check));
  179354. /* Simple signature checking function. This is the same as calling
  179355. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  179356. */
  179357. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  179358. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  179359. extern PNG_EXPORT(png_structp,png_create_read_struct)
  179360. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179361. png_error_ptr error_fn, png_error_ptr warn_fn));
  179362. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  179363. extern PNG_EXPORT(png_structp,png_create_write_struct)
  179364. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179365. png_error_ptr error_fn, png_error_ptr warn_fn));
  179366. #ifdef PNG_WRITE_SUPPORTED
  179367. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  179368. PNGARG((png_structp png_ptr));
  179369. #endif
  179370. #ifdef PNG_WRITE_SUPPORTED
  179371. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  179372. PNGARG((png_structp png_ptr, png_uint_32 size));
  179373. #endif
  179374. /* Reset the compression stream */
  179375. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  179376. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  179377. #ifdef PNG_USER_MEM_SUPPORTED
  179378. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  179379. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179380. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  179381. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179382. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  179383. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179384. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  179385. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179386. #endif
  179387. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  179388. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  179389. png_bytep chunk_name, png_bytep data, png_size_t length));
  179390. /* Write the start of a PNG chunk - length and chunk name. */
  179391. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  179392. png_bytep chunk_name, png_uint_32 length));
  179393. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  179394. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  179395. png_bytep data, png_size_t length));
  179396. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  179397. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  179398. /* Allocate and initialize the info structure */
  179399. extern PNG_EXPORT(png_infop,png_create_info_struct)
  179400. PNGARG((png_structp png_ptr));
  179401. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179402. /* Initialize the info structure (old interface - DEPRECATED) */
  179403. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  179404. #undef png_info_init
  179405. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  179406. png_sizeof(png_info));
  179407. #endif
  179408. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  179409. png_size_t png_info_struct_size));
  179410. /* Writes all the PNG information before the image. */
  179411. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  179412. png_infop info_ptr));
  179413. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  179414. png_infop info_ptr));
  179415. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179416. /* read the information before the actual image data. */
  179417. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  179418. png_infop info_ptr));
  179419. #endif
  179420. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179421. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  179422. PNGARG((png_structp png_ptr, png_timep ptime));
  179423. #endif
  179424. #if !defined(_WIN32_WCE)
  179425. /* "time.h" functions are not supported on WindowsCE */
  179426. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179427. /* convert from a struct tm to png_time */
  179428. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  179429. struct tm FAR * ttime));
  179430. /* convert from time_t to png_time. Uses gmtime() */
  179431. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  179432. time_t ttime));
  179433. #endif /* PNG_WRITE_tIME_SUPPORTED */
  179434. #endif /* _WIN32_WCE */
  179435. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179436. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  179437. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  179438. #if !defined(PNG_1_0_X)
  179439. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  179440. png_ptr));
  179441. #endif
  179442. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  179443. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  179444. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179445. /* Deprecated */
  179446. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  179447. #endif
  179448. #endif
  179449. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179450. /* Use blue, green, red order for pixels. */
  179451. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  179452. #endif
  179453. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179454. /* Expand the grayscale to 24-bit RGB if necessary. */
  179455. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  179456. #endif
  179457. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179458. /* Reduce RGB to grayscale. */
  179459. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179460. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  179461. int error_action, double red, double green ));
  179462. #endif
  179463. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  179464. int error_action, png_fixed_point red, png_fixed_point green ));
  179465. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  179466. png_ptr));
  179467. #endif
  179468. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  179469. png_colorp palette));
  179470. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179471. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  179472. #endif
  179473. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  179474. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179475. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  179476. #endif
  179477. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  179478. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179479. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  179480. #endif
  179481. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179482. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  179483. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  179484. png_uint_32 filler, int flags));
  179485. /* The values of the PNG_FILLER_ defines should NOT be changed */
  179486. #define PNG_FILLER_BEFORE 0
  179487. #define PNG_FILLER_AFTER 1
  179488. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  179489. #if !defined(PNG_1_0_X)
  179490. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  179491. png_uint_32 filler, int flags));
  179492. #endif
  179493. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  179494. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179495. /* Swap bytes in 16-bit depth files. */
  179496. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  179497. #endif
  179498. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  179499. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  179500. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  179501. #endif
  179502. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  179503. /* Swap packing order of pixels in bytes. */
  179504. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  179505. #endif
  179506. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  179507. /* Converts files to legal bit depths. */
  179508. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  179509. png_color_8p true_bits));
  179510. #endif
  179511. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  179512. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  179513. /* Have the code handle the interlacing. Returns the number of passes. */
  179514. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  179515. #endif
  179516. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  179517. /* Invert monochrome files */
  179518. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  179519. #endif
  179520. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  179521. /* Handle alpha and tRNS by replacing with a background color. */
  179522. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179523. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  179524. png_color_16p background_color, int background_gamma_code,
  179525. int need_expand, double background_gamma));
  179526. #endif
  179527. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  179528. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  179529. #define PNG_BACKGROUND_GAMMA_FILE 2
  179530. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  179531. #endif
  179532. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  179533. /* strip the second byte of information from a 16-bit depth file. */
  179534. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  179535. #endif
  179536. #if defined(PNG_READ_DITHER_SUPPORTED)
  179537. /* Turn on dithering, and reduce the palette to the number of colors available. */
  179538. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  179539. png_colorp palette, int num_palette, int maximum_colors,
  179540. png_uint_16p histogram, int full_dither));
  179541. #endif
  179542. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179543. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  179544. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179545. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  179546. double screen_gamma, double default_file_gamma));
  179547. #endif
  179548. #endif
  179549. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179550. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  179551. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  179552. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  179553. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  179554. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  179555. int empty_plte_permitted));
  179556. #endif
  179557. #endif
  179558. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179559. /* Set how many lines between output flushes - 0 for no flushing */
  179560. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  179561. /* Flush the current PNG output buffer */
  179562. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  179563. #endif
  179564. /* optional update palette with requested transformations */
  179565. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  179566. /* optional call to update the users info structure */
  179567. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  179568. png_infop info_ptr));
  179569. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179570. /* read one or more rows of image data. */
  179571. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  179572. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  179573. #endif
  179574. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179575. /* read a row of data. */
  179576. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  179577. png_bytep row,
  179578. png_bytep display_row));
  179579. #endif
  179580. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179581. /* read the whole image into memory at once. */
  179582. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  179583. png_bytepp image));
  179584. #endif
  179585. /* write a row of image data */
  179586. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  179587. png_bytep row));
  179588. /* write a few rows of image data */
  179589. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  179590. png_bytepp row, png_uint_32 num_rows));
  179591. /* write the image data */
  179592. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  179593. png_bytepp image));
  179594. /* writes the end of the PNG file. */
  179595. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  179596. png_infop info_ptr));
  179597. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179598. /* read the end of the PNG file. */
  179599. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  179600. png_infop info_ptr));
  179601. #endif
  179602. /* free any memory associated with the png_info_struct */
  179603. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  179604. png_infopp info_ptr_ptr));
  179605. /* free any memory associated with the png_struct and the png_info_structs */
  179606. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  179607. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  179608. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  179609. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  179610. png_infop end_info_ptr));
  179611. /* free any memory associated with the png_struct and the png_info_structs */
  179612. extern PNG_EXPORT(void,png_destroy_write_struct)
  179613. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  179614. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  179615. extern void png_write_destroy PNGARG((png_structp png_ptr));
  179616. /* set the libpng method of handling chunk CRC errors */
  179617. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  179618. int crit_action, int ancil_action));
  179619. /* Values for png_set_crc_action() to say how to handle CRC errors in
  179620. * ancillary and critical chunks, and whether to use the data contained
  179621. * therein. Note that it is impossible to "discard" data in a critical
  179622. * chunk. For versions prior to 0.90, the action was always error/quit,
  179623. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  179624. * chunks is warn/discard. These values should NOT be changed.
  179625. *
  179626. * value action:critical action:ancillary
  179627. */
  179628. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  179629. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  179630. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  179631. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  179632. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  179633. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  179634. /* These functions give the user control over the scan-line filtering in
  179635. * libpng and the compression methods used by zlib. These functions are
  179636. * mainly useful for testing, as the defaults should work with most users.
  179637. * Those users who are tight on memory or want faster performance at the
  179638. * expense of compression can modify them. See the compression library
  179639. * header file (zlib.h) for an explination of the compression functions.
  179640. */
  179641. /* set the filtering method(s) used by libpng. Currently, the only valid
  179642. * value for "method" is 0.
  179643. */
  179644. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  179645. int filters));
  179646. /* Flags for png_set_filter() to say which filters to use. The flags
  179647. * are chosen so that they don't conflict with real filter types
  179648. * below, in case they are supplied instead of the #defined constants.
  179649. * These values should NOT be changed.
  179650. */
  179651. #define PNG_NO_FILTERS 0x00
  179652. #define PNG_FILTER_NONE 0x08
  179653. #define PNG_FILTER_SUB 0x10
  179654. #define PNG_FILTER_UP 0x20
  179655. #define PNG_FILTER_AVG 0x40
  179656. #define PNG_FILTER_PAETH 0x80
  179657. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  179658. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  179659. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  179660. * These defines should NOT be changed.
  179661. */
  179662. #define PNG_FILTER_VALUE_NONE 0
  179663. #define PNG_FILTER_VALUE_SUB 1
  179664. #define PNG_FILTER_VALUE_UP 2
  179665. #define PNG_FILTER_VALUE_AVG 3
  179666. #define PNG_FILTER_VALUE_PAETH 4
  179667. #define PNG_FILTER_VALUE_LAST 5
  179668. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  179669. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  179670. * defines, either the default (minimum-sum-of-absolute-differences), or
  179671. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  179672. *
  179673. * Weights are factors >= 1.0, indicating how important it is to keep the
  179674. * filter type consistent between rows. Larger numbers mean the current
  179675. * filter is that many times as likely to be the same as the "num_weights"
  179676. * previous filters. This is cumulative for each previous row with a weight.
  179677. * There needs to be "num_weights" values in "filter_weights", or it can be
  179678. * NULL if the weights aren't being specified. Weights have no influence on
  179679. * the selection of the first row filter. Well chosen weights can (in theory)
  179680. * improve the compression for a given image.
  179681. *
  179682. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  179683. * filter type. Higher costs indicate more decoding expense, and are
  179684. * therefore less likely to be selected over a filter with lower computational
  179685. * costs. There needs to be a value in "filter_costs" for each valid filter
  179686. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  179687. * setting the costs. Costs try to improve the speed of decompression without
  179688. * unduly increasing the compressed image size.
  179689. *
  179690. * A negative weight or cost indicates the default value is to be used, and
  179691. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  179692. * The default values for both weights and costs are currently 1.0, but may
  179693. * change if good general weighting/cost heuristics can be found. If both
  179694. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  179695. * to the UNWEIGHTED method, but with added encoding time/computation.
  179696. */
  179697. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179698. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  179699. int heuristic_method, int num_weights, png_doublep filter_weights,
  179700. png_doublep filter_costs));
  179701. #endif
  179702. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  179703. /* Heuristic used for row filter selection. These defines should NOT be
  179704. * changed.
  179705. */
  179706. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  179707. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  179708. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  179709. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  179710. /* Set the library compression level. Currently, valid values range from
  179711. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  179712. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  179713. * shown that zlib compression levels 3-6 usually perform as well as level 9
  179714. * for PNG images, and do considerably fewer caclulations. In the future,
  179715. * these values may not correspond directly to the zlib compression levels.
  179716. */
  179717. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  179718. int level));
  179719. extern PNG_EXPORT(void,png_set_compression_mem_level)
  179720. PNGARG((png_structp png_ptr, int mem_level));
  179721. extern PNG_EXPORT(void,png_set_compression_strategy)
  179722. PNGARG((png_structp png_ptr, int strategy));
  179723. extern PNG_EXPORT(void,png_set_compression_window_bits)
  179724. PNGARG((png_structp png_ptr, int window_bits));
  179725. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  179726. int method));
  179727. /* These next functions are called for input/output, memory, and error
  179728. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  179729. * and call standard C I/O routines such as fread(), fwrite(), and
  179730. * fprintf(). These functions can be made to use other I/O routines
  179731. * at run time for those applications that need to handle I/O in a
  179732. * different manner by calling png_set_???_fn(). See libpng.txt for
  179733. * more information.
  179734. */
  179735. #if !defined(PNG_NO_STDIO)
  179736. /* Initialize the input/output for the PNG file to the default functions. */
  179737. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  179738. #endif
  179739. /* Replace the (error and abort), and warning functions with user
  179740. * supplied functions. If no messages are to be printed you must still
  179741. * write and use replacement functions. The replacement error_fn should
  179742. * still do a longjmp to the last setjmp location if you are using this
  179743. * method of error handling. If error_fn or warning_fn is NULL, the
  179744. * default function will be used.
  179745. */
  179746. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  179747. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  179748. /* Return the user pointer associated with the error functions */
  179749. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  179750. /* Replace the default data output functions with a user supplied one(s).
  179751. * If buffered output is not used, then output_flush_fn can be set to NULL.
  179752. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  179753. * output_flush_fn will be ignored (and thus can be NULL).
  179754. */
  179755. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  179756. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  179757. /* Replace the default data input function with a user supplied one. */
  179758. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  179759. png_voidp io_ptr, png_rw_ptr read_data_fn));
  179760. /* Return the user pointer associated with the I/O functions */
  179761. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  179762. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  179763. png_read_status_ptr read_row_fn));
  179764. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  179765. png_write_status_ptr write_row_fn));
  179766. #ifdef PNG_USER_MEM_SUPPORTED
  179767. /* Replace the default memory allocation functions with user supplied one(s). */
  179768. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  179769. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179770. /* Return the user pointer associated with the memory functions */
  179771. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  179772. #endif
  179773. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179774. defined(PNG_LEGACY_SUPPORTED)
  179775. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  179776. png_ptr, png_user_transform_ptr read_user_transform_fn));
  179777. #endif
  179778. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179779. defined(PNG_LEGACY_SUPPORTED)
  179780. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  179781. png_ptr, png_user_transform_ptr write_user_transform_fn));
  179782. #endif
  179783. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179784. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179785. defined(PNG_LEGACY_SUPPORTED)
  179786. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  179787. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  179788. int user_transform_channels));
  179789. /* Return the user pointer associated with the user transform functions */
  179790. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  179791. PNGARG((png_structp png_ptr));
  179792. #endif
  179793. #ifdef PNG_USER_CHUNKS_SUPPORTED
  179794. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  179795. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  179796. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  179797. png_ptr));
  179798. #endif
  179799. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179800. /* Sets the function callbacks for the push reader, and a pointer to a
  179801. * user-defined structure available to the callback functions.
  179802. */
  179803. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  179804. png_voidp progressive_ptr,
  179805. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  179806. png_progressive_end_ptr end_fn));
  179807. /* returns the user pointer associated with the push read functions */
  179808. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  179809. PNGARG((png_structp png_ptr));
  179810. /* function to be called when data becomes available */
  179811. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  179812. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  179813. /* function that combines rows. Not very much different than the
  179814. * png_combine_row() call. Is this even used?????
  179815. */
  179816. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  179817. png_bytep old_row, png_bytep new_row));
  179818. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179819. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  179820. png_uint_32 size));
  179821. #if defined(PNG_1_0_X)
  179822. # define png_malloc_warn png_malloc
  179823. #else
  179824. /* Added at libpng version 1.2.4 */
  179825. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  179826. png_uint_32 size));
  179827. #endif
  179828. /* frees a pointer allocated by png_malloc() */
  179829. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  179830. #if defined(PNG_1_0_X)
  179831. /* Function to allocate memory for zlib. */
  179832. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  179833. uInt size));
  179834. /* Function to free memory for zlib */
  179835. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  179836. #endif
  179837. /* Free data that was allocated internally */
  179838. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  179839. png_infop info_ptr, png_uint_32 free_me, int num));
  179840. #ifdef PNG_FREE_ME_SUPPORTED
  179841. /* Reassign responsibility for freeing existing data, whether allocated
  179842. * by libpng or by the application */
  179843. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  179844. png_infop info_ptr, int freer, png_uint_32 mask));
  179845. #endif
  179846. /* assignments for png_data_freer */
  179847. #define PNG_DESTROY_WILL_FREE_DATA 1
  179848. #define PNG_SET_WILL_FREE_DATA 1
  179849. #define PNG_USER_WILL_FREE_DATA 2
  179850. /* Flags for png_ptr->free_me and info_ptr->free_me */
  179851. #define PNG_FREE_HIST 0x0008
  179852. #define PNG_FREE_ICCP 0x0010
  179853. #define PNG_FREE_SPLT 0x0020
  179854. #define PNG_FREE_ROWS 0x0040
  179855. #define PNG_FREE_PCAL 0x0080
  179856. #define PNG_FREE_SCAL 0x0100
  179857. #define PNG_FREE_UNKN 0x0200
  179858. #define PNG_FREE_LIST 0x0400
  179859. #define PNG_FREE_PLTE 0x1000
  179860. #define PNG_FREE_TRNS 0x2000
  179861. #define PNG_FREE_TEXT 0x4000
  179862. #define PNG_FREE_ALL 0x7fff
  179863. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  179864. #ifdef PNG_USER_MEM_SUPPORTED
  179865. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  179866. png_uint_32 size));
  179867. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  179868. png_voidp ptr));
  179869. #endif
  179870. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  179871. png_voidp s1, png_voidp s2, png_uint_32 size));
  179872. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  179873. png_voidp s1, int value, png_uint_32 size));
  179874. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  179875. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  179876. int check));
  179877. #endif /* USE_FAR_KEYWORD */
  179878. #ifndef PNG_NO_ERROR_TEXT
  179879. /* Fatal error in PNG image of libpng - can't continue */
  179880. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  179881. png_const_charp error_message));
  179882. /* The same, but the chunk name is prepended to the error string. */
  179883. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  179884. png_const_charp error_message));
  179885. #else
  179886. /* Fatal error in PNG image of libpng - can't continue */
  179887. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  179888. #endif
  179889. #ifndef PNG_NO_WARNINGS
  179890. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  179891. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  179892. png_const_charp warning_message));
  179893. #ifdef PNG_READ_SUPPORTED
  179894. /* Non-fatal error in libpng, chunk name is prepended to message. */
  179895. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  179896. png_const_charp warning_message));
  179897. #endif /* PNG_READ_SUPPORTED */
  179898. #endif /* PNG_NO_WARNINGS */
  179899. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  179900. * Similarly, the png_get_<chunk> calls are used to read values from the
  179901. * png_info_struct, either storing the parameters in the passed variables, or
  179902. * setting pointers into the png_info_struct where the data is stored. The
  179903. * png_get_<chunk> functions return a non-zero value if the data was available
  179904. * in info_ptr, or return zero and do not change any of the parameters if the
  179905. * data was not available.
  179906. *
  179907. * These functions should be used instead of directly accessing png_info
  179908. * to avoid problems with future changes in the size and internal layout of
  179909. * png_info_struct.
  179910. */
  179911. /* Returns "flag" if chunk data is valid in info_ptr. */
  179912. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  179913. png_infop info_ptr, png_uint_32 flag));
  179914. /* Returns number of bytes needed to hold a transformed row. */
  179915. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  179916. png_infop info_ptr));
  179917. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179918. /* Returns row_pointers, which is an array of pointers to scanlines that was
  179919. returned from png_read_png(). */
  179920. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  179921. png_infop info_ptr));
  179922. /* Set row_pointers, which is an array of pointers to scanlines for use
  179923. by png_write_png(). */
  179924. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  179925. png_infop info_ptr, png_bytepp row_pointers));
  179926. #endif
  179927. /* Returns number of color channels in image. */
  179928. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  179929. png_infop info_ptr));
  179930. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179931. /* Returns image width in pixels. */
  179932. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  179933. png_ptr, png_infop info_ptr));
  179934. /* Returns image height in pixels. */
  179935. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  179936. png_ptr, png_infop info_ptr));
  179937. /* Returns image bit_depth. */
  179938. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  179939. png_ptr, png_infop info_ptr));
  179940. /* Returns image color_type. */
  179941. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  179942. png_ptr, png_infop info_ptr));
  179943. /* Returns image filter_type. */
  179944. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  179945. png_ptr, png_infop info_ptr));
  179946. /* Returns image interlace_type. */
  179947. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  179948. png_ptr, png_infop info_ptr));
  179949. /* Returns image compression_type. */
  179950. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  179951. png_ptr, png_infop info_ptr));
  179952. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  179953. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  179954. png_ptr, png_infop info_ptr));
  179955. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  179956. png_ptr, png_infop info_ptr));
  179957. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  179958. png_ptr, png_infop info_ptr));
  179959. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  179960. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179961. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  179962. png_ptr, png_infop info_ptr));
  179963. #endif
  179964. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  179965. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  179966. png_ptr, png_infop info_ptr));
  179967. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  179968. png_ptr, png_infop info_ptr));
  179969. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  179970. png_ptr, png_infop info_ptr));
  179971. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  179972. png_ptr, png_infop info_ptr));
  179973. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179974. /* Returns pointer to signature string read from PNG header */
  179975. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  179976. png_infop info_ptr));
  179977. #if defined(PNG_bKGD_SUPPORTED)
  179978. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  179979. png_infop info_ptr, png_color_16p *background));
  179980. #endif
  179981. #if defined(PNG_bKGD_SUPPORTED)
  179982. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  179983. png_infop info_ptr, png_color_16p background));
  179984. #endif
  179985. #if defined(PNG_cHRM_SUPPORTED)
  179986. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179987. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  179988. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  179989. double *red_y, double *green_x, double *green_y, double *blue_x,
  179990. double *blue_y));
  179991. #endif
  179992. #ifdef PNG_FIXED_POINT_SUPPORTED
  179993. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  179994. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  179995. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  179996. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  179997. *int_blue_x, png_fixed_point *int_blue_y));
  179998. #endif
  179999. #endif
  180000. #if defined(PNG_cHRM_SUPPORTED)
  180001. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180002. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  180003. png_infop info_ptr, double white_x, double white_y, double red_x,
  180004. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  180005. #endif
  180006. #ifdef PNG_FIXED_POINT_SUPPORTED
  180007. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  180008. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  180009. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  180010. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  180011. png_fixed_point int_blue_y));
  180012. #endif
  180013. #endif
  180014. #if defined(PNG_gAMA_SUPPORTED)
  180015. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180016. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  180017. png_infop info_ptr, double *file_gamma));
  180018. #endif
  180019. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  180020. png_infop info_ptr, png_fixed_point *int_file_gamma));
  180021. #endif
  180022. #if defined(PNG_gAMA_SUPPORTED)
  180023. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180024. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  180025. png_infop info_ptr, double file_gamma));
  180026. #endif
  180027. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  180028. png_infop info_ptr, png_fixed_point int_file_gamma));
  180029. #endif
  180030. #if defined(PNG_hIST_SUPPORTED)
  180031. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  180032. png_infop info_ptr, png_uint_16p *hist));
  180033. #endif
  180034. #if defined(PNG_hIST_SUPPORTED)
  180035. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  180036. png_infop info_ptr, png_uint_16p hist));
  180037. #endif
  180038. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  180039. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  180040. int *bit_depth, int *color_type, int *interlace_method,
  180041. int *compression_method, int *filter_method));
  180042. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  180043. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  180044. int color_type, int interlace_method, int compression_method,
  180045. int filter_method));
  180046. #if defined(PNG_oFFs_SUPPORTED)
  180047. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  180048. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  180049. int *unit_type));
  180050. #endif
  180051. #if defined(PNG_oFFs_SUPPORTED)
  180052. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  180053. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  180054. int unit_type));
  180055. #endif
  180056. #if defined(PNG_pCAL_SUPPORTED)
  180057. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  180058. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  180059. int *type, int *nparams, png_charp *units, png_charpp *params));
  180060. #endif
  180061. #if defined(PNG_pCAL_SUPPORTED)
  180062. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  180063. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  180064. int type, int nparams, png_charp units, png_charpp params));
  180065. #endif
  180066. #if defined(PNG_pHYs_SUPPORTED)
  180067. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  180068. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180069. #endif
  180070. #if defined(PNG_pHYs_SUPPORTED)
  180071. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  180072. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  180073. #endif
  180074. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  180075. png_infop info_ptr, png_colorp *palette, int *num_palette));
  180076. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  180077. png_infop info_ptr, png_colorp palette, int num_palette));
  180078. #if defined(PNG_sBIT_SUPPORTED)
  180079. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  180080. png_infop info_ptr, png_color_8p *sig_bit));
  180081. #endif
  180082. #if defined(PNG_sBIT_SUPPORTED)
  180083. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  180084. png_infop info_ptr, png_color_8p sig_bit));
  180085. #endif
  180086. #if defined(PNG_sRGB_SUPPORTED)
  180087. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  180088. png_infop info_ptr, int *intent));
  180089. #endif
  180090. #if defined(PNG_sRGB_SUPPORTED)
  180091. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  180092. png_infop info_ptr, int intent));
  180093. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  180094. png_infop info_ptr, int intent));
  180095. #endif
  180096. #if defined(PNG_iCCP_SUPPORTED)
  180097. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  180098. png_infop info_ptr, png_charpp name, int *compression_type,
  180099. png_charpp profile, png_uint_32 *proflen));
  180100. /* Note to maintainer: profile should be png_bytepp */
  180101. #endif
  180102. #if defined(PNG_iCCP_SUPPORTED)
  180103. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  180104. png_infop info_ptr, png_charp name, int compression_type,
  180105. png_charp profile, png_uint_32 proflen));
  180106. /* Note to maintainer: profile should be png_bytep */
  180107. #endif
  180108. #if defined(PNG_sPLT_SUPPORTED)
  180109. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  180110. png_infop info_ptr, png_sPLT_tpp entries));
  180111. #endif
  180112. #if defined(PNG_sPLT_SUPPORTED)
  180113. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  180114. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  180115. #endif
  180116. #if defined(PNG_TEXT_SUPPORTED)
  180117. /* png_get_text also returns the number of text chunks in *num_text */
  180118. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  180119. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  180120. #endif
  180121. /*
  180122. * Note while png_set_text() will accept a structure whose text,
  180123. * language, and translated keywords are NULL pointers, the structure
  180124. * returned by png_get_text will always contain regular
  180125. * zero-terminated C strings. They might be empty strings but
  180126. * they will never be NULL pointers.
  180127. */
  180128. #if defined(PNG_TEXT_SUPPORTED)
  180129. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  180130. png_infop info_ptr, png_textp text_ptr, int num_text));
  180131. #endif
  180132. #if defined(PNG_tIME_SUPPORTED)
  180133. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  180134. png_infop info_ptr, png_timep *mod_time));
  180135. #endif
  180136. #if defined(PNG_tIME_SUPPORTED)
  180137. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  180138. png_infop info_ptr, png_timep mod_time));
  180139. #endif
  180140. #if defined(PNG_tRNS_SUPPORTED)
  180141. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  180142. png_infop info_ptr, png_bytep *trans, int *num_trans,
  180143. png_color_16p *trans_values));
  180144. #endif
  180145. #if defined(PNG_tRNS_SUPPORTED)
  180146. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  180147. png_infop info_ptr, png_bytep trans, int num_trans,
  180148. png_color_16p trans_values));
  180149. #endif
  180150. #if defined(PNG_tRNS_SUPPORTED)
  180151. #endif
  180152. #if defined(PNG_sCAL_SUPPORTED)
  180153. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180154. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  180155. png_infop info_ptr, int *unit, double *width, double *height));
  180156. #else
  180157. #ifdef PNG_FIXED_POINT_SUPPORTED
  180158. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  180159. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  180160. #endif
  180161. #endif
  180162. #endif /* PNG_sCAL_SUPPORTED */
  180163. #if defined(PNG_sCAL_SUPPORTED)
  180164. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180165. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  180166. png_infop info_ptr, int unit, double width, double height));
  180167. #else
  180168. #ifdef PNG_FIXED_POINT_SUPPORTED
  180169. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  180170. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  180171. #endif
  180172. #endif
  180173. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  180174. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180175. /* provide a list of chunks and how they are to be handled, if the built-in
  180176. handling or default unknown chunk handling is not desired. Any chunks not
  180177. listed will be handled in the default manner. The IHDR and IEND chunks
  180178. must not be listed.
  180179. keep = 0: follow default behaviour
  180180. = 1: do not keep
  180181. = 2: keep only if safe-to-copy
  180182. = 3: keep even if unsafe-to-copy
  180183. */
  180184. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  180185. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  180186. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  180187. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  180188. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  180189. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  180190. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  180191. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  180192. #endif
  180193. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180194. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  180195. chunk_name));
  180196. #endif
  180197. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  180198. If you need to turn it off for a chunk that your application has freed,
  180199. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  180200. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  180201. png_infop info_ptr, int mask));
  180202. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180203. /* The "params" pointer is currently not used and is for future expansion. */
  180204. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  180205. png_infop info_ptr,
  180206. int transforms,
  180207. png_voidp params));
  180208. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  180209. png_infop info_ptr,
  180210. int transforms,
  180211. png_voidp params));
  180212. #endif
  180213. /* Define PNG_DEBUG at compile time for debugging information. Higher
  180214. * numbers for PNG_DEBUG mean more debugging information. This has
  180215. * only been added since version 0.95 so it is not implemented throughout
  180216. * libpng yet, but more support will be added as needed.
  180217. */
  180218. #ifdef PNG_DEBUG
  180219. #if (PNG_DEBUG > 0)
  180220. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  180221. #include <crtdbg.h>
  180222. #if (PNG_DEBUG > 1)
  180223. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  180224. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  180225. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  180226. #endif
  180227. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  180228. #ifndef PNG_DEBUG_FILE
  180229. #define PNG_DEBUG_FILE stderr
  180230. #endif /* PNG_DEBUG_FILE */
  180231. #if (PNG_DEBUG > 1)
  180232. #define png_debug(l,m) \
  180233. { \
  180234. int num_tabs=l; \
  180235. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180236. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  180237. }
  180238. #define png_debug1(l,m,p1) \
  180239. { \
  180240. int num_tabs=l; \
  180241. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180242. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  180243. }
  180244. #define png_debug2(l,m,p1,p2) \
  180245. { \
  180246. int num_tabs=l; \
  180247. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180248. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  180249. }
  180250. #endif /* (PNG_DEBUG > 1) */
  180251. #endif /* _MSC_VER */
  180252. #endif /* (PNG_DEBUG > 0) */
  180253. #endif /* PNG_DEBUG */
  180254. #ifndef png_debug
  180255. #define png_debug(l, m)
  180256. #endif
  180257. #ifndef png_debug1
  180258. #define png_debug1(l, m, p1)
  180259. #endif
  180260. #ifndef png_debug2
  180261. #define png_debug2(l, m, p1, p2)
  180262. #endif
  180263. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  180264. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  180265. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  180266. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  180267. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180268. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  180269. png_ptr, png_uint_32 mng_features_permitted));
  180270. #endif
  180271. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  180272. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  180273. #define PNG_HANDLE_CHUNK_NEVER 1
  180274. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  180275. #define PNG_HANDLE_CHUNK_ALWAYS 3
  180276. /* Added to version 1.2.0 */
  180277. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180278. #if defined(PNG_MMX_CODE_SUPPORTED)
  180279. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  180280. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  180281. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  180282. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  180283. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  180284. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  180285. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  180286. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  180287. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  180288. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  180289. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  180290. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  180291. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  180292. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  180293. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  180294. #define PNG_MMX_WRITE_FLAGS ( 0 )
  180295. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  180296. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  180297. | PNG_MMX_READ_FLAGS \
  180298. | PNG_MMX_WRITE_FLAGS )
  180299. #define PNG_SELECT_READ 1
  180300. #define PNG_SELECT_WRITE 2
  180301. #endif /* PNG_MMX_CODE_SUPPORTED */
  180302. #if !defined(PNG_1_0_X)
  180303. /* pngget.c */
  180304. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  180305. PNGARG((int flag_select, int *compilerID));
  180306. /* pngget.c */
  180307. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  180308. PNGARG((int flag_select));
  180309. /* pngget.c */
  180310. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  180311. PNGARG((png_structp png_ptr));
  180312. /* pngget.c */
  180313. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  180314. PNGARG((png_structp png_ptr));
  180315. /* pngget.c */
  180316. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  180317. PNGARG((png_structp png_ptr));
  180318. /* pngset.c */
  180319. extern PNG_EXPORT(void,png_set_asm_flags)
  180320. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  180321. /* pngset.c */
  180322. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  180323. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  180324. png_uint_32 mmx_rowbytes_threshold));
  180325. #endif /* PNG_1_0_X */
  180326. #if !defined(PNG_1_0_X)
  180327. /* png.c, pnggccrd.c, or pngvcrd.c */
  180328. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  180329. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  180330. /* Strip the prepended error numbers ("#nnn ") from error and warning
  180331. * messages before passing them to the error or warning handler. */
  180332. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180333. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  180334. png_ptr, png_uint_32 strip_mode));
  180335. #endif
  180336. #endif /* PNG_1_0_X */
  180337. /* Added at libpng-1.2.6 */
  180338. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180339. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  180340. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  180341. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  180342. png_ptr));
  180343. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  180344. png_ptr));
  180345. #endif
  180346. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  180347. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  180348. /* With these routines we avoid an integer divide, which will be slower on
  180349. * most machines. However, it does take more operations than the corresponding
  180350. * divide method, so it may be slower on a few RISC systems. There are two
  180351. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  180352. *
  180353. * Note that the rounding factors are NOT supposed to be the same! 128 and
  180354. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  180355. * standard method.
  180356. *
  180357. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  180358. */
  180359. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  180360. # define png_composite(composite, fg, alpha, bg) \
  180361. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  180362. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  180363. (png_uint_16)(alpha)) + (png_uint_16)128); \
  180364. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  180365. # define png_composite_16(composite, fg, alpha, bg) \
  180366. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  180367. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  180368. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  180369. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  180370. #else /* standard method using integer division */
  180371. # define png_composite(composite, fg, alpha, bg) \
  180372. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  180373. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  180374. (png_uint_16)127) / 255)
  180375. # define png_composite_16(composite, fg, alpha, bg) \
  180376. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  180377. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  180378. (png_uint_32)32767) / (png_uint_32)65535L)
  180379. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  180380. /* Inline macros to do direct reads of bytes from the input buffer. These
  180381. * require that you are using an architecture that uses PNG byte ordering
  180382. * (MSB first) and supports unaligned data storage. I think that PowerPC
  180383. * in big-endian mode and 680x0 are the only ones that will support this.
  180384. * The x86 line of processors definitely do not. The png_get_int_32()
  180385. * routine also assumes we are using two's complement format for negative
  180386. * values, which is almost certainly true.
  180387. */
  180388. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  180389. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  180390. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  180391. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  180392. #else
  180393. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  180394. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  180395. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  180396. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  180397. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  180398. PNGARG((png_structp png_ptr, png_bytep buf));
  180399. /* No png_get_int_16 -- may be added if there's a real need for it. */
  180400. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  180401. */
  180402. extern PNG_EXPORT(void,png_save_uint_32)
  180403. PNGARG((png_bytep buf, png_uint_32 i));
  180404. extern PNG_EXPORT(void,png_save_int_32)
  180405. PNGARG((png_bytep buf, png_int_32 i));
  180406. /* Place a 16-bit number into a buffer in PNG byte order.
  180407. * The parameter is declared unsigned int, not png_uint_16,
  180408. * just to avoid potential problems on pre-ANSI C compilers.
  180409. */
  180410. extern PNG_EXPORT(void,png_save_uint_16)
  180411. PNGARG((png_bytep buf, unsigned int i));
  180412. /* No png_save_int_16 -- may be added if there's a real need for it. */
  180413. /* ************************************************************************* */
  180414. /* These next functions are used internally in the code. They generally
  180415. * shouldn't be used unless you are writing code to add or replace some
  180416. * functionality in libpng. More information about most functions can
  180417. * be found in the files where the functions are located.
  180418. */
  180419. /* Various modes of operation, that are visible to applications because
  180420. * they are used for unknown chunk location.
  180421. */
  180422. #define PNG_HAVE_IHDR 0x01
  180423. #define PNG_HAVE_PLTE 0x02
  180424. #define PNG_HAVE_IDAT 0x04
  180425. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  180426. #define PNG_HAVE_IEND 0x10
  180427. #if defined(PNG_INTERNAL)
  180428. /* More modes of operation. Note that after an init, mode is set to
  180429. * zero automatically when the structure is created.
  180430. */
  180431. #define PNG_HAVE_gAMA 0x20
  180432. #define PNG_HAVE_cHRM 0x40
  180433. #define PNG_HAVE_sRGB 0x80
  180434. #define PNG_HAVE_CHUNK_HEADER 0x100
  180435. #define PNG_WROTE_tIME 0x200
  180436. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  180437. #define PNG_BACKGROUND_IS_GRAY 0x800
  180438. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  180439. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  180440. /* flags for the transformations the PNG library does on the image data */
  180441. #define PNG_BGR 0x0001
  180442. #define PNG_INTERLACE 0x0002
  180443. #define PNG_PACK 0x0004
  180444. #define PNG_SHIFT 0x0008
  180445. #define PNG_SWAP_BYTES 0x0010
  180446. #define PNG_INVERT_MONO 0x0020
  180447. #define PNG_DITHER 0x0040
  180448. #define PNG_BACKGROUND 0x0080
  180449. #define PNG_BACKGROUND_EXPAND 0x0100
  180450. /* 0x0200 unused */
  180451. #define PNG_16_TO_8 0x0400
  180452. #define PNG_RGBA 0x0800
  180453. #define PNG_EXPAND 0x1000
  180454. #define PNG_GAMMA 0x2000
  180455. #define PNG_GRAY_TO_RGB 0x4000
  180456. #define PNG_FILLER 0x8000L
  180457. #define PNG_PACKSWAP 0x10000L
  180458. #define PNG_SWAP_ALPHA 0x20000L
  180459. #define PNG_STRIP_ALPHA 0x40000L
  180460. #define PNG_INVERT_ALPHA 0x80000L
  180461. #define PNG_USER_TRANSFORM 0x100000L
  180462. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  180463. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  180464. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  180465. /* 0x800000L Unused */
  180466. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  180467. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  180468. /* 0x4000000L unused */
  180469. /* 0x8000000L unused */
  180470. /* 0x10000000L unused */
  180471. /* 0x20000000L unused */
  180472. /* 0x40000000L unused */
  180473. /* flags for png_create_struct */
  180474. #define PNG_STRUCT_PNG 0x0001
  180475. #define PNG_STRUCT_INFO 0x0002
  180476. /* Scaling factor for filter heuristic weighting calculations */
  180477. #define PNG_WEIGHT_SHIFT 8
  180478. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  180479. #define PNG_COST_SHIFT 3
  180480. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  180481. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  180482. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  180483. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  180484. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  180485. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  180486. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  180487. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  180488. #define PNG_FLAG_ROW_INIT 0x0040
  180489. #define PNG_FLAG_FILLER_AFTER 0x0080
  180490. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  180491. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  180492. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  180493. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  180494. #define PNG_FLAG_FREE_PLTE 0x1000
  180495. #define PNG_FLAG_FREE_TRNS 0x2000
  180496. #define PNG_FLAG_FREE_HIST 0x4000
  180497. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  180498. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  180499. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  180500. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  180501. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  180502. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  180503. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  180504. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  180505. /* 0x800000L unused */
  180506. /* 0x1000000L unused */
  180507. /* 0x2000000L unused */
  180508. /* 0x4000000L unused */
  180509. /* 0x8000000L unused */
  180510. /* 0x10000000L unused */
  180511. /* 0x20000000L unused */
  180512. /* 0x40000000L unused */
  180513. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  180514. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  180515. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  180516. PNG_FLAG_CRC_CRITICAL_IGNORE)
  180517. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  180518. PNG_FLAG_CRC_CRITICAL_MASK)
  180519. /* save typing and make code easier to understand */
  180520. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  180521. abs((int)((c1).green) - (int)((c2).green)) + \
  180522. abs((int)((c1).blue) - (int)((c2).blue)))
  180523. /* Added to libpng-1.2.6 JB */
  180524. #define PNG_ROWBYTES(pixel_bits, width) \
  180525. ((pixel_bits) >= 8 ? \
  180526. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  180527. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  180528. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  180529. ideal-delta..ideal+delta. Each argument is evaluated twice.
  180530. "ideal" and "delta" should be constants, normally simple
  180531. integers, "value" a variable. Added to libpng-1.2.6 JB */
  180532. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  180533. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  180534. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  180535. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  180536. /* place to hold the signature string for a PNG file. */
  180537. #ifdef PNG_USE_GLOBAL_ARRAYS
  180538. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  180539. #else
  180540. #endif
  180541. #endif /* PNG_NO_EXTERN */
  180542. /* Constant strings for known chunk types. If you need to add a chunk,
  180543. * define the name here, and add an invocation of the macro in png.c and
  180544. * wherever it's needed.
  180545. */
  180546. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  180547. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  180548. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  180549. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  180550. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  180551. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  180552. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  180553. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  180554. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  180555. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  180556. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  180557. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  180558. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  180559. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  180560. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  180561. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  180562. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  180563. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  180564. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  180565. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  180566. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  180567. #ifdef PNG_USE_GLOBAL_ARRAYS
  180568. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  180569. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  180570. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  180571. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  180572. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  180573. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  180574. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  180575. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  180576. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  180577. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  180578. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  180579. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  180580. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  180581. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  180582. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  180583. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  180584. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  180585. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  180586. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  180587. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  180588. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  180589. #endif /* PNG_USE_GLOBAL_ARRAYS */
  180590. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180591. /* Initialize png_ptr struct for reading, and allocate any other memory.
  180592. * (old interface - DEPRECATED - use png_create_read_struct instead).
  180593. */
  180594. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  180595. #undef png_read_init
  180596. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  180597. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  180598. #endif
  180599. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  180600. png_const_charp user_png_ver, png_size_t png_struct_size));
  180601. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180602. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  180603. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  180604. png_info_size));
  180605. #endif
  180606. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180607. /* Initialize png_ptr struct for writing, and allocate any other memory.
  180608. * (old interface - DEPRECATED - use png_create_write_struct instead).
  180609. */
  180610. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  180611. #undef png_write_init
  180612. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  180613. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  180614. #endif
  180615. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  180616. png_const_charp user_png_ver, png_size_t png_struct_size));
  180617. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  180618. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  180619. png_info_size));
  180620. /* Allocate memory for an internal libpng struct */
  180621. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  180622. /* Free memory from internal libpng struct */
  180623. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  180624. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  180625. malloc_fn, png_voidp mem_ptr));
  180626. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  180627. png_free_ptr free_fn, png_voidp mem_ptr));
  180628. /* Free any memory that info_ptr points to and reset struct. */
  180629. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  180630. png_infop info_ptr));
  180631. #ifndef PNG_1_0_X
  180632. /* Function to allocate memory for zlib. */
  180633. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  180634. /* Function to free memory for zlib */
  180635. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  180636. #ifdef PNG_SIZE_T
  180637. /* Function to convert a sizeof an item to png_sizeof item */
  180638. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  180639. #endif
  180640. /* Next four functions are used internally as callbacks. PNGAPI is required
  180641. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  180642. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  180643. png_bytep data, png_size_t length));
  180644. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180645. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  180646. png_bytep buffer, png_size_t length));
  180647. #endif
  180648. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  180649. png_bytep data, png_size_t length));
  180650. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  180651. #if !defined(PNG_NO_STDIO)
  180652. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  180653. #endif
  180654. #endif
  180655. #else /* PNG_1_0_X */
  180656. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180657. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  180658. png_bytep buffer, png_size_t length));
  180659. #endif
  180660. #endif /* PNG_1_0_X */
  180661. /* Reset the CRC variable */
  180662. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  180663. /* Write the "data" buffer to whatever output you are using. */
  180664. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  180665. png_size_t length));
  180666. /* Read data from whatever input you are using into the "data" buffer */
  180667. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  180668. png_size_t length));
  180669. /* Read bytes into buf, and update png_ptr->crc */
  180670. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  180671. png_size_t length));
  180672. /* Decompress data in a chunk that uses compression */
  180673. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  180674. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  180675. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  180676. int comp_type, png_charp chunkdata, png_size_t chunklength,
  180677. png_size_t prefix_length, png_size_t *data_length));
  180678. #endif
  180679. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  180680. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  180681. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  180682. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  180683. /* Calculate the CRC over a section of data. Note that we are only
  180684. * passing a maximum of 64K on systems that have this as a memory limit,
  180685. * since this is the maximum buffer size we can specify.
  180686. */
  180687. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  180688. png_size_t length));
  180689. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  180690. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  180691. #endif
  180692. /* simple function to write the signature */
  180693. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  180694. /* write various chunks */
  180695. /* Write the IHDR chunk, and update the png_struct with the necessary
  180696. * information.
  180697. */
  180698. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  180699. png_uint_32 height,
  180700. int bit_depth, int color_type, int compression_method, int filter_method,
  180701. int interlace_method));
  180702. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  180703. png_uint_32 num_pal));
  180704. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  180705. png_size_t length));
  180706. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  180707. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  180708. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180709. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  180710. #endif
  180711. #ifdef PNG_FIXED_POINT_SUPPORTED
  180712. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  180713. file_gamma));
  180714. #endif
  180715. #endif
  180716. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  180717. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  180718. int color_type));
  180719. #endif
  180720. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  180721. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180722. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  180723. double white_x, double white_y,
  180724. double red_x, double red_y, double green_x, double green_y,
  180725. double blue_x, double blue_y));
  180726. #endif
  180727. #ifdef PNG_FIXED_POINT_SUPPORTED
  180728. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  180729. png_fixed_point int_white_x, png_fixed_point int_white_y,
  180730. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  180731. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  180732. png_fixed_point int_blue_y));
  180733. #endif
  180734. #endif
  180735. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  180736. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  180737. int intent));
  180738. #endif
  180739. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  180740. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  180741. png_charp name, int compression_type,
  180742. png_charp profile, int proflen));
  180743. /* Note to maintainer: profile should be png_bytep */
  180744. #endif
  180745. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  180746. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  180747. png_sPLT_tp palette));
  180748. #endif
  180749. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  180750. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  180751. png_color_16p values, int number, int color_type));
  180752. #endif
  180753. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  180754. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  180755. png_color_16p values, int color_type));
  180756. #endif
  180757. #if defined(PNG_WRITE_hIST_SUPPORTED)
  180758. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  180759. int num_hist));
  180760. #endif
  180761. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  180762. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  180763. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  180764. png_charp key, png_charpp new_key));
  180765. #endif
  180766. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  180767. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  180768. png_charp text, png_size_t text_len));
  180769. #endif
  180770. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  180771. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  180772. png_charp text, png_size_t text_len, int compression));
  180773. #endif
  180774. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  180775. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  180776. int compression, png_charp key, png_charp lang, png_charp lang_key,
  180777. png_charp text));
  180778. #endif
  180779. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  180780. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  180781. png_infop info_ptr, png_textp text_ptr, int num_text));
  180782. #endif
  180783. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  180784. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  180785. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  180786. #endif
  180787. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  180788. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  180789. png_int_32 X0, png_int_32 X1, int type, int nparams,
  180790. png_charp units, png_charpp params));
  180791. #endif
  180792. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  180793. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  180794. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  180795. int unit_type));
  180796. #endif
  180797. #if defined(PNG_WRITE_tIME_SUPPORTED)
  180798. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  180799. png_timep mod_time));
  180800. #endif
  180801. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  180802. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  180803. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  180804. int unit, double width, double height));
  180805. #else
  180806. #ifdef PNG_FIXED_POINT_SUPPORTED
  180807. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  180808. int unit, png_charp width, png_charp height));
  180809. #endif
  180810. #endif
  180811. #endif
  180812. /* Called when finished processing a row of data */
  180813. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  180814. /* Internal use only. Called before first row of data */
  180815. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  180816. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180817. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  180818. #endif
  180819. /* combine a row of data, dealing with alpha, etc. if requested */
  180820. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  180821. int mask));
  180822. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  180823. /* expand an interlaced row */
  180824. /* OLD pre-1.0.9 interface:
  180825. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  180826. png_bytep row, int pass, png_uint_32 transformations));
  180827. */
  180828. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  180829. #endif
  180830. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  180831. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180832. /* grab pixels out of a row for an interlaced pass */
  180833. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  180834. png_bytep row, int pass));
  180835. #endif
  180836. /* unfilter a row */
  180837. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  180838. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  180839. /* Choose the best filter to use and filter the row data */
  180840. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  180841. png_row_infop row_info));
  180842. /* Write out the filtered row. */
  180843. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  180844. png_bytep filtered_row));
  180845. /* finish a row while reading, dealing with interlacing passes, etc. */
  180846. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  180847. /* initialize the row buffers, etc. */
  180848. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  180849. /* optional call to update the users info structure */
  180850. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  180851. png_infop info_ptr));
  180852. /* these are the functions that do the transformations */
  180853. #if defined(PNG_READ_FILLER_SUPPORTED)
  180854. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  180855. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  180856. #endif
  180857. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  180858. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  180859. png_bytep row));
  180860. #endif
  180861. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  180862. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  180863. png_bytep row));
  180864. #endif
  180865. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  180866. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  180867. png_bytep row));
  180868. #endif
  180869. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  180870. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  180871. png_bytep row));
  180872. #endif
  180873. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  180874. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  180875. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  180876. png_bytep row, png_uint_32 flags));
  180877. #endif
  180878. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  180879. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  180880. #endif
  180881. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  180882. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  180883. #endif
  180884. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180885. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  180886. row_info, png_bytep row));
  180887. #endif
  180888. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  180889. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  180890. png_bytep row));
  180891. #endif
  180892. #if defined(PNG_READ_PACK_SUPPORTED)
  180893. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  180894. #endif
  180895. #if defined(PNG_READ_SHIFT_SUPPORTED)
  180896. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  180897. png_color_8p sig_bits));
  180898. #endif
  180899. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  180900. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  180901. #endif
  180902. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  180903. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  180904. #endif
  180905. #if defined(PNG_READ_DITHER_SUPPORTED)
  180906. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  180907. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  180908. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  180909. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  180910. png_colorp palette, int num_palette));
  180911. # endif
  180912. #endif
  180913. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  180914. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  180915. #endif
  180916. #if defined(PNG_WRITE_PACK_SUPPORTED)
  180917. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  180918. png_bytep row, png_uint_32 bit_depth));
  180919. #endif
  180920. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  180921. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  180922. png_color_8p bit_depth));
  180923. #endif
  180924. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  180925. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180926. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180927. png_color_16p trans_values, png_color_16p background,
  180928. png_color_16p background_1,
  180929. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  180930. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  180931. png_uint_16pp gamma_16_to_1, int gamma_shift));
  180932. #else
  180933. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180934. png_color_16p trans_values, png_color_16p background));
  180935. #endif
  180936. #endif
  180937. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180938. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  180939. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  180940. int gamma_shift));
  180941. #endif
  180942. #if defined(PNG_READ_EXPAND_SUPPORTED)
  180943. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  180944. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  180945. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  180946. png_bytep row, png_color_16p trans_value));
  180947. #endif
  180948. /* The following decodes the appropriate chunks, and does error correction,
  180949. * then calls the appropriate callback for the chunk if it is valid.
  180950. */
  180951. /* decode the IHDR chunk */
  180952. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  180953. png_uint_32 length));
  180954. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  180955. png_uint_32 length));
  180956. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  180957. png_uint_32 length));
  180958. #if defined(PNG_READ_bKGD_SUPPORTED)
  180959. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  180960. png_uint_32 length));
  180961. #endif
  180962. #if defined(PNG_READ_cHRM_SUPPORTED)
  180963. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  180964. png_uint_32 length));
  180965. #endif
  180966. #if defined(PNG_READ_gAMA_SUPPORTED)
  180967. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  180968. png_uint_32 length));
  180969. #endif
  180970. #if defined(PNG_READ_hIST_SUPPORTED)
  180971. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  180972. png_uint_32 length));
  180973. #endif
  180974. #if defined(PNG_READ_iCCP_SUPPORTED)
  180975. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  180976. png_uint_32 length));
  180977. #endif /* PNG_READ_iCCP_SUPPORTED */
  180978. #if defined(PNG_READ_iTXt_SUPPORTED)
  180979. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180980. png_uint_32 length));
  180981. #endif
  180982. #if defined(PNG_READ_oFFs_SUPPORTED)
  180983. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180984. png_uint_32 length));
  180985. #endif
  180986. #if defined(PNG_READ_pCAL_SUPPORTED)
  180987. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180988. png_uint_32 length));
  180989. #endif
  180990. #if defined(PNG_READ_pHYs_SUPPORTED)
  180991. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180992. png_uint_32 length));
  180993. #endif
  180994. #if defined(PNG_READ_sBIT_SUPPORTED)
  180995. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180996. png_uint_32 length));
  180997. #endif
  180998. #if defined(PNG_READ_sCAL_SUPPORTED)
  180999. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  181000. png_uint_32 length));
  181001. #endif
  181002. #if defined(PNG_READ_sPLT_SUPPORTED)
  181003. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  181004. png_uint_32 length));
  181005. #endif /* PNG_READ_sPLT_SUPPORTED */
  181006. #if defined(PNG_READ_sRGB_SUPPORTED)
  181007. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  181008. png_uint_32 length));
  181009. #endif
  181010. #if defined(PNG_READ_tEXt_SUPPORTED)
  181011. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181012. png_uint_32 length));
  181013. #endif
  181014. #if defined(PNG_READ_tIME_SUPPORTED)
  181015. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  181016. png_uint_32 length));
  181017. #endif
  181018. #if defined(PNG_READ_tRNS_SUPPORTED)
  181019. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  181020. png_uint_32 length));
  181021. #endif
  181022. #if defined(PNG_READ_zTXt_SUPPORTED)
  181023. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181024. png_uint_32 length));
  181025. #endif
  181026. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  181027. png_infop info_ptr, png_uint_32 length));
  181028. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  181029. png_bytep chunk_name));
  181030. /* handle the transformations for reading and writing */
  181031. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  181032. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  181033. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  181034. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181035. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  181036. png_infop info_ptr));
  181037. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  181038. png_infop info_ptr));
  181039. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  181040. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  181041. png_uint_32 length));
  181042. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  181043. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  181044. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  181045. png_bytep buffer, png_size_t buffer_length));
  181046. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  181047. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  181048. png_bytep buffer, png_size_t buffer_length));
  181049. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  181050. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  181051. png_infop info_ptr, png_uint_32 length));
  181052. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  181053. png_infop info_ptr));
  181054. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  181055. png_infop info_ptr));
  181056. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  181057. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  181058. png_infop info_ptr));
  181059. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  181060. png_infop info_ptr));
  181061. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  181062. #if defined(PNG_READ_tEXt_SUPPORTED)
  181063. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  181064. png_infop info_ptr, png_uint_32 length));
  181065. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  181066. png_infop info_ptr));
  181067. #endif
  181068. #if defined(PNG_READ_zTXt_SUPPORTED)
  181069. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  181070. png_infop info_ptr, png_uint_32 length));
  181071. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  181072. png_infop info_ptr));
  181073. #endif
  181074. #if defined(PNG_READ_iTXt_SUPPORTED)
  181075. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  181076. png_infop info_ptr, png_uint_32 length));
  181077. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  181078. png_infop info_ptr));
  181079. #endif
  181080. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181081. #ifdef PNG_MNG_FEATURES_SUPPORTED
  181082. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  181083. png_bytep row));
  181084. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  181085. png_bytep row));
  181086. #endif
  181087. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181088. #if defined(PNG_MMX_CODE_SUPPORTED)
  181089. /* png.c */ /* PRIVATE */
  181090. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  181091. #endif
  181092. #endif
  181093. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181094. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  181095. png_infop info_ptr));
  181096. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  181097. png_infop info_ptr));
  181098. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  181099. png_infop info_ptr));
  181100. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  181101. png_infop info_ptr));
  181102. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  181103. png_infop info_ptr));
  181104. #if defined(PNG_pHYs_SUPPORTED)
  181105. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  181106. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  181107. #endif /* PNG_pHYs_SUPPORTED */
  181108. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181109. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  181110. #endif /* PNG_INTERNAL */
  181111. #ifdef __cplusplus
  181112. }
  181113. #endif
  181114. #endif /* PNG_VERSION_INFO_ONLY */
  181115. /* do not put anything past this line */
  181116. #endif /* PNG_H */
  181117. /*** End of inlined file: png.h ***/
  181118. #define PNG_NO_EXTERN
  181119. /*** Start of inlined file: png.c ***/
  181120. /* png.c - location for general purpose libpng functions
  181121. *
  181122. * Last changed in libpng 1.2.21 [October 4, 2007]
  181123. * For conditions of distribution and use, see copyright notice in png.h
  181124. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181125. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181126. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181127. */
  181128. #define PNG_INTERNAL
  181129. #define PNG_NO_EXTERN
  181130. /* Generate a compiler error if there is an old png.h in the search path. */
  181131. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  181132. /* Version information for C files. This had better match the version
  181133. * string defined in png.h. */
  181134. #ifdef PNG_USE_GLOBAL_ARRAYS
  181135. /* png_libpng_ver was changed to a function in version 1.0.5c */
  181136. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  181137. #ifdef PNG_READ_SUPPORTED
  181138. /* png_sig was changed to a function in version 1.0.5c */
  181139. /* Place to hold the signature string for a PNG file. */
  181140. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181141. #endif /* PNG_READ_SUPPORTED */
  181142. /* Invoke global declarations for constant strings for known chunk types */
  181143. PNG_IHDR;
  181144. PNG_IDAT;
  181145. PNG_IEND;
  181146. PNG_PLTE;
  181147. PNG_bKGD;
  181148. PNG_cHRM;
  181149. PNG_gAMA;
  181150. PNG_hIST;
  181151. PNG_iCCP;
  181152. PNG_iTXt;
  181153. PNG_oFFs;
  181154. PNG_pCAL;
  181155. PNG_sCAL;
  181156. PNG_pHYs;
  181157. PNG_sBIT;
  181158. PNG_sPLT;
  181159. PNG_sRGB;
  181160. PNG_tEXt;
  181161. PNG_tIME;
  181162. PNG_tRNS;
  181163. PNG_zTXt;
  181164. #ifdef PNG_READ_SUPPORTED
  181165. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  181166. /* start of interlace block */
  181167. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  181168. /* offset to next interlace block */
  181169. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  181170. /* start of interlace block in the y direction */
  181171. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  181172. /* offset to next interlace block in the y direction */
  181173. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  181174. /* Height of interlace block. This is not currently used - if you need
  181175. * it, uncomment it here and in png.h
  181176. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  181177. */
  181178. /* Mask to determine which pixels are valid in a pass */
  181179. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181180. /* Mask to determine which pixels to overwrite while displaying */
  181181. PNG_CONST int FARDATA png_pass_dsp_mask[]
  181182. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  181183. #endif /* PNG_READ_SUPPORTED */
  181184. #endif /* PNG_USE_GLOBAL_ARRAYS */
  181185. /* Tells libpng that we have already handled the first "num_bytes" bytes
  181186. * of the PNG file signature. If the PNG data is embedded into another
  181187. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  181188. * or write any of the magic bytes before it starts on the IHDR.
  181189. */
  181190. #ifdef PNG_READ_SUPPORTED
  181191. void PNGAPI
  181192. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  181193. {
  181194. if(png_ptr == NULL) return;
  181195. png_debug(1, "in png_set_sig_bytes\n");
  181196. if (num_bytes > 8)
  181197. png_error(png_ptr, "Too many bytes for PNG signature.");
  181198. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  181199. }
  181200. /* Checks whether the supplied bytes match the PNG signature. We allow
  181201. * checking less than the full 8-byte signature so that those apps that
  181202. * already read the first few bytes of a file to determine the file type
  181203. * can simply check the remaining bytes for extra assurance. Returns
  181204. * an integer less than, equal to, or greater than zero if sig is found,
  181205. * respectively, to be less than, to match, or be greater than the correct
  181206. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  181207. */
  181208. int PNGAPI
  181209. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  181210. {
  181211. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181212. if (num_to_check > 8)
  181213. num_to_check = 8;
  181214. else if (num_to_check < 1)
  181215. return (-1);
  181216. if (start > 7)
  181217. return (-1);
  181218. if (start + num_to_check > 8)
  181219. num_to_check = 8 - start;
  181220. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  181221. }
  181222. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181223. /* (Obsolete) function to check signature bytes. It does not allow one
  181224. * to check a partial signature. This function might be removed in the
  181225. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  181226. */
  181227. int PNGAPI
  181228. png_check_sig(png_bytep sig, int num)
  181229. {
  181230. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  181231. }
  181232. #endif
  181233. #endif /* PNG_READ_SUPPORTED */
  181234. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181235. /* Function to allocate memory for zlib and clear it to 0. */
  181236. #ifdef PNG_1_0_X
  181237. voidpf PNGAPI
  181238. #else
  181239. voidpf /* private */
  181240. #endif
  181241. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  181242. {
  181243. png_voidp ptr;
  181244. png_structp p=(png_structp)png_ptr;
  181245. png_uint_32 save_flags=p->flags;
  181246. png_uint_32 num_bytes;
  181247. if(png_ptr == NULL) return (NULL);
  181248. if (items > PNG_UINT_32_MAX/size)
  181249. {
  181250. png_warning (p, "Potential overflow in png_zalloc()");
  181251. return (NULL);
  181252. }
  181253. num_bytes = (png_uint_32)items * size;
  181254. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  181255. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  181256. p->flags=save_flags;
  181257. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  181258. if (ptr == NULL)
  181259. return ((voidpf)ptr);
  181260. if (num_bytes > (png_uint_32)0x8000L)
  181261. {
  181262. png_memset(ptr, 0, (png_size_t)0x8000L);
  181263. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  181264. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  181265. }
  181266. else
  181267. {
  181268. png_memset(ptr, 0, (png_size_t)num_bytes);
  181269. }
  181270. #endif
  181271. return ((voidpf)ptr);
  181272. }
  181273. /* function to free memory for zlib */
  181274. #ifdef PNG_1_0_X
  181275. void PNGAPI
  181276. #else
  181277. void /* private */
  181278. #endif
  181279. png_zfree(voidpf png_ptr, voidpf ptr)
  181280. {
  181281. png_free((png_structp)png_ptr, (png_voidp)ptr);
  181282. }
  181283. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  181284. * in case CRC is > 32 bits to leave the top bits 0.
  181285. */
  181286. void /* PRIVATE */
  181287. png_reset_crc(png_structp png_ptr)
  181288. {
  181289. png_ptr->crc = crc32(0, Z_NULL, 0);
  181290. }
  181291. /* Calculate the CRC over a section of data. We can only pass as
  181292. * much data to this routine as the largest single buffer size. We
  181293. * also check that this data will actually be used before going to the
  181294. * trouble of calculating it.
  181295. */
  181296. void /* PRIVATE */
  181297. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  181298. {
  181299. int need_crc = 1;
  181300. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  181301. {
  181302. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  181303. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  181304. need_crc = 0;
  181305. }
  181306. else /* critical */
  181307. {
  181308. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  181309. need_crc = 0;
  181310. }
  181311. if (need_crc)
  181312. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  181313. }
  181314. /* Allocate the memory for an info_struct for the application. We don't
  181315. * really need the png_ptr, but it could potentially be useful in the
  181316. * future. This should be used in favour of malloc(png_sizeof(png_info))
  181317. * and png_info_init() so that applications that want to use a shared
  181318. * libpng don't have to be recompiled if png_info changes size.
  181319. */
  181320. png_infop PNGAPI
  181321. png_create_info_struct(png_structp png_ptr)
  181322. {
  181323. png_infop info_ptr;
  181324. png_debug(1, "in png_create_info_struct\n");
  181325. if(png_ptr == NULL) return (NULL);
  181326. #ifdef PNG_USER_MEM_SUPPORTED
  181327. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  181328. png_ptr->malloc_fn, png_ptr->mem_ptr);
  181329. #else
  181330. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181331. #endif
  181332. if (info_ptr != NULL)
  181333. png_info_init_3(&info_ptr, png_sizeof(png_info));
  181334. return (info_ptr);
  181335. }
  181336. /* This function frees the memory associated with a single info struct.
  181337. * Normally, one would use either png_destroy_read_struct() or
  181338. * png_destroy_write_struct() to free an info struct, but this may be
  181339. * useful for some applications.
  181340. */
  181341. void PNGAPI
  181342. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  181343. {
  181344. png_infop info_ptr = NULL;
  181345. if(png_ptr == NULL) return;
  181346. png_debug(1, "in png_destroy_info_struct\n");
  181347. if (info_ptr_ptr != NULL)
  181348. info_ptr = *info_ptr_ptr;
  181349. if (info_ptr != NULL)
  181350. {
  181351. png_info_destroy(png_ptr, info_ptr);
  181352. #ifdef PNG_USER_MEM_SUPPORTED
  181353. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  181354. png_ptr->mem_ptr);
  181355. #else
  181356. png_destroy_struct((png_voidp)info_ptr);
  181357. #endif
  181358. *info_ptr_ptr = NULL;
  181359. }
  181360. }
  181361. /* Initialize the info structure. This is now an internal function (0.89)
  181362. * and applications using it are urged to use png_create_info_struct()
  181363. * instead.
  181364. */
  181365. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181366. #undef png_info_init
  181367. void PNGAPI
  181368. png_info_init(png_infop info_ptr)
  181369. {
  181370. /* We only come here via pre-1.0.12-compiled applications */
  181371. png_info_init_3(&info_ptr, 0);
  181372. }
  181373. #endif
  181374. void PNGAPI
  181375. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  181376. {
  181377. png_infop info_ptr = *ptr_ptr;
  181378. if(info_ptr == NULL) return;
  181379. png_debug(1, "in png_info_init_3\n");
  181380. if(png_sizeof(png_info) > png_info_struct_size)
  181381. {
  181382. png_destroy_struct(info_ptr);
  181383. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181384. *ptr_ptr = info_ptr;
  181385. }
  181386. /* set everything to 0 */
  181387. png_memset(info_ptr, 0, png_sizeof (png_info));
  181388. }
  181389. #ifdef PNG_FREE_ME_SUPPORTED
  181390. void PNGAPI
  181391. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  181392. int freer, png_uint_32 mask)
  181393. {
  181394. png_debug(1, "in png_data_freer\n");
  181395. if (png_ptr == NULL || info_ptr == NULL)
  181396. return;
  181397. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  181398. info_ptr->free_me |= mask;
  181399. else if(freer == PNG_USER_WILL_FREE_DATA)
  181400. info_ptr->free_me &= ~mask;
  181401. else
  181402. png_warning(png_ptr,
  181403. "Unknown freer parameter in png_data_freer.");
  181404. }
  181405. #endif
  181406. void PNGAPI
  181407. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  181408. int num)
  181409. {
  181410. png_debug(1, "in png_free_data\n");
  181411. if (png_ptr == NULL || info_ptr == NULL)
  181412. return;
  181413. #if defined(PNG_TEXT_SUPPORTED)
  181414. /* free text item num or (if num == -1) all text items */
  181415. #ifdef PNG_FREE_ME_SUPPORTED
  181416. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  181417. #else
  181418. if (mask & PNG_FREE_TEXT)
  181419. #endif
  181420. {
  181421. if (num != -1)
  181422. {
  181423. if (info_ptr->text && info_ptr->text[num].key)
  181424. {
  181425. png_free(png_ptr, info_ptr->text[num].key);
  181426. info_ptr->text[num].key = NULL;
  181427. }
  181428. }
  181429. else
  181430. {
  181431. int i;
  181432. for (i = 0; i < info_ptr->num_text; i++)
  181433. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  181434. png_free(png_ptr, info_ptr->text);
  181435. info_ptr->text = NULL;
  181436. info_ptr->num_text=0;
  181437. }
  181438. }
  181439. #endif
  181440. #if defined(PNG_tRNS_SUPPORTED)
  181441. /* free any tRNS entry */
  181442. #ifdef PNG_FREE_ME_SUPPORTED
  181443. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  181444. #else
  181445. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  181446. #endif
  181447. {
  181448. png_free(png_ptr, info_ptr->trans);
  181449. info_ptr->valid &= ~PNG_INFO_tRNS;
  181450. #ifndef PNG_FREE_ME_SUPPORTED
  181451. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  181452. #endif
  181453. info_ptr->trans = NULL;
  181454. }
  181455. #endif
  181456. #if defined(PNG_sCAL_SUPPORTED)
  181457. /* free any sCAL entry */
  181458. #ifdef PNG_FREE_ME_SUPPORTED
  181459. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  181460. #else
  181461. if (mask & PNG_FREE_SCAL)
  181462. #endif
  181463. {
  181464. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  181465. png_free(png_ptr, info_ptr->scal_s_width);
  181466. png_free(png_ptr, info_ptr->scal_s_height);
  181467. info_ptr->scal_s_width = NULL;
  181468. info_ptr->scal_s_height = NULL;
  181469. #endif
  181470. info_ptr->valid &= ~PNG_INFO_sCAL;
  181471. }
  181472. #endif
  181473. #if defined(PNG_pCAL_SUPPORTED)
  181474. /* free any pCAL entry */
  181475. #ifdef PNG_FREE_ME_SUPPORTED
  181476. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  181477. #else
  181478. if (mask & PNG_FREE_PCAL)
  181479. #endif
  181480. {
  181481. png_free(png_ptr, info_ptr->pcal_purpose);
  181482. png_free(png_ptr, info_ptr->pcal_units);
  181483. info_ptr->pcal_purpose = NULL;
  181484. info_ptr->pcal_units = NULL;
  181485. if (info_ptr->pcal_params != NULL)
  181486. {
  181487. int i;
  181488. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  181489. {
  181490. png_free(png_ptr, info_ptr->pcal_params[i]);
  181491. info_ptr->pcal_params[i]=NULL;
  181492. }
  181493. png_free(png_ptr, info_ptr->pcal_params);
  181494. info_ptr->pcal_params = NULL;
  181495. }
  181496. info_ptr->valid &= ~PNG_INFO_pCAL;
  181497. }
  181498. #endif
  181499. #if defined(PNG_iCCP_SUPPORTED)
  181500. /* free any iCCP entry */
  181501. #ifdef PNG_FREE_ME_SUPPORTED
  181502. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  181503. #else
  181504. if (mask & PNG_FREE_ICCP)
  181505. #endif
  181506. {
  181507. png_free(png_ptr, info_ptr->iccp_name);
  181508. png_free(png_ptr, info_ptr->iccp_profile);
  181509. info_ptr->iccp_name = NULL;
  181510. info_ptr->iccp_profile = NULL;
  181511. info_ptr->valid &= ~PNG_INFO_iCCP;
  181512. }
  181513. #endif
  181514. #if defined(PNG_sPLT_SUPPORTED)
  181515. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  181516. #ifdef PNG_FREE_ME_SUPPORTED
  181517. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  181518. #else
  181519. if (mask & PNG_FREE_SPLT)
  181520. #endif
  181521. {
  181522. if (num != -1)
  181523. {
  181524. if(info_ptr->splt_palettes)
  181525. {
  181526. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  181527. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  181528. info_ptr->splt_palettes[num].name = NULL;
  181529. info_ptr->splt_palettes[num].entries = NULL;
  181530. }
  181531. }
  181532. else
  181533. {
  181534. if(info_ptr->splt_palettes_num)
  181535. {
  181536. int i;
  181537. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  181538. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  181539. png_free(png_ptr, info_ptr->splt_palettes);
  181540. info_ptr->splt_palettes = NULL;
  181541. info_ptr->splt_palettes_num = 0;
  181542. }
  181543. info_ptr->valid &= ~PNG_INFO_sPLT;
  181544. }
  181545. }
  181546. #endif
  181547. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181548. if(png_ptr->unknown_chunk.data)
  181549. {
  181550. png_free(png_ptr, png_ptr->unknown_chunk.data);
  181551. png_ptr->unknown_chunk.data = NULL;
  181552. }
  181553. #ifdef PNG_FREE_ME_SUPPORTED
  181554. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  181555. #else
  181556. if (mask & PNG_FREE_UNKN)
  181557. #endif
  181558. {
  181559. if (num != -1)
  181560. {
  181561. if(info_ptr->unknown_chunks)
  181562. {
  181563. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  181564. info_ptr->unknown_chunks[num].data = NULL;
  181565. }
  181566. }
  181567. else
  181568. {
  181569. int i;
  181570. if(info_ptr->unknown_chunks_num)
  181571. {
  181572. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  181573. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  181574. png_free(png_ptr, info_ptr->unknown_chunks);
  181575. info_ptr->unknown_chunks = NULL;
  181576. info_ptr->unknown_chunks_num = 0;
  181577. }
  181578. }
  181579. }
  181580. #endif
  181581. #if defined(PNG_hIST_SUPPORTED)
  181582. /* free any hIST entry */
  181583. #ifdef PNG_FREE_ME_SUPPORTED
  181584. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  181585. #else
  181586. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  181587. #endif
  181588. {
  181589. png_free(png_ptr, info_ptr->hist);
  181590. info_ptr->hist = NULL;
  181591. info_ptr->valid &= ~PNG_INFO_hIST;
  181592. #ifndef PNG_FREE_ME_SUPPORTED
  181593. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  181594. #endif
  181595. }
  181596. #endif
  181597. /* free any PLTE entry that was internally allocated */
  181598. #ifdef PNG_FREE_ME_SUPPORTED
  181599. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  181600. #else
  181601. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  181602. #endif
  181603. {
  181604. png_zfree(png_ptr, info_ptr->palette);
  181605. info_ptr->palette = NULL;
  181606. info_ptr->valid &= ~PNG_INFO_PLTE;
  181607. #ifndef PNG_FREE_ME_SUPPORTED
  181608. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  181609. #endif
  181610. info_ptr->num_palette = 0;
  181611. }
  181612. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181613. /* free any image bits attached to the info structure */
  181614. #ifdef PNG_FREE_ME_SUPPORTED
  181615. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  181616. #else
  181617. if (mask & PNG_FREE_ROWS)
  181618. #endif
  181619. {
  181620. if(info_ptr->row_pointers)
  181621. {
  181622. int row;
  181623. for (row = 0; row < (int)info_ptr->height; row++)
  181624. {
  181625. png_free(png_ptr, info_ptr->row_pointers[row]);
  181626. info_ptr->row_pointers[row]=NULL;
  181627. }
  181628. png_free(png_ptr, info_ptr->row_pointers);
  181629. info_ptr->row_pointers=NULL;
  181630. }
  181631. info_ptr->valid &= ~PNG_INFO_IDAT;
  181632. }
  181633. #endif
  181634. #ifdef PNG_FREE_ME_SUPPORTED
  181635. if(num == -1)
  181636. info_ptr->free_me &= ~mask;
  181637. else
  181638. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  181639. #endif
  181640. }
  181641. /* This is an internal routine to free any memory that the info struct is
  181642. * pointing to before re-using it or freeing the struct itself. Recall
  181643. * that png_free() checks for NULL pointers for us.
  181644. */
  181645. void /* PRIVATE */
  181646. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  181647. {
  181648. png_debug(1, "in png_info_destroy\n");
  181649. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  181650. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181651. if (png_ptr->num_chunk_list)
  181652. {
  181653. png_free(png_ptr, png_ptr->chunk_list);
  181654. png_ptr->chunk_list=NULL;
  181655. png_ptr->num_chunk_list=0;
  181656. }
  181657. #endif
  181658. png_info_init_3(&info_ptr, png_sizeof(png_info));
  181659. }
  181660. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181661. /* This function returns a pointer to the io_ptr associated with the user
  181662. * functions. The application should free any memory associated with this
  181663. * pointer before png_write_destroy() or png_read_destroy() are called.
  181664. */
  181665. png_voidp PNGAPI
  181666. png_get_io_ptr(png_structp png_ptr)
  181667. {
  181668. if(png_ptr == NULL) return (NULL);
  181669. return (png_ptr->io_ptr);
  181670. }
  181671. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181672. #if !defined(PNG_NO_STDIO)
  181673. /* Initialize the default input/output functions for the PNG file. If you
  181674. * use your own read or write routines, you can call either png_set_read_fn()
  181675. * or png_set_write_fn() instead of png_init_io(). If you have defined
  181676. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  181677. * necessarily available.
  181678. */
  181679. void PNGAPI
  181680. png_init_io(png_structp png_ptr, png_FILE_p fp)
  181681. {
  181682. png_debug(1, "in png_init_io\n");
  181683. if(png_ptr == NULL) return;
  181684. png_ptr->io_ptr = (png_voidp)fp;
  181685. }
  181686. #endif
  181687. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181688. /* Convert the supplied time into an RFC 1123 string suitable for use in
  181689. * a "Creation Time" or other text-based time string.
  181690. */
  181691. png_charp PNGAPI
  181692. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  181693. {
  181694. static PNG_CONST char short_months[12][4] =
  181695. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  181696. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  181697. if(png_ptr == NULL) return (NULL);
  181698. if (png_ptr->time_buffer == NULL)
  181699. {
  181700. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  181701. png_sizeof(char)));
  181702. }
  181703. #if defined(_WIN32_WCE)
  181704. {
  181705. wchar_t time_buf[29];
  181706. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  181707. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  181708. ptime->year, ptime->hour % 24, ptime->minute % 60,
  181709. ptime->second % 61);
  181710. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  181711. NULL, NULL);
  181712. }
  181713. #else
  181714. #ifdef USE_FAR_KEYWORD
  181715. {
  181716. char near_time_buf[29];
  181717. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  181718. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  181719. ptime->year, ptime->hour % 24, ptime->minute % 60,
  181720. ptime->second % 61);
  181721. png_memcpy(png_ptr->time_buffer, near_time_buf,
  181722. 29*png_sizeof(char));
  181723. }
  181724. #else
  181725. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  181726. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  181727. ptime->year, ptime->hour % 24, ptime->minute % 60,
  181728. ptime->second % 61);
  181729. #endif
  181730. #endif /* _WIN32_WCE */
  181731. return ((png_charp)png_ptr->time_buffer);
  181732. }
  181733. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  181734. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181735. png_charp PNGAPI
  181736. png_get_copyright(png_structp png_ptr)
  181737. {
  181738. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181739. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  181740. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  181741. Copyright (c) 1996-1997 Andreas Dilger\n\
  181742. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  181743. }
  181744. /* The following return the library version as a short string in the
  181745. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  181746. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  181747. * is defined in png.h.
  181748. * Note: now there is no difference between png_get_libpng_ver() and
  181749. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  181750. * it is guaranteed that png.c uses the correct version of png.h.
  181751. */
  181752. png_charp PNGAPI
  181753. png_get_libpng_ver(png_structp png_ptr)
  181754. {
  181755. /* Version of *.c files used when building libpng */
  181756. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181757. return ((png_charp) PNG_LIBPNG_VER_STRING);
  181758. }
  181759. png_charp PNGAPI
  181760. png_get_header_ver(png_structp png_ptr)
  181761. {
  181762. /* Version of *.h files used when building libpng */
  181763. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181764. return ((png_charp) PNG_LIBPNG_VER_STRING);
  181765. }
  181766. png_charp PNGAPI
  181767. png_get_header_version(png_structp png_ptr)
  181768. {
  181769. /* Returns longer string containing both version and date */
  181770. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181771. return ((png_charp) PNG_HEADER_VERSION_STRING
  181772. #ifndef PNG_READ_SUPPORTED
  181773. " (NO READ SUPPORT)"
  181774. #endif
  181775. "\n");
  181776. }
  181777. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181778. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181779. int PNGAPI
  181780. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  181781. {
  181782. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  181783. int i;
  181784. png_bytep p;
  181785. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  181786. return 0;
  181787. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  181788. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  181789. if (!png_memcmp(chunk_name, p, 4))
  181790. return ((int)*(p+4));
  181791. return 0;
  181792. }
  181793. #endif
  181794. /* This function, added to libpng-1.0.6g, is untested. */
  181795. int PNGAPI
  181796. png_reset_zstream(png_structp png_ptr)
  181797. {
  181798. if (png_ptr == NULL) return Z_STREAM_ERROR;
  181799. return (inflateReset(&png_ptr->zstream));
  181800. }
  181801. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181802. /* This function was added to libpng-1.0.7 */
  181803. png_uint_32 PNGAPI
  181804. png_access_version_number(void)
  181805. {
  181806. /* Version of *.c files used when building libpng */
  181807. return((png_uint_32) PNG_LIBPNG_VER);
  181808. }
  181809. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181810. #if !defined(PNG_1_0_X)
  181811. /* this function was added to libpng 1.2.0 */
  181812. int PNGAPI
  181813. png_mmx_support(void)
  181814. {
  181815. /* obsolete, to be removed from libpng-1.4.0 */
  181816. return -1;
  181817. }
  181818. #endif /* PNG_1_0_X */
  181819. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  181820. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181821. #ifdef PNG_SIZE_T
  181822. /* Added at libpng version 1.2.6 */
  181823. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  181824. png_size_t PNGAPI
  181825. png_convert_size(size_t size)
  181826. {
  181827. if (size > (png_size_t)-1)
  181828. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  181829. return ((png_size_t)size);
  181830. }
  181831. #endif /* PNG_SIZE_T */
  181832. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181833. /*** End of inlined file: png.c ***/
  181834. /*** Start of inlined file: pngerror.c ***/
  181835. /* pngerror.c - stub functions for i/o and memory allocation
  181836. *
  181837. * Last changed in libpng 1.2.20 October 4, 2007
  181838. * For conditions of distribution and use, see copyright notice in png.h
  181839. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181840. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181841. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181842. *
  181843. * This file provides a location for all error handling. Users who
  181844. * need special error handling are expected to write replacement functions
  181845. * and use png_set_error_fn() to use those functions. See the instructions
  181846. * at each function.
  181847. */
  181848. #define PNG_INTERNAL
  181849. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181850. static void /* PRIVATE */
  181851. png_default_error PNGARG((png_structp png_ptr,
  181852. png_const_charp error_message));
  181853. #ifndef PNG_NO_WARNINGS
  181854. static void /* PRIVATE */
  181855. png_default_warning PNGARG((png_structp png_ptr,
  181856. png_const_charp warning_message));
  181857. #endif /* PNG_NO_WARNINGS */
  181858. /* This function is called whenever there is a fatal error. This function
  181859. * should not be changed. If there is a need to handle errors differently,
  181860. * you should supply a replacement error function and use png_set_error_fn()
  181861. * to replace the error function at run-time.
  181862. */
  181863. #ifndef PNG_NO_ERROR_TEXT
  181864. void PNGAPI
  181865. png_error(png_structp png_ptr, png_const_charp error_message)
  181866. {
  181867. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181868. char msg[16];
  181869. if (png_ptr != NULL)
  181870. {
  181871. if (png_ptr->flags&
  181872. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181873. {
  181874. if (*error_message == '#')
  181875. {
  181876. int offset;
  181877. for (offset=1; offset<15; offset++)
  181878. if (*(error_message+offset) == ' ')
  181879. break;
  181880. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181881. {
  181882. int i;
  181883. for (i=0; i<offset-1; i++)
  181884. msg[i]=error_message[i+1];
  181885. msg[i]='\0';
  181886. error_message=msg;
  181887. }
  181888. else
  181889. error_message+=offset;
  181890. }
  181891. else
  181892. {
  181893. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181894. {
  181895. msg[0]='0';
  181896. msg[1]='\0';
  181897. error_message=msg;
  181898. }
  181899. }
  181900. }
  181901. }
  181902. #endif
  181903. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181904. (*(png_ptr->error_fn))(png_ptr, error_message);
  181905. /* If the custom handler doesn't exist, or if it returns,
  181906. use the default handler, which will not return. */
  181907. png_default_error(png_ptr, error_message);
  181908. }
  181909. #else
  181910. void PNGAPI
  181911. png_err(png_structp png_ptr)
  181912. {
  181913. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181914. (*(png_ptr->error_fn))(png_ptr, '\0');
  181915. /* If the custom handler doesn't exist, or if it returns,
  181916. use the default handler, which will not return. */
  181917. png_default_error(png_ptr, '\0');
  181918. }
  181919. #endif /* PNG_NO_ERROR_TEXT */
  181920. #ifndef PNG_NO_WARNINGS
  181921. /* This function is called whenever there is a non-fatal error. This function
  181922. * should not be changed. If there is a need to handle warnings differently,
  181923. * you should supply a replacement warning function and use
  181924. * png_set_error_fn() to replace the warning function at run-time.
  181925. */
  181926. void PNGAPI
  181927. png_warning(png_structp png_ptr, png_const_charp warning_message)
  181928. {
  181929. int offset = 0;
  181930. if (png_ptr != NULL)
  181931. {
  181932. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181933. if (png_ptr->flags&
  181934. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181935. #endif
  181936. {
  181937. if (*warning_message == '#')
  181938. {
  181939. for (offset=1; offset<15; offset++)
  181940. if (*(warning_message+offset) == ' ')
  181941. break;
  181942. }
  181943. }
  181944. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  181945. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  181946. }
  181947. else
  181948. png_default_warning(png_ptr, warning_message+offset);
  181949. }
  181950. #endif /* PNG_NO_WARNINGS */
  181951. /* These utilities are used internally to build an error message that relates
  181952. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  181953. * this is used to prefix the message. The message is limited in length
  181954. * to 63 bytes, the name characters are output as hex digits wrapped in []
  181955. * if the character is invalid.
  181956. */
  181957. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  181958. /*static PNG_CONST char png_digit[16] = {
  181959. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  181960. 'A', 'B', 'C', 'D', 'E', 'F'
  181961. };*/
  181962. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  181963. static void /* PRIVATE */
  181964. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  181965. error_message)
  181966. {
  181967. int iout = 0, iin = 0;
  181968. while (iin < 4)
  181969. {
  181970. int c = png_ptr->chunk_name[iin++];
  181971. if (isnonalpha(c))
  181972. {
  181973. buffer[iout++] = '[';
  181974. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  181975. buffer[iout++] = png_digit[c & 0x0f];
  181976. buffer[iout++] = ']';
  181977. }
  181978. else
  181979. {
  181980. buffer[iout++] = (png_byte)c;
  181981. }
  181982. }
  181983. if (error_message == NULL)
  181984. buffer[iout] = 0;
  181985. else
  181986. {
  181987. buffer[iout++] = ':';
  181988. buffer[iout++] = ' ';
  181989. png_strncpy(buffer+iout, error_message, 63);
  181990. buffer[iout+63] = 0;
  181991. }
  181992. }
  181993. #ifdef PNG_READ_SUPPORTED
  181994. void PNGAPI
  181995. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  181996. {
  181997. char msg[18+64];
  181998. if (png_ptr == NULL)
  181999. png_error(png_ptr, error_message);
  182000. else
  182001. {
  182002. png_format_buffer(png_ptr, msg, error_message);
  182003. png_error(png_ptr, msg);
  182004. }
  182005. }
  182006. #endif /* PNG_READ_SUPPORTED */
  182007. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  182008. #ifndef PNG_NO_WARNINGS
  182009. void PNGAPI
  182010. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  182011. {
  182012. char msg[18+64];
  182013. if (png_ptr == NULL)
  182014. png_warning(png_ptr, warning_message);
  182015. else
  182016. {
  182017. png_format_buffer(png_ptr, msg, warning_message);
  182018. png_warning(png_ptr, msg);
  182019. }
  182020. }
  182021. #endif /* PNG_NO_WARNINGS */
  182022. /* This is the default error handling function. Note that replacements for
  182023. * this function MUST NOT RETURN, or the program will likely crash. This
  182024. * function is used by default, or if the program supplies NULL for the
  182025. * error function pointer in png_set_error_fn().
  182026. */
  182027. static void /* PRIVATE */
  182028. png_default_error(png_structp, png_const_charp error_message)
  182029. {
  182030. #ifndef PNG_NO_CONSOLE_IO
  182031. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182032. if (*error_message == '#')
  182033. {
  182034. int offset;
  182035. char error_number[16];
  182036. for (offset=0; offset<15; offset++)
  182037. {
  182038. error_number[offset] = *(error_message+offset+1);
  182039. if (*(error_message+offset) == ' ')
  182040. break;
  182041. }
  182042. if((offset > 1) && (offset < 15))
  182043. {
  182044. error_number[offset-1]='\0';
  182045. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  182046. error_message+offset);
  182047. }
  182048. else
  182049. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  182050. }
  182051. else
  182052. #endif
  182053. fprintf(stderr, "libpng error: %s\n", error_message);
  182054. #endif
  182055. #ifdef PNG_SETJMP_SUPPORTED
  182056. if (png_ptr)
  182057. {
  182058. # ifdef USE_FAR_KEYWORD
  182059. {
  182060. jmp_buf jmpbuf;
  182061. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  182062. longjmp(jmpbuf, 1);
  182063. }
  182064. # else
  182065. longjmp(png_ptr->jmpbuf, 1);
  182066. # endif
  182067. }
  182068. #else
  182069. PNG_ABORT();
  182070. #endif
  182071. #ifdef PNG_NO_CONSOLE_IO
  182072. error_message = error_message; /* make compiler happy */
  182073. #endif
  182074. }
  182075. #ifndef PNG_NO_WARNINGS
  182076. /* This function is called when there is a warning, but the library thinks
  182077. * it can continue anyway. Replacement functions don't have to do anything
  182078. * here if you don't want them to. In the default configuration, png_ptr is
  182079. * not used, but it is passed in case it may be useful.
  182080. */
  182081. static void /* PRIVATE */
  182082. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  182083. {
  182084. #ifndef PNG_NO_CONSOLE_IO
  182085. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182086. if (*warning_message == '#')
  182087. {
  182088. int offset;
  182089. char warning_number[16];
  182090. for (offset=0; offset<15; offset++)
  182091. {
  182092. warning_number[offset]=*(warning_message+offset+1);
  182093. if (*(warning_message+offset) == ' ')
  182094. break;
  182095. }
  182096. if((offset > 1) && (offset < 15))
  182097. {
  182098. warning_number[offset-1]='\0';
  182099. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  182100. warning_message+offset);
  182101. }
  182102. else
  182103. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182104. }
  182105. else
  182106. # endif
  182107. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182108. #else
  182109. warning_message = warning_message; /* make compiler happy */
  182110. #endif
  182111. png_ptr = png_ptr; /* make compiler happy */
  182112. }
  182113. #endif /* PNG_NO_WARNINGS */
  182114. /* This function is called when the application wants to use another method
  182115. * of handling errors and warnings. Note that the error function MUST NOT
  182116. * return to the calling routine or serious problems will occur. The return
  182117. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  182118. */
  182119. void PNGAPI
  182120. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  182121. png_error_ptr error_fn, png_error_ptr warning_fn)
  182122. {
  182123. if (png_ptr == NULL)
  182124. return;
  182125. png_ptr->error_ptr = error_ptr;
  182126. png_ptr->error_fn = error_fn;
  182127. png_ptr->warning_fn = warning_fn;
  182128. }
  182129. /* This function returns a pointer to the error_ptr associated with the user
  182130. * functions. The application should free any memory associated with this
  182131. * pointer before png_write_destroy and png_read_destroy are called.
  182132. */
  182133. png_voidp PNGAPI
  182134. png_get_error_ptr(png_structp png_ptr)
  182135. {
  182136. if (png_ptr == NULL)
  182137. return NULL;
  182138. return ((png_voidp)png_ptr->error_ptr);
  182139. }
  182140. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182141. void PNGAPI
  182142. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  182143. {
  182144. if(png_ptr != NULL)
  182145. {
  182146. png_ptr->flags &=
  182147. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  182148. }
  182149. }
  182150. #endif
  182151. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182152. /*** End of inlined file: pngerror.c ***/
  182153. /*** Start of inlined file: pngget.c ***/
  182154. /* pngget.c - retrieval of values from info struct
  182155. *
  182156. * Last changed in libpng 1.2.15 January 5, 2007
  182157. * For conditions of distribution and use, see copyright notice in png.h
  182158. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182159. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182160. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182161. */
  182162. #define PNG_INTERNAL
  182163. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182164. png_uint_32 PNGAPI
  182165. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  182166. {
  182167. if (png_ptr != NULL && info_ptr != NULL)
  182168. return(info_ptr->valid & flag);
  182169. else
  182170. return(0);
  182171. }
  182172. png_uint_32 PNGAPI
  182173. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  182174. {
  182175. if (png_ptr != NULL && info_ptr != NULL)
  182176. return(info_ptr->rowbytes);
  182177. else
  182178. return(0);
  182179. }
  182180. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182181. png_bytepp PNGAPI
  182182. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  182183. {
  182184. if (png_ptr != NULL && info_ptr != NULL)
  182185. return(info_ptr->row_pointers);
  182186. else
  182187. return(0);
  182188. }
  182189. #endif
  182190. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182191. /* easy access to info, added in libpng-0.99 */
  182192. png_uint_32 PNGAPI
  182193. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  182194. {
  182195. if (png_ptr != NULL && info_ptr != NULL)
  182196. {
  182197. return info_ptr->width;
  182198. }
  182199. return (0);
  182200. }
  182201. png_uint_32 PNGAPI
  182202. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  182203. {
  182204. if (png_ptr != NULL && info_ptr != NULL)
  182205. {
  182206. return info_ptr->height;
  182207. }
  182208. return (0);
  182209. }
  182210. png_byte PNGAPI
  182211. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  182212. {
  182213. if (png_ptr != NULL && info_ptr != NULL)
  182214. {
  182215. return info_ptr->bit_depth;
  182216. }
  182217. return (0);
  182218. }
  182219. png_byte PNGAPI
  182220. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  182221. {
  182222. if (png_ptr != NULL && info_ptr != NULL)
  182223. {
  182224. return info_ptr->color_type;
  182225. }
  182226. return (0);
  182227. }
  182228. png_byte PNGAPI
  182229. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  182230. {
  182231. if (png_ptr != NULL && info_ptr != NULL)
  182232. {
  182233. return info_ptr->filter_type;
  182234. }
  182235. return (0);
  182236. }
  182237. png_byte PNGAPI
  182238. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  182239. {
  182240. if (png_ptr != NULL && info_ptr != NULL)
  182241. {
  182242. return info_ptr->interlace_type;
  182243. }
  182244. return (0);
  182245. }
  182246. png_byte PNGAPI
  182247. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  182248. {
  182249. if (png_ptr != NULL && info_ptr != NULL)
  182250. {
  182251. return info_ptr->compression_type;
  182252. }
  182253. return (0);
  182254. }
  182255. png_uint_32 PNGAPI
  182256. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182257. {
  182258. if (png_ptr != NULL && info_ptr != NULL)
  182259. #if defined(PNG_pHYs_SUPPORTED)
  182260. if (info_ptr->valid & PNG_INFO_pHYs)
  182261. {
  182262. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  182263. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182264. return (0);
  182265. else return (info_ptr->x_pixels_per_unit);
  182266. }
  182267. #else
  182268. return (0);
  182269. #endif
  182270. return (0);
  182271. }
  182272. png_uint_32 PNGAPI
  182273. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182274. {
  182275. if (png_ptr != NULL && info_ptr != NULL)
  182276. #if defined(PNG_pHYs_SUPPORTED)
  182277. if (info_ptr->valid & PNG_INFO_pHYs)
  182278. {
  182279. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  182280. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182281. return (0);
  182282. else return (info_ptr->y_pixels_per_unit);
  182283. }
  182284. #else
  182285. return (0);
  182286. #endif
  182287. return (0);
  182288. }
  182289. png_uint_32 PNGAPI
  182290. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182291. {
  182292. if (png_ptr != NULL && info_ptr != NULL)
  182293. #if defined(PNG_pHYs_SUPPORTED)
  182294. if (info_ptr->valid & PNG_INFO_pHYs)
  182295. {
  182296. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  182297. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  182298. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  182299. return (0);
  182300. else return (info_ptr->x_pixels_per_unit);
  182301. }
  182302. #else
  182303. return (0);
  182304. #endif
  182305. return (0);
  182306. }
  182307. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182308. float PNGAPI
  182309. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  182310. {
  182311. if (png_ptr != NULL && info_ptr != NULL)
  182312. #if defined(PNG_pHYs_SUPPORTED)
  182313. if (info_ptr->valid & PNG_INFO_pHYs)
  182314. {
  182315. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  182316. if (info_ptr->x_pixels_per_unit == 0)
  182317. return ((float)0.0);
  182318. else
  182319. return ((float)((float)info_ptr->y_pixels_per_unit
  182320. /(float)info_ptr->x_pixels_per_unit));
  182321. }
  182322. #else
  182323. return (0.0);
  182324. #endif
  182325. return ((float)0.0);
  182326. }
  182327. #endif
  182328. png_int_32 PNGAPI
  182329. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182330. {
  182331. if (png_ptr != NULL && info_ptr != NULL)
  182332. #if defined(PNG_oFFs_SUPPORTED)
  182333. if (info_ptr->valid & PNG_INFO_oFFs)
  182334. {
  182335. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182336. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182337. return (0);
  182338. else return (info_ptr->x_offset);
  182339. }
  182340. #else
  182341. return (0);
  182342. #endif
  182343. return (0);
  182344. }
  182345. png_int_32 PNGAPI
  182346. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182347. {
  182348. if (png_ptr != NULL && info_ptr != NULL)
  182349. #if defined(PNG_oFFs_SUPPORTED)
  182350. if (info_ptr->valid & PNG_INFO_oFFs)
  182351. {
  182352. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182353. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182354. return (0);
  182355. else return (info_ptr->y_offset);
  182356. }
  182357. #else
  182358. return (0);
  182359. #endif
  182360. return (0);
  182361. }
  182362. png_int_32 PNGAPI
  182363. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  182364. {
  182365. if (png_ptr != NULL && info_ptr != NULL)
  182366. #if defined(PNG_oFFs_SUPPORTED)
  182367. if (info_ptr->valid & PNG_INFO_oFFs)
  182368. {
  182369. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182370. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  182371. return (0);
  182372. else return (info_ptr->x_offset);
  182373. }
  182374. #else
  182375. return (0);
  182376. #endif
  182377. return (0);
  182378. }
  182379. png_int_32 PNGAPI
  182380. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  182381. {
  182382. if (png_ptr != NULL && info_ptr != NULL)
  182383. #if defined(PNG_oFFs_SUPPORTED)
  182384. if (info_ptr->valid & PNG_INFO_oFFs)
  182385. {
  182386. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182387. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  182388. return (0);
  182389. else return (info_ptr->y_offset);
  182390. }
  182391. #else
  182392. return (0);
  182393. #endif
  182394. return (0);
  182395. }
  182396. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182397. png_uint_32 PNGAPI
  182398. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182399. {
  182400. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  182401. *.0254 +.5));
  182402. }
  182403. png_uint_32 PNGAPI
  182404. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182405. {
  182406. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  182407. *.0254 +.5));
  182408. }
  182409. png_uint_32 PNGAPI
  182410. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182411. {
  182412. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  182413. *.0254 +.5));
  182414. }
  182415. float PNGAPI
  182416. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  182417. {
  182418. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  182419. *.00003937);
  182420. }
  182421. float PNGAPI
  182422. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  182423. {
  182424. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  182425. *.00003937);
  182426. }
  182427. #if defined(PNG_pHYs_SUPPORTED)
  182428. png_uint_32 PNGAPI
  182429. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  182430. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  182431. {
  182432. png_uint_32 retval = 0;
  182433. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  182434. {
  182435. png_debug1(1, "in %s retrieval function\n", "pHYs");
  182436. if (res_x != NULL)
  182437. {
  182438. *res_x = info_ptr->x_pixels_per_unit;
  182439. retval |= PNG_INFO_pHYs;
  182440. }
  182441. if (res_y != NULL)
  182442. {
  182443. *res_y = info_ptr->y_pixels_per_unit;
  182444. retval |= PNG_INFO_pHYs;
  182445. }
  182446. if (unit_type != NULL)
  182447. {
  182448. *unit_type = (int)info_ptr->phys_unit_type;
  182449. retval |= PNG_INFO_pHYs;
  182450. if(*unit_type == 1)
  182451. {
  182452. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  182453. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  182454. }
  182455. }
  182456. }
  182457. return (retval);
  182458. }
  182459. #endif /* PNG_pHYs_SUPPORTED */
  182460. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  182461. /* png_get_channels really belongs in here, too, but it's been around longer */
  182462. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182463. png_byte PNGAPI
  182464. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  182465. {
  182466. if (png_ptr != NULL && info_ptr != NULL)
  182467. return(info_ptr->channels);
  182468. else
  182469. return (0);
  182470. }
  182471. png_bytep PNGAPI
  182472. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  182473. {
  182474. if (png_ptr != NULL && info_ptr != NULL)
  182475. return(info_ptr->signature);
  182476. else
  182477. return (NULL);
  182478. }
  182479. #if defined(PNG_bKGD_SUPPORTED)
  182480. png_uint_32 PNGAPI
  182481. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  182482. png_color_16p *background)
  182483. {
  182484. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  182485. && background != NULL)
  182486. {
  182487. png_debug1(1, "in %s retrieval function\n", "bKGD");
  182488. *background = &(info_ptr->background);
  182489. return (PNG_INFO_bKGD);
  182490. }
  182491. return (0);
  182492. }
  182493. #endif
  182494. #if defined(PNG_cHRM_SUPPORTED)
  182495. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182496. png_uint_32 PNGAPI
  182497. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  182498. double *white_x, double *white_y, double *red_x, double *red_y,
  182499. double *green_x, double *green_y, double *blue_x, double *blue_y)
  182500. {
  182501. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  182502. {
  182503. png_debug1(1, "in %s retrieval function\n", "cHRM");
  182504. if (white_x != NULL)
  182505. *white_x = (double)info_ptr->x_white;
  182506. if (white_y != NULL)
  182507. *white_y = (double)info_ptr->y_white;
  182508. if (red_x != NULL)
  182509. *red_x = (double)info_ptr->x_red;
  182510. if (red_y != NULL)
  182511. *red_y = (double)info_ptr->y_red;
  182512. if (green_x != NULL)
  182513. *green_x = (double)info_ptr->x_green;
  182514. if (green_y != NULL)
  182515. *green_y = (double)info_ptr->y_green;
  182516. if (blue_x != NULL)
  182517. *blue_x = (double)info_ptr->x_blue;
  182518. if (blue_y != NULL)
  182519. *blue_y = (double)info_ptr->y_blue;
  182520. return (PNG_INFO_cHRM);
  182521. }
  182522. return (0);
  182523. }
  182524. #endif
  182525. #ifdef PNG_FIXED_POINT_SUPPORTED
  182526. png_uint_32 PNGAPI
  182527. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  182528. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  182529. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  182530. png_fixed_point *blue_x, png_fixed_point *blue_y)
  182531. {
  182532. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  182533. {
  182534. png_debug1(1, "in %s retrieval function\n", "cHRM");
  182535. if (white_x != NULL)
  182536. *white_x = info_ptr->int_x_white;
  182537. if (white_y != NULL)
  182538. *white_y = info_ptr->int_y_white;
  182539. if (red_x != NULL)
  182540. *red_x = info_ptr->int_x_red;
  182541. if (red_y != NULL)
  182542. *red_y = info_ptr->int_y_red;
  182543. if (green_x != NULL)
  182544. *green_x = info_ptr->int_x_green;
  182545. if (green_y != NULL)
  182546. *green_y = info_ptr->int_y_green;
  182547. if (blue_x != NULL)
  182548. *blue_x = info_ptr->int_x_blue;
  182549. if (blue_y != NULL)
  182550. *blue_y = info_ptr->int_y_blue;
  182551. return (PNG_INFO_cHRM);
  182552. }
  182553. return (0);
  182554. }
  182555. #endif
  182556. #endif
  182557. #if defined(PNG_gAMA_SUPPORTED)
  182558. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182559. png_uint_32 PNGAPI
  182560. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  182561. {
  182562. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  182563. && file_gamma != NULL)
  182564. {
  182565. png_debug1(1, "in %s retrieval function\n", "gAMA");
  182566. *file_gamma = (double)info_ptr->gamma;
  182567. return (PNG_INFO_gAMA);
  182568. }
  182569. return (0);
  182570. }
  182571. #endif
  182572. #ifdef PNG_FIXED_POINT_SUPPORTED
  182573. png_uint_32 PNGAPI
  182574. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  182575. png_fixed_point *int_file_gamma)
  182576. {
  182577. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  182578. && int_file_gamma != NULL)
  182579. {
  182580. png_debug1(1, "in %s retrieval function\n", "gAMA");
  182581. *int_file_gamma = info_ptr->int_gamma;
  182582. return (PNG_INFO_gAMA);
  182583. }
  182584. return (0);
  182585. }
  182586. #endif
  182587. #endif
  182588. #if defined(PNG_sRGB_SUPPORTED)
  182589. png_uint_32 PNGAPI
  182590. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  182591. {
  182592. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  182593. && file_srgb_intent != NULL)
  182594. {
  182595. png_debug1(1, "in %s retrieval function\n", "sRGB");
  182596. *file_srgb_intent = (int)info_ptr->srgb_intent;
  182597. return (PNG_INFO_sRGB);
  182598. }
  182599. return (0);
  182600. }
  182601. #endif
  182602. #if defined(PNG_iCCP_SUPPORTED)
  182603. png_uint_32 PNGAPI
  182604. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  182605. png_charpp name, int *compression_type,
  182606. png_charpp profile, png_uint_32 *proflen)
  182607. {
  182608. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  182609. && name != NULL && profile != NULL && proflen != NULL)
  182610. {
  182611. png_debug1(1, "in %s retrieval function\n", "iCCP");
  182612. *name = info_ptr->iccp_name;
  182613. *profile = info_ptr->iccp_profile;
  182614. /* compression_type is a dummy so the API won't have to change
  182615. if we introduce multiple compression types later. */
  182616. *proflen = (int)info_ptr->iccp_proflen;
  182617. *compression_type = (int)info_ptr->iccp_compression;
  182618. return (PNG_INFO_iCCP);
  182619. }
  182620. return (0);
  182621. }
  182622. #endif
  182623. #if defined(PNG_sPLT_SUPPORTED)
  182624. png_uint_32 PNGAPI
  182625. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  182626. png_sPLT_tpp spalettes)
  182627. {
  182628. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  182629. {
  182630. *spalettes = info_ptr->splt_palettes;
  182631. return ((png_uint_32)info_ptr->splt_palettes_num);
  182632. }
  182633. return (0);
  182634. }
  182635. #endif
  182636. #if defined(PNG_hIST_SUPPORTED)
  182637. png_uint_32 PNGAPI
  182638. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  182639. {
  182640. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  182641. && hist != NULL)
  182642. {
  182643. png_debug1(1, "in %s retrieval function\n", "hIST");
  182644. *hist = info_ptr->hist;
  182645. return (PNG_INFO_hIST);
  182646. }
  182647. return (0);
  182648. }
  182649. #endif
  182650. png_uint_32 PNGAPI
  182651. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  182652. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  182653. int *color_type, int *interlace_type, int *compression_type,
  182654. int *filter_type)
  182655. {
  182656. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  182657. bit_depth != NULL && color_type != NULL)
  182658. {
  182659. png_debug1(1, "in %s retrieval function\n", "IHDR");
  182660. *width = info_ptr->width;
  182661. *height = info_ptr->height;
  182662. *bit_depth = info_ptr->bit_depth;
  182663. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  182664. png_error(png_ptr, "Invalid bit depth");
  182665. *color_type = info_ptr->color_type;
  182666. if (info_ptr->color_type > 6)
  182667. png_error(png_ptr, "Invalid color type");
  182668. if (compression_type != NULL)
  182669. *compression_type = info_ptr->compression_type;
  182670. if (filter_type != NULL)
  182671. *filter_type = info_ptr->filter_type;
  182672. if (interlace_type != NULL)
  182673. *interlace_type = info_ptr->interlace_type;
  182674. /* check for potential overflow of rowbytes */
  182675. if (*width == 0 || *width > PNG_UINT_31_MAX)
  182676. png_error(png_ptr, "Invalid image width");
  182677. if (*height == 0 || *height > PNG_UINT_31_MAX)
  182678. png_error(png_ptr, "Invalid image height");
  182679. if (info_ptr->width > (PNG_UINT_32_MAX
  182680. >> 3) /* 8-byte RGBA pixels */
  182681. - 64 /* bigrowbuf hack */
  182682. - 1 /* filter byte */
  182683. - 7*8 /* rounding of width to multiple of 8 pixels */
  182684. - 8) /* extra max_pixel_depth pad */
  182685. {
  182686. png_warning(png_ptr,
  182687. "Width too large for libpng to process image data.");
  182688. }
  182689. return (1);
  182690. }
  182691. return (0);
  182692. }
  182693. #if defined(PNG_oFFs_SUPPORTED)
  182694. png_uint_32 PNGAPI
  182695. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  182696. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  182697. {
  182698. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  182699. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  182700. {
  182701. png_debug1(1, "in %s retrieval function\n", "oFFs");
  182702. *offset_x = info_ptr->x_offset;
  182703. *offset_y = info_ptr->y_offset;
  182704. *unit_type = (int)info_ptr->offset_unit_type;
  182705. return (PNG_INFO_oFFs);
  182706. }
  182707. return (0);
  182708. }
  182709. #endif
  182710. #if defined(PNG_pCAL_SUPPORTED)
  182711. png_uint_32 PNGAPI
  182712. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  182713. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  182714. png_charp *units, png_charpp *params)
  182715. {
  182716. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  182717. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  182718. nparams != NULL && units != NULL && params != NULL)
  182719. {
  182720. png_debug1(1, "in %s retrieval function\n", "pCAL");
  182721. *purpose = info_ptr->pcal_purpose;
  182722. *X0 = info_ptr->pcal_X0;
  182723. *X1 = info_ptr->pcal_X1;
  182724. *type = (int)info_ptr->pcal_type;
  182725. *nparams = (int)info_ptr->pcal_nparams;
  182726. *units = info_ptr->pcal_units;
  182727. *params = info_ptr->pcal_params;
  182728. return (PNG_INFO_pCAL);
  182729. }
  182730. return (0);
  182731. }
  182732. #endif
  182733. #if defined(PNG_sCAL_SUPPORTED)
  182734. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182735. png_uint_32 PNGAPI
  182736. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  182737. int *unit, double *width, double *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_pixel_width;
  182744. *height = info_ptr->scal_pixel_height;
  182745. return (PNG_INFO_sCAL);
  182746. }
  182747. return(0);
  182748. }
  182749. #else
  182750. #ifdef PNG_FIXED_POINT_SUPPORTED
  182751. png_uint_32 PNGAPI
  182752. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  182753. int *unit, png_charpp width, png_charpp height)
  182754. {
  182755. if (png_ptr != NULL && info_ptr != NULL &&
  182756. (info_ptr->valid & PNG_INFO_sCAL))
  182757. {
  182758. *unit = info_ptr->scal_unit;
  182759. *width = info_ptr->scal_s_width;
  182760. *height = info_ptr->scal_s_height;
  182761. return (PNG_INFO_sCAL);
  182762. }
  182763. return(0);
  182764. }
  182765. #endif
  182766. #endif
  182767. #endif
  182768. #if defined(PNG_pHYs_SUPPORTED)
  182769. png_uint_32 PNGAPI
  182770. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  182771. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  182772. {
  182773. png_uint_32 retval = 0;
  182774. if (png_ptr != NULL && info_ptr != NULL &&
  182775. (info_ptr->valid & PNG_INFO_pHYs))
  182776. {
  182777. png_debug1(1, "in %s retrieval function\n", "pHYs");
  182778. if (res_x != NULL)
  182779. {
  182780. *res_x = info_ptr->x_pixels_per_unit;
  182781. retval |= PNG_INFO_pHYs;
  182782. }
  182783. if (res_y != NULL)
  182784. {
  182785. *res_y = info_ptr->y_pixels_per_unit;
  182786. retval |= PNG_INFO_pHYs;
  182787. }
  182788. if (unit_type != NULL)
  182789. {
  182790. *unit_type = (int)info_ptr->phys_unit_type;
  182791. retval |= PNG_INFO_pHYs;
  182792. }
  182793. }
  182794. return (retval);
  182795. }
  182796. #endif
  182797. png_uint_32 PNGAPI
  182798. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  182799. int *num_palette)
  182800. {
  182801. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  182802. && palette != NULL)
  182803. {
  182804. png_debug1(1, "in %s retrieval function\n", "PLTE");
  182805. *palette = info_ptr->palette;
  182806. *num_palette = info_ptr->num_palette;
  182807. png_debug1(3, "num_palette = %d\n", *num_palette);
  182808. return (PNG_INFO_PLTE);
  182809. }
  182810. return (0);
  182811. }
  182812. #if defined(PNG_sBIT_SUPPORTED)
  182813. png_uint_32 PNGAPI
  182814. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  182815. {
  182816. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  182817. && sig_bit != NULL)
  182818. {
  182819. png_debug1(1, "in %s retrieval function\n", "sBIT");
  182820. *sig_bit = &(info_ptr->sig_bit);
  182821. return (PNG_INFO_sBIT);
  182822. }
  182823. return (0);
  182824. }
  182825. #endif
  182826. #if defined(PNG_TEXT_SUPPORTED)
  182827. png_uint_32 PNGAPI
  182828. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  182829. int *num_text)
  182830. {
  182831. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  182832. {
  182833. png_debug1(1, "in %s retrieval function\n",
  182834. (png_ptr->chunk_name[0] == '\0' ? "text"
  182835. : (png_const_charp)png_ptr->chunk_name));
  182836. if (text_ptr != NULL)
  182837. *text_ptr = info_ptr->text;
  182838. if (num_text != NULL)
  182839. *num_text = info_ptr->num_text;
  182840. return ((png_uint_32)info_ptr->num_text);
  182841. }
  182842. if (num_text != NULL)
  182843. *num_text = 0;
  182844. return(0);
  182845. }
  182846. #endif
  182847. #if defined(PNG_tIME_SUPPORTED)
  182848. png_uint_32 PNGAPI
  182849. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  182850. {
  182851. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  182852. && mod_time != NULL)
  182853. {
  182854. png_debug1(1, "in %s retrieval function\n", "tIME");
  182855. *mod_time = &(info_ptr->mod_time);
  182856. return (PNG_INFO_tIME);
  182857. }
  182858. return (0);
  182859. }
  182860. #endif
  182861. #if defined(PNG_tRNS_SUPPORTED)
  182862. png_uint_32 PNGAPI
  182863. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  182864. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  182865. {
  182866. png_uint_32 retval = 0;
  182867. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  182868. {
  182869. png_debug1(1, "in %s retrieval function\n", "tRNS");
  182870. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  182871. {
  182872. if (trans != NULL)
  182873. {
  182874. *trans = info_ptr->trans;
  182875. retval |= PNG_INFO_tRNS;
  182876. }
  182877. if (trans_values != NULL)
  182878. *trans_values = &(info_ptr->trans_values);
  182879. }
  182880. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  182881. {
  182882. if (trans_values != NULL)
  182883. {
  182884. *trans_values = &(info_ptr->trans_values);
  182885. retval |= PNG_INFO_tRNS;
  182886. }
  182887. if(trans != NULL)
  182888. *trans = NULL;
  182889. }
  182890. if(num_trans != NULL)
  182891. {
  182892. *num_trans = info_ptr->num_trans;
  182893. retval |= PNG_INFO_tRNS;
  182894. }
  182895. }
  182896. return (retval);
  182897. }
  182898. #endif
  182899. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182900. png_uint_32 PNGAPI
  182901. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  182902. png_unknown_chunkpp unknowns)
  182903. {
  182904. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  182905. {
  182906. *unknowns = info_ptr->unknown_chunks;
  182907. return ((png_uint_32)info_ptr->unknown_chunks_num);
  182908. }
  182909. return (0);
  182910. }
  182911. #endif
  182912. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182913. png_byte PNGAPI
  182914. png_get_rgb_to_gray_status (png_structp png_ptr)
  182915. {
  182916. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  182917. }
  182918. #endif
  182919. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182920. png_voidp PNGAPI
  182921. png_get_user_chunk_ptr(png_structp png_ptr)
  182922. {
  182923. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  182924. }
  182925. #endif
  182926. #ifdef PNG_WRITE_SUPPORTED
  182927. png_uint_32 PNGAPI
  182928. png_get_compression_buffer_size(png_structp png_ptr)
  182929. {
  182930. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  182931. }
  182932. #endif
  182933. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  182934. #ifndef PNG_1_0_X
  182935. /* this function was added to libpng 1.2.0 and should exist by default */
  182936. png_uint_32 PNGAPI
  182937. png_get_asm_flags (png_structp png_ptr)
  182938. {
  182939. /* obsolete, to be removed from libpng-1.4.0 */
  182940. return (png_ptr? 0L: 0L);
  182941. }
  182942. /* this function was added to libpng 1.2.0 and should exist by default */
  182943. png_uint_32 PNGAPI
  182944. png_get_asm_flagmask (int flag_select)
  182945. {
  182946. /* obsolete, to be removed from libpng-1.4.0 */
  182947. flag_select=flag_select;
  182948. return 0L;
  182949. }
  182950. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  182951. /* this function was added to libpng 1.2.0 */
  182952. png_uint_32 PNGAPI
  182953. png_get_mmx_flagmask (int flag_select, int *compilerID)
  182954. {
  182955. /* obsolete, to be removed from libpng-1.4.0 */
  182956. flag_select=flag_select;
  182957. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  182958. return 0L;
  182959. }
  182960. /* this function was added to libpng 1.2.0 */
  182961. png_byte PNGAPI
  182962. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  182963. {
  182964. /* obsolete, to be removed from libpng-1.4.0 */
  182965. return (png_ptr? 0: 0);
  182966. }
  182967. /* this function was added to libpng 1.2.0 */
  182968. png_uint_32 PNGAPI
  182969. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  182970. {
  182971. /* obsolete, to be removed from libpng-1.4.0 */
  182972. return (png_ptr? 0L: 0L);
  182973. }
  182974. #endif /* ?PNG_1_0_X */
  182975. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  182976. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182977. /* these functions were added to libpng 1.2.6 */
  182978. png_uint_32 PNGAPI
  182979. png_get_user_width_max (png_structp png_ptr)
  182980. {
  182981. return (png_ptr? png_ptr->user_width_max : 0);
  182982. }
  182983. png_uint_32 PNGAPI
  182984. png_get_user_height_max (png_structp png_ptr)
  182985. {
  182986. return (png_ptr? png_ptr->user_height_max : 0);
  182987. }
  182988. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  182989. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182990. /*** End of inlined file: pngget.c ***/
  182991. /*** Start of inlined file: pngmem.c ***/
  182992. /* pngmem.c - stub functions for memory allocation
  182993. *
  182994. * Last changed in libpng 1.2.13 November 13, 2006
  182995. * For conditions of distribution and use, see copyright notice in png.h
  182996. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  182997. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182998. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182999. *
  183000. * This file provides a location for all memory allocation. Users who
  183001. * need special memory handling are expected to supply replacement
  183002. * functions for png_malloc() and png_free(), and to use
  183003. * png_create_read_struct_2() and png_create_write_struct_2() to
  183004. * identify the replacement functions.
  183005. */
  183006. #define PNG_INTERNAL
  183007. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183008. /* Borland DOS special memory handler */
  183009. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  183010. /* if you change this, be sure to change the one in png.h also */
  183011. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  183012. by a single call to calloc() if this is thought to improve performance. */
  183013. png_voidp /* PRIVATE */
  183014. png_create_struct(int type)
  183015. {
  183016. #ifdef PNG_USER_MEM_SUPPORTED
  183017. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183018. }
  183019. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  183020. png_voidp /* PRIVATE */
  183021. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183022. {
  183023. #endif /* PNG_USER_MEM_SUPPORTED */
  183024. png_size_t size;
  183025. png_voidp struct_ptr;
  183026. if (type == PNG_STRUCT_INFO)
  183027. size = png_sizeof(png_info);
  183028. else if (type == PNG_STRUCT_PNG)
  183029. size = png_sizeof(png_struct);
  183030. else
  183031. return (png_get_copyright(NULL));
  183032. #ifdef PNG_USER_MEM_SUPPORTED
  183033. if(malloc_fn != NULL)
  183034. {
  183035. png_struct dummy_struct;
  183036. png_structp png_ptr = &dummy_struct;
  183037. png_ptr->mem_ptr=mem_ptr;
  183038. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  183039. }
  183040. else
  183041. #endif /* PNG_USER_MEM_SUPPORTED */
  183042. struct_ptr = (png_voidp)farmalloc(size);
  183043. if (struct_ptr != NULL)
  183044. png_memset(struct_ptr, 0, size);
  183045. return (struct_ptr);
  183046. }
  183047. /* Free memory allocated by a png_create_struct() call */
  183048. void /* PRIVATE */
  183049. png_destroy_struct(png_voidp struct_ptr)
  183050. {
  183051. #ifdef PNG_USER_MEM_SUPPORTED
  183052. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183053. }
  183054. /* Free memory allocated by a png_create_struct() call */
  183055. void /* PRIVATE */
  183056. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183057. png_voidp mem_ptr)
  183058. {
  183059. #endif
  183060. if (struct_ptr != NULL)
  183061. {
  183062. #ifdef PNG_USER_MEM_SUPPORTED
  183063. if(free_fn != NULL)
  183064. {
  183065. png_struct dummy_struct;
  183066. png_structp png_ptr = &dummy_struct;
  183067. png_ptr->mem_ptr=mem_ptr;
  183068. (*(free_fn))(png_ptr, struct_ptr);
  183069. return;
  183070. }
  183071. #endif /* PNG_USER_MEM_SUPPORTED */
  183072. farfree (struct_ptr);
  183073. }
  183074. }
  183075. /* Allocate memory. For reasonable files, size should never exceed
  183076. * 64K. However, zlib may allocate more then 64K if you don't tell
  183077. * it not to. See zconf.h and png.h for more information. zlib does
  183078. * need to allocate exactly 64K, so whatever you call here must
  183079. * have the ability to do that.
  183080. *
  183081. * Borland seems to have a problem in DOS mode for exactly 64K.
  183082. * It gives you a segment with an offset of 8 (perhaps to store its
  183083. * memory stuff). zlib doesn't like this at all, so we have to
  183084. * detect and deal with it. This code should not be needed in
  183085. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  183086. * been updated by Alexander Lehmann for version 0.89 to waste less
  183087. * memory.
  183088. *
  183089. * Note that we can't use png_size_t for the "size" declaration,
  183090. * since on some systems a png_size_t is a 16-bit quantity, and as a
  183091. * result, we would be truncating potentially larger memory requests
  183092. * (which should cause a fatal error) and introducing major problems.
  183093. */
  183094. png_voidp PNGAPI
  183095. png_malloc(png_structp png_ptr, png_uint_32 size)
  183096. {
  183097. png_voidp ret;
  183098. if (png_ptr == NULL || size == 0)
  183099. return (NULL);
  183100. #ifdef PNG_USER_MEM_SUPPORTED
  183101. if(png_ptr->malloc_fn != NULL)
  183102. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183103. else
  183104. ret = (png_malloc_default(png_ptr, size));
  183105. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183106. png_error(png_ptr, "Out of memory!");
  183107. return (ret);
  183108. }
  183109. png_voidp PNGAPI
  183110. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183111. {
  183112. png_voidp ret;
  183113. #endif /* PNG_USER_MEM_SUPPORTED */
  183114. if (png_ptr == NULL || size == 0)
  183115. return (NULL);
  183116. #ifdef PNG_MAX_MALLOC_64K
  183117. if (size > (png_uint_32)65536L)
  183118. {
  183119. png_warning(png_ptr, "Cannot Allocate > 64K");
  183120. ret = NULL;
  183121. }
  183122. else
  183123. #endif
  183124. if (size != (size_t)size)
  183125. ret = NULL;
  183126. else if (size == (png_uint_32)65536L)
  183127. {
  183128. if (png_ptr->offset_table == NULL)
  183129. {
  183130. /* try to see if we need to do any of this fancy stuff */
  183131. ret = farmalloc(size);
  183132. if (ret == NULL || ((png_size_t)ret & 0xffff))
  183133. {
  183134. int num_blocks;
  183135. png_uint_32 total_size;
  183136. png_bytep table;
  183137. int i;
  183138. png_byte huge * hptr;
  183139. if (ret != NULL)
  183140. {
  183141. farfree(ret);
  183142. ret = NULL;
  183143. }
  183144. if(png_ptr->zlib_window_bits > 14)
  183145. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  183146. else
  183147. num_blocks = 1;
  183148. if (png_ptr->zlib_mem_level >= 7)
  183149. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  183150. else
  183151. num_blocks++;
  183152. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  183153. table = farmalloc(total_size);
  183154. if (table == NULL)
  183155. {
  183156. #ifndef PNG_USER_MEM_SUPPORTED
  183157. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183158. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  183159. else
  183160. png_warning(png_ptr, "Out Of Memory.");
  183161. #endif
  183162. return (NULL);
  183163. }
  183164. if ((png_size_t)table & 0xfff0)
  183165. {
  183166. #ifndef PNG_USER_MEM_SUPPORTED
  183167. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183168. png_error(png_ptr,
  183169. "Farmalloc didn't return normalized pointer");
  183170. else
  183171. png_warning(png_ptr,
  183172. "Farmalloc didn't return normalized pointer");
  183173. #endif
  183174. return (NULL);
  183175. }
  183176. png_ptr->offset_table = table;
  183177. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  183178. png_sizeof (png_bytep));
  183179. if (png_ptr->offset_table_ptr == NULL)
  183180. {
  183181. #ifndef PNG_USER_MEM_SUPPORTED
  183182. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183183. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  183184. else
  183185. png_warning(png_ptr, "Out Of memory.");
  183186. #endif
  183187. return (NULL);
  183188. }
  183189. hptr = (png_byte huge *)table;
  183190. if ((png_size_t)hptr & 0xf)
  183191. {
  183192. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  183193. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  183194. }
  183195. for (i = 0; i < num_blocks; i++)
  183196. {
  183197. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  183198. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  183199. }
  183200. png_ptr->offset_table_number = num_blocks;
  183201. png_ptr->offset_table_count = 0;
  183202. png_ptr->offset_table_count_free = 0;
  183203. }
  183204. }
  183205. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  183206. {
  183207. #ifndef PNG_USER_MEM_SUPPORTED
  183208. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183209. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  183210. else
  183211. png_warning(png_ptr, "Out of Memory.");
  183212. #endif
  183213. return (NULL);
  183214. }
  183215. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  183216. }
  183217. else
  183218. ret = farmalloc(size);
  183219. #ifndef PNG_USER_MEM_SUPPORTED
  183220. if (ret == NULL)
  183221. {
  183222. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183223. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183224. else
  183225. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183226. }
  183227. #endif
  183228. return (ret);
  183229. }
  183230. /* free a pointer allocated by png_malloc(). In the default
  183231. configuration, png_ptr is not used, but is passed in case it
  183232. is needed. If ptr is NULL, return without taking any action. */
  183233. void PNGAPI
  183234. png_free(png_structp png_ptr, png_voidp ptr)
  183235. {
  183236. if (png_ptr == NULL || ptr == NULL)
  183237. return;
  183238. #ifdef PNG_USER_MEM_SUPPORTED
  183239. if (png_ptr->free_fn != NULL)
  183240. {
  183241. (*(png_ptr->free_fn))(png_ptr, ptr);
  183242. return;
  183243. }
  183244. else png_free_default(png_ptr, ptr);
  183245. }
  183246. void PNGAPI
  183247. png_free_default(png_structp png_ptr, png_voidp ptr)
  183248. {
  183249. #endif /* PNG_USER_MEM_SUPPORTED */
  183250. if(png_ptr == NULL) return;
  183251. if (png_ptr->offset_table != NULL)
  183252. {
  183253. int i;
  183254. for (i = 0; i < png_ptr->offset_table_count; i++)
  183255. {
  183256. if (ptr == png_ptr->offset_table_ptr[i])
  183257. {
  183258. ptr = NULL;
  183259. png_ptr->offset_table_count_free++;
  183260. break;
  183261. }
  183262. }
  183263. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  183264. {
  183265. farfree(png_ptr->offset_table);
  183266. farfree(png_ptr->offset_table_ptr);
  183267. png_ptr->offset_table = NULL;
  183268. png_ptr->offset_table_ptr = NULL;
  183269. }
  183270. }
  183271. if (ptr != NULL)
  183272. {
  183273. farfree(ptr);
  183274. }
  183275. }
  183276. #else /* Not the Borland DOS special memory handler */
  183277. /* Allocate memory for a png_struct or a png_info. The malloc and
  183278. memset can be replaced by a single call to calloc() if this is thought
  183279. to improve performance noticably. */
  183280. png_voidp /* PRIVATE */
  183281. png_create_struct(int type)
  183282. {
  183283. #ifdef PNG_USER_MEM_SUPPORTED
  183284. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183285. }
  183286. /* Allocate memory for a png_struct or a png_info. The malloc and
  183287. memset can be replaced by a single call to calloc() if this is thought
  183288. to improve performance noticably. */
  183289. png_voidp /* PRIVATE */
  183290. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183291. {
  183292. #endif /* PNG_USER_MEM_SUPPORTED */
  183293. png_size_t size;
  183294. png_voidp struct_ptr;
  183295. if (type == PNG_STRUCT_INFO)
  183296. size = png_sizeof(png_info);
  183297. else if (type == PNG_STRUCT_PNG)
  183298. size = png_sizeof(png_struct);
  183299. else
  183300. return (NULL);
  183301. #ifdef PNG_USER_MEM_SUPPORTED
  183302. if(malloc_fn != NULL)
  183303. {
  183304. png_struct dummy_struct;
  183305. png_structp png_ptr = &dummy_struct;
  183306. png_ptr->mem_ptr=mem_ptr;
  183307. struct_ptr = (*(malloc_fn))(png_ptr, size);
  183308. if (struct_ptr != NULL)
  183309. png_memset(struct_ptr, 0, size);
  183310. return (struct_ptr);
  183311. }
  183312. #endif /* PNG_USER_MEM_SUPPORTED */
  183313. #if defined(__TURBOC__) && !defined(__FLAT__)
  183314. struct_ptr = (png_voidp)farmalloc(size);
  183315. #else
  183316. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183317. struct_ptr = (png_voidp)halloc(size,1);
  183318. # else
  183319. struct_ptr = (png_voidp)malloc(size);
  183320. # endif
  183321. #endif
  183322. if (struct_ptr != NULL)
  183323. png_memset(struct_ptr, 0, size);
  183324. return (struct_ptr);
  183325. }
  183326. /* Free memory allocated by a png_create_struct() call */
  183327. void /* PRIVATE */
  183328. png_destroy_struct(png_voidp struct_ptr)
  183329. {
  183330. #ifdef PNG_USER_MEM_SUPPORTED
  183331. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183332. }
  183333. /* Free memory allocated by a png_create_struct() call */
  183334. void /* PRIVATE */
  183335. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183336. png_voidp mem_ptr)
  183337. {
  183338. #endif /* PNG_USER_MEM_SUPPORTED */
  183339. if (struct_ptr != NULL)
  183340. {
  183341. #ifdef PNG_USER_MEM_SUPPORTED
  183342. if(free_fn != NULL)
  183343. {
  183344. png_struct dummy_struct;
  183345. png_structp png_ptr = &dummy_struct;
  183346. png_ptr->mem_ptr=mem_ptr;
  183347. (*(free_fn))(png_ptr, struct_ptr);
  183348. return;
  183349. }
  183350. #endif /* PNG_USER_MEM_SUPPORTED */
  183351. #if defined(__TURBOC__) && !defined(__FLAT__)
  183352. farfree(struct_ptr);
  183353. #else
  183354. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183355. hfree(struct_ptr);
  183356. # else
  183357. free(struct_ptr);
  183358. # endif
  183359. #endif
  183360. }
  183361. }
  183362. /* Allocate memory. For reasonable files, size should never exceed
  183363. 64K. However, zlib may allocate more then 64K if you don't tell
  183364. it not to. See zconf.h and png.h for more information. zlib does
  183365. need to allocate exactly 64K, so whatever you call here must
  183366. have the ability to do that. */
  183367. png_voidp PNGAPI
  183368. png_malloc(png_structp png_ptr, png_uint_32 size)
  183369. {
  183370. png_voidp ret;
  183371. #ifdef PNG_USER_MEM_SUPPORTED
  183372. if (png_ptr == NULL || size == 0)
  183373. return (NULL);
  183374. if(png_ptr->malloc_fn != NULL)
  183375. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183376. else
  183377. ret = (png_malloc_default(png_ptr, size));
  183378. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183379. png_error(png_ptr, "Out of Memory!");
  183380. return (ret);
  183381. }
  183382. png_voidp PNGAPI
  183383. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183384. {
  183385. png_voidp ret;
  183386. #endif /* PNG_USER_MEM_SUPPORTED */
  183387. if (png_ptr == NULL || size == 0)
  183388. return (NULL);
  183389. #ifdef PNG_MAX_MALLOC_64K
  183390. if (size > (png_uint_32)65536L)
  183391. {
  183392. #ifndef PNG_USER_MEM_SUPPORTED
  183393. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183394. png_error(png_ptr, "Cannot Allocate > 64K");
  183395. else
  183396. #endif
  183397. return NULL;
  183398. }
  183399. #endif
  183400. /* Check for overflow */
  183401. #if defined(__TURBOC__) && !defined(__FLAT__)
  183402. if (size != (unsigned long)size)
  183403. ret = NULL;
  183404. else
  183405. ret = farmalloc(size);
  183406. #else
  183407. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183408. if (size != (unsigned long)size)
  183409. ret = NULL;
  183410. else
  183411. ret = halloc(size, 1);
  183412. # else
  183413. if (size != (size_t)size)
  183414. ret = NULL;
  183415. else
  183416. ret = malloc((size_t)size);
  183417. # endif
  183418. #endif
  183419. #ifndef PNG_USER_MEM_SUPPORTED
  183420. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183421. png_error(png_ptr, "Out of Memory");
  183422. #endif
  183423. return (ret);
  183424. }
  183425. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  183426. without taking any action. */
  183427. void PNGAPI
  183428. png_free(png_structp png_ptr, png_voidp ptr)
  183429. {
  183430. if (png_ptr == NULL || ptr == NULL)
  183431. return;
  183432. #ifdef PNG_USER_MEM_SUPPORTED
  183433. if (png_ptr->free_fn != NULL)
  183434. {
  183435. (*(png_ptr->free_fn))(png_ptr, ptr);
  183436. return;
  183437. }
  183438. else png_free_default(png_ptr, ptr);
  183439. }
  183440. void PNGAPI
  183441. png_free_default(png_structp png_ptr, png_voidp ptr)
  183442. {
  183443. if (png_ptr == NULL || ptr == NULL)
  183444. return;
  183445. #endif /* PNG_USER_MEM_SUPPORTED */
  183446. #if defined(__TURBOC__) && !defined(__FLAT__)
  183447. farfree(ptr);
  183448. #else
  183449. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183450. hfree(ptr);
  183451. # else
  183452. free(ptr);
  183453. # endif
  183454. #endif
  183455. }
  183456. #endif /* Not Borland DOS special memory handler */
  183457. #if defined(PNG_1_0_X)
  183458. # define png_malloc_warn png_malloc
  183459. #else
  183460. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  183461. * function will set up png_malloc() to issue a png_warning and return NULL
  183462. * instead of issuing a png_error, if it fails to allocate the requested
  183463. * memory.
  183464. */
  183465. png_voidp PNGAPI
  183466. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  183467. {
  183468. png_voidp ptr;
  183469. png_uint_32 save_flags;
  183470. if(png_ptr == NULL) return (NULL);
  183471. save_flags=png_ptr->flags;
  183472. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183473. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  183474. png_ptr->flags=save_flags;
  183475. return(ptr);
  183476. }
  183477. #endif
  183478. png_voidp PNGAPI
  183479. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  183480. png_uint_32 length)
  183481. {
  183482. png_size_t size;
  183483. size = (png_size_t)length;
  183484. if ((png_uint_32)size != length)
  183485. png_error(png_ptr,"Overflow in png_memcpy_check.");
  183486. return(png_memcpy (s1, s2, size));
  183487. }
  183488. png_voidp PNGAPI
  183489. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  183490. png_uint_32 length)
  183491. {
  183492. png_size_t size;
  183493. size = (png_size_t)length;
  183494. if ((png_uint_32)size != length)
  183495. png_error(png_ptr,"Overflow in png_memset_check.");
  183496. return (png_memset (s1, value, size));
  183497. }
  183498. #ifdef PNG_USER_MEM_SUPPORTED
  183499. /* This function is called when the application wants to use another method
  183500. * of allocating and freeing memory.
  183501. */
  183502. void PNGAPI
  183503. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  183504. malloc_fn, png_free_ptr free_fn)
  183505. {
  183506. if(png_ptr != NULL) {
  183507. png_ptr->mem_ptr = mem_ptr;
  183508. png_ptr->malloc_fn = malloc_fn;
  183509. png_ptr->free_fn = free_fn;
  183510. }
  183511. }
  183512. /* This function returns a pointer to the mem_ptr associated with the user
  183513. * functions. The application should free any memory associated with this
  183514. * pointer before png_write_destroy and png_read_destroy are called.
  183515. */
  183516. png_voidp PNGAPI
  183517. png_get_mem_ptr(png_structp png_ptr)
  183518. {
  183519. if(png_ptr == NULL) return (NULL);
  183520. return ((png_voidp)png_ptr->mem_ptr);
  183521. }
  183522. #endif /* PNG_USER_MEM_SUPPORTED */
  183523. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  183524. /*** End of inlined file: pngmem.c ***/
  183525. /*** Start of inlined file: pngread.c ***/
  183526. /* pngread.c - read a PNG file
  183527. *
  183528. * Last changed in libpng 1.2.20 September 7, 2007
  183529. * For conditions of distribution and use, see copyright notice in png.h
  183530. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183531. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183532. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183533. *
  183534. * This file contains routines that an application calls directly to
  183535. * read a PNG file or stream.
  183536. */
  183537. #define PNG_INTERNAL
  183538. #if defined(PNG_READ_SUPPORTED)
  183539. /* Create a PNG structure for reading, and allocate any memory needed. */
  183540. png_structp PNGAPI
  183541. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  183542. png_error_ptr error_fn, png_error_ptr warn_fn)
  183543. {
  183544. #ifdef PNG_USER_MEM_SUPPORTED
  183545. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  183546. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  183547. }
  183548. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  183549. png_structp PNGAPI
  183550. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  183551. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183552. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  183553. {
  183554. #endif /* PNG_USER_MEM_SUPPORTED */
  183555. png_structp png_ptr;
  183556. #ifdef PNG_SETJMP_SUPPORTED
  183557. #ifdef USE_FAR_KEYWORD
  183558. jmp_buf jmpbuf;
  183559. #endif
  183560. #endif
  183561. int i;
  183562. png_debug(1, "in png_create_read_struct\n");
  183563. #ifdef PNG_USER_MEM_SUPPORTED
  183564. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  183565. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  183566. #else
  183567. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  183568. #endif
  183569. if (png_ptr == NULL)
  183570. return (NULL);
  183571. /* added at libpng-1.2.6 */
  183572. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183573. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  183574. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  183575. #endif
  183576. #ifdef PNG_SETJMP_SUPPORTED
  183577. #ifdef USE_FAR_KEYWORD
  183578. if (setjmp(jmpbuf))
  183579. #else
  183580. if (setjmp(png_ptr->jmpbuf))
  183581. #endif
  183582. {
  183583. png_free(png_ptr, png_ptr->zbuf);
  183584. png_ptr->zbuf=NULL;
  183585. #ifdef PNG_USER_MEM_SUPPORTED
  183586. png_destroy_struct_2((png_voidp)png_ptr,
  183587. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  183588. #else
  183589. png_destroy_struct((png_voidp)png_ptr);
  183590. #endif
  183591. return (NULL);
  183592. }
  183593. #ifdef USE_FAR_KEYWORD
  183594. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  183595. #endif
  183596. #endif
  183597. #ifdef PNG_USER_MEM_SUPPORTED
  183598. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  183599. #endif
  183600. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  183601. i=0;
  183602. do
  183603. {
  183604. if(user_png_ver[i] != png_libpng_ver[i])
  183605. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  183606. } while (png_libpng_ver[i++]);
  183607. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  183608. {
  183609. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  183610. * we must recompile any applications that use any older library version.
  183611. * For versions after libpng 1.0, we will be compatible, so we need
  183612. * only check the first digit.
  183613. */
  183614. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  183615. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  183616. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  183617. {
  183618. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  183619. char msg[80];
  183620. if (user_png_ver)
  183621. {
  183622. png_snprintf(msg, 80,
  183623. "Application was compiled with png.h from libpng-%.20s",
  183624. user_png_ver);
  183625. png_warning(png_ptr, msg);
  183626. }
  183627. png_snprintf(msg, 80,
  183628. "Application is running with png.c from libpng-%.20s",
  183629. png_libpng_ver);
  183630. png_warning(png_ptr, msg);
  183631. #endif
  183632. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183633. png_ptr->flags=0;
  183634. #endif
  183635. png_error(png_ptr,
  183636. "Incompatible libpng version in application and library");
  183637. }
  183638. }
  183639. /* initialize zbuf - compression buffer */
  183640. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  183641. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  183642. (png_uint_32)png_ptr->zbuf_size);
  183643. png_ptr->zstream.zalloc = png_zalloc;
  183644. png_ptr->zstream.zfree = png_zfree;
  183645. png_ptr->zstream.opaque = (voidpf)png_ptr;
  183646. switch (inflateInit(&png_ptr->zstream))
  183647. {
  183648. case Z_OK: /* Do nothing */ break;
  183649. case Z_MEM_ERROR:
  183650. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  183651. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  183652. default: png_error(png_ptr, "Unknown zlib error");
  183653. }
  183654. png_ptr->zstream.next_out = png_ptr->zbuf;
  183655. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183656. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  183657. #ifdef PNG_SETJMP_SUPPORTED
  183658. /* Applications that neglect to set up their own setjmp() and then encounter
  183659. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  183660. abort instead of returning. */
  183661. #ifdef USE_FAR_KEYWORD
  183662. if (setjmp(jmpbuf))
  183663. PNG_ABORT();
  183664. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  183665. #else
  183666. if (setjmp(png_ptr->jmpbuf))
  183667. PNG_ABORT();
  183668. #endif
  183669. #endif
  183670. return (png_ptr);
  183671. }
  183672. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183673. /* Initialize PNG structure for reading, and allocate any memory needed.
  183674. This interface is deprecated in favour of the png_create_read_struct(),
  183675. and it will disappear as of libpng-1.3.0. */
  183676. #undef png_read_init
  183677. void PNGAPI
  183678. png_read_init(png_structp png_ptr)
  183679. {
  183680. /* We only come here via pre-1.0.7-compiled applications */
  183681. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  183682. }
  183683. void PNGAPI
  183684. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  183685. png_size_t png_struct_size, png_size_t png_info_size)
  183686. {
  183687. /* We only come here via pre-1.0.12-compiled applications */
  183688. if(png_ptr == NULL) return;
  183689. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  183690. if(png_sizeof(png_struct) > png_struct_size ||
  183691. png_sizeof(png_info) > png_info_size)
  183692. {
  183693. char msg[80];
  183694. png_ptr->warning_fn=NULL;
  183695. if (user_png_ver)
  183696. {
  183697. png_snprintf(msg, 80,
  183698. "Application was compiled with png.h from libpng-%.20s",
  183699. user_png_ver);
  183700. png_warning(png_ptr, msg);
  183701. }
  183702. png_snprintf(msg, 80,
  183703. "Application is running with png.c from libpng-%.20s",
  183704. png_libpng_ver);
  183705. png_warning(png_ptr, msg);
  183706. }
  183707. #endif
  183708. if(png_sizeof(png_struct) > png_struct_size)
  183709. {
  183710. png_ptr->error_fn=NULL;
  183711. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183712. png_ptr->flags=0;
  183713. #endif
  183714. png_error(png_ptr,
  183715. "The png struct allocated by the application for reading is too small.");
  183716. }
  183717. if(png_sizeof(png_info) > png_info_size)
  183718. {
  183719. png_ptr->error_fn=NULL;
  183720. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183721. png_ptr->flags=0;
  183722. #endif
  183723. png_error(png_ptr,
  183724. "The info struct allocated by application for reading is too small.");
  183725. }
  183726. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  183727. }
  183728. #endif /* PNG_1_0_X || PNG_1_2_X */
  183729. void PNGAPI
  183730. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  183731. png_size_t png_struct_size)
  183732. {
  183733. #ifdef PNG_SETJMP_SUPPORTED
  183734. jmp_buf tmp_jmp; /* to save current jump buffer */
  183735. #endif
  183736. int i=0;
  183737. png_structp png_ptr=*ptr_ptr;
  183738. if(png_ptr == NULL) return;
  183739. do
  183740. {
  183741. if(user_png_ver[i] != png_libpng_ver[i])
  183742. {
  183743. #ifdef PNG_LEGACY_SUPPORTED
  183744. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  183745. #else
  183746. png_ptr->warning_fn=NULL;
  183747. png_warning(png_ptr,
  183748. "Application uses deprecated png_read_init() and should be recompiled.");
  183749. break;
  183750. #endif
  183751. }
  183752. } while (png_libpng_ver[i++]);
  183753. png_debug(1, "in png_read_init_3\n");
  183754. #ifdef PNG_SETJMP_SUPPORTED
  183755. /* save jump buffer and error functions */
  183756. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183757. #endif
  183758. if(png_sizeof(png_struct) > png_struct_size)
  183759. {
  183760. png_destroy_struct(png_ptr);
  183761. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  183762. png_ptr = *ptr_ptr;
  183763. }
  183764. /* reset all variables to 0 */
  183765. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183766. #ifdef PNG_SETJMP_SUPPORTED
  183767. /* restore jump buffer */
  183768. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183769. #endif
  183770. /* added at libpng-1.2.6 */
  183771. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183772. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  183773. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  183774. #endif
  183775. /* initialize zbuf - compression buffer */
  183776. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  183777. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  183778. (png_uint_32)png_ptr->zbuf_size);
  183779. png_ptr->zstream.zalloc = png_zalloc;
  183780. png_ptr->zstream.zfree = png_zfree;
  183781. png_ptr->zstream.opaque = (voidpf)png_ptr;
  183782. switch (inflateInit(&png_ptr->zstream))
  183783. {
  183784. case Z_OK: /* Do nothing */ break;
  183785. case Z_MEM_ERROR:
  183786. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  183787. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  183788. default: png_error(png_ptr, "Unknown zlib error");
  183789. }
  183790. png_ptr->zstream.next_out = png_ptr->zbuf;
  183791. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183792. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  183793. }
  183794. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183795. /* Read the information before the actual image data. This has been
  183796. * changed in v0.90 to allow reading a file that already has the magic
  183797. * bytes read from the stream. You can tell libpng how many bytes have
  183798. * been read from the beginning of the stream (up to the maximum of 8)
  183799. * via png_set_sig_bytes(), and we will only check the remaining bytes
  183800. * here. The application can then have access to the signature bytes we
  183801. * read if it is determined that this isn't a valid PNG file.
  183802. */
  183803. void PNGAPI
  183804. png_read_info(png_structp png_ptr, png_infop info_ptr)
  183805. {
  183806. if(png_ptr == NULL) return;
  183807. png_debug(1, "in png_read_info\n");
  183808. /* If we haven't checked all of the PNG signature bytes, do so now. */
  183809. if (png_ptr->sig_bytes < 8)
  183810. {
  183811. png_size_t num_checked = png_ptr->sig_bytes,
  183812. num_to_check = 8 - num_checked;
  183813. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  183814. png_ptr->sig_bytes = 8;
  183815. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  183816. {
  183817. if (num_checked < 4 &&
  183818. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  183819. png_error(png_ptr, "Not a PNG file");
  183820. else
  183821. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  183822. }
  183823. if (num_checked < 3)
  183824. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  183825. }
  183826. for(;;)
  183827. {
  183828. #ifdef PNG_USE_LOCAL_ARRAYS
  183829. PNG_CONST PNG_IHDR;
  183830. PNG_CONST PNG_IDAT;
  183831. PNG_CONST PNG_IEND;
  183832. PNG_CONST PNG_PLTE;
  183833. #if defined(PNG_READ_bKGD_SUPPORTED)
  183834. PNG_CONST PNG_bKGD;
  183835. #endif
  183836. #if defined(PNG_READ_cHRM_SUPPORTED)
  183837. PNG_CONST PNG_cHRM;
  183838. #endif
  183839. #if defined(PNG_READ_gAMA_SUPPORTED)
  183840. PNG_CONST PNG_gAMA;
  183841. #endif
  183842. #if defined(PNG_READ_hIST_SUPPORTED)
  183843. PNG_CONST PNG_hIST;
  183844. #endif
  183845. #if defined(PNG_READ_iCCP_SUPPORTED)
  183846. PNG_CONST PNG_iCCP;
  183847. #endif
  183848. #if defined(PNG_READ_iTXt_SUPPORTED)
  183849. PNG_CONST PNG_iTXt;
  183850. #endif
  183851. #if defined(PNG_READ_oFFs_SUPPORTED)
  183852. PNG_CONST PNG_oFFs;
  183853. #endif
  183854. #if defined(PNG_READ_pCAL_SUPPORTED)
  183855. PNG_CONST PNG_pCAL;
  183856. #endif
  183857. #if defined(PNG_READ_pHYs_SUPPORTED)
  183858. PNG_CONST PNG_pHYs;
  183859. #endif
  183860. #if defined(PNG_READ_sBIT_SUPPORTED)
  183861. PNG_CONST PNG_sBIT;
  183862. #endif
  183863. #if defined(PNG_READ_sCAL_SUPPORTED)
  183864. PNG_CONST PNG_sCAL;
  183865. #endif
  183866. #if defined(PNG_READ_sPLT_SUPPORTED)
  183867. PNG_CONST PNG_sPLT;
  183868. #endif
  183869. #if defined(PNG_READ_sRGB_SUPPORTED)
  183870. PNG_CONST PNG_sRGB;
  183871. #endif
  183872. #if defined(PNG_READ_tEXt_SUPPORTED)
  183873. PNG_CONST PNG_tEXt;
  183874. #endif
  183875. #if defined(PNG_READ_tIME_SUPPORTED)
  183876. PNG_CONST PNG_tIME;
  183877. #endif
  183878. #if defined(PNG_READ_tRNS_SUPPORTED)
  183879. PNG_CONST PNG_tRNS;
  183880. #endif
  183881. #if defined(PNG_READ_zTXt_SUPPORTED)
  183882. PNG_CONST PNG_zTXt;
  183883. #endif
  183884. #endif /* PNG_USE_LOCAL_ARRAYS */
  183885. png_byte chunk_length[4];
  183886. png_uint_32 length;
  183887. png_read_data(png_ptr, chunk_length, 4);
  183888. length = png_get_uint_31(png_ptr,chunk_length);
  183889. png_reset_crc(png_ptr);
  183890. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183891. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  183892. length);
  183893. /* This should be a binary subdivision search or a hash for
  183894. * matching the chunk name rather than a linear search.
  183895. */
  183896. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183897. if(png_ptr->mode & PNG_AFTER_IDAT)
  183898. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  183899. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183900. png_handle_IHDR(png_ptr, info_ptr, length);
  183901. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183902. png_handle_IEND(png_ptr, info_ptr, length);
  183903. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183904. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183905. {
  183906. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183907. png_ptr->mode |= PNG_HAVE_IDAT;
  183908. png_handle_unknown(png_ptr, info_ptr, length);
  183909. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183910. png_ptr->mode |= PNG_HAVE_PLTE;
  183911. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183912. {
  183913. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183914. png_error(png_ptr, "Missing IHDR before IDAT");
  183915. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183916. !(png_ptr->mode & PNG_HAVE_PLTE))
  183917. png_error(png_ptr, "Missing PLTE before IDAT");
  183918. break;
  183919. }
  183920. }
  183921. #endif
  183922. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183923. png_handle_PLTE(png_ptr, info_ptr, length);
  183924. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183925. {
  183926. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183927. png_error(png_ptr, "Missing IHDR before IDAT");
  183928. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183929. !(png_ptr->mode & PNG_HAVE_PLTE))
  183930. png_error(png_ptr, "Missing PLTE before IDAT");
  183931. png_ptr->idat_size = length;
  183932. png_ptr->mode |= PNG_HAVE_IDAT;
  183933. break;
  183934. }
  183935. #if defined(PNG_READ_bKGD_SUPPORTED)
  183936. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183937. png_handle_bKGD(png_ptr, info_ptr, length);
  183938. #endif
  183939. #if defined(PNG_READ_cHRM_SUPPORTED)
  183940. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183941. png_handle_cHRM(png_ptr, info_ptr, length);
  183942. #endif
  183943. #if defined(PNG_READ_gAMA_SUPPORTED)
  183944. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183945. png_handle_gAMA(png_ptr, info_ptr, length);
  183946. #endif
  183947. #if defined(PNG_READ_hIST_SUPPORTED)
  183948. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183949. png_handle_hIST(png_ptr, info_ptr, length);
  183950. #endif
  183951. #if defined(PNG_READ_oFFs_SUPPORTED)
  183952. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183953. png_handle_oFFs(png_ptr, info_ptr, length);
  183954. #endif
  183955. #if defined(PNG_READ_pCAL_SUPPORTED)
  183956. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183957. png_handle_pCAL(png_ptr, info_ptr, length);
  183958. #endif
  183959. #if defined(PNG_READ_sCAL_SUPPORTED)
  183960. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183961. png_handle_sCAL(png_ptr, info_ptr, length);
  183962. #endif
  183963. #if defined(PNG_READ_pHYs_SUPPORTED)
  183964. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183965. png_handle_pHYs(png_ptr, info_ptr, length);
  183966. #endif
  183967. #if defined(PNG_READ_sBIT_SUPPORTED)
  183968. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183969. png_handle_sBIT(png_ptr, info_ptr, length);
  183970. #endif
  183971. #if defined(PNG_READ_sRGB_SUPPORTED)
  183972. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183973. png_handle_sRGB(png_ptr, info_ptr, length);
  183974. #endif
  183975. #if defined(PNG_READ_iCCP_SUPPORTED)
  183976. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183977. png_handle_iCCP(png_ptr, info_ptr, length);
  183978. #endif
  183979. #if defined(PNG_READ_sPLT_SUPPORTED)
  183980. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183981. png_handle_sPLT(png_ptr, info_ptr, length);
  183982. #endif
  183983. #if defined(PNG_READ_tEXt_SUPPORTED)
  183984. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183985. png_handle_tEXt(png_ptr, info_ptr, length);
  183986. #endif
  183987. #if defined(PNG_READ_tIME_SUPPORTED)
  183988. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183989. png_handle_tIME(png_ptr, info_ptr, length);
  183990. #endif
  183991. #if defined(PNG_READ_tRNS_SUPPORTED)
  183992. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183993. png_handle_tRNS(png_ptr, info_ptr, length);
  183994. #endif
  183995. #if defined(PNG_READ_zTXt_SUPPORTED)
  183996. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183997. png_handle_zTXt(png_ptr, info_ptr, length);
  183998. #endif
  183999. #if defined(PNG_READ_iTXt_SUPPORTED)
  184000. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184001. png_handle_iTXt(png_ptr, info_ptr, length);
  184002. #endif
  184003. else
  184004. png_handle_unknown(png_ptr, info_ptr, length);
  184005. }
  184006. }
  184007. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184008. /* optional call to update the users info_ptr structure */
  184009. void PNGAPI
  184010. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  184011. {
  184012. png_debug(1, "in png_read_update_info\n");
  184013. if(png_ptr == NULL) return;
  184014. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184015. png_read_start_row(png_ptr);
  184016. else
  184017. png_warning(png_ptr,
  184018. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  184019. png_read_transform_info(png_ptr, info_ptr);
  184020. }
  184021. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184022. /* Initialize palette, background, etc, after transformations
  184023. * are set, but before any reading takes place. This allows
  184024. * the user to obtain a gamma-corrected palette, for example.
  184025. * If the user doesn't call this, we will do it ourselves.
  184026. */
  184027. void PNGAPI
  184028. png_start_read_image(png_structp png_ptr)
  184029. {
  184030. png_debug(1, "in png_start_read_image\n");
  184031. if(png_ptr == NULL) return;
  184032. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184033. png_read_start_row(png_ptr);
  184034. }
  184035. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184036. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184037. void PNGAPI
  184038. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  184039. {
  184040. #ifdef PNG_USE_LOCAL_ARRAYS
  184041. PNG_CONST PNG_IDAT;
  184042. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  184043. 0xff};
  184044. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184045. #endif
  184046. int ret;
  184047. if(png_ptr == NULL) return;
  184048. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  184049. png_ptr->row_number, png_ptr->pass);
  184050. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184051. png_read_start_row(png_ptr);
  184052. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  184053. {
  184054. /* check for transforms that have been set but were defined out */
  184055. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  184056. if (png_ptr->transformations & PNG_INVERT_MONO)
  184057. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  184058. #endif
  184059. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  184060. if (png_ptr->transformations & PNG_FILLER)
  184061. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  184062. #endif
  184063. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  184064. if (png_ptr->transformations & PNG_PACKSWAP)
  184065. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  184066. #endif
  184067. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  184068. if (png_ptr->transformations & PNG_PACK)
  184069. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  184070. #endif
  184071. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  184072. if (png_ptr->transformations & PNG_SHIFT)
  184073. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  184074. #endif
  184075. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  184076. if (png_ptr->transformations & PNG_BGR)
  184077. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  184078. #endif
  184079. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  184080. if (png_ptr->transformations & PNG_SWAP_BYTES)
  184081. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  184082. #endif
  184083. }
  184084. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184085. /* if interlaced and we do not need a new row, combine row and return */
  184086. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184087. {
  184088. switch (png_ptr->pass)
  184089. {
  184090. case 0:
  184091. if (png_ptr->row_number & 0x07)
  184092. {
  184093. if (dsp_row != NULL)
  184094. png_combine_row(png_ptr, dsp_row,
  184095. png_pass_dsp_mask[png_ptr->pass]);
  184096. png_read_finish_row(png_ptr);
  184097. return;
  184098. }
  184099. break;
  184100. case 1:
  184101. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  184102. {
  184103. if (dsp_row != NULL)
  184104. png_combine_row(png_ptr, dsp_row,
  184105. png_pass_dsp_mask[png_ptr->pass]);
  184106. png_read_finish_row(png_ptr);
  184107. return;
  184108. }
  184109. break;
  184110. case 2:
  184111. if ((png_ptr->row_number & 0x07) != 4)
  184112. {
  184113. if (dsp_row != NULL && (png_ptr->row_number & 4))
  184114. png_combine_row(png_ptr, dsp_row,
  184115. png_pass_dsp_mask[png_ptr->pass]);
  184116. png_read_finish_row(png_ptr);
  184117. return;
  184118. }
  184119. break;
  184120. case 3:
  184121. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  184122. {
  184123. if (dsp_row != NULL)
  184124. png_combine_row(png_ptr, dsp_row,
  184125. png_pass_dsp_mask[png_ptr->pass]);
  184126. png_read_finish_row(png_ptr);
  184127. return;
  184128. }
  184129. break;
  184130. case 4:
  184131. if ((png_ptr->row_number & 3) != 2)
  184132. {
  184133. if (dsp_row != NULL && (png_ptr->row_number & 2))
  184134. png_combine_row(png_ptr, dsp_row,
  184135. png_pass_dsp_mask[png_ptr->pass]);
  184136. png_read_finish_row(png_ptr);
  184137. return;
  184138. }
  184139. break;
  184140. case 5:
  184141. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  184142. {
  184143. if (dsp_row != NULL)
  184144. png_combine_row(png_ptr, dsp_row,
  184145. png_pass_dsp_mask[png_ptr->pass]);
  184146. png_read_finish_row(png_ptr);
  184147. return;
  184148. }
  184149. break;
  184150. case 6:
  184151. if (!(png_ptr->row_number & 1))
  184152. {
  184153. png_read_finish_row(png_ptr);
  184154. return;
  184155. }
  184156. break;
  184157. }
  184158. }
  184159. #endif
  184160. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  184161. png_error(png_ptr, "Invalid attempt to read row data");
  184162. png_ptr->zstream.next_out = png_ptr->row_buf;
  184163. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184164. do
  184165. {
  184166. if (!(png_ptr->zstream.avail_in))
  184167. {
  184168. while (!png_ptr->idat_size)
  184169. {
  184170. png_byte chunk_length[4];
  184171. png_crc_finish(png_ptr, 0);
  184172. png_read_data(png_ptr, chunk_length, 4);
  184173. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  184174. png_reset_crc(png_ptr);
  184175. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184176. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184177. png_error(png_ptr, "Not enough image data");
  184178. }
  184179. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  184180. png_ptr->zstream.next_in = png_ptr->zbuf;
  184181. if (png_ptr->zbuf_size > png_ptr->idat_size)
  184182. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  184183. png_crc_read(png_ptr, png_ptr->zbuf,
  184184. (png_size_t)png_ptr->zstream.avail_in);
  184185. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  184186. }
  184187. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184188. if (ret == Z_STREAM_END)
  184189. {
  184190. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  184191. png_ptr->idat_size)
  184192. png_error(png_ptr, "Extra compressed data");
  184193. png_ptr->mode |= PNG_AFTER_IDAT;
  184194. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184195. break;
  184196. }
  184197. if (ret != Z_OK)
  184198. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  184199. "Decompression error");
  184200. } while (png_ptr->zstream.avail_out);
  184201. png_ptr->row_info.color_type = png_ptr->color_type;
  184202. png_ptr->row_info.width = png_ptr->iwidth;
  184203. png_ptr->row_info.channels = png_ptr->channels;
  184204. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184205. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184206. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184207. png_ptr->row_info.width);
  184208. if(png_ptr->row_buf[0])
  184209. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184210. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184211. (int)(png_ptr->row_buf[0]));
  184212. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184213. png_ptr->rowbytes + 1);
  184214. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  184215. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  184216. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  184217. {
  184218. /* Intrapixel differencing */
  184219. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184220. }
  184221. #endif
  184222. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184223. png_do_read_transformations(png_ptr);
  184224. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184225. /* blow up interlaced rows to full size */
  184226. if (png_ptr->interlaced &&
  184227. (png_ptr->transformations & PNG_INTERLACE))
  184228. {
  184229. if (png_ptr->pass < 6)
  184230. /* old interface (pre-1.0.9):
  184231. png_do_read_interlace(&(png_ptr->row_info),
  184232. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184233. */
  184234. png_do_read_interlace(png_ptr);
  184235. if (dsp_row != NULL)
  184236. png_combine_row(png_ptr, dsp_row,
  184237. png_pass_dsp_mask[png_ptr->pass]);
  184238. if (row != NULL)
  184239. png_combine_row(png_ptr, row,
  184240. png_pass_mask[png_ptr->pass]);
  184241. }
  184242. else
  184243. #endif
  184244. {
  184245. if (row != NULL)
  184246. png_combine_row(png_ptr, row, 0xff);
  184247. if (dsp_row != NULL)
  184248. png_combine_row(png_ptr, dsp_row, 0xff);
  184249. }
  184250. png_read_finish_row(png_ptr);
  184251. if (png_ptr->read_row_fn != NULL)
  184252. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  184253. }
  184254. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184255. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184256. /* Read one or more rows of image data. If the image is interlaced,
  184257. * and png_set_interlace_handling() has been called, the rows need to
  184258. * contain the contents of the rows from the previous pass. If the
  184259. * image has alpha or transparency, and png_handle_alpha()[*] has been
  184260. * called, the rows contents must be initialized to the contents of the
  184261. * screen.
  184262. *
  184263. * "row" holds the actual image, and pixels are placed in it
  184264. * as they arrive. If the image is displayed after each pass, it will
  184265. * appear to "sparkle" in. "display_row" can be used to display a
  184266. * "chunky" progressive image, with finer detail added as it becomes
  184267. * available. If you do not want this "chunky" display, you may pass
  184268. * NULL for display_row. If you do not want the sparkle display, and
  184269. * you have not called png_handle_alpha(), you may pass NULL for rows.
  184270. * If you have called png_handle_alpha(), and the image has either an
  184271. * alpha channel or a transparency chunk, you must provide a buffer for
  184272. * rows. In this case, you do not have to provide a display_row buffer
  184273. * also, but you may. If the image is not interlaced, or if you have
  184274. * not called png_set_interlace_handling(), the display_row buffer will
  184275. * be ignored, so pass NULL to it.
  184276. *
  184277. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184278. */
  184279. void PNGAPI
  184280. png_read_rows(png_structp png_ptr, png_bytepp row,
  184281. png_bytepp display_row, png_uint_32 num_rows)
  184282. {
  184283. png_uint_32 i;
  184284. png_bytepp rp;
  184285. png_bytepp dp;
  184286. png_debug(1, "in png_read_rows\n");
  184287. if(png_ptr == NULL) return;
  184288. rp = row;
  184289. dp = display_row;
  184290. if (rp != NULL && dp != NULL)
  184291. for (i = 0; i < num_rows; i++)
  184292. {
  184293. png_bytep rptr = *rp++;
  184294. png_bytep dptr = *dp++;
  184295. png_read_row(png_ptr, rptr, dptr);
  184296. }
  184297. else if(rp != NULL)
  184298. for (i = 0; i < num_rows; i++)
  184299. {
  184300. png_bytep rptr = *rp;
  184301. png_read_row(png_ptr, rptr, png_bytep_NULL);
  184302. rp++;
  184303. }
  184304. else if(dp != NULL)
  184305. for (i = 0; i < num_rows; i++)
  184306. {
  184307. png_bytep dptr = *dp;
  184308. png_read_row(png_ptr, png_bytep_NULL, dptr);
  184309. dp++;
  184310. }
  184311. }
  184312. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184313. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184314. /* Read the entire image. If the image has an alpha channel or a tRNS
  184315. * chunk, and you have called png_handle_alpha()[*], you will need to
  184316. * initialize the image to the current image that PNG will be overlaying.
  184317. * We set the num_rows again here, in case it was incorrectly set in
  184318. * png_read_start_row() by a call to png_read_update_info() or
  184319. * png_start_read_image() if png_set_interlace_handling() wasn't called
  184320. * prior to either of these functions like it should have been. You can
  184321. * only call this function once. If you desire to have an image for
  184322. * each pass of a interlaced image, use png_read_rows() instead.
  184323. *
  184324. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184325. */
  184326. void PNGAPI
  184327. png_read_image(png_structp png_ptr, png_bytepp image)
  184328. {
  184329. png_uint_32 i,image_height;
  184330. int pass, j;
  184331. png_bytepp rp;
  184332. png_debug(1, "in png_read_image\n");
  184333. if(png_ptr == NULL) return;
  184334. #ifdef PNG_READ_INTERLACING_SUPPORTED
  184335. pass = png_set_interlace_handling(png_ptr);
  184336. #else
  184337. if (png_ptr->interlaced)
  184338. png_error(png_ptr,
  184339. "Cannot read interlaced image -- interlace handler disabled.");
  184340. pass = 1;
  184341. #endif
  184342. image_height=png_ptr->height;
  184343. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  184344. for (j = 0; j < pass; j++)
  184345. {
  184346. rp = image;
  184347. for (i = 0; i < image_height; i++)
  184348. {
  184349. png_read_row(png_ptr, *rp, png_bytep_NULL);
  184350. rp++;
  184351. }
  184352. }
  184353. }
  184354. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184355. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184356. /* Read the end of the PNG file. Will not read past the end of the
  184357. * file, will verify the end is accurate, and will read any comments
  184358. * or time information at the end of the file, if info is not NULL.
  184359. */
  184360. void PNGAPI
  184361. png_read_end(png_structp png_ptr, png_infop info_ptr)
  184362. {
  184363. png_byte chunk_length[4];
  184364. png_uint_32 length;
  184365. png_debug(1, "in png_read_end\n");
  184366. if(png_ptr == NULL) return;
  184367. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  184368. do
  184369. {
  184370. #ifdef PNG_USE_LOCAL_ARRAYS
  184371. PNG_CONST PNG_IHDR;
  184372. PNG_CONST PNG_IDAT;
  184373. PNG_CONST PNG_IEND;
  184374. PNG_CONST PNG_PLTE;
  184375. #if defined(PNG_READ_bKGD_SUPPORTED)
  184376. PNG_CONST PNG_bKGD;
  184377. #endif
  184378. #if defined(PNG_READ_cHRM_SUPPORTED)
  184379. PNG_CONST PNG_cHRM;
  184380. #endif
  184381. #if defined(PNG_READ_gAMA_SUPPORTED)
  184382. PNG_CONST PNG_gAMA;
  184383. #endif
  184384. #if defined(PNG_READ_hIST_SUPPORTED)
  184385. PNG_CONST PNG_hIST;
  184386. #endif
  184387. #if defined(PNG_READ_iCCP_SUPPORTED)
  184388. PNG_CONST PNG_iCCP;
  184389. #endif
  184390. #if defined(PNG_READ_iTXt_SUPPORTED)
  184391. PNG_CONST PNG_iTXt;
  184392. #endif
  184393. #if defined(PNG_READ_oFFs_SUPPORTED)
  184394. PNG_CONST PNG_oFFs;
  184395. #endif
  184396. #if defined(PNG_READ_pCAL_SUPPORTED)
  184397. PNG_CONST PNG_pCAL;
  184398. #endif
  184399. #if defined(PNG_READ_pHYs_SUPPORTED)
  184400. PNG_CONST PNG_pHYs;
  184401. #endif
  184402. #if defined(PNG_READ_sBIT_SUPPORTED)
  184403. PNG_CONST PNG_sBIT;
  184404. #endif
  184405. #if defined(PNG_READ_sCAL_SUPPORTED)
  184406. PNG_CONST PNG_sCAL;
  184407. #endif
  184408. #if defined(PNG_READ_sPLT_SUPPORTED)
  184409. PNG_CONST PNG_sPLT;
  184410. #endif
  184411. #if defined(PNG_READ_sRGB_SUPPORTED)
  184412. PNG_CONST PNG_sRGB;
  184413. #endif
  184414. #if defined(PNG_READ_tEXt_SUPPORTED)
  184415. PNG_CONST PNG_tEXt;
  184416. #endif
  184417. #if defined(PNG_READ_tIME_SUPPORTED)
  184418. PNG_CONST PNG_tIME;
  184419. #endif
  184420. #if defined(PNG_READ_tRNS_SUPPORTED)
  184421. PNG_CONST PNG_tRNS;
  184422. #endif
  184423. #if defined(PNG_READ_zTXt_SUPPORTED)
  184424. PNG_CONST PNG_zTXt;
  184425. #endif
  184426. #endif /* PNG_USE_LOCAL_ARRAYS */
  184427. png_read_data(png_ptr, chunk_length, 4);
  184428. length = png_get_uint_31(png_ptr,chunk_length);
  184429. png_reset_crc(png_ptr);
  184430. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184431. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  184432. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184433. png_handle_IHDR(png_ptr, info_ptr, length);
  184434. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184435. png_handle_IEND(png_ptr, info_ptr, length);
  184436. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184437. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184438. {
  184439. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184440. {
  184441. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184442. png_error(png_ptr, "Too many IDAT's found");
  184443. }
  184444. png_handle_unknown(png_ptr, info_ptr, length);
  184445. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184446. png_ptr->mode |= PNG_HAVE_PLTE;
  184447. }
  184448. #endif
  184449. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184450. {
  184451. /* Zero length IDATs are legal after the last IDAT has been
  184452. * read, but not after other chunks have been read.
  184453. */
  184454. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184455. png_error(png_ptr, "Too many IDAT's found");
  184456. png_crc_finish(png_ptr, length);
  184457. }
  184458. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184459. png_handle_PLTE(png_ptr, info_ptr, length);
  184460. #if defined(PNG_READ_bKGD_SUPPORTED)
  184461. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184462. png_handle_bKGD(png_ptr, info_ptr, length);
  184463. #endif
  184464. #if defined(PNG_READ_cHRM_SUPPORTED)
  184465. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184466. png_handle_cHRM(png_ptr, info_ptr, length);
  184467. #endif
  184468. #if defined(PNG_READ_gAMA_SUPPORTED)
  184469. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184470. png_handle_gAMA(png_ptr, info_ptr, length);
  184471. #endif
  184472. #if defined(PNG_READ_hIST_SUPPORTED)
  184473. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184474. png_handle_hIST(png_ptr, info_ptr, length);
  184475. #endif
  184476. #if defined(PNG_READ_oFFs_SUPPORTED)
  184477. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184478. png_handle_oFFs(png_ptr, info_ptr, length);
  184479. #endif
  184480. #if defined(PNG_READ_pCAL_SUPPORTED)
  184481. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184482. png_handle_pCAL(png_ptr, info_ptr, length);
  184483. #endif
  184484. #if defined(PNG_READ_sCAL_SUPPORTED)
  184485. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184486. png_handle_sCAL(png_ptr, info_ptr, length);
  184487. #endif
  184488. #if defined(PNG_READ_pHYs_SUPPORTED)
  184489. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184490. png_handle_pHYs(png_ptr, info_ptr, length);
  184491. #endif
  184492. #if defined(PNG_READ_sBIT_SUPPORTED)
  184493. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184494. png_handle_sBIT(png_ptr, info_ptr, length);
  184495. #endif
  184496. #if defined(PNG_READ_sRGB_SUPPORTED)
  184497. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184498. png_handle_sRGB(png_ptr, info_ptr, length);
  184499. #endif
  184500. #if defined(PNG_READ_iCCP_SUPPORTED)
  184501. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184502. png_handle_iCCP(png_ptr, info_ptr, length);
  184503. #endif
  184504. #if defined(PNG_READ_sPLT_SUPPORTED)
  184505. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184506. png_handle_sPLT(png_ptr, info_ptr, length);
  184507. #endif
  184508. #if defined(PNG_READ_tEXt_SUPPORTED)
  184509. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184510. png_handle_tEXt(png_ptr, info_ptr, length);
  184511. #endif
  184512. #if defined(PNG_READ_tIME_SUPPORTED)
  184513. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184514. png_handle_tIME(png_ptr, info_ptr, length);
  184515. #endif
  184516. #if defined(PNG_READ_tRNS_SUPPORTED)
  184517. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184518. png_handle_tRNS(png_ptr, info_ptr, length);
  184519. #endif
  184520. #if defined(PNG_READ_zTXt_SUPPORTED)
  184521. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184522. png_handle_zTXt(png_ptr, info_ptr, length);
  184523. #endif
  184524. #if defined(PNG_READ_iTXt_SUPPORTED)
  184525. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184526. png_handle_iTXt(png_ptr, info_ptr, length);
  184527. #endif
  184528. else
  184529. png_handle_unknown(png_ptr, info_ptr, length);
  184530. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  184531. }
  184532. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184533. /* free all memory used by the read */
  184534. void PNGAPI
  184535. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  184536. png_infopp end_info_ptr_ptr)
  184537. {
  184538. png_structp png_ptr = NULL;
  184539. png_infop info_ptr = NULL, end_info_ptr = NULL;
  184540. #ifdef PNG_USER_MEM_SUPPORTED
  184541. png_free_ptr free_fn;
  184542. png_voidp mem_ptr;
  184543. #endif
  184544. png_debug(1, "in png_destroy_read_struct\n");
  184545. if (png_ptr_ptr != NULL)
  184546. png_ptr = *png_ptr_ptr;
  184547. if (info_ptr_ptr != NULL)
  184548. info_ptr = *info_ptr_ptr;
  184549. if (end_info_ptr_ptr != NULL)
  184550. end_info_ptr = *end_info_ptr_ptr;
  184551. #ifdef PNG_USER_MEM_SUPPORTED
  184552. free_fn = png_ptr->free_fn;
  184553. mem_ptr = png_ptr->mem_ptr;
  184554. #endif
  184555. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  184556. if (info_ptr != NULL)
  184557. {
  184558. #if defined(PNG_TEXT_SUPPORTED)
  184559. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  184560. #endif
  184561. #ifdef PNG_USER_MEM_SUPPORTED
  184562. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  184563. (png_voidp)mem_ptr);
  184564. #else
  184565. png_destroy_struct((png_voidp)info_ptr);
  184566. #endif
  184567. *info_ptr_ptr = NULL;
  184568. }
  184569. if (end_info_ptr != NULL)
  184570. {
  184571. #if defined(PNG_READ_TEXT_SUPPORTED)
  184572. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  184573. #endif
  184574. #ifdef PNG_USER_MEM_SUPPORTED
  184575. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  184576. (png_voidp)mem_ptr);
  184577. #else
  184578. png_destroy_struct((png_voidp)end_info_ptr);
  184579. #endif
  184580. *end_info_ptr_ptr = NULL;
  184581. }
  184582. if (png_ptr != NULL)
  184583. {
  184584. #ifdef PNG_USER_MEM_SUPPORTED
  184585. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  184586. (png_voidp)mem_ptr);
  184587. #else
  184588. png_destroy_struct((png_voidp)png_ptr);
  184589. #endif
  184590. *png_ptr_ptr = NULL;
  184591. }
  184592. }
  184593. /* free all memory used by the read (old method) */
  184594. void /* PRIVATE */
  184595. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  184596. {
  184597. #ifdef PNG_SETJMP_SUPPORTED
  184598. jmp_buf tmp_jmp;
  184599. #endif
  184600. png_error_ptr error_fn;
  184601. png_error_ptr warning_fn;
  184602. png_voidp error_ptr;
  184603. #ifdef PNG_USER_MEM_SUPPORTED
  184604. png_free_ptr free_fn;
  184605. #endif
  184606. png_debug(1, "in png_read_destroy\n");
  184607. if (info_ptr != NULL)
  184608. png_info_destroy(png_ptr, info_ptr);
  184609. if (end_info_ptr != NULL)
  184610. png_info_destroy(png_ptr, end_info_ptr);
  184611. png_free(png_ptr, png_ptr->zbuf);
  184612. png_free(png_ptr, png_ptr->big_row_buf);
  184613. png_free(png_ptr, png_ptr->prev_row);
  184614. #if defined(PNG_READ_DITHER_SUPPORTED)
  184615. png_free(png_ptr, png_ptr->palette_lookup);
  184616. png_free(png_ptr, png_ptr->dither_index);
  184617. #endif
  184618. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184619. png_free(png_ptr, png_ptr->gamma_table);
  184620. #endif
  184621. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184622. png_free(png_ptr, png_ptr->gamma_from_1);
  184623. png_free(png_ptr, png_ptr->gamma_to_1);
  184624. #endif
  184625. #ifdef PNG_FREE_ME_SUPPORTED
  184626. if (png_ptr->free_me & PNG_FREE_PLTE)
  184627. png_zfree(png_ptr, png_ptr->palette);
  184628. png_ptr->free_me &= ~PNG_FREE_PLTE;
  184629. #else
  184630. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  184631. png_zfree(png_ptr, png_ptr->palette);
  184632. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184633. #endif
  184634. #if defined(PNG_tRNS_SUPPORTED) || \
  184635. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  184636. #ifdef PNG_FREE_ME_SUPPORTED
  184637. if (png_ptr->free_me & PNG_FREE_TRNS)
  184638. png_free(png_ptr, png_ptr->trans);
  184639. png_ptr->free_me &= ~PNG_FREE_TRNS;
  184640. #else
  184641. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  184642. png_free(png_ptr, png_ptr->trans);
  184643. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184644. #endif
  184645. #endif
  184646. #if defined(PNG_READ_hIST_SUPPORTED)
  184647. #ifdef PNG_FREE_ME_SUPPORTED
  184648. if (png_ptr->free_me & PNG_FREE_HIST)
  184649. png_free(png_ptr, png_ptr->hist);
  184650. png_ptr->free_me &= ~PNG_FREE_HIST;
  184651. #else
  184652. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  184653. png_free(png_ptr, png_ptr->hist);
  184654. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184655. #endif
  184656. #endif
  184657. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184658. if (png_ptr->gamma_16_table != NULL)
  184659. {
  184660. int i;
  184661. int istop = (1 << (8 - png_ptr->gamma_shift));
  184662. for (i = 0; i < istop; i++)
  184663. {
  184664. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  184665. }
  184666. png_free(png_ptr, png_ptr->gamma_16_table);
  184667. }
  184668. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184669. if (png_ptr->gamma_16_from_1 != NULL)
  184670. {
  184671. int i;
  184672. int istop = (1 << (8 - png_ptr->gamma_shift));
  184673. for (i = 0; i < istop; i++)
  184674. {
  184675. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  184676. }
  184677. png_free(png_ptr, png_ptr->gamma_16_from_1);
  184678. }
  184679. if (png_ptr->gamma_16_to_1 != NULL)
  184680. {
  184681. int i;
  184682. int istop = (1 << (8 - png_ptr->gamma_shift));
  184683. for (i = 0; i < istop; i++)
  184684. {
  184685. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  184686. }
  184687. png_free(png_ptr, png_ptr->gamma_16_to_1);
  184688. }
  184689. #endif
  184690. #endif
  184691. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184692. png_free(png_ptr, png_ptr->time_buffer);
  184693. #endif
  184694. inflateEnd(&png_ptr->zstream);
  184695. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184696. png_free(png_ptr, png_ptr->save_buffer);
  184697. #endif
  184698. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184699. #ifdef PNG_TEXT_SUPPORTED
  184700. png_free(png_ptr, png_ptr->current_text);
  184701. #endif /* PNG_TEXT_SUPPORTED */
  184702. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184703. /* Save the important info out of the png_struct, in case it is
  184704. * being used again.
  184705. */
  184706. #ifdef PNG_SETJMP_SUPPORTED
  184707. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  184708. #endif
  184709. error_fn = png_ptr->error_fn;
  184710. warning_fn = png_ptr->warning_fn;
  184711. error_ptr = png_ptr->error_ptr;
  184712. #ifdef PNG_USER_MEM_SUPPORTED
  184713. free_fn = png_ptr->free_fn;
  184714. #endif
  184715. png_memset(png_ptr, 0, png_sizeof (png_struct));
  184716. png_ptr->error_fn = error_fn;
  184717. png_ptr->warning_fn = warning_fn;
  184718. png_ptr->error_ptr = error_ptr;
  184719. #ifdef PNG_USER_MEM_SUPPORTED
  184720. png_ptr->free_fn = free_fn;
  184721. #endif
  184722. #ifdef PNG_SETJMP_SUPPORTED
  184723. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  184724. #endif
  184725. }
  184726. void PNGAPI
  184727. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  184728. {
  184729. if(png_ptr == NULL) return;
  184730. png_ptr->read_row_fn = read_row_fn;
  184731. }
  184732. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184733. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184734. void PNGAPI
  184735. png_read_png(png_structp png_ptr, png_infop info_ptr,
  184736. int transforms,
  184737. voidp params)
  184738. {
  184739. int row;
  184740. if(png_ptr == NULL) return;
  184741. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184742. /* invert the alpha channel from opacity to transparency
  184743. */
  184744. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  184745. png_set_invert_alpha(png_ptr);
  184746. #endif
  184747. /* png_read_info() gives us all of the information from the
  184748. * PNG file before the first IDAT (image data chunk).
  184749. */
  184750. png_read_info(png_ptr, info_ptr);
  184751. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  184752. png_error(png_ptr,"Image is too high to process with png_read_png()");
  184753. /* -------------- image transformations start here ------------------- */
  184754. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184755. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  184756. */
  184757. if (transforms & PNG_TRANSFORM_STRIP_16)
  184758. png_set_strip_16(png_ptr);
  184759. #endif
  184760. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184761. /* Strip alpha bytes from the input data without combining with
  184762. * the background (not recommended).
  184763. */
  184764. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  184765. png_set_strip_alpha(png_ptr);
  184766. #endif
  184767. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  184768. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  184769. * byte into separate bytes (useful for paletted and grayscale images).
  184770. */
  184771. if (transforms & PNG_TRANSFORM_PACKING)
  184772. png_set_packing(png_ptr);
  184773. #endif
  184774. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  184775. /* Change the order of packed pixels to least significant bit first
  184776. * (not useful if you are using png_set_packing).
  184777. */
  184778. if (transforms & PNG_TRANSFORM_PACKSWAP)
  184779. png_set_packswap(png_ptr);
  184780. #endif
  184781. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184782. /* Expand paletted colors into true RGB triplets
  184783. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  184784. * Expand paletted or RGB images with transparency to full alpha
  184785. * channels so the data will be available as RGBA quartets.
  184786. */
  184787. if (transforms & PNG_TRANSFORM_EXPAND)
  184788. if ((png_ptr->bit_depth < 8) ||
  184789. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  184790. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  184791. png_set_expand(png_ptr);
  184792. #endif
  184793. /* We don't handle background color or gamma transformation or dithering.
  184794. */
  184795. #if defined(PNG_READ_INVERT_SUPPORTED)
  184796. /* invert monochrome files to have 0 as white and 1 as black
  184797. */
  184798. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  184799. png_set_invert_mono(png_ptr);
  184800. #endif
  184801. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184802. /* If you want to shift the pixel values from the range [0,255] or
  184803. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  184804. * colors were originally in:
  184805. */
  184806. if ((transforms & PNG_TRANSFORM_SHIFT)
  184807. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  184808. {
  184809. png_color_8p sig_bit;
  184810. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  184811. png_set_shift(png_ptr, sig_bit);
  184812. }
  184813. #endif
  184814. #if defined(PNG_READ_BGR_SUPPORTED)
  184815. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  184816. */
  184817. if (transforms & PNG_TRANSFORM_BGR)
  184818. png_set_bgr(png_ptr);
  184819. #endif
  184820. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184821. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  184822. */
  184823. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  184824. png_set_swap_alpha(png_ptr);
  184825. #endif
  184826. #if defined(PNG_READ_SWAP_SUPPORTED)
  184827. /* swap bytes of 16 bit files to least significant byte first
  184828. */
  184829. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  184830. png_set_swap(png_ptr);
  184831. #endif
  184832. /* We don't handle adding filler bytes */
  184833. /* Optional call to gamma correct and add the background to the palette
  184834. * and update info structure. REQUIRED if you are expecting libpng to
  184835. * update the palette for you (i.e., you selected such a transform above).
  184836. */
  184837. png_read_update_info(png_ptr, info_ptr);
  184838. /* -------------- image transformations end here ------------------- */
  184839. #ifdef PNG_FREE_ME_SUPPORTED
  184840. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  184841. #endif
  184842. if(info_ptr->row_pointers == NULL)
  184843. {
  184844. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  184845. info_ptr->height * png_sizeof(png_bytep));
  184846. #ifdef PNG_FREE_ME_SUPPORTED
  184847. info_ptr->free_me |= PNG_FREE_ROWS;
  184848. #endif
  184849. for (row = 0; row < (int)info_ptr->height; row++)
  184850. {
  184851. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  184852. png_get_rowbytes(png_ptr, info_ptr));
  184853. }
  184854. }
  184855. png_read_image(png_ptr, info_ptr->row_pointers);
  184856. info_ptr->valid |= PNG_INFO_IDAT;
  184857. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  184858. png_read_end(png_ptr, info_ptr);
  184859. transforms = transforms; /* quiet compiler warnings */
  184860. params = params;
  184861. }
  184862. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  184863. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184864. #endif /* PNG_READ_SUPPORTED */
  184865. /*** End of inlined file: pngread.c ***/
  184866. /*** Start of inlined file: pngpread.c ***/
  184867. /* pngpread.c - read a png file in push mode
  184868. *
  184869. * Last changed in libpng 1.2.21 October 4, 2007
  184870. * For conditions of distribution and use, see copyright notice in png.h
  184871. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184872. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184873. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184874. */
  184875. #define PNG_INTERNAL
  184876. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184877. /* push model modes */
  184878. #define PNG_READ_SIG_MODE 0
  184879. #define PNG_READ_CHUNK_MODE 1
  184880. #define PNG_READ_IDAT_MODE 2
  184881. #define PNG_SKIP_MODE 3
  184882. #define PNG_READ_tEXt_MODE 4
  184883. #define PNG_READ_zTXt_MODE 5
  184884. #define PNG_READ_DONE_MODE 6
  184885. #define PNG_READ_iTXt_MODE 7
  184886. #define PNG_ERROR_MODE 8
  184887. void PNGAPI
  184888. png_process_data(png_structp png_ptr, png_infop info_ptr,
  184889. png_bytep buffer, png_size_t buffer_size)
  184890. {
  184891. if(png_ptr == NULL) return;
  184892. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  184893. while (png_ptr->buffer_size)
  184894. {
  184895. png_process_some_data(png_ptr, info_ptr);
  184896. }
  184897. }
  184898. /* What we do with the incoming data depends on what we were previously
  184899. * doing before we ran out of data...
  184900. */
  184901. void /* PRIVATE */
  184902. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  184903. {
  184904. if(png_ptr == NULL) return;
  184905. switch (png_ptr->process_mode)
  184906. {
  184907. case PNG_READ_SIG_MODE:
  184908. {
  184909. png_push_read_sig(png_ptr, info_ptr);
  184910. break;
  184911. }
  184912. case PNG_READ_CHUNK_MODE:
  184913. {
  184914. png_push_read_chunk(png_ptr, info_ptr);
  184915. break;
  184916. }
  184917. case PNG_READ_IDAT_MODE:
  184918. {
  184919. png_push_read_IDAT(png_ptr);
  184920. break;
  184921. }
  184922. #if defined(PNG_READ_tEXt_SUPPORTED)
  184923. case PNG_READ_tEXt_MODE:
  184924. {
  184925. png_push_read_tEXt(png_ptr, info_ptr);
  184926. break;
  184927. }
  184928. #endif
  184929. #if defined(PNG_READ_zTXt_SUPPORTED)
  184930. case PNG_READ_zTXt_MODE:
  184931. {
  184932. png_push_read_zTXt(png_ptr, info_ptr);
  184933. break;
  184934. }
  184935. #endif
  184936. #if defined(PNG_READ_iTXt_SUPPORTED)
  184937. case PNG_READ_iTXt_MODE:
  184938. {
  184939. png_push_read_iTXt(png_ptr, info_ptr);
  184940. break;
  184941. }
  184942. #endif
  184943. case PNG_SKIP_MODE:
  184944. {
  184945. png_push_crc_finish(png_ptr);
  184946. break;
  184947. }
  184948. default:
  184949. {
  184950. png_ptr->buffer_size = 0;
  184951. break;
  184952. }
  184953. }
  184954. }
  184955. /* Read any remaining signature bytes from the stream and compare them with
  184956. * the correct PNG signature. It is possible that this routine is called
  184957. * with bytes already read from the signature, either because they have been
  184958. * checked by the calling application, or because of multiple calls to this
  184959. * routine.
  184960. */
  184961. void /* PRIVATE */
  184962. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  184963. {
  184964. png_size_t num_checked = png_ptr->sig_bytes,
  184965. num_to_check = 8 - num_checked;
  184966. if (png_ptr->buffer_size < num_to_check)
  184967. {
  184968. num_to_check = png_ptr->buffer_size;
  184969. }
  184970. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  184971. num_to_check);
  184972. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  184973. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184974. {
  184975. if (num_checked < 4 &&
  184976. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184977. png_error(png_ptr, "Not a PNG file");
  184978. else
  184979. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184980. }
  184981. else
  184982. {
  184983. if (png_ptr->sig_bytes >= 8)
  184984. {
  184985. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184986. }
  184987. }
  184988. }
  184989. void /* PRIVATE */
  184990. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  184991. {
  184992. #ifdef PNG_USE_LOCAL_ARRAYS
  184993. PNG_CONST PNG_IHDR;
  184994. PNG_CONST PNG_IDAT;
  184995. PNG_CONST PNG_IEND;
  184996. PNG_CONST PNG_PLTE;
  184997. #if defined(PNG_READ_bKGD_SUPPORTED)
  184998. PNG_CONST PNG_bKGD;
  184999. #endif
  185000. #if defined(PNG_READ_cHRM_SUPPORTED)
  185001. PNG_CONST PNG_cHRM;
  185002. #endif
  185003. #if defined(PNG_READ_gAMA_SUPPORTED)
  185004. PNG_CONST PNG_gAMA;
  185005. #endif
  185006. #if defined(PNG_READ_hIST_SUPPORTED)
  185007. PNG_CONST PNG_hIST;
  185008. #endif
  185009. #if defined(PNG_READ_iCCP_SUPPORTED)
  185010. PNG_CONST PNG_iCCP;
  185011. #endif
  185012. #if defined(PNG_READ_iTXt_SUPPORTED)
  185013. PNG_CONST PNG_iTXt;
  185014. #endif
  185015. #if defined(PNG_READ_oFFs_SUPPORTED)
  185016. PNG_CONST PNG_oFFs;
  185017. #endif
  185018. #if defined(PNG_READ_pCAL_SUPPORTED)
  185019. PNG_CONST PNG_pCAL;
  185020. #endif
  185021. #if defined(PNG_READ_pHYs_SUPPORTED)
  185022. PNG_CONST PNG_pHYs;
  185023. #endif
  185024. #if defined(PNG_READ_sBIT_SUPPORTED)
  185025. PNG_CONST PNG_sBIT;
  185026. #endif
  185027. #if defined(PNG_READ_sCAL_SUPPORTED)
  185028. PNG_CONST PNG_sCAL;
  185029. #endif
  185030. #if defined(PNG_READ_sRGB_SUPPORTED)
  185031. PNG_CONST PNG_sRGB;
  185032. #endif
  185033. #if defined(PNG_READ_sPLT_SUPPORTED)
  185034. PNG_CONST PNG_sPLT;
  185035. #endif
  185036. #if defined(PNG_READ_tEXt_SUPPORTED)
  185037. PNG_CONST PNG_tEXt;
  185038. #endif
  185039. #if defined(PNG_READ_tIME_SUPPORTED)
  185040. PNG_CONST PNG_tIME;
  185041. #endif
  185042. #if defined(PNG_READ_tRNS_SUPPORTED)
  185043. PNG_CONST PNG_tRNS;
  185044. #endif
  185045. #if defined(PNG_READ_zTXt_SUPPORTED)
  185046. PNG_CONST PNG_zTXt;
  185047. #endif
  185048. #endif /* PNG_USE_LOCAL_ARRAYS */
  185049. /* First we make sure we have enough data for the 4 byte chunk name
  185050. * and the 4 byte chunk length before proceeding with decoding the
  185051. * chunk data. To fully decode each of these chunks, we also make
  185052. * sure we have enough data in the buffer for the 4 byte CRC at the
  185053. * end of every chunk (except IDAT, which is handled separately).
  185054. */
  185055. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185056. {
  185057. png_byte chunk_length[4];
  185058. if (png_ptr->buffer_size < 8)
  185059. {
  185060. png_push_save_buffer(png_ptr);
  185061. return;
  185062. }
  185063. png_push_fill_buffer(png_ptr, chunk_length, 4);
  185064. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  185065. png_reset_crc(png_ptr);
  185066. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185067. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  185068. }
  185069. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185070. if(png_ptr->mode & PNG_AFTER_IDAT)
  185071. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  185072. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  185073. {
  185074. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185075. {
  185076. png_push_save_buffer(png_ptr);
  185077. return;
  185078. }
  185079. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  185080. }
  185081. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  185082. {
  185083. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185084. {
  185085. png_push_save_buffer(png_ptr);
  185086. return;
  185087. }
  185088. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  185089. png_ptr->process_mode = PNG_READ_DONE_MODE;
  185090. png_push_have_end(png_ptr, info_ptr);
  185091. }
  185092. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185093. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  185094. {
  185095. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185096. {
  185097. png_push_save_buffer(png_ptr);
  185098. return;
  185099. }
  185100. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185101. png_ptr->mode |= PNG_HAVE_IDAT;
  185102. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185103. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185104. png_ptr->mode |= PNG_HAVE_PLTE;
  185105. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185106. {
  185107. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185108. png_error(png_ptr, "Missing IHDR before IDAT");
  185109. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185110. !(png_ptr->mode & PNG_HAVE_PLTE))
  185111. png_error(png_ptr, "Missing PLTE before IDAT");
  185112. }
  185113. }
  185114. #endif
  185115. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185116. {
  185117. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185118. {
  185119. png_push_save_buffer(png_ptr);
  185120. return;
  185121. }
  185122. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  185123. }
  185124. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185125. {
  185126. /* If we reach an IDAT chunk, this means we have read all of the
  185127. * header chunks, and we can start reading the image (or if this
  185128. * is called after the image has been read - we have an error).
  185129. */
  185130. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185131. png_error(png_ptr, "Missing IHDR before IDAT");
  185132. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185133. !(png_ptr->mode & PNG_HAVE_PLTE))
  185134. png_error(png_ptr, "Missing PLTE before IDAT");
  185135. if (png_ptr->mode & PNG_HAVE_IDAT)
  185136. {
  185137. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  185138. if (png_ptr->push_length == 0)
  185139. return;
  185140. if (png_ptr->mode & PNG_AFTER_IDAT)
  185141. png_error(png_ptr, "Too many IDAT's found");
  185142. }
  185143. png_ptr->idat_size = png_ptr->push_length;
  185144. png_ptr->mode |= PNG_HAVE_IDAT;
  185145. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  185146. png_push_have_info(png_ptr, info_ptr);
  185147. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  185148. png_ptr->zstream.next_out = png_ptr->row_buf;
  185149. return;
  185150. }
  185151. #if defined(PNG_READ_gAMA_SUPPORTED)
  185152. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  185153. {
  185154. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185155. {
  185156. png_push_save_buffer(png_ptr);
  185157. return;
  185158. }
  185159. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  185160. }
  185161. #endif
  185162. #if defined(PNG_READ_sBIT_SUPPORTED)
  185163. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  185164. {
  185165. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185166. {
  185167. png_push_save_buffer(png_ptr);
  185168. return;
  185169. }
  185170. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  185171. }
  185172. #endif
  185173. #if defined(PNG_READ_cHRM_SUPPORTED)
  185174. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  185175. {
  185176. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185177. {
  185178. png_push_save_buffer(png_ptr);
  185179. return;
  185180. }
  185181. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  185182. }
  185183. #endif
  185184. #if defined(PNG_READ_sRGB_SUPPORTED)
  185185. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  185186. {
  185187. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185188. {
  185189. png_push_save_buffer(png_ptr);
  185190. return;
  185191. }
  185192. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  185193. }
  185194. #endif
  185195. #if defined(PNG_READ_iCCP_SUPPORTED)
  185196. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  185197. {
  185198. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185199. {
  185200. png_push_save_buffer(png_ptr);
  185201. return;
  185202. }
  185203. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  185204. }
  185205. #endif
  185206. #if defined(PNG_READ_sPLT_SUPPORTED)
  185207. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  185208. {
  185209. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185210. {
  185211. png_push_save_buffer(png_ptr);
  185212. return;
  185213. }
  185214. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  185215. }
  185216. #endif
  185217. #if defined(PNG_READ_tRNS_SUPPORTED)
  185218. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  185219. {
  185220. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185221. {
  185222. png_push_save_buffer(png_ptr);
  185223. return;
  185224. }
  185225. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  185226. }
  185227. #endif
  185228. #if defined(PNG_READ_bKGD_SUPPORTED)
  185229. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  185230. {
  185231. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185232. {
  185233. png_push_save_buffer(png_ptr);
  185234. return;
  185235. }
  185236. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  185237. }
  185238. #endif
  185239. #if defined(PNG_READ_hIST_SUPPORTED)
  185240. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  185241. {
  185242. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185243. {
  185244. png_push_save_buffer(png_ptr);
  185245. return;
  185246. }
  185247. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  185248. }
  185249. #endif
  185250. #if defined(PNG_READ_pHYs_SUPPORTED)
  185251. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  185252. {
  185253. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185254. {
  185255. png_push_save_buffer(png_ptr);
  185256. return;
  185257. }
  185258. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  185259. }
  185260. #endif
  185261. #if defined(PNG_READ_oFFs_SUPPORTED)
  185262. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  185263. {
  185264. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185265. {
  185266. png_push_save_buffer(png_ptr);
  185267. return;
  185268. }
  185269. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  185270. }
  185271. #endif
  185272. #if defined(PNG_READ_pCAL_SUPPORTED)
  185273. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  185274. {
  185275. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185276. {
  185277. png_push_save_buffer(png_ptr);
  185278. return;
  185279. }
  185280. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  185281. }
  185282. #endif
  185283. #if defined(PNG_READ_sCAL_SUPPORTED)
  185284. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  185285. {
  185286. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185287. {
  185288. png_push_save_buffer(png_ptr);
  185289. return;
  185290. }
  185291. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  185292. }
  185293. #endif
  185294. #if defined(PNG_READ_tIME_SUPPORTED)
  185295. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  185296. {
  185297. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185298. {
  185299. png_push_save_buffer(png_ptr);
  185300. return;
  185301. }
  185302. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  185303. }
  185304. #endif
  185305. #if defined(PNG_READ_tEXt_SUPPORTED)
  185306. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  185307. {
  185308. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185309. {
  185310. png_push_save_buffer(png_ptr);
  185311. return;
  185312. }
  185313. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  185314. }
  185315. #endif
  185316. #if defined(PNG_READ_zTXt_SUPPORTED)
  185317. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  185318. {
  185319. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185320. {
  185321. png_push_save_buffer(png_ptr);
  185322. return;
  185323. }
  185324. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  185325. }
  185326. #endif
  185327. #if defined(PNG_READ_iTXt_SUPPORTED)
  185328. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  185329. {
  185330. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185331. {
  185332. png_push_save_buffer(png_ptr);
  185333. return;
  185334. }
  185335. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  185336. }
  185337. #endif
  185338. else
  185339. {
  185340. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185341. {
  185342. png_push_save_buffer(png_ptr);
  185343. return;
  185344. }
  185345. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185346. }
  185347. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  185348. }
  185349. void /* PRIVATE */
  185350. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  185351. {
  185352. png_ptr->process_mode = PNG_SKIP_MODE;
  185353. png_ptr->skip_length = skip;
  185354. }
  185355. void /* PRIVATE */
  185356. png_push_crc_finish(png_structp png_ptr)
  185357. {
  185358. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  185359. {
  185360. png_size_t save_size;
  185361. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  185362. save_size = (png_size_t)png_ptr->skip_length;
  185363. else
  185364. save_size = png_ptr->save_buffer_size;
  185365. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185366. png_ptr->skip_length -= save_size;
  185367. png_ptr->buffer_size -= save_size;
  185368. png_ptr->save_buffer_size -= save_size;
  185369. png_ptr->save_buffer_ptr += save_size;
  185370. }
  185371. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  185372. {
  185373. png_size_t save_size;
  185374. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  185375. save_size = (png_size_t)png_ptr->skip_length;
  185376. else
  185377. save_size = png_ptr->current_buffer_size;
  185378. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185379. png_ptr->skip_length -= save_size;
  185380. png_ptr->buffer_size -= save_size;
  185381. png_ptr->current_buffer_size -= save_size;
  185382. png_ptr->current_buffer_ptr += save_size;
  185383. }
  185384. if (!png_ptr->skip_length)
  185385. {
  185386. if (png_ptr->buffer_size < 4)
  185387. {
  185388. png_push_save_buffer(png_ptr);
  185389. return;
  185390. }
  185391. png_crc_finish(png_ptr, 0);
  185392. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185393. }
  185394. }
  185395. void PNGAPI
  185396. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  185397. {
  185398. png_bytep ptr;
  185399. if(png_ptr == NULL) return;
  185400. ptr = buffer;
  185401. if (png_ptr->save_buffer_size)
  185402. {
  185403. png_size_t save_size;
  185404. if (length < png_ptr->save_buffer_size)
  185405. save_size = length;
  185406. else
  185407. save_size = png_ptr->save_buffer_size;
  185408. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  185409. length -= save_size;
  185410. ptr += save_size;
  185411. png_ptr->buffer_size -= save_size;
  185412. png_ptr->save_buffer_size -= save_size;
  185413. png_ptr->save_buffer_ptr += save_size;
  185414. }
  185415. if (length && png_ptr->current_buffer_size)
  185416. {
  185417. png_size_t save_size;
  185418. if (length < png_ptr->current_buffer_size)
  185419. save_size = length;
  185420. else
  185421. save_size = png_ptr->current_buffer_size;
  185422. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  185423. png_ptr->buffer_size -= save_size;
  185424. png_ptr->current_buffer_size -= save_size;
  185425. png_ptr->current_buffer_ptr += save_size;
  185426. }
  185427. }
  185428. void /* PRIVATE */
  185429. png_push_save_buffer(png_structp png_ptr)
  185430. {
  185431. if (png_ptr->save_buffer_size)
  185432. {
  185433. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  185434. {
  185435. png_size_t i,istop;
  185436. png_bytep sp;
  185437. png_bytep dp;
  185438. istop = png_ptr->save_buffer_size;
  185439. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  185440. i < istop; i++, sp++, dp++)
  185441. {
  185442. *dp = *sp;
  185443. }
  185444. }
  185445. }
  185446. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  185447. png_ptr->save_buffer_max)
  185448. {
  185449. png_size_t new_max;
  185450. png_bytep old_buffer;
  185451. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  185452. (png_ptr->current_buffer_size + 256))
  185453. {
  185454. png_error(png_ptr, "Potential overflow of save_buffer");
  185455. }
  185456. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  185457. old_buffer = png_ptr->save_buffer;
  185458. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  185459. (png_uint_32)new_max);
  185460. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  185461. png_free(png_ptr, old_buffer);
  185462. png_ptr->save_buffer_max = new_max;
  185463. }
  185464. if (png_ptr->current_buffer_size)
  185465. {
  185466. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  185467. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  185468. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  185469. png_ptr->current_buffer_size = 0;
  185470. }
  185471. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  185472. png_ptr->buffer_size = 0;
  185473. }
  185474. void /* PRIVATE */
  185475. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  185476. png_size_t buffer_length)
  185477. {
  185478. png_ptr->current_buffer = buffer;
  185479. png_ptr->current_buffer_size = buffer_length;
  185480. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  185481. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  185482. }
  185483. void /* PRIVATE */
  185484. png_push_read_IDAT(png_structp png_ptr)
  185485. {
  185486. #ifdef PNG_USE_LOCAL_ARRAYS
  185487. PNG_CONST PNG_IDAT;
  185488. #endif
  185489. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185490. {
  185491. png_byte chunk_length[4];
  185492. if (png_ptr->buffer_size < 8)
  185493. {
  185494. png_push_save_buffer(png_ptr);
  185495. return;
  185496. }
  185497. png_push_fill_buffer(png_ptr, chunk_length, 4);
  185498. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  185499. png_reset_crc(png_ptr);
  185500. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185501. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  185502. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185503. {
  185504. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185505. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  185506. png_error(png_ptr, "Not enough compressed data");
  185507. return;
  185508. }
  185509. png_ptr->idat_size = png_ptr->push_length;
  185510. }
  185511. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  185512. {
  185513. png_size_t save_size;
  185514. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  185515. {
  185516. save_size = (png_size_t)png_ptr->idat_size;
  185517. /* check for overflow */
  185518. if((png_uint_32)save_size != png_ptr->idat_size)
  185519. png_error(png_ptr, "save_size overflowed in pngpread");
  185520. }
  185521. else
  185522. save_size = png_ptr->save_buffer_size;
  185523. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185524. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  185525. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185526. png_ptr->idat_size -= save_size;
  185527. png_ptr->buffer_size -= save_size;
  185528. png_ptr->save_buffer_size -= save_size;
  185529. png_ptr->save_buffer_ptr += save_size;
  185530. }
  185531. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  185532. {
  185533. png_size_t save_size;
  185534. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  185535. {
  185536. save_size = (png_size_t)png_ptr->idat_size;
  185537. /* check for overflow */
  185538. if((png_uint_32)save_size != png_ptr->idat_size)
  185539. png_error(png_ptr, "save_size overflowed in pngpread");
  185540. }
  185541. else
  185542. save_size = png_ptr->current_buffer_size;
  185543. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185544. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  185545. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185546. png_ptr->idat_size -= save_size;
  185547. png_ptr->buffer_size -= save_size;
  185548. png_ptr->current_buffer_size -= save_size;
  185549. png_ptr->current_buffer_ptr += save_size;
  185550. }
  185551. if (!png_ptr->idat_size)
  185552. {
  185553. if (png_ptr->buffer_size < 4)
  185554. {
  185555. png_push_save_buffer(png_ptr);
  185556. return;
  185557. }
  185558. png_crc_finish(png_ptr, 0);
  185559. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  185560. png_ptr->mode |= PNG_AFTER_IDAT;
  185561. }
  185562. }
  185563. void /* PRIVATE */
  185564. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  185565. png_size_t buffer_length)
  185566. {
  185567. int ret;
  185568. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  185569. png_error(png_ptr, "Extra compression data");
  185570. png_ptr->zstream.next_in = buffer;
  185571. png_ptr->zstream.avail_in = (uInt)buffer_length;
  185572. for(;;)
  185573. {
  185574. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185575. if (ret != Z_OK)
  185576. {
  185577. if (ret == Z_STREAM_END)
  185578. {
  185579. if (png_ptr->zstream.avail_in)
  185580. png_error(png_ptr, "Extra compressed data");
  185581. if (!(png_ptr->zstream.avail_out))
  185582. {
  185583. png_push_process_row(png_ptr);
  185584. }
  185585. png_ptr->mode |= PNG_AFTER_IDAT;
  185586. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  185587. break;
  185588. }
  185589. else if (ret == Z_BUF_ERROR)
  185590. break;
  185591. else
  185592. png_error(png_ptr, "Decompression Error");
  185593. }
  185594. if (!(png_ptr->zstream.avail_out))
  185595. {
  185596. if ((
  185597. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  185598. png_ptr->interlaced && png_ptr->pass > 6) ||
  185599. (!png_ptr->interlaced &&
  185600. #endif
  185601. png_ptr->row_number == png_ptr->num_rows))
  185602. {
  185603. if (png_ptr->zstream.avail_in)
  185604. {
  185605. png_warning(png_ptr, "Too much data in IDAT chunks");
  185606. }
  185607. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  185608. break;
  185609. }
  185610. png_push_process_row(png_ptr);
  185611. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  185612. png_ptr->zstream.next_out = png_ptr->row_buf;
  185613. }
  185614. else
  185615. break;
  185616. }
  185617. }
  185618. void /* PRIVATE */
  185619. png_push_process_row(png_structp png_ptr)
  185620. {
  185621. png_ptr->row_info.color_type = png_ptr->color_type;
  185622. png_ptr->row_info.width = png_ptr->iwidth;
  185623. png_ptr->row_info.channels = png_ptr->channels;
  185624. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  185625. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  185626. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  185627. png_ptr->row_info.width);
  185628. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  185629. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  185630. (int)(png_ptr->row_buf[0]));
  185631. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  185632. png_ptr->rowbytes + 1);
  185633. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  185634. png_do_read_transformations(png_ptr);
  185635. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  185636. /* blow up interlaced rows to full size */
  185637. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  185638. {
  185639. if (png_ptr->pass < 6)
  185640. /* old interface (pre-1.0.9):
  185641. png_do_read_interlace(&(png_ptr->row_info),
  185642. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  185643. */
  185644. png_do_read_interlace(png_ptr);
  185645. switch (png_ptr->pass)
  185646. {
  185647. case 0:
  185648. {
  185649. int i;
  185650. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  185651. {
  185652. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185653. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  185654. }
  185655. if (png_ptr->pass == 2) /* pass 1 might be empty */
  185656. {
  185657. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185658. {
  185659. png_push_have_row(png_ptr, png_bytep_NULL);
  185660. png_read_push_finish_row(png_ptr);
  185661. }
  185662. }
  185663. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  185664. {
  185665. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185666. {
  185667. png_push_have_row(png_ptr, png_bytep_NULL);
  185668. png_read_push_finish_row(png_ptr);
  185669. }
  185670. }
  185671. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  185672. {
  185673. png_push_have_row(png_ptr, png_bytep_NULL);
  185674. png_read_push_finish_row(png_ptr);
  185675. }
  185676. break;
  185677. }
  185678. case 1:
  185679. {
  185680. int i;
  185681. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  185682. {
  185683. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185684. png_read_push_finish_row(png_ptr);
  185685. }
  185686. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  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. }
  185694. break;
  185695. }
  185696. case 2:
  185697. {
  185698. int i;
  185699. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185700. {
  185701. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185702. png_read_push_finish_row(png_ptr);
  185703. }
  185704. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185705. {
  185706. png_push_have_row(png_ptr, png_bytep_NULL);
  185707. png_read_push_finish_row(png_ptr);
  185708. }
  185709. if (png_ptr->pass == 4) /* pass 3 might be empty */
  185710. {
  185711. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185712. {
  185713. png_push_have_row(png_ptr, png_bytep_NULL);
  185714. png_read_push_finish_row(png_ptr);
  185715. }
  185716. }
  185717. break;
  185718. }
  185719. case 3:
  185720. {
  185721. int i;
  185722. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  185723. {
  185724. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185725. png_read_push_finish_row(png_ptr);
  185726. }
  185727. if (png_ptr->pass == 4) /* skip top two generated rows */
  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. }
  185735. break;
  185736. }
  185737. case 4:
  185738. {
  185739. int i;
  185740. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185741. {
  185742. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185743. png_read_push_finish_row(png_ptr);
  185744. }
  185745. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185746. {
  185747. png_push_have_row(png_ptr, png_bytep_NULL);
  185748. png_read_push_finish_row(png_ptr);
  185749. }
  185750. if (png_ptr->pass == 6) /* pass 5 might be empty */
  185751. {
  185752. png_push_have_row(png_ptr, png_bytep_NULL);
  185753. png_read_push_finish_row(png_ptr);
  185754. }
  185755. break;
  185756. }
  185757. case 5:
  185758. {
  185759. int i;
  185760. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  185761. {
  185762. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185763. png_read_push_finish_row(png_ptr);
  185764. }
  185765. if (png_ptr->pass == 6) /* skip top generated row */
  185766. {
  185767. png_push_have_row(png_ptr, png_bytep_NULL);
  185768. png_read_push_finish_row(png_ptr);
  185769. }
  185770. break;
  185771. }
  185772. case 6:
  185773. {
  185774. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185775. png_read_push_finish_row(png_ptr);
  185776. if (png_ptr->pass != 6)
  185777. break;
  185778. png_push_have_row(png_ptr, png_bytep_NULL);
  185779. png_read_push_finish_row(png_ptr);
  185780. }
  185781. }
  185782. }
  185783. else
  185784. #endif
  185785. {
  185786. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185787. png_read_push_finish_row(png_ptr);
  185788. }
  185789. }
  185790. void /* PRIVATE */
  185791. png_read_push_finish_row(png_structp png_ptr)
  185792. {
  185793. #ifdef PNG_USE_LOCAL_ARRAYS
  185794. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  185795. /* start of interlace block */
  185796. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  185797. /* offset to next interlace block */
  185798. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  185799. /* start of interlace block in the y direction */
  185800. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  185801. /* offset to next interlace block in the y direction */
  185802. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  185803. /* Height of interlace block. This is not currently used - if you need
  185804. * it, uncomment it here and in png.h
  185805. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  185806. */
  185807. #endif
  185808. png_ptr->row_number++;
  185809. if (png_ptr->row_number < png_ptr->num_rows)
  185810. return;
  185811. if (png_ptr->interlaced)
  185812. {
  185813. png_ptr->row_number = 0;
  185814. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  185815. png_ptr->rowbytes + 1);
  185816. do
  185817. {
  185818. png_ptr->pass++;
  185819. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  185820. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  185821. (png_ptr->pass == 5 && png_ptr->width < 2))
  185822. png_ptr->pass++;
  185823. if (png_ptr->pass > 7)
  185824. png_ptr->pass--;
  185825. if (png_ptr->pass >= 7)
  185826. break;
  185827. png_ptr->iwidth = (png_ptr->width +
  185828. png_pass_inc[png_ptr->pass] - 1 -
  185829. png_pass_start[png_ptr->pass]) /
  185830. png_pass_inc[png_ptr->pass];
  185831. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  185832. png_ptr->iwidth) + 1;
  185833. if (png_ptr->transformations & PNG_INTERLACE)
  185834. break;
  185835. png_ptr->num_rows = (png_ptr->height +
  185836. png_pass_yinc[png_ptr->pass] - 1 -
  185837. png_pass_ystart[png_ptr->pass]) /
  185838. png_pass_yinc[png_ptr->pass];
  185839. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  185840. }
  185841. }
  185842. #if defined(PNG_READ_tEXt_SUPPORTED)
  185843. void /* PRIVATE */
  185844. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185845. length)
  185846. {
  185847. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185848. {
  185849. png_error(png_ptr, "Out of place tEXt");
  185850. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185851. }
  185852. #ifdef PNG_MAX_MALLOC_64K
  185853. png_ptr->skip_length = 0; /* This may not be necessary */
  185854. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185855. {
  185856. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  185857. png_ptr->skip_length = length - (png_uint_32)65535L;
  185858. length = (png_uint_32)65535L;
  185859. }
  185860. #endif
  185861. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185862. (png_uint_32)(length+1));
  185863. png_ptr->current_text[length] = '\0';
  185864. png_ptr->current_text_ptr = png_ptr->current_text;
  185865. png_ptr->current_text_size = (png_size_t)length;
  185866. png_ptr->current_text_left = (png_size_t)length;
  185867. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  185868. }
  185869. void /* PRIVATE */
  185870. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  185871. {
  185872. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185873. {
  185874. png_size_t text_size;
  185875. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185876. text_size = png_ptr->buffer_size;
  185877. else
  185878. text_size = png_ptr->current_text_left;
  185879. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185880. png_ptr->current_text_left -= text_size;
  185881. png_ptr->current_text_ptr += text_size;
  185882. }
  185883. if (!(png_ptr->current_text_left))
  185884. {
  185885. png_textp text_ptr;
  185886. png_charp text;
  185887. png_charp key;
  185888. int ret;
  185889. if (png_ptr->buffer_size < 4)
  185890. {
  185891. png_push_save_buffer(png_ptr);
  185892. return;
  185893. }
  185894. png_push_crc_finish(png_ptr);
  185895. #if defined(PNG_MAX_MALLOC_64K)
  185896. if (png_ptr->skip_length)
  185897. return;
  185898. #endif
  185899. key = png_ptr->current_text;
  185900. for (text = key; *text; text++)
  185901. /* empty loop */ ;
  185902. if (text < key + png_ptr->current_text_size)
  185903. text++;
  185904. text_ptr = (png_textp)png_malloc(png_ptr,
  185905. (png_uint_32)png_sizeof(png_text));
  185906. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  185907. text_ptr->key = key;
  185908. #ifdef PNG_iTXt_SUPPORTED
  185909. text_ptr->lang = NULL;
  185910. text_ptr->lang_key = NULL;
  185911. #endif
  185912. text_ptr->text = text;
  185913. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185914. png_free(png_ptr, key);
  185915. png_free(png_ptr, text_ptr);
  185916. png_ptr->current_text = NULL;
  185917. if (ret)
  185918. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185919. }
  185920. }
  185921. #endif
  185922. #if defined(PNG_READ_zTXt_SUPPORTED)
  185923. void /* PRIVATE */
  185924. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185925. length)
  185926. {
  185927. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185928. {
  185929. png_error(png_ptr, "Out of place zTXt");
  185930. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185931. }
  185932. #ifdef PNG_MAX_MALLOC_64K
  185933. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  185934. * to be able to store the uncompressed data. Actually, the threshold
  185935. * is probably around 32K, but it isn't as definite as 64K is.
  185936. */
  185937. if (length > (png_uint_32)65535L)
  185938. {
  185939. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  185940. png_push_crc_skip(png_ptr, length);
  185941. return;
  185942. }
  185943. #endif
  185944. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185945. (png_uint_32)(length+1));
  185946. png_ptr->current_text[length] = '\0';
  185947. png_ptr->current_text_ptr = png_ptr->current_text;
  185948. png_ptr->current_text_size = (png_size_t)length;
  185949. png_ptr->current_text_left = (png_size_t)length;
  185950. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  185951. }
  185952. void /* PRIVATE */
  185953. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  185954. {
  185955. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185956. {
  185957. png_size_t text_size;
  185958. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  185959. text_size = png_ptr->buffer_size;
  185960. else
  185961. text_size = png_ptr->current_text_left;
  185962. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185963. png_ptr->current_text_left -= text_size;
  185964. png_ptr->current_text_ptr += text_size;
  185965. }
  185966. if (!(png_ptr->current_text_left))
  185967. {
  185968. png_textp text_ptr;
  185969. png_charp text;
  185970. png_charp key;
  185971. int ret;
  185972. png_size_t text_size, key_size;
  185973. if (png_ptr->buffer_size < 4)
  185974. {
  185975. png_push_save_buffer(png_ptr);
  185976. return;
  185977. }
  185978. png_push_crc_finish(png_ptr);
  185979. key = png_ptr->current_text;
  185980. for (text = key; *text; text++)
  185981. /* empty loop */ ;
  185982. /* zTXt can't have zero text */
  185983. if (text >= key + png_ptr->current_text_size)
  185984. {
  185985. png_ptr->current_text = NULL;
  185986. png_free(png_ptr, key);
  185987. return;
  185988. }
  185989. text++;
  185990. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  185991. {
  185992. png_ptr->current_text = NULL;
  185993. png_free(png_ptr, key);
  185994. return;
  185995. }
  185996. text++;
  185997. png_ptr->zstream.next_in = (png_bytep )text;
  185998. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  185999. (text - key));
  186000. png_ptr->zstream.next_out = png_ptr->zbuf;
  186001. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186002. key_size = text - key;
  186003. text_size = 0;
  186004. text = NULL;
  186005. ret = Z_STREAM_END;
  186006. while (png_ptr->zstream.avail_in)
  186007. {
  186008. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186009. if (ret != Z_OK && ret != Z_STREAM_END)
  186010. {
  186011. inflateReset(&png_ptr->zstream);
  186012. png_ptr->zstream.avail_in = 0;
  186013. png_ptr->current_text = NULL;
  186014. png_free(png_ptr, key);
  186015. png_free(png_ptr, text);
  186016. return;
  186017. }
  186018. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  186019. {
  186020. if (text == NULL)
  186021. {
  186022. text = (png_charp)png_malloc(png_ptr,
  186023. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186024. + key_size + 1));
  186025. png_memcpy(text + key_size, png_ptr->zbuf,
  186026. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186027. png_memcpy(text, key, key_size);
  186028. text_size = key_size + png_ptr->zbuf_size -
  186029. png_ptr->zstream.avail_out;
  186030. *(text + text_size) = '\0';
  186031. }
  186032. else
  186033. {
  186034. png_charp tmp;
  186035. tmp = text;
  186036. text = (png_charp)png_malloc(png_ptr, text_size +
  186037. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186038. + 1));
  186039. png_memcpy(text, tmp, text_size);
  186040. png_free(png_ptr, tmp);
  186041. png_memcpy(text + text_size, png_ptr->zbuf,
  186042. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186043. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  186044. *(text + text_size) = '\0';
  186045. }
  186046. if (ret != Z_STREAM_END)
  186047. {
  186048. png_ptr->zstream.next_out = png_ptr->zbuf;
  186049. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186050. }
  186051. }
  186052. else
  186053. {
  186054. break;
  186055. }
  186056. if (ret == Z_STREAM_END)
  186057. break;
  186058. }
  186059. inflateReset(&png_ptr->zstream);
  186060. png_ptr->zstream.avail_in = 0;
  186061. if (ret != Z_STREAM_END)
  186062. {
  186063. png_ptr->current_text = NULL;
  186064. png_free(png_ptr, key);
  186065. png_free(png_ptr, text);
  186066. return;
  186067. }
  186068. png_ptr->current_text = NULL;
  186069. png_free(png_ptr, key);
  186070. key = text;
  186071. text += key_size;
  186072. text_ptr = (png_textp)png_malloc(png_ptr,
  186073. (png_uint_32)png_sizeof(png_text));
  186074. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  186075. text_ptr->key = key;
  186076. #ifdef PNG_iTXt_SUPPORTED
  186077. text_ptr->lang = NULL;
  186078. text_ptr->lang_key = NULL;
  186079. #endif
  186080. text_ptr->text = text;
  186081. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186082. png_free(png_ptr, key);
  186083. png_free(png_ptr, text_ptr);
  186084. if (ret)
  186085. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  186086. }
  186087. }
  186088. #endif
  186089. #if defined(PNG_READ_iTXt_SUPPORTED)
  186090. void /* PRIVATE */
  186091. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186092. length)
  186093. {
  186094. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186095. {
  186096. png_error(png_ptr, "Out of place iTXt");
  186097. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186098. }
  186099. #ifdef PNG_MAX_MALLOC_64K
  186100. png_ptr->skip_length = 0; /* This may not be necessary */
  186101. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  186102. {
  186103. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  186104. png_ptr->skip_length = length - (png_uint_32)65535L;
  186105. length = (png_uint_32)65535L;
  186106. }
  186107. #endif
  186108. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186109. (png_uint_32)(length+1));
  186110. png_ptr->current_text[length] = '\0';
  186111. png_ptr->current_text_ptr = png_ptr->current_text;
  186112. png_ptr->current_text_size = (png_size_t)length;
  186113. png_ptr->current_text_left = (png_size_t)length;
  186114. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  186115. }
  186116. void /* PRIVATE */
  186117. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  186118. {
  186119. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186120. {
  186121. png_size_t text_size;
  186122. if (png_ptr->buffer_size < png_ptr->current_text_left)
  186123. text_size = png_ptr->buffer_size;
  186124. else
  186125. text_size = png_ptr->current_text_left;
  186126. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186127. png_ptr->current_text_left -= text_size;
  186128. png_ptr->current_text_ptr += text_size;
  186129. }
  186130. if (!(png_ptr->current_text_left))
  186131. {
  186132. png_textp text_ptr;
  186133. png_charp key;
  186134. int comp_flag;
  186135. png_charp lang;
  186136. png_charp lang_key;
  186137. png_charp text;
  186138. int ret;
  186139. if (png_ptr->buffer_size < 4)
  186140. {
  186141. png_push_save_buffer(png_ptr);
  186142. return;
  186143. }
  186144. png_push_crc_finish(png_ptr);
  186145. #if defined(PNG_MAX_MALLOC_64K)
  186146. if (png_ptr->skip_length)
  186147. return;
  186148. #endif
  186149. key = png_ptr->current_text;
  186150. for (lang = key; *lang; lang++)
  186151. /* empty loop */ ;
  186152. if (lang < key + png_ptr->current_text_size - 3)
  186153. lang++;
  186154. comp_flag = *lang++;
  186155. lang++; /* skip comp_type, always zero */
  186156. for (lang_key = lang; *lang_key; lang_key++)
  186157. /* empty loop */ ;
  186158. lang_key++; /* skip NUL separator */
  186159. text=lang_key;
  186160. if (lang_key < key + png_ptr->current_text_size - 1)
  186161. {
  186162. for (; *text; text++)
  186163. /* empty loop */ ;
  186164. }
  186165. if (text < key + png_ptr->current_text_size)
  186166. text++;
  186167. text_ptr = (png_textp)png_malloc(png_ptr,
  186168. (png_uint_32)png_sizeof(png_text));
  186169. text_ptr->compression = comp_flag + 2;
  186170. text_ptr->key = key;
  186171. text_ptr->lang = lang;
  186172. text_ptr->lang_key = lang_key;
  186173. text_ptr->text = text;
  186174. text_ptr->text_length = 0;
  186175. text_ptr->itxt_length = png_strlen(text);
  186176. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186177. png_ptr->current_text = NULL;
  186178. png_free(png_ptr, text_ptr);
  186179. if (ret)
  186180. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  186181. }
  186182. }
  186183. #endif
  186184. /* This function is called when we haven't found a handler for this
  186185. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  186186. * name or a critical chunk), the chunk is (currently) silently ignored.
  186187. */
  186188. void /* PRIVATE */
  186189. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186190. length)
  186191. {
  186192. png_uint_32 skip=0;
  186193. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  186194. if (!(png_ptr->chunk_name[0] & 0x20))
  186195. {
  186196. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186197. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186198. PNG_HANDLE_CHUNK_ALWAYS
  186199. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186200. && png_ptr->read_user_chunk_fn == NULL
  186201. #endif
  186202. )
  186203. #endif
  186204. png_chunk_error(png_ptr, "unknown critical chunk");
  186205. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186206. }
  186207. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186208. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  186209. {
  186210. #ifdef PNG_MAX_MALLOC_64K
  186211. if (length > (png_uint_32)65535L)
  186212. {
  186213. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  186214. skip = length - (png_uint_32)65535L;
  186215. length = (png_uint_32)65535L;
  186216. }
  186217. #endif
  186218. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  186219. (png_charp)png_ptr->chunk_name, 5);
  186220. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  186221. png_ptr->unknown_chunk.size = (png_size_t)length;
  186222. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  186223. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186224. if(png_ptr->read_user_chunk_fn != NULL)
  186225. {
  186226. /* callback to user unknown chunk handler */
  186227. int ret;
  186228. ret = (*(png_ptr->read_user_chunk_fn))
  186229. (png_ptr, &png_ptr->unknown_chunk);
  186230. if (ret < 0)
  186231. png_chunk_error(png_ptr, "error in user chunk");
  186232. if (ret == 0)
  186233. {
  186234. if (!(png_ptr->chunk_name[0] & 0x20))
  186235. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186236. PNG_HANDLE_CHUNK_ALWAYS)
  186237. png_chunk_error(png_ptr, "unknown critical chunk");
  186238. png_set_unknown_chunks(png_ptr, info_ptr,
  186239. &png_ptr->unknown_chunk, 1);
  186240. }
  186241. }
  186242. #else
  186243. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  186244. #endif
  186245. png_free(png_ptr, png_ptr->unknown_chunk.data);
  186246. png_ptr->unknown_chunk.data = NULL;
  186247. }
  186248. else
  186249. #endif
  186250. skip=length;
  186251. png_push_crc_skip(png_ptr, skip);
  186252. }
  186253. void /* PRIVATE */
  186254. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  186255. {
  186256. if (png_ptr->info_fn != NULL)
  186257. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  186258. }
  186259. void /* PRIVATE */
  186260. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  186261. {
  186262. if (png_ptr->end_fn != NULL)
  186263. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  186264. }
  186265. void /* PRIVATE */
  186266. png_push_have_row(png_structp png_ptr, png_bytep row)
  186267. {
  186268. if (png_ptr->row_fn != NULL)
  186269. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  186270. (int)png_ptr->pass);
  186271. }
  186272. void PNGAPI
  186273. png_progressive_combine_row (png_structp png_ptr,
  186274. png_bytep old_row, png_bytep new_row)
  186275. {
  186276. #ifdef PNG_USE_LOCAL_ARRAYS
  186277. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  186278. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  186279. #endif
  186280. if(png_ptr == NULL) return;
  186281. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  186282. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  186283. }
  186284. void PNGAPI
  186285. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  186286. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  186287. png_progressive_end_ptr end_fn)
  186288. {
  186289. if(png_ptr == NULL) return;
  186290. png_ptr->info_fn = info_fn;
  186291. png_ptr->row_fn = row_fn;
  186292. png_ptr->end_fn = end_fn;
  186293. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  186294. }
  186295. png_voidp PNGAPI
  186296. png_get_progressive_ptr(png_structp png_ptr)
  186297. {
  186298. if(png_ptr == NULL) return (NULL);
  186299. return png_ptr->io_ptr;
  186300. }
  186301. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  186302. /*** End of inlined file: pngpread.c ***/
  186303. /*** Start of inlined file: pngrio.c ***/
  186304. /* pngrio.c - functions for data input
  186305. *
  186306. * Last changed in libpng 1.2.13 November 13, 2006
  186307. * For conditions of distribution and use, see copyright notice in png.h
  186308. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186309. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186310. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186311. *
  186312. * This file provides a location for all input. Users who need
  186313. * special handling are expected to write a function that has the same
  186314. * arguments as this and performs a similar function, but that possibly
  186315. * has a different input method. Note that you shouldn't change this
  186316. * function, but rather write a replacement function and then make
  186317. * libpng use it at run time with png_set_read_fn(...).
  186318. */
  186319. #define PNG_INTERNAL
  186320. #if defined(PNG_READ_SUPPORTED)
  186321. /* Read the data from whatever input you are using. The default routine
  186322. reads from a file pointer. Note that this routine sometimes gets called
  186323. with very small lengths, so you should implement some kind of simple
  186324. buffering if you are using unbuffered reads. This should never be asked
  186325. to read more then 64K on a 16 bit machine. */
  186326. void /* PRIVATE */
  186327. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186328. {
  186329. png_debug1(4,"reading %d bytes\n", (int)length);
  186330. if (png_ptr->read_data_fn != NULL)
  186331. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  186332. else
  186333. png_error(png_ptr, "Call to NULL read function");
  186334. }
  186335. #if !defined(PNG_NO_STDIO)
  186336. /* This is the function that does the actual reading of data. If you are
  186337. not reading from a standard C stream, you should create a replacement
  186338. read_data function and use it at run time with png_set_read_fn(), rather
  186339. than changing the library. */
  186340. #ifndef USE_FAR_KEYWORD
  186341. void PNGAPI
  186342. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186343. {
  186344. png_size_t check;
  186345. if(png_ptr == NULL) return;
  186346. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  186347. * instead of an int, which is what fread() actually returns.
  186348. */
  186349. #if defined(_WIN32_WCE)
  186350. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186351. check = 0;
  186352. #else
  186353. check = (png_size_t)fread(data, (png_size_t)1, length,
  186354. (png_FILE_p)png_ptr->io_ptr);
  186355. #endif
  186356. if (check != length)
  186357. png_error(png_ptr, "Read Error");
  186358. }
  186359. #else
  186360. /* this is the model-independent version. Since the standard I/O library
  186361. can't handle far buffers in the medium and small models, we have to copy
  186362. the data.
  186363. */
  186364. #define NEAR_BUF_SIZE 1024
  186365. #define MIN(a,b) (a <= b ? a : b)
  186366. static void PNGAPI
  186367. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186368. {
  186369. int check;
  186370. png_byte *n_data;
  186371. png_FILE_p io_ptr;
  186372. if(png_ptr == NULL) return;
  186373. /* Check if data really is near. If so, use usual code. */
  186374. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  186375. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  186376. if ((png_bytep)n_data == data)
  186377. {
  186378. #if defined(_WIN32_WCE)
  186379. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186380. check = 0;
  186381. #else
  186382. check = fread(n_data, 1, length, io_ptr);
  186383. #endif
  186384. }
  186385. else
  186386. {
  186387. png_byte buf[NEAR_BUF_SIZE];
  186388. png_size_t read, remaining, err;
  186389. check = 0;
  186390. remaining = length;
  186391. do
  186392. {
  186393. read = MIN(NEAR_BUF_SIZE, remaining);
  186394. #if defined(_WIN32_WCE)
  186395. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  186396. err = 0;
  186397. #else
  186398. err = fread(buf, (png_size_t)1, read, io_ptr);
  186399. #endif
  186400. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  186401. if(err != read)
  186402. break;
  186403. else
  186404. check += err;
  186405. data += read;
  186406. remaining -= read;
  186407. }
  186408. while (remaining != 0);
  186409. }
  186410. if ((png_uint_32)check != (png_uint_32)length)
  186411. png_error(png_ptr, "read Error");
  186412. }
  186413. #endif
  186414. #endif
  186415. /* This function allows the application to supply a new input function
  186416. for libpng if standard C streams aren't being used.
  186417. This function takes as its arguments:
  186418. png_ptr - pointer to a png input data structure
  186419. io_ptr - pointer to user supplied structure containing info about
  186420. the input functions. May be NULL.
  186421. read_data_fn - pointer to a new input function that takes as its
  186422. arguments a pointer to a png_struct, a pointer to
  186423. a location where input data can be stored, and a 32-bit
  186424. unsigned int that is the number of bytes to be read.
  186425. To exit and output any fatal error messages the new write
  186426. function should call png_error(png_ptr, "Error msg"). */
  186427. void PNGAPI
  186428. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  186429. png_rw_ptr read_data_fn)
  186430. {
  186431. if(png_ptr == NULL) return;
  186432. png_ptr->io_ptr = io_ptr;
  186433. #if !defined(PNG_NO_STDIO)
  186434. if (read_data_fn != NULL)
  186435. png_ptr->read_data_fn = read_data_fn;
  186436. else
  186437. png_ptr->read_data_fn = png_default_read_data;
  186438. #else
  186439. png_ptr->read_data_fn = read_data_fn;
  186440. #endif
  186441. /* It is an error to write to a read device */
  186442. if (png_ptr->write_data_fn != NULL)
  186443. {
  186444. png_ptr->write_data_fn = NULL;
  186445. png_warning(png_ptr,
  186446. "It's an error to set both read_data_fn and write_data_fn in the ");
  186447. png_warning(png_ptr,
  186448. "same structure. Resetting write_data_fn to NULL.");
  186449. }
  186450. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  186451. png_ptr->output_flush_fn = NULL;
  186452. #endif
  186453. }
  186454. #endif /* PNG_READ_SUPPORTED */
  186455. /*** End of inlined file: pngrio.c ***/
  186456. /*** Start of inlined file: pngrtran.c ***/
  186457. /* pngrtran.c - transforms the data in a row for PNG readers
  186458. *
  186459. * Last changed in libpng 1.2.21 [October 4, 2007]
  186460. * For conditions of distribution and use, see copyright notice in png.h
  186461. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186462. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186463. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186464. *
  186465. * This file contains functions optionally called by an application
  186466. * in order to tell libpng how to handle data when reading a PNG.
  186467. * Transformations that are used in both reading and writing are
  186468. * in pngtrans.c.
  186469. */
  186470. #define PNG_INTERNAL
  186471. #if defined(PNG_READ_SUPPORTED)
  186472. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  186473. void PNGAPI
  186474. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  186475. {
  186476. png_debug(1, "in png_set_crc_action\n");
  186477. /* Tell libpng how we react to CRC errors in critical chunks */
  186478. if(png_ptr == NULL) return;
  186479. switch (crit_action)
  186480. {
  186481. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  186482. break;
  186483. case PNG_CRC_WARN_USE: /* warn/use data */
  186484. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186485. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  186486. break;
  186487. case PNG_CRC_QUIET_USE: /* quiet/use data */
  186488. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186489. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  186490. PNG_FLAG_CRC_CRITICAL_IGNORE;
  186491. break;
  186492. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  186493. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  186494. case PNG_CRC_ERROR_QUIT: /* error/quit */
  186495. case PNG_CRC_DEFAULT:
  186496. default:
  186497. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186498. break;
  186499. }
  186500. switch (ancil_action)
  186501. {
  186502. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  186503. break;
  186504. case PNG_CRC_WARN_USE: /* warn/use data */
  186505. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186506. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  186507. break;
  186508. case PNG_CRC_QUIET_USE: /* quiet/use data */
  186509. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186510. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  186511. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  186512. break;
  186513. case PNG_CRC_ERROR_QUIT: /* error/quit */
  186514. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186515. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  186516. break;
  186517. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  186518. case PNG_CRC_DEFAULT:
  186519. default:
  186520. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186521. break;
  186522. }
  186523. }
  186524. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  186525. defined(PNG_FLOATING_POINT_SUPPORTED)
  186526. /* handle alpha and tRNS via a background color */
  186527. void PNGAPI
  186528. png_set_background(png_structp png_ptr,
  186529. png_color_16p background_color, int background_gamma_code,
  186530. int need_expand, double background_gamma)
  186531. {
  186532. png_debug(1, "in png_set_background\n");
  186533. if(png_ptr == NULL) return;
  186534. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  186535. {
  186536. png_warning(png_ptr, "Application must supply a known background gamma");
  186537. return;
  186538. }
  186539. png_ptr->transformations |= PNG_BACKGROUND;
  186540. png_memcpy(&(png_ptr->background), background_color,
  186541. png_sizeof(png_color_16));
  186542. png_ptr->background_gamma = (float)background_gamma;
  186543. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  186544. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  186545. }
  186546. #endif
  186547. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186548. /* strip 16 bit depth files to 8 bit depth */
  186549. void PNGAPI
  186550. png_set_strip_16(png_structp png_ptr)
  186551. {
  186552. png_debug(1, "in png_set_strip_16\n");
  186553. if(png_ptr == NULL) return;
  186554. png_ptr->transformations |= PNG_16_TO_8;
  186555. }
  186556. #endif
  186557. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186558. void PNGAPI
  186559. png_set_strip_alpha(png_structp png_ptr)
  186560. {
  186561. png_debug(1, "in png_set_strip_alpha\n");
  186562. if(png_ptr == NULL) return;
  186563. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  186564. }
  186565. #endif
  186566. #if defined(PNG_READ_DITHER_SUPPORTED)
  186567. /* Dither file to 8 bit. Supply a palette, the current number
  186568. * of elements in the palette, the maximum number of elements
  186569. * allowed, and a histogram if possible. If the current number
  186570. * of colors is greater then the maximum number, the palette will be
  186571. * modified to fit in the maximum number. "full_dither" indicates
  186572. * whether we need a dithering cube set up for RGB images, or if we
  186573. * simply are reducing the number of colors in a paletted image.
  186574. */
  186575. typedef struct png_dsort_struct
  186576. {
  186577. struct png_dsort_struct FAR * next;
  186578. png_byte left;
  186579. png_byte right;
  186580. } png_dsort;
  186581. typedef png_dsort FAR * png_dsortp;
  186582. typedef png_dsort FAR * FAR * png_dsortpp;
  186583. void PNGAPI
  186584. png_set_dither(png_structp png_ptr, png_colorp palette,
  186585. int num_palette, int maximum_colors, png_uint_16p histogram,
  186586. int full_dither)
  186587. {
  186588. png_debug(1, "in png_set_dither\n");
  186589. if(png_ptr == NULL) return;
  186590. png_ptr->transformations |= PNG_DITHER;
  186591. if (!full_dither)
  186592. {
  186593. int i;
  186594. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  186595. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186596. for (i = 0; i < num_palette; i++)
  186597. png_ptr->dither_index[i] = (png_byte)i;
  186598. }
  186599. if (num_palette > maximum_colors)
  186600. {
  186601. if (histogram != NULL)
  186602. {
  186603. /* This is easy enough, just throw out the least used colors.
  186604. Perhaps not the best solution, but good enough. */
  186605. int i;
  186606. /* initialize an array to sort colors */
  186607. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  186608. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186609. /* initialize the dither_sort array */
  186610. for (i = 0; i < num_palette; i++)
  186611. png_ptr->dither_sort[i] = (png_byte)i;
  186612. /* Find the least used palette entries by starting a
  186613. bubble sort, and running it until we have sorted
  186614. out enough colors. Note that we don't care about
  186615. sorting all the colors, just finding which are
  186616. least used. */
  186617. for (i = num_palette - 1; i >= maximum_colors; i--)
  186618. {
  186619. int done; /* to stop early if the list is pre-sorted */
  186620. int j;
  186621. done = 1;
  186622. for (j = 0; j < i; j++)
  186623. {
  186624. if (histogram[png_ptr->dither_sort[j]]
  186625. < histogram[png_ptr->dither_sort[j + 1]])
  186626. {
  186627. png_byte t;
  186628. t = png_ptr->dither_sort[j];
  186629. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  186630. png_ptr->dither_sort[j + 1] = t;
  186631. done = 0;
  186632. }
  186633. }
  186634. if (done)
  186635. break;
  186636. }
  186637. /* swap the palette around, and set up a table, if necessary */
  186638. if (full_dither)
  186639. {
  186640. int j = num_palette;
  186641. /* put all the useful colors within the max, but don't
  186642. move the others */
  186643. for (i = 0; i < maximum_colors; i++)
  186644. {
  186645. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  186646. {
  186647. do
  186648. j--;
  186649. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  186650. palette[i] = palette[j];
  186651. }
  186652. }
  186653. }
  186654. else
  186655. {
  186656. int j = num_palette;
  186657. /* move all the used colors inside the max limit, and
  186658. develop a translation table */
  186659. for (i = 0; i < maximum_colors; i++)
  186660. {
  186661. /* only move the colors we need to */
  186662. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  186663. {
  186664. png_color tmp_color;
  186665. do
  186666. j--;
  186667. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  186668. tmp_color = palette[j];
  186669. palette[j] = palette[i];
  186670. palette[i] = tmp_color;
  186671. /* indicate where the color went */
  186672. png_ptr->dither_index[j] = (png_byte)i;
  186673. png_ptr->dither_index[i] = (png_byte)j;
  186674. }
  186675. }
  186676. /* find closest color for those colors we are not using */
  186677. for (i = 0; i < num_palette; i++)
  186678. {
  186679. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  186680. {
  186681. int min_d, k, min_k, d_index;
  186682. /* find the closest color to one we threw out */
  186683. d_index = png_ptr->dither_index[i];
  186684. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  186685. for (k = 1, min_k = 0; k < maximum_colors; k++)
  186686. {
  186687. int d;
  186688. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  186689. if (d < min_d)
  186690. {
  186691. min_d = d;
  186692. min_k = k;
  186693. }
  186694. }
  186695. /* point to closest color */
  186696. png_ptr->dither_index[i] = (png_byte)min_k;
  186697. }
  186698. }
  186699. }
  186700. png_free(png_ptr, png_ptr->dither_sort);
  186701. png_ptr->dither_sort=NULL;
  186702. }
  186703. else
  186704. {
  186705. /* This is much harder to do simply (and quickly). Perhaps
  186706. we need to go through a median cut routine, but those
  186707. don't always behave themselves with only a few colors
  186708. as input. So we will just find the closest two colors,
  186709. and throw out one of them (chosen somewhat randomly).
  186710. [We don't understand this at all, so if someone wants to
  186711. work on improving it, be our guest - AED, GRP]
  186712. */
  186713. int i;
  186714. int max_d;
  186715. int num_new_palette;
  186716. png_dsortp t;
  186717. png_dsortpp hash;
  186718. t=NULL;
  186719. /* initialize palette index arrays */
  186720. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  186721. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186722. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  186723. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186724. /* initialize the sort array */
  186725. for (i = 0; i < num_palette; i++)
  186726. {
  186727. png_ptr->index_to_palette[i] = (png_byte)i;
  186728. png_ptr->palette_to_index[i] = (png_byte)i;
  186729. }
  186730. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  186731. png_sizeof (png_dsortp)));
  186732. for (i = 0; i < 769; i++)
  186733. hash[i] = NULL;
  186734. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  186735. num_new_palette = num_palette;
  186736. /* initial wild guess at how far apart the farthest pixel
  186737. pair we will be eliminating will be. Larger
  186738. numbers mean more areas will be allocated, Smaller
  186739. numbers run the risk of not saving enough data, and
  186740. having to do this all over again.
  186741. I have not done extensive checking on this number.
  186742. */
  186743. max_d = 96;
  186744. while (num_new_palette > maximum_colors)
  186745. {
  186746. for (i = 0; i < num_new_palette - 1; i++)
  186747. {
  186748. int j;
  186749. for (j = i + 1; j < num_new_palette; j++)
  186750. {
  186751. int d;
  186752. d = PNG_COLOR_DIST(palette[i], palette[j]);
  186753. if (d <= max_d)
  186754. {
  186755. t = (png_dsortp)png_malloc_warn(png_ptr,
  186756. (png_uint_32)(png_sizeof(png_dsort)));
  186757. if (t == NULL)
  186758. break;
  186759. t->next = hash[d];
  186760. t->left = (png_byte)i;
  186761. t->right = (png_byte)j;
  186762. hash[d] = t;
  186763. }
  186764. }
  186765. if (t == NULL)
  186766. break;
  186767. }
  186768. if (t != NULL)
  186769. for (i = 0; i <= max_d; i++)
  186770. {
  186771. if (hash[i] != NULL)
  186772. {
  186773. png_dsortp p;
  186774. for (p = hash[i]; p; p = p->next)
  186775. {
  186776. if ((int)png_ptr->index_to_palette[p->left]
  186777. < num_new_palette &&
  186778. (int)png_ptr->index_to_palette[p->right]
  186779. < num_new_palette)
  186780. {
  186781. int j, next_j;
  186782. if (num_new_palette & 0x01)
  186783. {
  186784. j = p->left;
  186785. next_j = p->right;
  186786. }
  186787. else
  186788. {
  186789. j = p->right;
  186790. next_j = p->left;
  186791. }
  186792. num_new_palette--;
  186793. palette[png_ptr->index_to_palette[j]]
  186794. = palette[num_new_palette];
  186795. if (!full_dither)
  186796. {
  186797. int k;
  186798. for (k = 0; k < num_palette; k++)
  186799. {
  186800. if (png_ptr->dither_index[k] ==
  186801. png_ptr->index_to_palette[j])
  186802. png_ptr->dither_index[k] =
  186803. png_ptr->index_to_palette[next_j];
  186804. if ((int)png_ptr->dither_index[k] ==
  186805. num_new_palette)
  186806. png_ptr->dither_index[k] =
  186807. png_ptr->index_to_palette[j];
  186808. }
  186809. }
  186810. png_ptr->index_to_palette[png_ptr->palette_to_index
  186811. [num_new_palette]] = png_ptr->index_to_palette[j];
  186812. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  186813. = png_ptr->palette_to_index[num_new_palette];
  186814. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  186815. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  186816. }
  186817. if (num_new_palette <= maximum_colors)
  186818. break;
  186819. }
  186820. if (num_new_palette <= maximum_colors)
  186821. break;
  186822. }
  186823. }
  186824. for (i = 0; i < 769; i++)
  186825. {
  186826. if (hash[i] != NULL)
  186827. {
  186828. png_dsortp p = hash[i];
  186829. while (p)
  186830. {
  186831. t = p->next;
  186832. png_free(png_ptr, p);
  186833. p = t;
  186834. }
  186835. }
  186836. hash[i] = 0;
  186837. }
  186838. max_d += 96;
  186839. }
  186840. png_free(png_ptr, hash);
  186841. png_free(png_ptr, png_ptr->palette_to_index);
  186842. png_free(png_ptr, png_ptr->index_to_palette);
  186843. png_ptr->palette_to_index=NULL;
  186844. png_ptr->index_to_palette=NULL;
  186845. }
  186846. num_palette = maximum_colors;
  186847. }
  186848. if (png_ptr->palette == NULL)
  186849. {
  186850. png_ptr->palette = palette;
  186851. }
  186852. png_ptr->num_palette = (png_uint_16)num_palette;
  186853. if (full_dither)
  186854. {
  186855. int i;
  186856. png_bytep distance;
  186857. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  186858. PNG_DITHER_BLUE_BITS;
  186859. int num_red = (1 << PNG_DITHER_RED_BITS);
  186860. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  186861. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  186862. png_size_t num_entries = ((png_size_t)1 << total_bits);
  186863. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  186864. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  186865. png_memset(png_ptr->palette_lookup, 0, num_entries *
  186866. png_sizeof (png_byte));
  186867. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  186868. png_sizeof(png_byte)));
  186869. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  186870. for (i = 0; i < num_palette; i++)
  186871. {
  186872. int ir, ig, ib;
  186873. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  186874. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  186875. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  186876. for (ir = 0; ir < num_red; ir++)
  186877. {
  186878. /* int dr = abs(ir - r); */
  186879. int dr = ((ir > r) ? ir - r : r - ir);
  186880. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  186881. for (ig = 0; ig < num_green; ig++)
  186882. {
  186883. /* int dg = abs(ig - g); */
  186884. int dg = ((ig > g) ? ig - g : g - ig);
  186885. int dt = dr + dg;
  186886. int dm = ((dr > dg) ? dr : dg);
  186887. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  186888. for (ib = 0; ib < num_blue; ib++)
  186889. {
  186890. int d_index = index_g | ib;
  186891. /* int db = abs(ib - b); */
  186892. int db = ((ib > b) ? ib - b : b - ib);
  186893. int dmax = ((dm > db) ? dm : db);
  186894. int d = dmax + dt + db;
  186895. if (d < (int)distance[d_index])
  186896. {
  186897. distance[d_index] = (png_byte)d;
  186898. png_ptr->palette_lookup[d_index] = (png_byte)i;
  186899. }
  186900. }
  186901. }
  186902. }
  186903. }
  186904. png_free(png_ptr, distance);
  186905. }
  186906. }
  186907. #endif
  186908. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186909. /* Transform the image from the file_gamma to the screen_gamma. We
  186910. * only do transformations on images where the file_gamma and screen_gamma
  186911. * are not close reciprocals, otherwise it slows things down slightly, and
  186912. * also needlessly introduces small errors.
  186913. *
  186914. * We will turn off gamma transformation later if no semitransparent entries
  186915. * are present in the tRNS array for palette images. We can't do it here
  186916. * because we don't necessarily have the tRNS chunk yet.
  186917. */
  186918. void PNGAPI
  186919. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  186920. {
  186921. png_debug(1, "in png_set_gamma\n");
  186922. if(png_ptr == NULL) return;
  186923. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  186924. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  186925. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  186926. png_ptr->transformations |= PNG_GAMMA;
  186927. png_ptr->gamma = (float)file_gamma;
  186928. png_ptr->screen_gamma = (float)scrn_gamma;
  186929. }
  186930. #endif
  186931. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186932. /* Expand paletted images to RGB, expand grayscale images of
  186933. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  186934. * to alpha channels.
  186935. */
  186936. void PNGAPI
  186937. png_set_expand(png_structp png_ptr)
  186938. {
  186939. png_debug(1, "in png_set_expand\n");
  186940. if(png_ptr == NULL) return;
  186941. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186942. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186943. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186944. #endif
  186945. }
  186946. /* GRR 19990627: the following three functions currently are identical
  186947. * to png_set_expand(). However, it is entirely reasonable that someone
  186948. * might wish to expand an indexed image to RGB but *not* expand a single,
  186949. * fully transparent palette entry to a full alpha channel--perhaps instead
  186950. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  186951. * the transparent color with a particular RGB value, or drop tRNS entirely.
  186952. * IOW, a future version of the library may make the transformations flag
  186953. * a bit more fine-grained, with separate bits for each of these three
  186954. * functions.
  186955. *
  186956. * More to the point, these functions make it obvious what libpng will be
  186957. * doing, whereas "expand" can (and does) mean any number of things.
  186958. *
  186959. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  186960. * to expand only the sample depth but not to expand the tRNS to alpha.
  186961. */
  186962. /* Expand paletted images to RGB. */
  186963. void PNGAPI
  186964. png_set_palette_to_rgb(png_structp png_ptr)
  186965. {
  186966. png_debug(1, "in png_set_palette_to_rgb\n");
  186967. if(png_ptr == NULL) return;
  186968. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186969. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186970. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  186971. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186972. #endif
  186973. }
  186974. #if !defined(PNG_1_0_X)
  186975. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186976. void PNGAPI
  186977. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  186978. {
  186979. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  186980. if(png_ptr == NULL) return;
  186981. png_ptr->transformations |= PNG_EXPAND;
  186982. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186983. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186984. #endif
  186985. }
  186986. #endif
  186987. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186988. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186989. /* Deprecated as of libpng-1.2.9 */
  186990. void PNGAPI
  186991. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  186992. {
  186993. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  186994. if(png_ptr == NULL) return;
  186995. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186996. }
  186997. #endif
  186998. /* Expand tRNS chunks to alpha channels. */
  186999. void PNGAPI
  187000. png_set_tRNS_to_alpha(png_structp png_ptr)
  187001. {
  187002. png_debug(1, "in png_set_tRNS_to_alpha\n");
  187003. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187004. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187005. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187006. #endif
  187007. }
  187008. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  187009. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187010. void PNGAPI
  187011. png_set_gray_to_rgb(png_structp png_ptr)
  187012. {
  187013. png_debug(1, "in png_set_gray_to_rgb\n");
  187014. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  187015. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187016. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187017. #endif
  187018. }
  187019. #endif
  187020. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187021. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  187022. /* Convert a RGB image to a grayscale of the same width. This allows us,
  187023. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  187024. */
  187025. void PNGAPI
  187026. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  187027. double green)
  187028. {
  187029. int red_fixed = (int)((float)red*100000.0 + 0.5);
  187030. int green_fixed = (int)((float)green*100000.0 + 0.5);
  187031. if(png_ptr == NULL) return;
  187032. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  187033. }
  187034. #endif
  187035. void PNGAPI
  187036. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  187037. png_fixed_point red, png_fixed_point green)
  187038. {
  187039. png_debug(1, "in png_set_rgb_to_gray\n");
  187040. if(png_ptr == NULL) return;
  187041. switch(error_action)
  187042. {
  187043. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  187044. break;
  187045. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  187046. break;
  187047. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  187048. }
  187049. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187050. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187051. png_ptr->transformations |= PNG_EXPAND;
  187052. #else
  187053. {
  187054. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  187055. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  187056. }
  187057. #endif
  187058. {
  187059. png_uint_16 red_int, green_int;
  187060. if(red < 0 || green < 0)
  187061. {
  187062. red_int = 6968; /* .212671 * 32768 + .5 */
  187063. green_int = 23434; /* .715160 * 32768 + .5 */
  187064. }
  187065. else if(red + green < 100000L)
  187066. {
  187067. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  187068. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  187069. }
  187070. else
  187071. {
  187072. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  187073. red_int = 6968;
  187074. green_int = 23434;
  187075. }
  187076. png_ptr->rgb_to_gray_red_coeff = red_int;
  187077. png_ptr->rgb_to_gray_green_coeff = green_int;
  187078. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  187079. }
  187080. }
  187081. #endif
  187082. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  187083. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  187084. defined(PNG_LEGACY_SUPPORTED)
  187085. void PNGAPI
  187086. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  187087. read_user_transform_fn)
  187088. {
  187089. png_debug(1, "in png_set_read_user_transform_fn\n");
  187090. if(png_ptr == NULL) return;
  187091. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187092. png_ptr->transformations |= PNG_USER_TRANSFORM;
  187093. png_ptr->read_user_transform_fn = read_user_transform_fn;
  187094. #endif
  187095. #ifdef PNG_LEGACY_SUPPORTED
  187096. if(read_user_transform_fn)
  187097. png_warning(png_ptr,
  187098. "This version of libpng does not support user transforms");
  187099. #endif
  187100. }
  187101. #endif
  187102. /* Initialize everything needed for the read. This includes modifying
  187103. * the palette.
  187104. */
  187105. void /* PRIVATE */
  187106. png_init_read_transformations(png_structp png_ptr)
  187107. {
  187108. png_debug(1, "in png_init_read_transformations\n");
  187109. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187110. if(png_ptr != NULL)
  187111. #endif
  187112. {
  187113. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  187114. || defined(PNG_READ_GAMMA_SUPPORTED)
  187115. int color_type = png_ptr->color_type;
  187116. #endif
  187117. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  187118. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187119. /* Detect gray background and attempt to enable optimization
  187120. * for gray --> RGB case */
  187121. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  187122. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  187123. * background color might actually be gray yet not be flagged as such.
  187124. * This is not a problem for the current code, which uses
  187125. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  187126. * png_do_gray_to_rgb() transformation.
  187127. */
  187128. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187129. !(color_type & PNG_COLOR_MASK_COLOR))
  187130. {
  187131. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187132. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187133. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187134. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187135. png_ptr->background.red == png_ptr->background.green &&
  187136. png_ptr->background.red == png_ptr->background.blue)
  187137. {
  187138. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187139. png_ptr->background.gray = png_ptr->background.red;
  187140. }
  187141. #endif
  187142. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187143. (png_ptr->transformations & PNG_EXPAND))
  187144. {
  187145. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  187146. {
  187147. /* expand background and tRNS chunks */
  187148. switch (png_ptr->bit_depth)
  187149. {
  187150. case 1:
  187151. png_ptr->background.gray *= (png_uint_16)0xff;
  187152. png_ptr->background.red = png_ptr->background.green
  187153. = png_ptr->background.blue = png_ptr->background.gray;
  187154. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187155. {
  187156. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  187157. png_ptr->trans_values.red = png_ptr->trans_values.green
  187158. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187159. }
  187160. break;
  187161. case 2:
  187162. png_ptr->background.gray *= (png_uint_16)0x55;
  187163. png_ptr->background.red = png_ptr->background.green
  187164. = png_ptr->background.blue = png_ptr->background.gray;
  187165. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187166. {
  187167. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  187168. png_ptr->trans_values.red = png_ptr->trans_values.green
  187169. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187170. }
  187171. break;
  187172. case 4:
  187173. png_ptr->background.gray *= (png_uint_16)0x11;
  187174. png_ptr->background.red = png_ptr->background.green
  187175. = png_ptr->background.blue = png_ptr->background.gray;
  187176. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187177. {
  187178. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  187179. png_ptr->trans_values.red = png_ptr->trans_values.green
  187180. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187181. }
  187182. break;
  187183. case 8:
  187184. case 16:
  187185. png_ptr->background.red = png_ptr->background.green
  187186. = png_ptr->background.blue = png_ptr->background.gray;
  187187. break;
  187188. }
  187189. }
  187190. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  187191. {
  187192. png_ptr->background.red =
  187193. png_ptr->palette[png_ptr->background.index].red;
  187194. png_ptr->background.green =
  187195. png_ptr->palette[png_ptr->background.index].green;
  187196. png_ptr->background.blue =
  187197. png_ptr->palette[png_ptr->background.index].blue;
  187198. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187199. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  187200. {
  187201. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187202. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187203. #endif
  187204. {
  187205. /* invert the alpha channel (in tRNS) unless the pixels are
  187206. going to be expanded, in which case leave it for later */
  187207. int i,istop;
  187208. istop=(int)png_ptr->num_trans;
  187209. for (i=0; i<istop; i++)
  187210. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  187211. }
  187212. }
  187213. #endif
  187214. }
  187215. }
  187216. #endif
  187217. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  187218. png_ptr->background_1 = png_ptr->background;
  187219. #endif
  187220. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187221. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  187222. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  187223. < PNG_GAMMA_THRESHOLD))
  187224. {
  187225. int i,k;
  187226. k=0;
  187227. for (i=0; i<png_ptr->num_trans; i++)
  187228. {
  187229. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  187230. k=1; /* partial transparency is present */
  187231. }
  187232. if (k == 0)
  187233. png_ptr->transformations &= (~PNG_GAMMA);
  187234. }
  187235. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  187236. png_ptr->gamma != 0.0)
  187237. {
  187238. png_build_gamma_table(png_ptr);
  187239. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187240. if (png_ptr->transformations & PNG_BACKGROUND)
  187241. {
  187242. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187243. {
  187244. /* could skip if no transparency and
  187245. */
  187246. png_color back, back_1;
  187247. png_colorp palette = png_ptr->palette;
  187248. int num_palette = png_ptr->num_palette;
  187249. int i;
  187250. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187251. {
  187252. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187253. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187254. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187255. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187256. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187257. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187258. }
  187259. else
  187260. {
  187261. double g, gs;
  187262. switch (png_ptr->background_gamma_type)
  187263. {
  187264. case PNG_BACKGROUND_GAMMA_SCREEN:
  187265. g = (png_ptr->screen_gamma);
  187266. gs = 1.0;
  187267. break;
  187268. case PNG_BACKGROUND_GAMMA_FILE:
  187269. g = 1.0 / (png_ptr->gamma);
  187270. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187271. break;
  187272. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187273. g = 1.0 / (png_ptr->background_gamma);
  187274. gs = 1.0 / (png_ptr->background_gamma *
  187275. png_ptr->screen_gamma);
  187276. break;
  187277. default:
  187278. g = 1.0; /* back_1 */
  187279. gs = 1.0; /* back */
  187280. }
  187281. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  187282. {
  187283. back.red = (png_byte)png_ptr->background.red;
  187284. back.green = (png_byte)png_ptr->background.green;
  187285. back.blue = (png_byte)png_ptr->background.blue;
  187286. }
  187287. else
  187288. {
  187289. back.red = (png_byte)(pow(
  187290. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  187291. back.green = (png_byte)(pow(
  187292. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  187293. back.blue = (png_byte)(pow(
  187294. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  187295. }
  187296. back_1.red = (png_byte)(pow(
  187297. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  187298. back_1.green = (png_byte)(pow(
  187299. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  187300. back_1.blue = (png_byte)(pow(
  187301. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  187302. }
  187303. for (i = 0; i < num_palette; i++)
  187304. {
  187305. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187306. {
  187307. if (png_ptr->trans[i] == 0)
  187308. {
  187309. palette[i] = back;
  187310. }
  187311. else /* if (png_ptr->trans[i] != 0xff) */
  187312. {
  187313. png_byte v, w;
  187314. v = png_ptr->gamma_to_1[palette[i].red];
  187315. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187316. palette[i].red = png_ptr->gamma_from_1[w];
  187317. v = png_ptr->gamma_to_1[palette[i].green];
  187318. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187319. palette[i].green = png_ptr->gamma_from_1[w];
  187320. v = png_ptr->gamma_to_1[palette[i].blue];
  187321. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187322. palette[i].blue = png_ptr->gamma_from_1[w];
  187323. }
  187324. }
  187325. else
  187326. {
  187327. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187328. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187329. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187330. }
  187331. }
  187332. }
  187333. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  187334. else
  187335. /* color_type != PNG_COLOR_TYPE_PALETTE */
  187336. {
  187337. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  187338. double g = 1.0;
  187339. double gs = 1.0;
  187340. switch (png_ptr->background_gamma_type)
  187341. {
  187342. case PNG_BACKGROUND_GAMMA_SCREEN:
  187343. g = (png_ptr->screen_gamma);
  187344. gs = 1.0;
  187345. break;
  187346. case PNG_BACKGROUND_GAMMA_FILE:
  187347. g = 1.0 / (png_ptr->gamma);
  187348. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187349. break;
  187350. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187351. g = 1.0 / (png_ptr->background_gamma);
  187352. gs = 1.0 / (png_ptr->background_gamma *
  187353. png_ptr->screen_gamma);
  187354. break;
  187355. }
  187356. png_ptr->background_1.gray = (png_uint_16)(pow(
  187357. (double)png_ptr->background.gray / m, g) * m + .5);
  187358. png_ptr->background.gray = (png_uint_16)(pow(
  187359. (double)png_ptr->background.gray / m, gs) * m + .5);
  187360. if ((png_ptr->background.red != png_ptr->background.green) ||
  187361. (png_ptr->background.red != png_ptr->background.blue) ||
  187362. (png_ptr->background.red != png_ptr->background.gray))
  187363. {
  187364. /* RGB or RGBA with color background */
  187365. png_ptr->background_1.red = (png_uint_16)(pow(
  187366. (double)png_ptr->background.red / m, g) * m + .5);
  187367. png_ptr->background_1.green = (png_uint_16)(pow(
  187368. (double)png_ptr->background.green / m, g) * m + .5);
  187369. png_ptr->background_1.blue = (png_uint_16)(pow(
  187370. (double)png_ptr->background.blue / m, g) * m + .5);
  187371. png_ptr->background.red = (png_uint_16)(pow(
  187372. (double)png_ptr->background.red / m, gs) * m + .5);
  187373. png_ptr->background.green = (png_uint_16)(pow(
  187374. (double)png_ptr->background.green / m, gs) * m + .5);
  187375. png_ptr->background.blue = (png_uint_16)(pow(
  187376. (double)png_ptr->background.blue / m, gs) * m + .5);
  187377. }
  187378. else
  187379. {
  187380. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  187381. png_ptr->background_1.red = png_ptr->background_1.green
  187382. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  187383. png_ptr->background.red = png_ptr->background.green
  187384. = png_ptr->background.blue = png_ptr->background.gray;
  187385. }
  187386. }
  187387. }
  187388. else
  187389. /* transformation does not include PNG_BACKGROUND */
  187390. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  187391. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187392. {
  187393. png_colorp palette = png_ptr->palette;
  187394. int num_palette = png_ptr->num_palette;
  187395. int i;
  187396. for (i = 0; i < num_palette; i++)
  187397. {
  187398. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187399. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187400. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187401. }
  187402. }
  187403. }
  187404. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187405. else
  187406. #endif
  187407. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  187408. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187409. /* No GAMMA transformation */
  187410. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187411. (color_type == PNG_COLOR_TYPE_PALETTE))
  187412. {
  187413. int i;
  187414. int istop = (int)png_ptr->num_trans;
  187415. png_color back;
  187416. png_colorp palette = png_ptr->palette;
  187417. back.red = (png_byte)png_ptr->background.red;
  187418. back.green = (png_byte)png_ptr->background.green;
  187419. back.blue = (png_byte)png_ptr->background.blue;
  187420. for (i = 0; i < istop; i++)
  187421. {
  187422. if (png_ptr->trans[i] == 0)
  187423. {
  187424. palette[i] = back;
  187425. }
  187426. else if (png_ptr->trans[i] != 0xff)
  187427. {
  187428. /* The png_composite() macro is defined in png.h */
  187429. png_composite(palette[i].red, palette[i].red,
  187430. png_ptr->trans[i], back.red);
  187431. png_composite(palette[i].green, palette[i].green,
  187432. png_ptr->trans[i], back.green);
  187433. png_composite(palette[i].blue, palette[i].blue,
  187434. png_ptr->trans[i], back.blue);
  187435. }
  187436. }
  187437. }
  187438. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  187439. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187440. if ((png_ptr->transformations & PNG_SHIFT) &&
  187441. (color_type == PNG_COLOR_TYPE_PALETTE))
  187442. {
  187443. png_uint_16 i;
  187444. png_uint_16 istop = png_ptr->num_palette;
  187445. int sr = 8 - png_ptr->sig_bit.red;
  187446. int sg = 8 - png_ptr->sig_bit.green;
  187447. int sb = 8 - png_ptr->sig_bit.blue;
  187448. if (sr < 0 || sr > 8)
  187449. sr = 0;
  187450. if (sg < 0 || sg > 8)
  187451. sg = 0;
  187452. if (sb < 0 || sb > 8)
  187453. sb = 0;
  187454. for (i = 0; i < istop; i++)
  187455. {
  187456. png_ptr->palette[i].red >>= sr;
  187457. png_ptr->palette[i].green >>= sg;
  187458. png_ptr->palette[i].blue >>= sb;
  187459. }
  187460. }
  187461. #endif /* PNG_READ_SHIFT_SUPPORTED */
  187462. }
  187463. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  187464. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  187465. if(png_ptr)
  187466. return;
  187467. #endif
  187468. }
  187469. /* Modify the info structure to reflect the transformations. The
  187470. * info should be updated so a PNG file could be written with it,
  187471. * assuming the transformations result in valid PNG data.
  187472. */
  187473. void /* PRIVATE */
  187474. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  187475. {
  187476. png_debug(1, "in png_read_transform_info\n");
  187477. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187478. if (png_ptr->transformations & PNG_EXPAND)
  187479. {
  187480. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187481. {
  187482. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  187483. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  187484. else
  187485. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  187486. info_ptr->bit_depth = 8;
  187487. info_ptr->num_trans = 0;
  187488. }
  187489. else
  187490. {
  187491. if (png_ptr->num_trans)
  187492. {
  187493. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  187494. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  187495. else
  187496. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  187497. }
  187498. if (info_ptr->bit_depth < 8)
  187499. info_ptr->bit_depth = 8;
  187500. info_ptr->num_trans = 0;
  187501. }
  187502. }
  187503. #endif
  187504. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187505. if (png_ptr->transformations & PNG_BACKGROUND)
  187506. {
  187507. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187508. info_ptr->num_trans = 0;
  187509. info_ptr->background = png_ptr->background;
  187510. }
  187511. #endif
  187512. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187513. if (png_ptr->transformations & PNG_GAMMA)
  187514. {
  187515. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187516. info_ptr->gamma = png_ptr->gamma;
  187517. #endif
  187518. #ifdef PNG_FIXED_POINT_SUPPORTED
  187519. info_ptr->int_gamma = png_ptr->int_gamma;
  187520. #endif
  187521. }
  187522. #endif
  187523. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187524. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  187525. info_ptr->bit_depth = 8;
  187526. #endif
  187527. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187528. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  187529. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  187530. #endif
  187531. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187532. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  187533. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  187534. #endif
  187535. #if defined(PNG_READ_DITHER_SUPPORTED)
  187536. if (png_ptr->transformations & PNG_DITHER)
  187537. {
  187538. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  187539. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  187540. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  187541. {
  187542. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  187543. }
  187544. }
  187545. #endif
  187546. #if defined(PNG_READ_PACK_SUPPORTED)
  187547. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  187548. info_ptr->bit_depth = 8;
  187549. #endif
  187550. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187551. info_ptr->channels = 1;
  187552. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187553. info_ptr->channels = 3;
  187554. else
  187555. info_ptr->channels = 1;
  187556. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187557. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  187558. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187559. #endif
  187560. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  187561. info_ptr->channels++;
  187562. #if defined(PNG_READ_FILLER_SUPPORTED)
  187563. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  187564. if ((png_ptr->transformations & PNG_FILLER) &&
  187565. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  187566. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  187567. {
  187568. info_ptr->channels++;
  187569. /* if adding a true alpha channel not just filler */
  187570. #if !defined(PNG_1_0_X)
  187571. if (png_ptr->transformations & PNG_ADD_ALPHA)
  187572. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  187573. #endif
  187574. }
  187575. #endif
  187576. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  187577. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187578. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  187579. {
  187580. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  187581. info_ptr->bit_depth = png_ptr->user_transform_depth;
  187582. if(info_ptr->channels < png_ptr->user_transform_channels)
  187583. info_ptr->channels = png_ptr->user_transform_channels;
  187584. }
  187585. #endif
  187586. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  187587. info_ptr->bit_depth);
  187588. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  187589. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  187590. if(png_ptr)
  187591. return;
  187592. #endif
  187593. }
  187594. /* Transform the row. The order of transformations is significant,
  187595. * and is very touchy. If you add a transformation, take care to
  187596. * decide how it fits in with the other transformations here.
  187597. */
  187598. void /* PRIVATE */
  187599. png_do_read_transformations(png_structp png_ptr)
  187600. {
  187601. png_debug(1, "in png_do_read_transformations\n");
  187602. if (png_ptr->row_buf == NULL)
  187603. {
  187604. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187605. char msg[50];
  187606. png_snprintf2(msg, 50,
  187607. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  187608. png_ptr->pass);
  187609. png_error(png_ptr, msg);
  187610. #else
  187611. png_error(png_ptr, "NULL row buffer");
  187612. #endif
  187613. }
  187614. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187615. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187616. /* Application has failed to call either png_read_start_image()
  187617. * or png_read_update_info() after setting transforms that expand
  187618. * pixels. This check added to libpng-1.2.19 */
  187619. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  187620. png_error(png_ptr, "Uninitialized row");
  187621. #else
  187622. png_warning(png_ptr, "Uninitialized row");
  187623. #endif
  187624. #endif
  187625. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187626. if (png_ptr->transformations & PNG_EXPAND)
  187627. {
  187628. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  187629. {
  187630. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187631. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  187632. }
  187633. else
  187634. {
  187635. if (png_ptr->num_trans &&
  187636. (png_ptr->transformations & PNG_EXPAND_tRNS))
  187637. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187638. &(png_ptr->trans_values));
  187639. else
  187640. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187641. NULL);
  187642. }
  187643. }
  187644. #endif
  187645. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187646. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  187647. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187648. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  187649. #endif
  187650. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187651. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  187652. {
  187653. int rgb_error =
  187654. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  187655. if(rgb_error)
  187656. {
  187657. png_ptr->rgb_to_gray_status=1;
  187658. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  187659. PNG_RGB_TO_GRAY_WARN)
  187660. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  187661. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  187662. PNG_RGB_TO_GRAY_ERR)
  187663. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  187664. }
  187665. }
  187666. #endif
  187667. /*
  187668. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  187669. In most cases, the "simple transparency" should be done prior to doing
  187670. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  187671. pixel is transparent. You would also need to make sure that the
  187672. transparency information is upgraded to RGB.
  187673. To summarize, the current flow is:
  187674. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  187675. with background "in place" if transparent,
  187676. convert to RGB if necessary
  187677. - Gray + alpha -> composite with gray background and remove alpha bytes,
  187678. convert to RGB if necessary
  187679. To support RGB backgrounds for gray images we need:
  187680. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  187681. 3 or 6 bytes and composite with background
  187682. "in place" if transparent (3x compare/pixel
  187683. compared to doing composite with gray bkgrnd)
  187684. - Gray + alpha -> convert to RGB + alpha, composite with background and
  187685. remove alpha bytes (3x float operations/pixel
  187686. compared with composite on gray background)
  187687. Greg's change will do this. The reason it wasn't done before is for
  187688. performance, as this increases the per-pixel operations. If we would check
  187689. in advance if the background was gray or RGB, and position the gray-to-RGB
  187690. transform appropriately, then it would save a lot of work/time.
  187691. */
  187692. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187693. /* if gray -> RGB, do so now only if background is non-gray; else do later
  187694. * for performance reasons */
  187695. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187696. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  187697. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187698. #endif
  187699. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187700. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187701. ((png_ptr->num_trans != 0 ) ||
  187702. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  187703. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187704. &(png_ptr->trans_values), &(png_ptr->background)
  187705. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187706. , &(png_ptr->background_1),
  187707. png_ptr->gamma_table, png_ptr->gamma_from_1,
  187708. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  187709. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  187710. png_ptr->gamma_shift
  187711. #endif
  187712. );
  187713. #endif
  187714. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187715. if ((png_ptr->transformations & PNG_GAMMA) &&
  187716. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187717. !((png_ptr->transformations & PNG_BACKGROUND) &&
  187718. ((png_ptr->num_trans != 0) ||
  187719. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  187720. #endif
  187721. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  187722. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187723. png_ptr->gamma_table, png_ptr->gamma_16_table,
  187724. png_ptr->gamma_shift);
  187725. #endif
  187726. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187727. if (png_ptr->transformations & PNG_16_TO_8)
  187728. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187729. #endif
  187730. #if defined(PNG_READ_DITHER_SUPPORTED)
  187731. if (png_ptr->transformations & PNG_DITHER)
  187732. {
  187733. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  187734. png_ptr->palette_lookup, png_ptr->dither_index);
  187735. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  187736. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  187737. }
  187738. #endif
  187739. #if defined(PNG_READ_INVERT_SUPPORTED)
  187740. if (png_ptr->transformations & PNG_INVERT_MONO)
  187741. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187742. #endif
  187743. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187744. if (png_ptr->transformations & PNG_SHIFT)
  187745. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187746. &(png_ptr->shift));
  187747. #endif
  187748. #if defined(PNG_READ_PACK_SUPPORTED)
  187749. if (png_ptr->transformations & PNG_PACK)
  187750. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187751. #endif
  187752. #if defined(PNG_READ_BGR_SUPPORTED)
  187753. if (png_ptr->transformations & PNG_BGR)
  187754. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187755. #endif
  187756. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187757. if (png_ptr->transformations & PNG_PACKSWAP)
  187758. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187759. #endif
  187760. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187761. /* if gray -> RGB, do so now only if we did not do so above */
  187762. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187763. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  187764. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187765. #endif
  187766. #if defined(PNG_READ_FILLER_SUPPORTED)
  187767. if (png_ptr->transformations & PNG_FILLER)
  187768. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187769. (png_uint_32)png_ptr->filler, png_ptr->flags);
  187770. #endif
  187771. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187772. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  187773. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187774. #endif
  187775. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187776. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  187777. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187778. #endif
  187779. #if defined(PNG_READ_SWAP_SUPPORTED)
  187780. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187781. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187782. #endif
  187783. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187784. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  187785. {
  187786. if(png_ptr->read_user_transform_fn != NULL)
  187787. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  187788. (png_ptr, /* png_ptr */
  187789. &(png_ptr->row_info), /* row_info: */
  187790. /* png_uint_32 width; width of row */
  187791. /* png_uint_32 rowbytes; number of bytes in row */
  187792. /* png_byte color_type; color type of pixels */
  187793. /* png_byte bit_depth; bit depth of samples */
  187794. /* png_byte channels; number of channels (1-4) */
  187795. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  187796. png_ptr->row_buf + 1); /* start of pixel data for row */
  187797. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  187798. if(png_ptr->user_transform_depth)
  187799. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  187800. if(png_ptr->user_transform_channels)
  187801. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  187802. #endif
  187803. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  187804. png_ptr->row_info.channels);
  187805. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187806. png_ptr->row_info.width);
  187807. }
  187808. #endif
  187809. }
  187810. #if defined(PNG_READ_PACK_SUPPORTED)
  187811. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  187812. * without changing the actual values. Thus, if you had a row with
  187813. * a bit depth of 1, you would end up with bytes that only contained
  187814. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  187815. * png_do_shift() after this.
  187816. */
  187817. void /* PRIVATE */
  187818. png_do_unpack(png_row_infop row_info, png_bytep row)
  187819. {
  187820. png_debug(1, "in png_do_unpack\n");
  187821. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187822. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  187823. #else
  187824. if (row_info->bit_depth < 8)
  187825. #endif
  187826. {
  187827. png_uint_32 i;
  187828. png_uint_32 row_width=row_info->width;
  187829. switch (row_info->bit_depth)
  187830. {
  187831. case 1:
  187832. {
  187833. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  187834. png_bytep dp = row + (png_size_t)row_width - 1;
  187835. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  187836. for (i = 0; i < row_width; i++)
  187837. {
  187838. *dp = (png_byte)((*sp >> shift) & 0x01);
  187839. if (shift == 7)
  187840. {
  187841. shift = 0;
  187842. sp--;
  187843. }
  187844. else
  187845. shift++;
  187846. dp--;
  187847. }
  187848. break;
  187849. }
  187850. case 2:
  187851. {
  187852. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  187853. png_bytep dp = row + (png_size_t)row_width - 1;
  187854. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187855. for (i = 0; i < row_width; i++)
  187856. {
  187857. *dp = (png_byte)((*sp >> shift) & 0x03);
  187858. if (shift == 6)
  187859. {
  187860. shift = 0;
  187861. sp--;
  187862. }
  187863. else
  187864. shift += 2;
  187865. dp--;
  187866. }
  187867. break;
  187868. }
  187869. case 4:
  187870. {
  187871. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  187872. png_bytep dp = row + (png_size_t)row_width - 1;
  187873. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187874. for (i = 0; i < row_width; i++)
  187875. {
  187876. *dp = (png_byte)((*sp >> shift) & 0x0f);
  187877. if (shift == 4)
  187878. {
  187879. shift = 0;
  187880. sp--;
  187881. }
  187882. else
  187883. shift = 4;
  187884. dp--;
  187885. }
  187886. break;
  187887. }
  187888. }
  187889. row_info->bit_depth = 8;
  187890. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187891. row_info->rowbytes = row_width * row_info->channels;
  187892. }
  187893. }
  187894. #endif
  187895. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187896. /* Reverse the effects of png_do_shift. This routine merely shifts the
  187897. * pixels back to their significant bits values. Thus, if you have
  187898. * a row of bit depth 8, but only 5 are significant, this will shift
  187899. * the values back to 0 through 31.
  187900. */
  187901. void /* PRIVATE */
  187902. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  187903. {
  187904. png_debug(1, "in png_do_unshift\n");
  187905. if (
  187906. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187907. row != NULL && row_info != NULL && sig_bits != NULL &&
  187908. #endif
  187909. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  187910. {
  187911. int shift[4];
  187912. int channels = 0;
  187913. int c;
  187914. png_uint_16 value = 0;
  187915. png_uint_32 row_width = row_info->width;
  187916. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  187917. {
  187918. shift[channels++] = row_info->bit_depth - sig_bits->red;
  187919. shift[channels++] = row_info->bit_depth - sig_bits->green;
  187920. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  187921. }
  187922. else
  187923. {
  187924. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  187925. }
  187926. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187927. {
  187928. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  187929. }
  187930. for (c = 0; c < channels; c++)
  187931. {
  187932. if (shift[c] <= 0)
  187933. shift[c] = 0;
  187934. else
  187935. value = 1;
  187936. }
  187937. if (!value)
  187938. return;
  187939. switch (row_info->bit_depth)
  187940. {
  187941. case 2:
  187942. {
  187943. png_bytep bp;
  187944. png_uint_32 i;
  187945. png_uint_32 istop = row_info->rowbytes;
  187946. for (bp = row, i = 0; i < istop; i++)
  187947. {
  187948. *bp >>= 1;
  187949. *bp++ &= 0x55;
  187950. }
  187951. break;
  187952. }
  187953. case 4:
  187954. {
  187955. png_bytep bp = row;
  187956. png_uint_32 i;
  187957. png_uint_32 istop = row_info->rowbytes;
  187958. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  187959. (png_byte)((int)0xf >> shift[0]));
  187960. for (i = 0; i < istop; i++)
  187961. {
  187962. *bp >>= shift[0];
  187963. *bp++ &= mask;
  187964. }
  187965. break;
  187966. }
  187967. case 8:
  187968. {
  187969. png_bytep bp = row;
  187970. png_uint_32 i;
  187971. png_uint_32 istop = row_width * channels;
  187972. for (i = 0; i < istop; i++)
  187973. {
  187974. *bp++ >>= shift[i%channels];
  187975. }
  187976. break;
  187977. }
  187978. case 16:
  187979. {
  187980. png_bytep bp = row;
  187981. png_uint_32 i;
  187982. png_uint_32 istop = channels * row_width;
  187983. for (i = 0; i < istop; i++)
  187984. {
  187985. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  187986. value >>= shift[i%channels];
  187987. *bp++ = (png_byte)(value >> 8);
  187988. *bp++ = (png_byte)(value & 0xff);
  187989. }
  187990. break;
  187991. }
  187992. }
  187993. }
  187994. }
  187995. #endif
  187996. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187997. /* chop rows of bit depth 16 down to 8 */
  187998. void /* PRIVATE */
  187999. png_do_chop(png_row_infop row_info, png_bytep row)
  188000. {
  188001. png_debug(1, "in png_do_chop\n");
  188002. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188003. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  188004. #else
  188005. if (row_info->bit_depth == 16)
  188006. #endif
  188007. {
  188008. png_bytep sp = row;
  188009. png_bytep dp = row;
  188010. png_uint_32 i;
  188011. png_uint_32 istop = row_info->width * row_info->channels;
  188012. for (i = 0; i<istop; i++, sp += 2, dp++)
  188013. {
  188014. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  188015. /* This does a more accurate scaling of the 16-bit color
  188016. * value, rather than a simple low-byte truncation.
  188017. *
  188018. * What the ideal calculation should be:
  188019. * *dp = (((((png_uint_32)(*sp) << 8) |
  188020. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  188021. *
  188022. * GRR: no, I think this is what it really should be:
  188023. * *dp = (((((png_uint_32)(*sp) << 8) |
  188024. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  188025. *
  188026. * GRR: here's the exact calculation with shifts:
  188027. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  188028. * *dp = (temp - (temp >> 8)) >> 8;
  188029. *
  188030. * Approximate calculation with shift/add instead of multiply/divide:
  188031. * *dp = ((((png_uint_32)(*sp) << 8) |
  188032. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  188033. *
  188034. * What we actually do to avoid extra shifting and conversion:
  188035. */
  188036. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  188037. #else
  188038. /* Simply discard the low order byte */
  188039. *dp = *sp;
  188040. #endif
  188041. }
  188042. row_info->bit_depth = 8;
  188043. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  188044. row_info->rowbytes = row_info->width * row_info->channels;
  188045. }
  188046. }
  188047. #endif
  188048. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188049. void /* PRIVATE */
  188050. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  188051. {
  188052. png_debug(1, "in png_do_read_swap_alpha\n");
  188053. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188054. if (row != NULL && row_info != NULL)
  188055. #endif
  188056. {
  188057. png_uint_32 row_width = row_info->width;
  188058. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188059. {
  188060. /* This converts from RGBA to ARGB */
  188061. if (row_info->bit_depth == 8)
  188062. {
  188063. png_bytep sp = row + row_info->rowbytes;
  188064. png_bytep dp = sp;
  188065. png_byte save;
  188066. png_uint_32 i;
  188067. for (i = 0; i < row_width; i++)
  188068. {
  188069. save = *(--sp);
  188070. *(--dp) = *(--sp);
  188071. *(--dp) = *(--sp);
  188072. *(--dp) = *(--sp);
  188073. *(--dp) = save;
  188074. }
  188075. }
  188076. /* This converts from RRGGBBAA to AARRGGBB */
  188077. else
  188078. {
  188079. png_bytep sp = row + row_info->rowbytes;
  188080. png_bytep dp = sp;
  188081. png_byte save[2];
  188082. png_uint_32 i;
  188083. for (i = 0; i < row_width; i++)
  188084. {
  188085. save[0] = *(--sp);
  188086. save[1] = *(--sp);
  188087. *(--dp) = *(--sp);
  188088. *(--dp) = *(--sp);
  188089. *(--dp) = *(--sp);
  188090. *(--dp) = *(--sp);
  188091. *(--dp) = *(--sp);
  188092. *(--dp) = *(--sp);
  188093. *(--dp) = save[0];
  188094. *(--dp) = save[1];
  188095. }
  188096. }
  188097. }
  188098. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188099. {
  188100. /* This converts from GA to AG */
  188101. if (row_info->bit_depth == 8)
  188102. {
  188103. png_bytep sp = row + row_info->rowbytes;
  188104. png_bytep dp = sp;
  188105. png_byte save;
  188106. png_uint_32 i;
  188107. for (i = 0; i < row_width; i++)
  188108. {
  188109. save = *(--sp);
  188110. *(--dp) = *(--sp);
  188111. *(--dp) = save;
  188112. }
  188113. }
  188114. /* This converts from GGAA to AAGG */
  188115. else
  188116. {
  188117. png_bytep sp = row + row_info->rowbytes;
  188118. png_bytep dp = sp;
  188119. png_byte save[2];
  188120. png_uint_32 i;
  188121. for (i = 0; i < row_width; i++)
  188122. {
  188123. save[0] = *(--sp);
  188124. save[1] = *(--sp);
  188125. *(--dp) = *(--sp);
  188126. *(--dp) = *(--sp);
  188127. *(--dp) = save[0];
  188128. *(--dp) = save[1];
  188129. }
  188130. }
  188131. }
  188132. }
  188133. }
  188134. #endif
  188135. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188136. void /* PRIVATE */
  188137. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  188138. {
  188139. png_debug(1, "in png_do_read_invert_alpha\n");
  188140. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188141. if (row != NULL && row_info != NULL)
  188142. #endif
  188143. {
  188144. png_uint_32 row_width = row_info->width;
  188145. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188146. {
  188147. /* This inverts the alpha channel in RGBA */
  188148. if (row_info->bit_depth == 8)
  188149. {
  188150. png_bytep sp = row + row_info->rowbytes;
  188151. png_bytep dp = sp;
  188152. png_uint_32 i;
  188153. for (i = 0; i < row_width; i++)
  188154. {
  188155. *(--dp) = (png_byte)(255 - *(--sp));
  188156. /* This does nothing:
  188157. *(--dp) = *(--sp);
  188158. *(--dp) = *(--sp);
  188159. *(--dp) = *(--sp);
  188160. We can replace it with:
  188161. */
  188162. sp-=3;
  188163. dp=sp;
  188164. }
  188165. }
  188166. /* This inverts the alpha channel in RRGGBBAA */
  188167. else
  188168. {
  188169. png_bytep sp = row + row_info->rowbytes;
  188170. png_bytep dp = sp;
  188171. png_uint_32 i;
  188172. for (i = 0; i < row_width; i++)
  188173. {
  188174. *(--dp) = (png_byte)(255 - *(--sp));
  188175. *(--dp) = (png_byte)(255 - *(--sp));
  188176. /* This does nothing:
  188177. *(--dp) = *(--sp);
  188178. *(--dp) = *(--sp);
  188179. *(--dp) = *(--sp);
  188180. *(--dp) = *(--sp);
  188181. *(--dp) = *(--sp);
  188182. *(--dp) = *(--sp);
  188183. We can replace it with:
  188184. */
  188185. sp-=6;
  188186. dp=sp;
  188187. }
  188188. }
  188189. }
  188190. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188191. {
  188192. /* This inverts the alpha channel in GA */
  188193. if (row_info->bit_depth == 8)
  188194. {
  188195. png_bytep sp = row + row_info->rowbytes;
  188196. png_bytep dp = sp;
  188197. png_uint_32 i;
  188198. for (i = 0; i < row_width; i++)
  188199. {
  188200. *(--dp) = (png_byte)(255 - *(--sp));
  188201. *(--dp) = *(--sp);
  188202. }
  188203. }
  188204. /* This inverts the alpha channel in GGAA */
  188205. else
  188206. {
  188207. png_bytep sp = row + row_info->rowbytes;
  188208. png_bytep dp = sp;
  188209. png_uint_32 i;
  188210. for (i = 0; i < row_width; i++)
  188211. {
  188212. *(--dp) = (png_byte)(255 - *(--sp));
  188213. *(--dp) = (png_byte)(255 - *(--sp));
  188214. /*
  188215. *(--dp) = *(--sp);
  188216. *(--dp) = *(--sp);
  188217. */
  188218. sp-=2;
  188219. dp=sp;
  188220. }
  188221. }
  188222. }
  188223. }
  188224. }
  188225. #endif
  188226. #if defined(PNG_READ_FILLER_SUPPORTED)
  188227. /* Add filler channel if we have RGB color */
  188228. void /* PRIVATE */
  188229. png_do_read_filler(png_row_infop row_info, png_bytep row,
  188230. png_uint_32 filler, png_uint_32 flags)
  188231. {
  188232. png_uint_32 i;
  188233. png_uint_32 row_width = row_info->width;
  188234. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  188235. png_byte lo_filler = (png_byte)(filler & 0xff);
  188236. png_debug(1, "in png_do_read_filler\n");
  188237. if (
  188238. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188239. row != NULL && row_info != NULL &&
  188240. #endif
  188241. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188242. {
  188243. if(row_info->bit_depth == 8)
  188244. {
  188245. /* This changes the data from G to GX */
  188246. if (flags & PNG_FLAG_FILLER_AFTER)
  188247. {
  188248. png_bytep sp = row + (png_size_t)row_width;
  188249. png_bytep dp = sp + (png_size_t)row_width;
  188250. for (i = 1; i < row_width; i++)
  188251. {
  188252. *(--dp) = lo_filler;
  188253. *(--dp) = *(--sp);
  188254. }
  188255. *(--dp) = lo_filler;
  188256. row_info->channels = 2;
  188257. row_info->pixel_depth = 16;
  188258. row_info->rowbytes = row_width * 2;
  188259. }
  188260. /* This changes the data from G to XG */
  188261. else
  188262. {
  188263. png_bytep sp = row + (png_size_t)row_width;
  188264. png_bytep dp = sp + (png_size_t)row_width;
  188265. for (i = 0; i < row_width; i++)
  188266. {
  188267. *(--dp) = *(--sp);
  188268. *(--dp) = lo_filler;
  188269. }
  188270. row_info->channels = 2;
  188271. row_info->pixel_depth = 16;
  188272. row_info->rowbytes = row_width * 2;
  188273. }
  188274. }
  188275. else if(row_info->bit_depth == 16)
  188276. {
  188277. /* This changes the data from GG to GGXX */
  188278. if (flags & PNG_FLAG_FILLER_AFTER)
  188279. {
  188280. png_bytep sp = row + (png_size_t)row_width * 2;
  188281. png_bytep dp = sp + (png_size_t)row_width * 2;
  188282. for (i = 1; i < row_width; i++)
  188283. {
  188284. *(--dp) = hi_filler;
  188285. *(--dp) = lo_filler;
  188286. *(--dp) = *(--sp);
  188287. *(--dp) = *(--sp);
  188288. }
  188289. *(--dp) = hi_filler;
  188290. *(--dp) = lo_filler;
  188291. row_info->channels = 2;
  188292. row_info->pixel_depth = 32;
  188293. row_info->rowbytes = row_width * 4;
  188294. }
  188295. /* This changes the data from GG to XXGG */
  188296. else
  188297. {
  188298. png_bytep sp = row + (png_size_t)row_width * 2;
  188299. png_bytep dp = sp + (png_size_t)row_width * 2;
  188300. for (i = 0; i < row_width; i++)
  188301. {
  188302. *(--dp) = *(--sp);
  188303. *(--dp) = *(--sp);
  188304. *(--dp) = hi_filler;
  188305. *(--dp) = lo_filler;
  188306. }
  188307. row_info->channels = 2;
  188308. row_info->pixel_depth = 32;
  188309. row_info->rowbytes = row_width * 4;
  188310. }
  188311. }
  188312. } /* COLOR_TYPE == GRAY */
  188313. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188314. {
  188315. if(row_info->bit_depth == 8)
  188316. {
  188317. /* This changes the data from RGB to RGBX */
  188318. if (flags & PNG_FLAG_FILLER_AFTER)
  188319. {
  188320. png_bytep sp = row + (png_size_t)row_width * 3;
  188321. png_bytep dp = sp + (png_size_t)row_width;
  188322. for (i = 1; i < row_width; i++)
  188323. {
  188324. *(--dp) = lo_filler;
  188325. *(--dp) = *(--sp);
  188326. *(--dp) = *(--sp);
  188327. *(--dp) = *(--sp);
  188328. }
  188329. *(--dp) = lo_filler;
  188330. row_info->channels = 4;
  188331. row_info->pixel_depth = 32;
  188332. row_info->rowbytes = row_width * 4;
  188333. }
  188334. /* This changes the data from RGB to XRGB */
  188335. else
  188336. {
  188337. png_bytep sp = row + (png_size_t)row_width * 3;
  188338. png_bytep dp = sp + (png_size_t)row_width;
  188339. for (i = 0; i < row_width; i++)
  188340. {
  188341. *(--dp) = *(--sp);
  188342. *(--dp) = *(--sp);
  188343. *(--dp) = *(--sp);
  188344. *(--dp) = lo_filler;
  188345. }
  188346. row_info->channels = 4;
  188347. row_info->pixel_depth = 32;
  188348. row_info->rowbytes = row_width * 4;
  188349. }
  188350. }
  188351. else if(row_info->bit_depth == 16)
  188352. {
  188353. /* This changes the data from RRGGBB to RRGGBBXX */
  188354. if (flags & PNG_FLAG_FILLER_AFTER)
  188355. {
  188356. png_bytep sp = row + (png_size_t)row_width * 6;
  188357. png_bytep dp = sp + (png_size_t)row_width * 2;
  188358. for (i = 1; i < row_width; i++)
  188359. {
  188360. *(--dp) = hi_filler;
  188361. *(--dp) = lo_filler;
  188362. *(--dp) = *(--sp);
  188363. *(--dp) = *(--sp);
  188364. *(--dp) = *(--sp);
  188365. *(--dp) = *(--sp);
  188366. *(--dp) = *(--sp);
  188367. *(--dp) = *(--sp);
  188368. }
  188369. *(--dp) = hi_filler;
  188370. *(--dp) = lo_filler;
  188371. row_info->channels = 4;
  188372. row_info->pixel_depth = 64;
  188373. row_info->rowbytes = row_width * 8;
  188374. }
  188375. /* This changes the data from RRGGBB to XXRRGGBB */
  188376. else
  188377. {
  188378. png_bytep sp = row + (png_size_t)row_width * 6;
  188379. png_bytep dp = sp + (png_size_t)row_width * 2;
  188380. for (i = 0; i < row_width; i++)
  188381. {
  188382. *(--dp) = *(--sp);
  188383. *(--dp) = *(--sp);
  188384. *(--dp) = *(--sp);
  188385. *(--dp) = *(--sp);
  188386. *(--dp) = *(--sp);
  188387. *(--dp) = *(--sp);
  188388. *(--dp) = hi_filler;
  188389. *(--dp) = lo_filler;
  188390. }
  188391. row_info->channels = 4;
  188392. row_info->pixel_depth = 64;
  188393. row_info->rowbytes = row_width * 8;
  188394. }
  188395. }
  188396. } /* COLOR_TYPE == RGB */
  188397. }
  188398. #endif
  188399. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188400. /* expand grayscale files to RGB, with or without alpha */
  188401. void /* PRIVATE */
  188402. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  188403. {
  188404. png_uint_32 i;
  188405. png_uint_32 row_width = row_info->width;
  188406. png_debug(1, "in png_do_gray_to_rgb\n");
  188407. if (row_info->bit_depth >= 8 &&
  188408. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188409. row != NULL && row_info != NULL &&
  188410. #endif
  188411. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  188412. {
  188413. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188414. {
  188415. if (row_info->bit_depth == 8)
  188416. {
  188417. png_bytep sp = row + (png_size_t)row_width - 1;
  188418. png_bytep dp = sp + (png_size_t)row_width * 2;
  188419. for (i = 0; i < row_width; i++)
  188420. {
  188421. *(dp--) = *sp;
  188422. *(dp--) = *sp;
  188423. *(dp--) = *(sp--);
  188424. }
  188425. }
  188426. else
  188427. {
  188428. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  188429. png_bytep dp = sp + (png_size_t)row_width * 4;
  188430. for (i = 0; i < row_width; i++)
  188431. {
  188432. *(dp--) = *sp;
  188433. *(dp--) = *(sp - 1);
  188434. *(dp--) = *sp;
  188435. *(dp--) = *(sp - 1);
  188436. *(dp--) = *(sp--);
  188437. *(dp--) = *(sp--);
  188438. }
  188439. }
  188440. }
  188441. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188442. {
  188443. if (row_info->bit_depth == 8)
  188444. {
  188445. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  188446. png_bytep dp = sp + (png_size_t)row_width * 2;
  188447. for (i = 0; i < row_width; i++)
  188448. {
  188449. *(dp--) = *(sp--);
  188450. *(dp--) = *sp;
  188451. *(dp--) = *sp;
  188452. *(dp--) = *(sp--);
  188453. }
  188454. }
  188455. else
  188456. {
  188457. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  188458. png_bytep dp = sp + (png_size_t)row_width * 4;
  188459. for (i = 0; i < row_width; i++)
  188460. {
  188461. *(dp--) = *(sp--);
  188462. *(dp--) = *(sp--);
  188463. *(dp--) = *sp;
  188464. *(dp--) = *(sp - 1);
  188465. *(dp--) = *sp;
  188466. *(dp--) = *(sp - 1);
  188467. *(dp--) = *(sp--);
  188468. *(dp--) = *(sp--);
  188469. }
  188470. }
  188471. }
  188472. row_info->channels += (png_byte)2;
  188473. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  188474. row_info->pixel_depth = (png_byte)(row_info->channels *
  188475. row_info->bit_depth);
  188476. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188477. }
  188478. }
  188479. #endif
  188480. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188481. /* reduce RGB files to grayscale, with or without alpha
  188482. * using the equation given in Poynton's ColorFAQ at
  188483. * <http://www.inforamp.net/~poynton/>
  188484. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  188485. *
  188486. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  188487. *
  188488. * We approximate this with
  188489. *
  188490. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  188491. *
  188492. * which can be expressed with integers as
  188493. *
  188494. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  188495. *
  188496. * The calculation is to be done in a linear colorspace.
  188497. *
  188498. * Other integer coefficents can be used via png_set_rgb_to_gray().
  188499. */
  188500. int /* PRIVATE */
  188501. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  188502. {
  188503. png_uint_32 i;
  188504. png_uint_32 row_width = row_info->width;
  188505. int rgb_error = 0;
  188506. png_debug(1, "in png_do_rgb_to_gray\n");
  188507. if (
  188508. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188509. row != NULL && row_info != NULL &&
  188510. #endif
  188511. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  188512. {
  188513. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  188514. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  188515. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  188516. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188517. {
  188518. if (row_info->bit_depth == 8)
  188519. {
  188520. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188521. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  188522. {
  188523. png_bytep sp = row;
  188524. png_bytep dp = row;
  188525. for (i = 0; i < row_width; i++)
  188526. {
  188527. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  188528. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  188529. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  188530. if(red != green || red != blue)
  188531. {
  188532. rgb_error |= 1;
  188533. *(dp++) = png_ptr->gamma_from_1[
  188534. (rc*red+gc*green+bc*blue)>>15];
  188535. }
  188536. else
  188537. *(dp++) = *(sp-1);
  188538. }
  188539. }
  188540. else
  188541. #endif
  188542. {
  188543. png_bytep sp = row;
  188544. png_bytep dp = row;
  188545. for (i = 0; i < row_width; i++)
  188546. {
  188547. png_byte red = *(sp++);
  188548. png_byte green = *(sp++);
  188549. png_byte blue = *(sp++);
  188550. if(red != green || red != blue)
  188551. {
  188552. rgb_error |= 1;
  188553. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  188554. }
  188555. else
  188556. *(dp++) = *(sp-1);
  188557. }
  188558. }
  188559. }
  188560. else /* RGB bit_depth == 16 */
  188561. {
  188562. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188563. if (png_ptr->gamma_16_to_1 != NULL &&
  188564. png_ptr->gamma_16_from_1 != NULL)
  188565. {
  188566. png_bytep sp = row;
  188567. png_bytep dp = row;
  188568. for (i = 0; i < row_width; i++)
  188569. {
  188570. png_uint_16 red, green, blue, w;
  188571. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188572. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188573. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188574. if(red == green && red == blue)
  188575. w = red;
  188576. else
  188577. {
  188578. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  188579. png_ptr->gamma_shift][red>>8];
  188580. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  188581. png_ptr->gamma_shift][green>>8];
  188582. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  188583. png_ptr->gamma_shift][blue>>8];
  188584. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  188585. + bc*blue_1)>>15);
  188586. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  188587. png_ptr->gamma_shift][gray16 >> 8];
  188588. rgb_error |= 1;
  188589. }
  188590. *(dp++) = (png_byte)((w>>8) & 0xff);
  188591. *(dp++) = (png_byte)(w & 0xff);
  188592. }
  188593. }
  188594. else
  188595. #endif
  188596. {
  188597. png_bytep sp = row;
  188598. png_bytep dp = row;
  188599. for (i = 0; i < row_width; i++)
  188600. {
  188601. png_uint_16 red, green, blue, gray16;
  188602. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188603. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188604. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188605. if(red != green || red != blue)
  188606. rgb_error |= 1;
  188607. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  188608. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  188609. *(dp++) = (png_byte)(gray16 & 0xff);
  188610. }
  188611. }
  188612. }
  188613. }
  188614. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188615. {
  188616. if (row_info->bit_depth == 8)
  188617. {
  188618. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188619. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  188620. {
  188621. png_bytep sp = row;
  188622. png_bytep dp = row;
  188623. for (i = 0; i < row_width; i++)
  188624. {
  188625. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  188626. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  188627. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  188628. if(red != green || red != blue)
  188629. rgb_error |= 1;
  188630. *(dp++) = png_ptr->gamma_from_1
  188631. [(rc*red + gc*green + bc*blue)>>15];
  188632. *(dp++) = *(sp++); /* alpha */
  188633. }
  188634. }
  188635. else
  188636. #endif
  188637. {
  188638. png_bytep sp = row;
  188639. png_bytep dp = row;
  188640. for (i = 0; i < row_width; i++)
  188641. {
  188642. png_byte red = *(sp++);
  188643. png_byte green = *(sp++);
  188644. png_byte blue = *(sp++);
  188645. if(red != green || red != blue)
  188646. rgb_error |= 1;
  188647. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  188648. *(dp++) = *(sp++); /* alpha */
  188649. }
  188650. }
  188651. }
  188652. else /* RGBA bit_depth == 16 */
  188653. {
  188654. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188655. if (png_ptr->gamma_16_to_1 != NULL &&
  188656. png_ptr->gamma_16_from_1 != NULL)
  188657. {
  188658. png_bytep sp = row;
  188659. png_bytep dp = row;
  188660. for (i = 0; i < row_width; i++)
  188661. {
  188662. png_uint_16 red, green, blue, w;
  188663. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188664. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188665. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188666. if(red == green && red == blue)
  188667. w = red;
  188668. else
  188669. {
  188670. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  188671. png_ptr->gamma_shift][red>>8];
  188672. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  188673. png_ptr->gamma_shift][green>>8];
  188674. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  188675. png_ptr->gamma_shift][blue>>8];
  188676. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  188677. + gc * green_1 + bc * blue_1)>>15);
  188678. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  188679. png_ptr->gamma_shift][gray16 >> 8];
  188680. rgb_error |= 1;
  188681. }
  188682. *(dp++) = (png_byte)((w>>8) & 0xff);
  188683. *(dp++) = (png_byte)(w & 0xff);
  188684. *(dp++) = *(sp++); /* alpha */
  188685. *(dp++) = *(sp++);
  188686. }
  188687. }
  188688. else
  188689. #endif
  188690. {
  188691. png_bytep sp = row;
  188692. png_bytep dp = row;
  188693. for (i = 0; i < row_width; i++)
  188694. {
  188695. png_uint_16 red, green, blue, gray16;
  188696. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  188697. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  188698. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  188699. if(red != green || red != blue)
  188700. rgb_error |= 1;
  188701. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  188702. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  188703. *(dp++) = (png_byte)(gray16 & 0xff);
  188704. *(dp++) = *(sp++); /* alpha */
  188705. *(dp++) = *(sp++);
  188706. }
  188707. }
  188708. }
  188709. }
  188710. row_info->channels -= (png_byte)2;
  188711. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  188712. row_info->pixel_depth = (png_byte)(row_info->channels *
  188713. row_info->bit_depth);
  188714. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188715. }
  188716. return rgb_error;
  188717. }
  188718. #endif
  188719. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  188720. * large of png_color. This lets grayscale images be treated as
  188721. * paletted. Most useful for gamma correction and simplification
  188722. * of code.
  188723. */
  188724. void PNGAPI
  188725. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  188726. {
  188727. int num_palette;
  188728. int color_inc;
  188729. int i;
  188730. int v;
  188731. png_debug(1, "in png_do_build_grayscale_palette\n");
  188732. if (palette == NULL)
  188733. return;
  188734. switch (bit_depth)
  188735. {
  188736. case 1:
  188737. num_palette = 2;
  188738. color_inc = 0xff;
  188739. break;
  188740. case 2:
  188741. num_palette = 4;
  188742. color_inc = 0x55;
  188743. break;
  188744. case 4:
  188745. num_palette = 16;
  188746. color_inc = 0x11;
  188747. break;
  188748. case 8:
  188749. num_palette = 256;
  188750. color_inc = 1;
  188751. break;
  188752. default:
  188753. num_palette = 0;
  188754. color_inc = 0;
  188755. break;
  188756. }
  188757. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  188758. {
  188759. palette[i].red = (png_byte)v;
  188760. palette[i].green = (png_byte)v;
  188761. palette[i].blue = (png_byte)v;
  188762. }
  188763. }
  188764. /* This function is currently unused. Do we really need it? */
  188765. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  188766. void /* PRIVATE */
  188767. png_correct_palette(png_structp png_ptr, png_colorp palette,
  188768. int num_palette)
  188769. {
  188770. png_debug(1, "in png_correct_palette\n");
  188771. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  188772. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  188773. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  188774. {
  188775. png_color back, back_1;
  188776. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  188777. {
  188778. back.red = png_ptr->gamma_table[png_ptr->background.red];
  188779. back.green = png_ptr->gamma_table[png_ptr->background.green];
  188780. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  188781. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  188782. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  188783. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  188784. }
  188785. else
  188786. {
  188787. double g;
  188788. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  188789. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  188790. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  188791. {
  188792. back.red = png_ptr->background.red;
  188793. back.green = png_ptr->background.green;
  188794. back.blue = png_ptr->background.blue;
  188795. }
  188796. else
  188797. {
  188798. back.red =
  188799. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  188800. 255.0 + 0.5);
  188801. back.green =
  188802. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  188803. 255.0 + 0.5);
  188804. back.blue =
  188805. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188806. 255.0 + 0.5);
  188807. }
  188808. g = 1.0 / png_ptr->background_gamma;
  188809. back_1.red =
  188810. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  188811. 255.0 + 0.5);
  188812. back_1.green =
  188813. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  188814. 255.0 + 0.5);
  188815. back_1.blue =
  188816. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188817. 255.0 + 0.5);
  188818. }
  188819. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188820. {
  188821. png_uint_32 i;
  188822. for (i = 0; i < (png_uint_32)num_palette; i++)
  188823. {
  188824. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  188825. {
  188826. palette[i] = back;
  188827. }
  188828. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  188829. {
  188830. png_byte v, w;
  188831. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  188832. png_composite(w, v, png_ptr->trans[i], back_1.red);
  188833. palette[i].red = png_ptr->gamma_from_1[w];
  188834. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  188835. png_composite(w, v, png_ptr->trans[i], back_1.green);
  188836. palette[i].green = png_ptr->gamma_from_1[w];
  188837. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  188838. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  188839. palette[i].blue = png_ptr->gamma_from_1[w];
  188840. }
  188841. else
  188842. {
  188843. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188844. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188845. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188846. }
  188847. }
  188848. }
  188849. else
  188850. {
  188851. int i;
  188852. for (i = 0; i < num_palette; i++)
  188853. {
  188854. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  188855. {
  188856. palette[i] = back;
  188857. }
  188858. else
  188859. {
  188860. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188861. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188862. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188863. }
  188864. }
  188865. }
  188866. }
  188867. else
  188868. #endif
  188869. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188870. if (png_ptr->transformations & PNG_GAMMA)
  188871. {
  188872. int i;
  188873. for (i = 0; i < num_palette; i++)
  188874. {
  188875. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188876. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188877. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188878. }
  188879. }
  188880. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188881. else
  188882. #endif
  188883. #endif
  188884. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188885. if (png_ptr->transformations & PNG_BACKGROUND)
  188886. {
  188887. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188888. {
  188889. png_color back;
  188890. back.red = (png_byte)png_ptr->background.red;
  188891. back.green = (png_byte)png_ptr->background.green;
  188892. back.blue = (png_byte)png_ptr->background.blue;
  188893. for (i = 0; i < (int)png_ptr->num_trans; i++)
  188894. {
  188895. if (png_ptr->trans[i] == 0)
  188896. {
  188897. palette[i].red = back.red;
  188898. palette[i].green = back.green;
  188899. palette[i].blue = back.blue;
  188900. }
  188901. else if (png_ptr->trans[i] != 0xff)
  188902. {
  188903. png_composite(palette[i].red, png_ptr->palette[i].red,
  188904. png_ptr->trans[i], back.red);
  188905. png_composite(palette[i].green, png_ptr->palette[i].green,
  188906. png_ptr->trans[i], back.green);
  188907. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  188908. png_ptr->trans[i], back.blue);
  188909. }
  188910. }
  188911. }
  188912. else /* assume grayscale palette (what else could it be?) */
  188913. {
  188914. int i;
  188915. for (i = 0; i < num_palette; i++)
  188916. {
  188917. if (i == (png_byte)png_ptr->trans_values.gray)
  188918. {
  188919. palette[i].red = (png_byte)png_ptr->background.red;
  188920. palette[i].green = (png_byte)png_ptr->background.green;
  188921. palette[i].blue = (png_byte)png_ptr->background.blue;
  188922. }
  188923. }
  188924. }
  188925. }
  188926. #endif
  188927. }
  188928. #endif
  188929. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188930. /* Replace any alpha or transparency with the supplied background color.
  188931. * "background" is already in the screen gamma, while "background_1" is
  188932. * at a gamma of 1.0. Paletted files have already been taken care of.
  188933. */
  188934. void /* PRIVATE */
  188935. png_do_background(png_row_infop row_info, png_bytep row,
  188936. png_color_16p trans_values, png_color_16p background
  188937. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188938. , png_color_16p background_1,
  188939. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  188940. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  188941. png_uint_16pp gamma_16_to_1, int gamma_shift
  188942. #endif
  188943. )
  188944. {
  188945. png_bytep sp, dp;
  188946. png_uint_32 i;
  188947. png_uint_32 row_width=row_info->width;
  188948. int shift;
  188949. png_debug(1, "in png_do_background\n");
  188950. if (background != NULL &&
  188951. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188952. row != NULL && row_info != NULL &&
  188953. #endif
  188954. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  188955. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  188956. {
  188957. switch (row_info->color_type)
  188958. {
  188959. case PNG_COLOR_TYPE_GRAY:
  188960. {
  188961. switch (row_info->bit_depth)
  188962. {
  188963. case 1:
  188964. {
  188965. sp = row;
  188966. shift = 7;
  188967. for (i = 0; i < row_width; i++)
  188968. {
  188969. if ((png_uint_16)((*sp >> shift) & 0x01)
  188970. == trans_values->gray)
  188971. {
  188972. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  188973. *sp |= (png_byte)(background->gray << shift);
  188974. }
  188975. if (!shift)
  188976. {
  188977. shift = 7;
  188978. sp++;
  188979. }
  188980. else
  188981. shift--;
  188982. }
  188983. break;
  188984. }
  188985. case 2:
  188986. {
  188987. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188988. if (gamma_table != NULL)
  188989. {
  188990. sp = row;
  188991. shift = 6;
  188992. for (i = 0; i < row_width; i++)
  188993. {
  188994. if ((png_uint_16)((*sp >> shift) & 0x03)
  188995. == trans_values->gray)
  188996. {
  188997. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188998. *sp |= (png_byte)(background->gray << shift);
  188999. }
  189000. else
  189001. {
  189002. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  189003. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  189004. (p << 4) | (p << 6)] >> 6) & 0x03);
  189005. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189006. *sp |= (png_byte)(g << shift);
  189007. }
  189008. if (!shift)
  189009. {
  189010. shift = 6;
  189011. sp++;
  189012. }
  189013. else
  189014. shift -= 2;
  189015. }
  189016. }
  189017. else
  189018. #endif
  189019. {
  189020. sp = row;
  189021. shift = 6;
  189022. for (i = 0; i < row_width; i++)
  189023. {
  189024. if ((png_uint_16)((*sp >> shift) & 0x03)
  189025. == trans_values->gray)
  189026. {
  189027. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189028. *sp |= (png_byte)(background->gray << shift);
  189029. }
  189030. if (!shift)
  189031. {
  189032. shift = 6;
  189033. sp++;
  189034. }
  189035. else
  189036. shift -= 2;
  189037. }
  189038. }
  189039. break;
  189040. }
  189041. case 4:
  189042. {
  189043. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189044. if (gamma_table != NULL)
  189045. {
  189046. sp = row;
  189047. shift = 4;
  189048. for (i = 0; i < row_width; i++)
  189049. {
  189050. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189051. == trans_values->gray)
  189052. {
  189053. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189054. *sp |= (png_byte)(background->gray << shift);
  189055. }
  189056. else
  189057. {
  189058. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  189059. png_byte g = (png_byte)((gamma_table[p |
  189060. (p << 4)] >> 4) & 0x0f);
  189061. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189062. *sp |= (png_byte)(g << shift);
  189063. }
  189064. if (!shift)
  189065. {
  189066. shift = 4;
  189067. sp++;
  189068. }
  189069. else
  189070. shift -= 4;
  189071. }
  189072. }
  189073. else
  189074. #endif
  189075. {
  189076. sp = row;
  189077. shift = 4;
  189078. for (i = 0; i < row_width; i++)
  189079. {
  189080. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189081. == trans_values->gray)
  189082. {
  189083. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189084. *sp |= (png_byte)(background->gray << shift);
  189085. }
  189086. if (!shift)
  189087. {
  189088. shift = 4;
  189089. sp++;
  189090. }
  189091. else
  189092. shift -= 4;
  189093. }
  189094. }
  189095. break;
  189096. }
  189097. case 8:
  189098. {
  189099. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189100. if (gamma_table != NULL)
  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. else
  189110. {
  189111. *sp = gamma_table[*sp];
  189112. }
  189113. }
  189114. }
  189115. else
  189116. #endif
  189117. {
  189118. sp = row;
  189119. for (i = 0; i < row_width; i++, sp++)
  189120. {
  189121. if (*sp == trans_values->gray)
  189122. {
  189123. *sp = (png_byte)background->gray;
  189124. }
  189125. }
  189126. }
  189127. break;
  189128. }
  189129. case 16:
  189130. {
  189131. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189132. if (gamma_16 != NULL)
  189133. {
  189134. sp = row;
  189135. for (i = 0; i < row_width; i++, sp += 2)
  189136. {
  189137. png_uint_16 v;
  189138. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189139. if (v == trans_values->gray)
  189140. {
  189141. /* background is already in screen gamma */
  189142. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189143. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189144. }
  189145. else
  189146. {
  189147. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189148. *sp = (png_byte)((v >> 8) & 0xff);
  189149. *(sp + 1) = (png_byte)(v & 0xff);
  189150. }
  189151. }
  189152. }
  189153. else
  189154. #endif
  189155. {
  189156. sp = row;
  189157. for (i = 0; i < row_width; i++, sp += 2)
  189158. {
  189159. png_uint_16 v;
  189160. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189161. if (v == trans_values->gray)
  189162. {
  189163. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189164. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189165. }
  189166. }
  189167. }
  189168. break;
  189169. }
  189170. }
  189171. break;
  189172. }
  189173. case PNG_COLOR_TYPE_RGB:
  189174. {
  189175. if (row_info->bit_depth == 8)
  189176. {
  189177. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189178. if (gamma_table != NULL)
  189179. {
  189180. sp = row;
  189181. for (i = 0; i < row_width; i++, sp += 3)
  189182. {
  189183. if (*sp == trans_values->red &&
  189184. *(sp + 1) == trans_values->green &&
  189185. *(sp + 2) == trans_values->blue)
  189186. {
  189187. *sp = (png_byte)background->red;
  189188. *(sp + 1) = (png_byte)background->green;
  189189. *(sp + 2) = (png_byte)background->blue;
  189190. }
  189191. else
  189192. {
  189193. *sp = gamma_table[*sp];
  189194. *(sp + 1) = gamma_table[*(sp + 1)];
  189195. *(sp + 2) = gamma_table[*(sp + 2)];
  189196. }
  189197. }
  189198. }
  189199. else
  189200. #endif
  189201. {
  189202. sp = row;
  189203. for (i = 0; i < row_width; i++, sp += 3)
  189204. {
  189205. if (*sp == trans_values->red &&
  189206. *(sp + 1) == trans_values->green &&
  189207. *(sp + 2) == trans_values->blue)
  189208. {
  189209. *sp = (png_byte)background->red;
  189210. *(sp + 1) = (png_byte)background->green;
  189211. *(sp + 2) = (png_byte)background->blue;
  189212. }
  189213. }
  189214. }
  189215. }
  189216. else /* if (row_info->bit_depth == 16) */
  189217. {
  189218. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189219. if (gamma_16 != NULL)
  189220. {
  189221. sp = row;
  189222. for (i = 0; i < row_width; i++, sp += 6)
  189223. {
  189224. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189225. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189226. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189227. if (r == trans_values->red && g == trans_values->green &&
  189228. b == trans_values->blue)
  189229. {
  189230. /* background is already in screen gamma */
  189231. *sp = (png_byte)((background->red >> 8) & 0xff);
  189232. *(sp + 1) = (png_byte)(background->red & 0xff);
  189233. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189234. *(sp + 3) = (png_byte)(background->green & 0xff);
  189235. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189236. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189237. }
  189238. else
  189239. {
  189240. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189241. *sp = (png_byte)((v >> 8) & 0xff);
  189242. *(sp + 1) = (png_byte)(v & 0xff);
  189243. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189244. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  189245. *(sp + 3) = (png_byte)(v & 0xff);
  189246. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189247. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  189248. *(sp + 5) = (png_byte)(v & 0xff);
  189249. }
  189250. }
  189251. }
  189252. else
  189253. #endif
  189254. {
  189255. sp = row;
  189256. for (i = 0; i < row_width; i++, sp += 6)
  189257. {
  189258. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  189259. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189260. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189261. if (r == trans_values->red && g == trans_values->green &&
  189262. b == trans_values->blue)
  189263. {
  189264. *sp = (png_byte)((background->red >> 8) & 0xff);
  189265. *(sp + 1) = (png_byte)(background->red & 0xff);
  189266. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189267. *(sp + 3) = (png_byte)(background->green & 0xff);
  189268. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189269. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189270. }
  189271. }
  189272. }
  189273. }
  189274. break;
  189275. }
  189276. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189277. {
  189278. if (row_info->bit_depth == 8)
  189279. {
  189280. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189281. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189282. gamma_table != NULL)
  189283. {
  189284. sp = row;
  189285. dp = row;
  189286. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189287. {
  189288. png_uint_16 a = *(sp + 1);
  189289. if (a == 0xff)
  189290. {
  189291. *dp = gamma_table[*sp];
  189292. }
  189293. else if (a == 0)
  189294. {
  189295. /* background is already in screen gamma */
  189296. *dp = (png_byte)background->gray;
  189297. }
  189298. else
  189299. {
  189300. png_byte v, w;
  189301. v = gamma_to_1[*sp];
  189302. png_composite(w, v, a, background_1->gray);
  189303. *dp = gamma_from_1[w];
  189304. }
  189305. }
  189306. }
  189307. else
  189308. #endif
  189309. {
  189310. sp = row;
  189311. dp = row;
  189312. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189313. {
  189314. png_byte a = *(sp + 1);
  189315. if (a == 0xff)
  189316. {
  189317. *dp = *sp;
  189318. }
  189319. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189320. else if (a == 0)
  189321. {
  189322. *dp = (png_byte)background->gray;
  189323. }
  189324. else
  189325. {
  189326. png_composite(*dp, *sp, a, background_1->gray);
  189327. }
  189328. #else
  189329. *dp = (png_byte)background->gray;
  189330. #endif
  189331. }
  189332. }
  189333. }
  189334. else /* if (png_ptr->bit_depth == 16) */
  189335. {
  189336. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189337. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189338. gamma_16_to_1 != NULL)
  189339. {
  189340. sp = row;
  189341. dp = row;
  189342. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189343. {
  189344. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189345. if (a == (png_uint_16)0xffff)
  189346. {
  189347. png_uint_16 v;
  189348. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189349. *dp = (png_byte)((v >> 8) & 0xff);
  189350. *(dp + 1) = (png_byte)(v & 0xff);
  189351. }
  189352. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189353. else if (a == 0)
  189354. #else
  189355. else
  189356. #endif
  189357. {
  189358. /* background is already in screen gamma */
  189359. *dp = (png_byte)((background->gray >> 8) & 0xff);
  189360. *(dp + 1) = (png_byte)(background->gray & 0xff);
  189361. }
  189362. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189363. else
  189364. {
  189365. png_uint_16 g, v, w;
  189366. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  189367. png_composite_16(v, g, a, background_1->gray);
  189368. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  189369. *dp = (png_byte)((w >> 8) & 0xff);
  189370. *(dp + 1) = (png_byte)(w & 0xff);
  189371. }
  189372. #endif
  189373. }
  189374. }
  189375. else
  189376. #endif
  189377. {
  189378. sp = row;
  189379. dp = row;
  189380. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189381. {
  189382. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189383. if (a == (png_uint_16)0xffff)
  189384. {
  189385. png_memcpy(dp, sp, 2);
  189386. }
  189387. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189388. else if (a == 0)
  189389. #else
  189390. else
  189391. #endif
  189392. {
  189393. *dp = (png_byte)((background->gray >> 8) & 0xff);
  189394. *(dp + 1) = (png_byte)(background->gray & 0xff);
  189395. }
  189396. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189397. else
  189398. {
  189399. png_uint_16 g, v;
  189400. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189401. png_composite_16(v, g, a, background_1->gray);
  189402. *dp = (png_byte)((v >> 8) & 0xff);
  189403. *(dp + 1) = (png_byte)(v & 0xff);
  189404. }
  189405. #endif
  189406. }
  189407. }
  189408. }
  189409. break;
  189410. }
  189411. case PNG_COLOR_TYPE_RGB_ALPHA:
  189412. {
  189413. if (row_info->bit_depth == 8)
  189414. {
  189415. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189416. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189417. gamma_table != NULL)
  189418. {
  189419. sp = row;
  189420. dp = row;
  189421. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  189422. {
  189423. png_byte a = *(sp + 3);
  189424. if (a == 0xff)
  189425. {
  189426. *dp = gamma_table[*sp];
  189427. *(dp + 1) = gamma_table[*(sp + 1)];
  189428. *(dp + 2) = gamma_table[*(sp + 2)];
  189429. }
  189430. else if (a == 0)
  189431. {
  189432. /* background is already in screen gamma */
  189433. *dp = (png_byte)background->red;
  189434. *(dp + 1) = (png_byte)background->green;
  189435. *(dp + 2) = (png_byte)background->blue;
  189436. }
  189437. else
  189438. {
  189439. png_byte v, w;
  189440. v = gamma_to_1[*sp];
  189441. png_composite(w, v, a, background_1->red);
  189442. *dp = gamma_from_1[w];
  189443. v = gamma_to_1[*(sp + 1)];
  189444. png_composite(w, v, a, background_1->green);
  189445. *(dp + 1) = gamma_from_1[w];
  189446. v = gamma_to_1[*(sp + 2)];
  189447. png_composite(w, v, a, background_1->blue);
  189448. *(dp + 2) = gamma_from_1[w];
  189449. }
  189450. }
  189451. }
  189452. else
  189453. #endif
  189454. {
  189455. sp = row;
  189456. dp = row;
  189457. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  189458. {
  189459. png_byte a = *(sp + 3);
  189460. if (a == 0xff)
  189461. {
  189462. *dp = *sp;
  189463. *(dp + 1) = *(sp + 1);
  189464. *(dp + 2) = *(sp + 2);
  189465. }
  189466. else if (a == 0)
  189467. {
  189468. *dp = (png_byte)background->red;
  189469. *(dp + 1) = (png_byte)background->green;
  189470. *(dp + 2) = (png_byte)background->blue;
  189471. }
  189472. else
  189473. {
  189474. png_composite(*dp, *sp, a, background->red);
  189475. png_composite(*(dp + 1), *(sp + 1), a,
  189476. background->green);
  189477. png_composite(*(dp + 2), *(sp + 2), a,
  189478. background->blue);
  189479. }
  189480. }
  189481. }
  189482. }
  189483. else /* if (row_info->bit_depth == 16) */
  189484. {
  189485. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189486. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189487. gamma_16_to_1 != NULL)
  189488. {
  189489. sp = row;
  189490. dp = row;
  189491. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  189492. {
  189493. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  189494. << 8) + (png_uint_16)(*(sp + 7)));
  189495. if (a == (png_uint_16)0xffff)
  189496. {
  189497. png_uint_16 v;
  189498. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189499. *dp = (png_byte)((v >> 8) & 0xff);
  189500. *(dp + 1) = (png_byte)(v & 0xff);
  189501. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189502. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  189503. *(dp + 3) = (png_byte)(v & 0xff);
  189504. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189505. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  189506. *(dp + 5) = (png_byte)(v & 0xff);
  189507. }
  189508. else if (a == 0)
  189509. {
  189510. /* background is already in screen gamma */
  189511. *dp = (png_byte)((background->red >> 8) & 0xff);
  189512. *(dp + 1) = (png_byte)(background->red & 0xff);
  189513. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189514. *(dp + 3) = (png_byte)(background->green & 0xff);
  189515. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189516. *(dp + 5) = (png_byte)(background->blue & 0xff);
  189517. }
  189518. else
  189519. {
  189520. png_uint_16 v, w, x;
  189521. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  189522. png_composite_16(w, v, a, background_1->red);
  189523. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  189524. *dp = (png_byte)((x >> 8) & 0xff);
  189525. *(dp + 1) = (png_byte)(x & 0xff);
  189526. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189527. png_composite_16(w, v, a, background_1->green);
  189528. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  189529. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  189530. *(dp + 3) = (png_byte)(x & 0xff);
  189531. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189532. png_composite_16(w, v, a, background_1->blue);
  189533. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  189534. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  189535. *(dp + 5) = (png_byte)(x & 0xff);
  189536. }
  189537. }
  189538. }
  189539. else
  189540. #endif
  189541. {
  189542. sp = row;
  189543. dp = row;
  189544. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  189545. {
  189546. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  189547. << 8) + (png_uint_16)(*(sp + 7)));
  189548. if (a == (png_uint_16)0xffff)
  189549. {
  189550. png_memcpy(dp, sp, 6);
  189551. }
  189552. else if (a == 0)
  189553. {
  189554. *dp = (png_byte)((background->red >> 8) & 0xff);
  189555. *(dp + 1) = (png_byte)(background->red & 0xff);
  189556. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189557. *(dp + 3) = (png_byte)(background->green & 0xff);
  189558. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189559. *(dp + 5) = (png_byte)(background->blue & 0xff);
  189560. }
  189561. else
  189562. {
  189563. png_uint_16 v;
  189564. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189565. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  189566. + *(sp + 3));
  189567. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  189568. + *(sp + 5));
  189569. png_composite_16(v, r, a, background->red);
  189570. *dp = (png_byte)((v >> 8) & 0xff);
  189571. *(dp + 1) = (png_byte)(v & 0xff);
  189572. png_composite_16(v, g, a, background->green);
  189573. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  189574. *(dp + 3) = (png_byte)(v & 0xff);
  189575. png_composite_16(v, b, a, background->blue);
  189576. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  189577. *(dp + 5) = (png_byte)(v & 0xff);
  189578. }
  189579. }
  189580. }
  189581. }
  189582. break;
  189583. }
  189584. }
  189585. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  189586. {
  189587. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  189588. row_info->channels--;
  189589. row_info->pixel_depth = (png_byte)(row_info->channels *
  189590. row_info->bit_depth);
  189591. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189592. }
  189593. }
  189594. }
  189595. #endif
  189596. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189597. /* Gamma correct the image, avoiding the alpha channel. Make sure
  189598. * you do this after you deal with the transparency issue on grayscale
  189599. * or RGB images. If your bit depth is 8, use gamma_table, if it
  189600. * is 16, use gamma_16_table and gamma_shift. Build these with
  189601. * build_gamma_table().
  189602. */
  189603. void /* PRIVATE */
  189604. png_do_gamma(png_row_infop row_info, png_bytep row,
  189605. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  189606. int gamma_shift)
  189607. {
  189608. png_bytep sp;
  189609. png_uint_32 i;
  189610. png_uint_32 row_width=row_info->width;
  189611. png_debug(1, "in png_do_gamma\n");
  189612. if (
  189613. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189614. row != NULL && row_info != NULL &&
  189615. #endif
  189616. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  189617. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  189618. {
  189619. switch (row_info->color_type)
  189620. {
  189621. case PNG_COLOR_TYPE_RGB:
  189622. {
  189623. if (row_info->bit_depth == 8)
  189624. {
  189625. sp = row;
  189626. for (i = 0; i < row_width; i++)
  189627. {
  189628. *sp = gamma_table[*sp];
  189629. sp++;
  189630. *sp = gamma_table[*sp];
  189631. sp++;
  189632. *sp = gamma_table[*sp];
  189633. sp++;
  189634. }
  189635. }
  189636. else /* if (row_info->bit_depth == 16) */
  189637. {
  189638. sp = row;
  189639. for (i = 0; i < row_width; i++)
  189640. {
  189641. png_uint_16 v;
  189642. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189643. *sp = (png_byte)((v >> 8) & 0xff);
  189644. *(sp + 1) = (png_byte)(v & 0xff);
  189645. sp += 2;
  189646. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189647. *sp = (png_byte)((v >> 8) & 0xff);
  189648. *(sp + 1) = (png_byte)(v & 0xff);
  189649. sp += 2;
  189650. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189651. *sp = (png_byte)((v >> 8) & 0xff);
  189652. *(sp + 1) = (png_byte)(v & 0xff);
  189653. sp += 2;
  189654. }
  189655. }
  189656. break;
  189657. }
  189658. case PNG_COLOR_TYPE_RGB_ALPHA:
  189659. {
  189660. if (row_info->bit_depth == 8)
  189661. {
  189662. sp = row;
  189663. for (i = 0; i < row_width; i++)
  189664. {
  189665. *sp = gamma_table[*sp];
  189666. sp++;
  189667. *sp = gamma_table[*sp];
  189668. sp++;
  189669. *sp = gamma_table[*sp];
  189670. sp++;
  189671. sp++;
  189672. }
  189673. }
  189674. else /* if (row_info->bit_depth == 16) */
  189675. {
  189676. sp = row;
  189677. for (i = 0; i < row_width; i++)
  189678. {
  189679. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189680. *sp = (png_byte)((v >> 8) & 0xff);
  189681. *(sp + 1) = (png_byte)(v & 0xff);
  189682. sp += 2;
  189683. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189684. *sp = (png_byte)((v >> 8) & 0xff);
  189685. *(sp + 1) = (png_byte)(v & 0xff);
  189686. sp += 2;
  189687. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189688. *sp = (png_byte)((v >> 8) & 0xff);
  189689. *(sp + 1) = (png_byte)(v & 0xff);
  189690. sp += 4;
  189691. }
  189692. }
  189693. break;
  189694. }
  189695. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189696. {
  189697. if (row_info->bit_depth == 8)
  189698. {
  189699. sp = row;
  189700. for (i = 0; i < row_width; i++)
  189701. {
  189702. *sp = gamma_table[*sp];
  189703. sp += 2;
  189704. }
  189705. }
  189706. else /* if (row_info->bit_depth == 16) */
  189707. {
  189708. sp = row;
  189709. for (i = 0; i < row_width; i++)
  189710. {
  189711. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189712. *sp = (png_byte)((v >> 8) & 0xff);
  189713. *(sp + 1) = (png_byte)(v & 0xff);
  189714. sp += 4;
  189715. }
  189716. }
  189717. break;
  189718. }
  189719. case PNG_COLOR_TYPE_GRAY:
  189720. {
  189721. if (row_info->bit_depth == 2)
  189722. {
  189723. sp = row;
  189724. for (i = 0; i < row_width; i += 4)
  189725. {
  189726. int a = *sp & 0xc0;
  189727. int b = *sp & 0x30;
  189728. int c = *sp & 0x0c;
  189729. int d = *sp & 0x03;
  189730. *sp = (png_byte)(
  189731. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  189732. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  189733. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  189734. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  189735. sp++;
  189736. }
  189737. }
  189738. if (row_info->bit_depth == 4)
  189739. {
  189740. sp = row;
  189741. for (i = 0; i < row_width; i += 2)
  189742. {
  189743. int msb = *sp & 0xf0;
  189744. int lsb = *sp & 0x0f;
  189745. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  189746. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  189747. sp++;
  189748. }
  189749. }
  189750. else if (row_info->bit_depth == 8)
  189751. {
  189752. sp = row;
  189753. for (i = 0; i < row_width; i++)
  189754. {
  189755. *sp = gamma_table[*sp];
  189756. sp++;
  189757. }
  189758. }
  189759. else if (row_info->bit_depth == 16)
  189760. {
  189761. sp = row;
  189762. for (i = 0; i < row_width; i++)
  189763. {
  189764. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189765. *sp = (png_byte)((v >> 8) & 0xff);
  189766. *(sp + 1) = (png_byte)(v & 0xff);
  189767. sp += 2;
  189768. }
  189769. }
  189770. break;
  189771. }
  189772. }
  189773. }
  189774. }
  189775. #endif
  189776. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189777. /* Expands a palette row to an RGB or RGBA row depending
  189778. * upon whether you supply trans and num_trans.
  189779. */
  189780. void /* PRIVATE */
  189781. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  189782. png_colorp palette, png_bytep trans, int num_trans)
  189783. {
  189784. int shift, value;
  189785. png_bytep sp, dp;
  189786. png_uint_32 i;
  189787. png_uint_32 row_width=row_info->width;
  189788. png_debug(1, "in png_do_expand_palette\n");
  189789. if (
  189790. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189791. row != NULL && row_info != NULL &&
  189792. #endif
  189793. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  189794. {
  189795. if (row_info->bit_depth < 8)
  189796. {
  189797. switch (row_info->bit_depth)
  189798. {
  189799. case 1:
  189800. {
  189801. sp = row + (png_size_t)((row_width - 1) >> 3);
  189802. dp = row + (png_size_t)row_width - 1;
  189803. shift = 7 - (int)((row_width + 7) & 0x07);
  189804. for (i = 0; i < row_width; i++)
  189805. {
  189806. if ((*sp >> shift) & 0x01)
  189807. *dp = 1;
  189808. else
  189809. *dp = 0;
  189810. if (shift == 7)
  189811. {
  189812. shift = 0;
  189813. sp--;
  189814. }
  189815. else
  189816. shift++;
  189817. dp--;
  189818. }
  189819. break;
  189820. }
  189821. case 2:
  189822. {
  189823. sp = row + (png_size_t)((row_width - 1) >> 2);
  189824. dp = row + (png_size_t)row_width - 1;
  189825. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189826. for (i = 0; i < row_width; i++)
  189827. {
  189828. value = (*sp >> shift) & 0x03;
  189829. *dp = (png_byte)value;
  189830. if (shift == 6)
  189831. {
  189832. shift = 0;
  189833. sp--;
  189834. }
  189835. else
  189836. shift += 2;
  189837. dp--;
  189838. }
  189839. break;
  189840. }
  189841. case 4:
  189842. {
  189843. sp = row + (png_size_t)((row_width - 1) >> 1);
  189844. dp = row + (png_size_t)row_width - 1;
  189845. shift = (int)((row_width & 0x01) << 2);
  189846. for (i = 0; i < row_width; i++)
  189847. {
  189848. value = (*sp >> shift) & 0x0f;
  189849. *dp = (png_byte)value;
  189850. if (shift == 4)
  189851. {
  189852. shift = 0;
  189853. sp--;
  189854. }
  189855. else
  189856. shift += 4;
  189857. dp--;
  189858. }
  189859. break;
  189860. }
  189861. }
  189862. row_info->bit_depth = 8;
  189863. row_info->pixel_depth = 8;
  189864. row_info->rowbytes = row_width;
  189865. }
  189866. switch (row_info->bit_depth)
  189867. {
  189868. case 8:
  189869. {
  189870. if (trans != NULL)
  189871. {
  189872. sp = row + (png_size_t)row_width - 1;
  189873. dp = row + (png_size_t)(row_width << 2) - 1;
  189874. for (i = 0; i < row_width; i++)
  189875. {
  189876. if ((int)(*sp) >= num_trans)
  189877. *dp-- = 0xff;
  189878. else
  189879. *dp-- = trans[*sp];
  189880. *dp-- = palette[*sp].blue;
  189881. *dp-- = palette[*sp].green;
  189882. *dp-- = palette[*sp].red;
  189883. sp--;
  189884. }
  189885. row_info->bit_depth = 8;
  189886. row_info->pixel_depth = 32;
  189887. row_info->rowbytes = row_width * 4;
  189888. row_info->color_type = 6;
  189889. row_info->channels = 4;
  189890. }
  189891. else
  189892. {
  189893. sp = row + (png_size_t)row_width - 1;
  189894. dp = row + (png_size_t)(row_width * 3) - 1;
  189895. for (i = 0; i < row_width; i++)
  189896. {
  189897. *dp-- = palette[*sp].blue;
  189898. *dp-- = palette[*sp].green;
  189899. *dp-- = palette[*sp].red;
  189900. sp--;
  189901. }
  189902. row_info->bit_depth = 8;
  189903. row_info->pixel_depth = 24;
  189904. row_info->rowbytes = row_width * 3;
  189905. row_info->color_type = 2;
  189906. row_info->channels = 3;
  189907. }
  189908. break;
  189909. }
  189910. }
  189911. }
  189912. }
  189913. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  189914. * expanded transparency value is supplied, an alpha channel is built.
  189915. */
  189916. void /* PRIVATE */
  189917. png_do_expand(png_row_infop row_info, png_bytep row,
  189918. png_color_16p trans_value)
  189919. {
  189920. int shift, value;
  189921. png_bytep sp, dp;
  189922. png_uint_32 i;
  189923. png_uint_32 row_width=row_info->width;
  189924. png_debug(1, "in png_do_expand\n");
  189925. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189926. if (row != NULL && row_info != NULL)
  189927. #endif
  189928. {
  189929. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  189930. {
  189931. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  189932. if (row_info->bit_depth < 8)
  189933. {
  189934. switch (row_info->bit_depth)
  189935. {
  189936. case 1:
  189937. {
  189938. gray = (png_uint_16)((gray&0x01)*0xff);
  189939. sp = row + (png_size_t)((row_width - 1) >> 3);
  189940. dp = row + (png_size_t)row_width - 1;
  189941. shift = 7 - (int)((row_width + 7) & 0x07);
  189942. for (i = 0; i < row_width; i++)
  189943. {
  189944. if ((*sp >> shift) & 0x01)
  189945. *dp = 0xff;
  189946. else
  189947. *dp = 0;
  189948. if (shift == 7)
  189949. {
  189950. shift = 0;
  189951. sp--;
  189952. }
  189953. else
  189954. shift++;
  189955. dp--;
  189956. }
  189957. break;
  189958. }
  189959. case 2:
  189960. {
  189961. gray = (png_uint_16)((gray&0x03)*0x55);
  189962. sp = row + (png_size_t)((row_width - 1) >> 2);
  189963. dp = row + (png_size_t)row_width - 1;
  189964. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189965. for (i = 0; i < row_width; i++)
  189966. {
  189967. value = (*sp >> shift) & 0x03;
  189968. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  189969. (value << 6));
  189970. if (shift == 6)
  189971. {
  189972. shift = 0;
  189973. sp--;
  189974. }
  189975. else
  189976. shift += 2;
  189977. dp--;
  189978. }
  189979. break;
  189980. }
  189981. case 4:
  189982. {
  189983. gray = (png_uint_16)((gray&0x0f)*0x11);
  189984. sp = row + (png_size_t)((row_width - 1) >> 1);
  189985. dp = row + (png_size_t)row_width - 1;
  189986. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  189987. for (i = 0; i < row_width; i++)
  189988. {
  189989. value = (*sp >> shift) & 0x0f;
  189990. *dp = (png_byte)(value | (value << 4));
  189991. if (shift == 4)
  189992. {
  189993. shift = 0;
  189994. sp--;
  189995. }
  189996. else
  189997. shift = 4;
  189998. dp--;
  189999. }
  190000. break;
  190001. }
  190002. }
  190003. row_info->bit_depth = 8;
  190004. row_info->pixel_depth = 8;
  190005. row_info->rowbytes = row_width;
  190006. }
  190007. if (trans_value != NULL)
  190008. {
  190009. if (row_info->bit_depth == 8)
  190010. {
  190011. gray = gray & 0xff;
  190012. sp = row + (png_size_t)row_width - 1;
  190013. dp = row + (png_size_t)(row_width << 1) - 1;
  190014. for (i = 0; i < row_width; i++)
  190015. {
  190016. if (*sp == gray)
  190017. *dp-- = 0;
  190018. else
  190019. *dp-- = 0xff;
  190020. *dp-- = *sp--;
  190021. }
  190022. }
  190023. else if (row_info->bit_depth == 16)
  190024. {
  190025. png_byte gray_high = (gray >> 8) & 0xff;
  190026. png_byte gray_low = gray & 0xff;
  190027. sp = row + row_info->rowbytes - 1;
  190028. dp = row + (row_info->rowbytes << 1) - 1;
  190029. for (i = 0; i < row_width; i++)
  190030. {
  190031. if (*(sp-1) == gray_high && *(sp) == gray_low)
  190032. {
  190033. *dp-- = 0;
  190034. *dp-- = 0;
  190035. }
  190036. else
  190037. {
  190038. *dp-- = 0xff;
  190039. *dp-- = 0xff;
  190040. }
  190041. *dp-- = *sp--;
  190042. *dp-- = *sp--;
  190043. }
  190044. }
  190045. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  190046. row_info->channels = 2;
  190047. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  190048. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  190049. row_width);
  190050. }
  190051. }
  190052. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  190053. {
  190054. if (row_info->bit_depth == 8)
  190055. {
  190056. png_byte red = trans_value->red & 0xff;
  190057. png_byte green = trans_value->green & 0xff;
  190058. png_byte blue = trans_value->blue & 0xff;
  190059. sp = row + (png_size_t)row_info->rowbytes - 1;
  190060. dp = row + (png_size_t)(row_width << 2) - 1;
  190061. for (i = 0; i < row_width; i++)
  190062. {
  190063. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  190064. *dp-- = 0;
  190065. else
  190066. *dp-- = 0xff;
  190067. *dp-- = *sp--;
  190068. *dp-- = *sp--;
  190069. *dp-- = *sp--;
  190070. }
  190071. }
  190072. else if (row_info->bit_depth == 16)
  190073. {
  190074. png_byte red_high = (trans_value->red >> 8) & 0xff;
  190075. png_byte green_high = (trans_value->green >> 8) & 0xff;
  190076. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  190077. png_byte red_low = trans_value->red & 0xff;
  190078. png_byte green_low = trans_value->green & 0xff;
  190079. png_byte blue_low = trans_value->blue & 0xff;
  190080. sp = row + row_info->rowbytes - 1;
  190081. dp = row + (png_size_t)(row_width << 3) - 1;
  190082. for (i = 0; i < row_width; i++)
  190083. {
  190084. if (*(sp - 5) == red_high &&
  190085. *(sp - 4) == red_low &&
  190086. *(sp - 3) == green_high &&
  190087. *(sp - 2) == green_low &&
  190088. *(sp - 1) == blue_high &&
  190089. *(sp ) == blue_low)
  190090. {
  190091. *dp-- = 0;
  190092. *dp-- = 0;
  190093. }
  190094. else
  190095. {
  190096. *dp-- = 0xff;
  190097. *dp-- = 0xff;
  190098. }
  190099. *dp-- = *sp--;
  190100. *dp-- = *sp--;
  190101. *dp-- = *sp--;
  190102. *dp-- = *sp--;
  190103. *dp-- = *sp--;
  190104. *dp-- = *sp--;
  190105. }
  190106. }
  190107. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190108. row_info->channels = 4;
  190109. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  190110. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190111. }
  190112. }
  190113. }
  190114. #endif
  190115. #if defined(PNG_READ_DITHER_SUPPORTED)
  190116. void /* PRIVATE */
  190117. png_do_dither(png_row_infop row_info, png_bytep row,
  190118. png_bytep palette_lookup, png_bytep dither_lookup)
  190119. {
  190120. png_bytep sp, dp;
  190121. png_uint_32 i;
  190122. png_uint_32 row_width=row_info->width;
  190123. png_debug(1, "in png_do_dither\n");
  190124. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190125. if (row != NULL && row_info != NULL)
  190126. #endif
  190127. {
  190128. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  190129. palette_lookup && row_info->bit_depth == 8)
  190130. {
  190131. int r, g, b, p;
  190132. sp = row;
  190133. dp = row;
  190134. for (i = 0; i < row_width; i++)
  190135. {
  190136. r = *sp++;
  190137. g = *sp++;
  190138. b = *sp++;
  190139. /* this looks real messy, but the compiler will reduce
  190140. it down to a reasonable formula. For example, with
  190141. 5 bits per color, we get:
  190142. p = (((r >> 3) & 0x1f) << 10) |
  190143. (((g >> 3) & 0x1f) << 5) |
  190144. ((b >> 3) & 0x1f);
  190145. */
  190146. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190147. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190148. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190149. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190150. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190151. (PNG_DITHER_BLUE_BITS)) |
  190152. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190153. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190154. *dp++ = palette_lookup[p];
  190155. }
  190156. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190157. row_info->channels = 1;
  190158. row_info->pixel_depth = row_info->bit_depth;
  190159. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190160. }
  190161. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  190162. palette_lookup != NULL && row_info->bit_depth == 8)
  190163. {
  190164. int r, g, b, p;
  190165. sp = row;
  190166. dp = row;
  190167. for (i = 0; i < row_width; i++)
  190168. {
  190169. r = *sp++;
  190170. g = *sp++;
  190171. b = *sp++;
  190172. sp++;
  190173. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190174. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190175. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190176. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190177. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190178. (PNG_DITHER_BLUE_BITS)) |
  190179. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190180. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190181. *dp++ = palette_lookup[p];
  190182. }
  190183. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190184. row_info->channels = 1;
  190185. row_info->pixel_depth = row_info->bit_depth;
  190186. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190187. }
  190188. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  190189. dither_lookup && row_info->bit_depth == 8)
  190190. {
  190191. sp = row;
  190192. for (i = 0; i < row_width; i++, sp++)
  190193. {
  190194. *sp = dither_lookup[*sp];
  190195. }
  190196. }
  190197. }
  190198. }
  190199. #endif
  190200. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190201. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190202. static PNG_CONST int png_gamma_shift[] =
  190203. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  190204. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  190205. * tables, we don't make a full table if we are reducing to 8-bit in
  190206. * the future. Note also how the gamma_16 tables are segmented so that
  190207. * we don't need to allocate > 64K chunks for a full 16-bit table.
  190208. */
  190209. void /* PRIVATE */
  190210. png_build_gamma_table(png_structp png_ptr)
  190211. {
  190212. png_debug(1, "in png_build_gamma_table\n");
  190213. if (png_ptr->bit_depth <= 8)
  190214. {
  190215. int i;
  190216. double g;
  190217. if (png_ptr->screen_gamma > .000001)
  190218. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190219. else
  190220. g = 1.0;
  190221. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  190222. (png_uint_32)256);
  190223. for (i = 0; i < 256; i++)
  190224. {
  190225. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  190226. g) * 255.0 + .5);
  190227. }
  190228. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190229. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190230. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  190231. {
  190232. g = 1.0 / (png_ptr->gamma);
  190233. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  190234. (png_uint_32)256);
  190235. for (i = 0; i < 256; i++)
  190236. {
  190237. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  190238. g) * 255.0 + .5);
  190239. }
  190240. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  190241. (png_uint_32)256);
  190242. if(png_ptr->screen_gamma > 0.000001)
  190243. g = 1.0 / png_ptr->screen_gamma;
  190244. else
  190245. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190246. for (i = 0; i < 256; i++)
  190247. {
  190248. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  190249. g) * 255.0 + .5);
  190250. }
  190251. }
  190252. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190253. }
  190254. else
  190255. {
  190256. double g;
  190257. int i, j, shift, num;
  190258. int sig_bit;
  190259. png_uint_32 ig;
  190260. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190261. {
  190262. sig_bit = (int)png_ptr->sig_bit.red;
  190263. if ((int)png_ptr->sig_bit.green > sig_bit)
  190264. sig_bit = png_ptr->sig_bit.green;
  190265. if ((int)png_ptr->sig_bit.blue > sig_bit)
  190266. sig_bit = png_ptr->sig_bit.blue;
  190267. }
  190268. else
  190269. {
  190270. sig_bit = (int)png_ptr->sig_bit.gray;
  190271. }
  190272. if (sig_bit > 0)
  190273. shift = 16 - sig_bit;
  190274. else
  190275. shift = 0;
  190276. if (png_ptr->transformations & PNG_16_TO_8)
  190277. {
  190278. if (shift < (16 - PNG_MAX_GAMMA_8))
  190279. shift = (16 - PNG_MAX_GAMMA_8);
  190280. }
  190281. if (shift > 8)
  190282. shift = 8;
  190283. if (shift < 0)
  190284. shift = 0;
  190285. png_ptr->gamma_shift = (png_byte)shift;
  190286. num = (1 << (8 - shift));
  190287. if (png_ptr->screen_gamma > .000001)
  190288. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190289. else
  190290. g = 1.0;
  190291. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  190292. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190293. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  190294. {
  190295. double fin, fout;
  190296. png_uint_32 last, max;
  190297. for (i = 0; i < num; i++)
  190298. {
  190299. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190300. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190301. }
  190302. g = 1.0 / g;
  190303. last = 0;
  190304. for (i = 0; i < 256; i++)
  190305. {
  190306. fout = ((double)i + 0.5) / 256.0;
  190307. fin = pow(fout, g);
  190308. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  190309. while (last <= max)
  190310. {
  190311. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190312. [(int)(last >> (8 - shift))] = (png_uint_16)(
  190313. (png_uint_16)i | ((png_uint_16)i << 8));
  190314. last++;
  190315. }
  190316. }
  190317. while (last < ((png_uint_32)num << 8))
  190318. {
  190319. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190320. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  190321. last++;
  190322. }
  190323. }
  190324. else
  190325. {
  190326. for (i = 0; i < num; i++)
  190327. {
  190328. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190329. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190330. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  190331. for (j = 0; j < 256; j++)
  190332. {
  190333. png_ptr->gamma_16_table[i][j] =
  190334. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190335. 65535.0, g) * 65535.0 + .5);
  190336. }
  190337. }
  190338. }
  190339. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190340. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190341. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  190342. {
  190343. g = 1.0 / (png_ptr->gamma);
  190344. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  190345. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  190346. for (i = 0; i < num; i++)
  190347. {
  190348. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190349. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190350. ig = (((png_uint_32)i *
  190351. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190352. for (j = 0; j < 256; j++)
  190353. {
  190354. png_ptr->gamma_16_to_1[i][j] =
  190355. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190356. 65535.0, g) * 65535.0 + .5);
  190357. }
  190358. }
  190359. if(png_ptr->screen_gamma > 0.000001)
  190360. g = 1.0 / png_ptr->screen_gamma;
  190361. else
  190362. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190363. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  190364. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190365. for (i = 0; i < num; i++)
  190366. {
  190367. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190368. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190369. ig = (((png_uint_32)i *
  190370. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190371. for (j = 0; j < 256; j++)
  190372. {
  190373. png_ptr->gamma_16_from_1[i][j] =
  190374. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190375. 65535.0, g) * 65535.0 + .5);
  190376. }
  190377. }
  190378. }
  190379. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190380. }
  190381. }
  190382. #endif
  190383. /* To do: install integer version of png_build_gamma_table here */
  190384. #endif
  190385. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190386. /* undoes intrapixel differencing */
  190387. void /* PRIVATE */
  190388. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  190389. {
  190390. png_debug(1, "in png_do_read_intrapixel\n");
  190391. if (
  190392. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190393. row != NULL && row_info != NULL &&
  190394. #endif
  190395. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  190396. {
  190397. int bytes_per_pixel;
  190398. png_uint_32 row_width = row_info->width;
  190399. if (row_info->bit_depth == 8)
  190400. {
  190401. png_bytep rp;
  190402. png_uint_32 i;
  190403. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190404. bytes_per_pixel = 3;
  190405. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190406. bytes_per_pixel = 4;
  190407. else
  190408. return;
  190409. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  190410. {
  190411. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  190412. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  190413. }
  190414. }
  190415. else if (row_info->bit_depth == 16)
  190416. {
  190417. png_bytep rp;
  190418. png_uint_32 i;
  190419. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190420. bytes_per_pixel = 6;
  190421. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190422. bytes_per_pixel = 8;
  190423. else
  190424. return;
  190425. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  190426. {
  190427. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  190428. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  190429. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  190430. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  190431. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  190432. *(rp ) = (png_byte)((red >> 8) & 0xff);
  190433. *(rp+1) = (png_byte)(red & 0xff);
  190434. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  190435. *(rp+5) = (png_byte)(blue & 0xff);
  190436. }
  190437. }
  190438. }
  190439. }
  190440. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  190441. #endif /* PNG_READ_SUPPORTED */
  190442. /*** End of inlined file: pngrtran.c ***/
  190443. /*** Start of inlined file: pngrutil.c ***/
  190444. /* pngrutil.c - utilities to read a PNG file
  190445. *
  190446. * Last changed in libpng 1.2.21 [October 4, 2007]
  190447. * For conditions of distribution and use, see copyright notice in png.h
  190448. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190449. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190450. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190451. *
  190452. * This file contains routines that are only called from within
  190453. * libpng itself during the course of reading an image.
  190454. */
  190455. #define PNG_INTERNAL
  190456. #if defined(PNG_READ_SUPPORTED)
  190457. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  190458. # define WIN32_WCE_OLD
  190459. #endif
  190460. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190461. # if defined(WIN32_WCE_OLD)
  190462. /* strtod() function is not supported on WindowsCE */
  190463. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  190464. {
  190465. double result = 0;
  190466. int len;
  190467. wchar_t *str, *end;
  190468. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  190469. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  190470. if ( NULL != str )
  190471. {
  190472. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  190473. result = wcstod(str, &end);
  190474. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  190475. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  190476. png_free(png_ptr, str);
  190477. }
  190478. return result;
  190479. }
  190480. # else
  190481. # define png_strtod(p,a,b) strtod(a,b)
  190482. # endif
  190483. #endif
  190484. png_uint_32 PNGAPI
  190485. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  190486. {
  190487. png_uint_32 i = png_get_uint_32(buf);
  190488. if (i > PNG_UINT_31_MAX)
  190489. png_error(png_ptr, "PNG unsigned integer out of range.");
  190490. return (i);
  190491. }
  190492. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  190493. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  190494. png_uint_32 PNGAPI
  190495. png_get_uint_32(png_bytep buf)
  190496. {
  190497. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  190498. ((png_uint_32)(*(buf + 1)) << 16) +
  190499. ((png_uint_32)(*(buf + 2)) << 8) +
  190500. (png_uint_32)(*(buf + 3));
  190501. return (i);
  190502. }
  190503. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  190504. * data is stored in the PNG file in two's complement format, and it is
  190505. * assumed that the machine format for signed integers is the same. */
  190506. png_int_32 PNGAPI
  190507. png_get_int_32(png_bytep buf)
  190508. {
  190509. png_int_32 i = ((png_int_32)(*buf) << 24) +
  190510. ((png_int_32)(*(buf + 1)) << 16) +
  190511. ((png_int_32)(*(buf + 2)) << 8) +
  190512. (png_int_32)(*(buf + 3));
  190513. return (i);
  190514. }
  190515. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  190516. png_uint_16 PNGAPI
  190517. png_get_uint_16(png_bytep buf)
  190518. {
  190519. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  190520. (png_uint_16)(*(buf + 1)));
  190521. return (i);
  190522. }
  190523. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  190524. /* Read data, and (optionally) run it through the CRC. */
  190525. void /* PRIVATE */
  190526. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  190527. {
  190528. if(png_ptr == NULL) return;
  190529. png_read_data(png_ptr, buf, length);
  190530. png_calculate_crc(png_ptr, buf, length);
  190531. }
  190532. /* Optionally skip data and then check the CRC. Depending on whether we
  190533. are reading a ancillary or critical chunk, and how the program has set
  190534. things up, we may calculate the CRC on the data and print a message.
  190535. Returns '1' if there was a CRC error, '0' otherwise. */
  190536. int /* PRIVATE */
  190537. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  190538. {
  190539. png_size_t i;
  190540. png_size_t istop = png_ptr->zbuf_size;
  190541. for (i = (png_size_t)skip; i > istop; i -= istop)
  190542. {
  190543. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  190544. }
  190545. if (i)
  190546. {
  190547. png_crc_read(png_ptr, png_ptr->zbuf, i);
  190548. }
  190549. if (png_crc_error(png_ptr))
  190550. {
  190551. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  190552. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  190553. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  190554. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  190555. {
  190556. png_chunk_warning(png_ptr, "CRC error");
  190557. }
  190558. else
  190559. {
  190560. png_chunk_error(png_ptr, "CRC error");
  190561. }
  190562. return (1);
  190563. }
  190564. return (0);
  190565. }
  190566. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  190567. the data it has read thus far. */
  190568. int /* PRIVATE */
  190569. png_crc_error(png_structp png_ptr)
  190570. {
  190571. png_byte crc_bytes[4];
  190572. png_uint_32 crc;
  190573. int need_crc = 1;
  190574. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  190575. {
  190576. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  190577. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  190578. need_crc = 0;
  190579. }
  190580. else /* critical */
  190581. {
  190582. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  190583. need_crc = 0;
  190584. }
  190585. png_read_data(png_ptr, crc_bytes, 4);
  190586. if (need_crc)
  190587. {
  190588. crc = png_get_uint_32(crc_bytes);
  190589. return ((int)(crc != png_ptr->crc));
  190590. }
  190591. else
  190592. return (0);
  190593. }
  190594. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  190595. defined(PNG_READ_iCCP_SUPPORTED)
  190596. /*
  190597. * Decompress trailing data in a chunk. The assumption is that chunkdata
  190598. * points at an allocated area holding the contents of a chunk with a
  190599. * trailing compressed part. What we get back is an allocated area
  190600. * holding the original prefix part and an uncompressed version of the
  190601. * trailing part (the malloc area passed in is freed).
  190602. */
  190603. png_charp /* PRIVATE */
  190604. png_decompress_chunk(png_structp png_ptr, int comp_type,
  190605. png_charp chunkdata, png_size_t chunklength,
  190606. png_size_t prefix_size, png_size_t *newlength)
  190607. {
  190608. static PNG_CONST char msg[] = "Error decoding compressed text";
  190609. png_charp text;
  190610. png_size_t text_size;
  190611. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  190612. {
  190613. int ret = Z_OK;
  190614. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  190615. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  190616. png_ptr->zstream.next_out = png_ptr->zbuf;
  190617. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  190618. text_size = 0;
  190619. text = NULL;
  190620. while (png_ptr->zstream.avail_in)
  190621. {
  190622. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190623. if (ret != Z_OK && ret != Z_STREAM_END)
  190624. {
  190625. if (png_ptr->zstream.msg != NULL)
  190626. png_warning(png_ptr, png_ptr->zstream.msg);
  190627. else
  190628. png_warning(png_ptr, msg);
  190629. inflateReset(&png_ptr->zstream);
  190630. png_ptr->zstream.avail_in = 0;
  190631. if (text == NULL)
  190632. {
  190633. text_size = prefix_size + png_sizeof(msg) + 1;
  190634. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  190635. if (text == NULL)
  190636. {
  190637. png_free(png_ptr,chunkdata);
  190638. png_error(png_ptr,"Not enough memory to decompress chunk");
  190639. }
  190640. png_memcpy(text, chunkdata, prefix_size);
  190641. }
  190642. text[text_size - 1] = 0x00;
  190643. /* Copy what we can of the error message into the text chunk */
  190644. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  190645. text_size = png_sizeof(msg) > text_size ? text_size :
  190646. png_sizeof(msg);
  190647. png_memcpy(text + prefix_size, msg, text_size + 1);
  190648. break;
  190649. }
  190650. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  190651. {
  190652. if (text == NULL)
  190653. {
  190654. text_size = prefix_size +
  190655. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  190656. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  190657. if (text == NULL)
  190658. {
  190659. png_free(png_ptr,chunkdata);
  190660. png_error(png_ptr,"Not enough memory to decompress chunk.");
  190661. }
  190662. png_memcpy(text + prefix_size, png_ptr->zbuf,
  190663. text_size - prefix_size);
  190664. png_memcpy(text, chunkdata, prefix_size);
  190665. *(text + text_size) = 0x00;
  190666. }
  190667. else
  190668. {
  190669. png_charp tmp;
  190670. tmp = text;
  190671. text = (png_charp)png_malloc_warn(png_ptr,
  190672. (png_uint_32)(text_size +
  190673. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  190674. if (text == NULL)
  190675. {
  190676. png_free(png_ptr, tmp);
  190677. png_free(png_ptr, chunkdata);
  190678. png_error(png_ptr,"Not enough memory to decompress chunk..");
  190679. }
  190680. png_memcpy(text, tmp, text_size);
  190681. png_free(png_ptr, tmp);
  190682. png_memcpy(text + text_size, png_ptr->zbuf,
  190683. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  190684. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  190685. *(text + text_size) = 0x00;
  190686. }
  190687. if (ret == Z_STREAM_END)
  190688. break;
  190689. else
  190690. {
  190691. png_ptr->zstream.next_out = png_ptr->zbuf;
  190692. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  190693. }
  190694. }
  190695. }
  190696. if (ret != Z_STREAM_END)
  190697. {
  190698. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190699. char umsg[52];
  190700. if (ret == Z_BUF_ERROR)
  190701. png_snprintf(umsg, 52,
  190702. "Buffer error in compressed datastream in %s chunk",
  190703. png_ptr->chunk_name);
  190704. else if (ret == Z_DATA_ERROR)
  190705. png_snprintf(umsg, 52,
  190706. "Data error in compressed datastream in %s chunk",
  190707. png_ptr->chunk_name);
  190708. else
  190709. png_snprintf(umsg, 52,
  190710. "Incomplete compressed datastream in %s chunk",
  190711. png_ptr->chunk_name);
  190712. png_warning(png_ptr, umsg);
  190713. #else
  190714. png_warning(png_ptr,
  190715. "Incomplete compressed datastream in chunk other than IDAT");
  190716. #endif
  190717. text_size=prefix_size;
  190718. if (text == NULL)
  190719. {
  190720. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  190721. if (text == NULL)
  190722. {
  190723. png_free(png_ptr, chunkdata);
  190724. png_error(png_ptr,"Not enough memory for text.");
  190725. }
  190726. png_memcpy(text, chunkdata, prefix_size);
  190727. }
  190728. *(text + text_size) = 0x00;
  190729. }
  190730. inflateReset(&png_ptr->zstream);
  190731. png_ptr->zstream.avail_in = 0;
  190732. png_free(png_ptr, chunkdata);
  190733. chunkdata = text;
  190734. *newlength=text_size;
  190735. }
  190736. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  190737. {
  190738. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190739. char umsg[50];
  190740. png_snprintf(umsg, 50,
  190741. "Unknown zTXt compression type %d", comp_type);
  190742. png_warning(png_ptr, umsg);
  190743. #else
  190744. png_warning(png_ptr, "Unknown zTXt compression type");
  190745. #endif
  190746. *(chunkdata + prefix_size) = 0x00;
  190747. *newlength=prefix_size;
  190748. }
  190749. return chunkdata;
  190750. }
  190751. #endif
  190752. /* read and check the IDHR chunk */
  190753. void /* PRIVATE */
  190754. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190755. {
  190756. png_byte buf[13];
  190757. png_uint_32 width, height;
  190758. int bit_depth, color_type, compression_type, filter_type;
  190759. int interlace_type;
  190760. png_debug(1, "in png_handle_IHDR\n");
  190761. if (png_ptr->mode & PNG_HAVE_IHDR)
  190762. png_error(png_ptr, "Out of place IHDR");
  190763. /* check the length */
  190764. if (length != 13)
  190765. png_error(png_ptr, "Invalid IHDR chunk");
  190766. png_ptr->mode |= PNG_HAVE_IHDR;
  190767. png_crc_read(png_ptr, buf, 13);
  190768. png_crc_finish(png_ptr, 0);
  190769. width = png_get_uint_31(png_ptr, buf);
  190770. height = png_get_uint_31(png_ptr, buf + 4);
  190771. bit_depth = buf[8];
  190772. color_type = buf[9];
  190773. compression_type = buf[10];
  190774. filter_type = buf[11];
  190775. interlace_type = buf[12];
  190776. /* set internal variables */
  190777. png_ptr->width = width;
  190778. png_ptr->height = height;
  190779. png_ptr->bit_depth = (png_byte)bit_depth;
  190780. png_ptr->interlaced = (png_byte)interlace_type;
  190781. png_ptr->color_type = (png_byte)color_type;
  190782. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190783. png_ptr->filter_type = (png_byte)filter_type;
  190784. #endif
  190785. png_ptr->compression_type = (png_byte)compression_type;
  190786. /* find number of channels */
  190787. switch (png_ptr->color_type)
  190788. {
  190789. case PNG_COLOR_TYPE_GRAY:
  190790. case PNG_COLOR_TYPE_PALETTE:
  190791. png_ptr->channels = 1;
  190792. break;
  190793. case PNG_COLOR_TYPE_RGB:
  190794. png_ptr->channels = 3;
  190795. break;
  190796. case PNG_COLOR_TYPE_GRAY_ALPHA:
  190797. png_ptr->channels = 2;
  190798. break;
  190799. case PNG_COLOR_TYPE_RGB_ALPHA:
  190800. png_ptr->channels = 4;
  190801. break;
  190802. }
  190803. /* set up other useful info */
  190804. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  190805. png_ptr->channels);
  190806. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  190807. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  190808. png_debug1(3,"channels = %d\n", png_ptr->channels);
  190809. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  190810. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  190811. color_type, interlace_type, compression_type, filter_type);
  190812. }
  190813. /* read and check the palette */
  190814. void /* PRIVATE */
  190815. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190816. {
  190817. png_color palette[PNG_MAX_PALETTE_LENGTH];
  190818. int num, i;
  190819. #ifndef PNG_NO_POINTER_INDEXING
  190820. png_colorp pal_ptr;
  190821. #endif
  190822. png_debug(1, "in png_handle_PLTE\n");
  190823. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190824. png_error(png_ptr, "Missing IHDR before PLTE");
  190825. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190826. {
  190827. png_warning(png_ptr, "Invalid PLTE after IDAT");
  190828. png_crc_finish(png_ptr, length);
  190829. return;
  190830. }
  190831. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190832. png_error(png_ptr, "Duplicate PLTE chunk");
  190833. png_ptr->mode |= PNG_HAVE_PLTE;
  190834. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  190835. {
  190836. png_warning(png_ptr,
  190837. "Ignoring PLTE chunk in grayscale PNG");
  190838. png_crc_finish(png_ptr, length);
  190839. return;
  190840. }
  190841. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190842. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190843. {
  190844. png_crc_finish(png_ptr, length);
  190845. return;
  190846. }
  190847. #endif
  190848. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  190849. {
  190850. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190851. {
  190852. png_warning(png_ptr, "Invalid palette chunk");
  190853. png_crc_finish(png_ptr, length);
  190854. return;
  190855. }
  190856. else
  190857. {
  190858. png_error(png_ptr, "Invalid palette chunk");
  190859. }
  190860. }
  190861. num = (int)length / 3;
  190862. #ifndef PNG_NO_POINTER_INDEXING
  190863. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  190864. {
  190865. png_byte buf[3];
  190866. png_crc_read(png_ptr, buf, 3);
  190867. pal_ptr->red = buf[0];
  190868. pal_ptr->green = buf[1];
  190869. pal_ptr->blue = buf[2];
  190870. }
  190871. #else
  190872. for (i = 0; i < num; i++)
  190873. {
  190874. png_byte buf[3];
  190875. png_crc_read(png_ptr, buf, 3);
  190876. /* don't depend upon png_color being any order */
  190877. palette[i].red = buf[0];
  190878. palette[i].green = buf[1];
  190879. palette[i].blue = buf[2];
  190880. }
  190881. #endif
  190882. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  190883. whatever the normal CRC configuration tells us. However, if we
  190884. have an RGB image, the PLTE can be considered ancillary, so
  190885. we will act as though it is. */
  190886. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190887. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190888. #endif
  190889. {
  190890. png_crc_finish(png_ptr, 0);
  190891. }
  190892. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190893. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  190894. {
  190895. /* If we don't want to use the data from an ancillary chunk,
  190896. we have two options: an error abort, or a warning and we
  190897. ignore the data in this chunk (which should be OK, since
  190898. it's considered ancillary for a RGB or RGBA image). */
  190899. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  190900. {
  190901. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  190902. {
  190903. png_chunk_error(png_ptr, "CRC error");
  190904. }
  190905. else
  190906. {
  190907. png_chunk_warning(png_ptr, "CRC error");
  190908. return;
  190909. }
  190910. }
  190911. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  190912. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  190913. {
  190914. png_chunk_warning(png_ptr, "CRC error");
  190915. }
  190916. }
  190917. #endif
  190918. png_set_PLTE(png_ptr, info_ptr, palette, num);
  190919. #if defined(PNG_READ_tRNS_SUPPORTED)
  190920. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190921. {
  190922. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190923. {
  190924. if (png_ptr->num_trans > (png_uint_16)num)
  190925. {
  190926. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  190927. png_ptr->num_trans = (png_uint_16)num;
  190928. }
  190929. if (info_ptr->num_trans > (png_uint_16)num)
  190930. {
  190931. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  190932. info_ptr->num_trans = (png_uint_16)num;
  190933. }
  190934. }
  190935. }
  190936. #endif
  190937. }
  190938. void /* PRIVATE */
  190939. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190940. {
  190941. png_debug(1, "in png_handle_IEND\n");
  190942. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  190943. {
  190944. png_error(png_ptr, "No image in file");
  190945. }
  190946. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  190947. if (length != 0)
  190948. {
  190949. png_warning(png_ptr, "Incorrect IEND chunk length");
  190950. }
  190951. png_crc_finish(png_ptr, length);
  190952. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  190953. }
  190954. #if defined(PNG_READ_gAMA_SUPPORTED)
  190955. void /* PRIVATE */
  190956. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190957. {
  190958. png_fixed_point igamma;
  190959. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190960. float file_gamma;
  190961. #endif
  190962. png_byte buf[4];
  190963. png_debug(1, "in png_handle_gAMA\n");
  190964. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190965. png_error(png_ptr, "Missing IHDR before gAMA");
  190966. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190967. {
  190968. png_warning(png_ptr, "Invalid gAMA after IDAT");
  190969. png_crc_finish(png_ptr, length);
  190970. return;
  190971. }
  190972. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190973. /* Should be an error, but we can cope with it */
  190974. png_warning(png_ptr, "Out of place gAMA chunk");
  190975. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  190976. #if defined(PNG_READ_sRGB_SUPPORTED)
  190977. && !(info_ptr->valid & PNG_INFO_sRGB)
  190978. #endif
  190979. )
  190980. {
  190981. png_warning(png_ptr, "Duplicate gAMA chunk");
  190982. png_crc_finish(png_ptr, length);
  190983. return;
  190984. }
  190985. if (length != 4)
  190986. {
  190987. png_warning(png_ptr, "Incorrect gAMA chunk length");
  190988. png_crc_finish(png_ptr, length);
  190989. return;
  190990. }
  190991. png_crc_read(png_ptr, buf, 4);
  190992. if (png_crc_finish(png_ptr, 0))
  190993. return;
  190994. igamma = (png_fixed_point)png_get_uint_32(buf);
  190995. /* check for zero gamma */
  190996. if (igamma == 0)
  190997. {
  190998. png_warning(png_ptr,
  190999. "Ignoring gAMA chunk with gamma=0");
  191000. return;
  191001. }
  191002. #if defined(PNG_READ_sRGB_SUPPORTED)
  191003. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191004. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191005. {
  191006. png_warning(png_ptr,
  191007. "Ignoring incorrect gAMA value when sRGB is also present");
  191008. #ifndef PNG_NO_CONSOLE_IO
  191009. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  191010. #endif
  191011. return;
  191012. }
  191013. #endif /* PNG_READ_sRGB_SUPPORTED */
  191014. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191015. file_gamma = (float)igamma / (float)100000.0;
  191016. # ifdef PNG_READ_GAMMA_SUPPORTED
  191017. png_ptr->gamma = file_gamma;
  191018. # endif
  191019. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191020. #endif
  191021. #ifdef PNG_FIXED_POINT_SUPPORTED
  191022. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  191023. #endif
  191024. }
  191025. #endif
  191026. #if defined(PNG_READ_sBIT_SUPPORTED)
  191027. void /* PRIVATE */
  191028. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191029. {
  191030. png_size_t truelen;
  191031. png_byte buf[4];
  191032. png_debug(1, "in png_handle_sBIT\n");
  191033. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  191034. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191035. png_error(png_ptr, "Missing IHDR before sBIT");
  191036. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191037. {
  191038. png_warning(png_ptr, "Invalid sBIT after IDAT");
  191039. png_crc_finish(png_ptr, length);
  191040. return;
  191041. }
  191042. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191043. {
  191044. /* Should be an error, but we can cope with it */
  191045. png_warning(png_ptr, "Out of place sBIT chunk");
  191046. }
  191047. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  191048. {
  191049. png_warning(png_ptr, "Duplicate sBIT chunk");
  191050. png_crc_finish(png_ptr, length);
  191051. return;
  191052. }
  191053. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191054. truelen = 3;
  191055. else
  191056. truelen = (png_size_t)png_ptr->channels;
  191057. if (length != truelen || length > 4)
  191058. {
  191059. png_warning(png_ptr, "Incorrect sBIT chunk length");
  191060. png_crc_finish(png_ptr, length);
  191061. return;
  191062. }
  191063. png_crc_read(png_ptr, buf, truelen);
  191064. if (png_crc_finish(png_ptr, 0))
  191065. return;
  191066. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191067. {
  191068. png_ptr->sig_bit.red = buf[0];
  191069. png_ptr->sig_bit.green = buf[1];
  191070. png_ptr->sig_bit.blue = buf[2];
  191071. png_ptr->sig_bit.alpha = buf[3];
  191072. }
  191073. else
  191074. {
  191075. png_ptr->sig_bit.gray = buf[0];
  191076. png_ptr->sig_bit.red = buf[0];
  191077. png_ptr->sig_bit.green = buf[0];
  191078. png_ptr->sig_bit.blue = buf[0];
  191079. png_ptr->sig_bit.alpha = buf[1];
  191080. }
  191081. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  191082. }
  191083. #endif
  191084. #if defined(PNG_READ_cHRM_SUPPORTED)
  191085. void /* PRIVATE */
  191086. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191087. {
  191088. png_byte buf[4];
  191089. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191090. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191091. #endif
  191092. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191093. int_y_green, int_x_blue, int_y_blue;
  191094. png_uint_32 uint_x, uint_y;
  191095. png_debug(1, "in png_handle_cHRM\n");
  191096. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191097. png_error(png_ptr, "Missing IHDR before cHRM");
  191098. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191099. {
  191100. png_warning(png_ptr, "Invalid cHRM after IDAT");
  191101. png_crc_finish(png_ptr, length);
  191102. return;
  191103. }
  191104. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191105. /* Should be an error, but we can cope with it */
  191106. png_warning(png_ptr, "Missing PLTE before cHRM");
  191107. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  191108. #if defined(PNG_READ_sRGB_SUPPORTED)
  191109. && !(info_ptr->valid & PNG_INFO_sRGB)
  191110. #endif
  191111. )
  191112. {
  191113. png_warning(png_ptr, "Duplicate cHRM chunk");
  191114. png_crc_finish(png_ptr, length);
  191115. return;
  191116. }
  191117. if (length != 32)
  191118. {
  191119. png_warning(png_ptr, "Incorrect cHRM chunk length");
  191120. png_crc_finish(png_ptr, length);
  191121. return;
  191122. }
  191123. png_crc_read(png_ptr, buf, 4);
  191124. uint_x = png_get_uint_32(buf);
  191125. png_crc_read(png_ptr, buf, 4);
  191126. uint_y = png_get_uint_32(buf);
  191127. if (uint_x > 80000L || uint_y > 80000L ||
  191128. uint_x + uint_y > 100000L)
  191129. {
  191130. png_warning(png_ptr, "Invalid cHRM white point");
  191131. png_crc_finish(png_ptr, 24);
  191132. return;
  191133. }
  191134. int_x_white = (png_fixed_point)uint_x;
  191135. int_y_white = (png_fixed_point)uint_y;
  191136. png_crc_read(png_ptr, buf, 4);
  191137. uint_x = png_get_uint_32(buf);
  191138. png_crc_read(png_ptr, buf, 4);
  191139. uint_y = png_get_uint_32(buf);
  191140. if (uint_x + uint_y > 100000L)
  191141. {
  191142. png_warning(png_ptr, "Invalid cHRM red point");
  191143. png_crc_finish(png_ptr, 16);
  191144. return;
  191145. }
  191146. int_x_red = (png_fixed_point)uint_x;
  191147. int_y_red = (png_fixed_point)uint_y;
  191148. png_crc_read(png_ptr, buf, 4);
  191149. uint_x = png_get_uint_32(buf);
  191150. png_crc_read(png_ptr, buf, 4);
  191151. uint_y = png_get_uint_32(buf);
  191152. if (uint_x + uint_y > 100000L)
  191153. {
  191154. png_warning(png_ptr, "Invalid cHRM green point");
  191155. png_crc_finish(png_ptr, 8);
  191156. return;
  191157. }
  191158. int_x_green = (png_fixed_point)uint_x;
  191159. int_y_green = (png_fixed_point)uint_y;
  191160. png_crc_read(png_ptr, buf, 4);
  191161. uint_x = png_get_uint_32(buf);
  191162. png_crc_read(png_ptr, buf, 4);
  191163. uint_y = png_get_uint_32(buf);
  191164. if (uint_x + uint_y > 100000L)
  191165. {
  191166. png_warning(png_ptr, "Invalid cHRM blue point");
  191167. png_crc_finish(png_ptr, 0);
  191168. return;
  191169. }
  191170. int_x_blue = (png_fixed_point)uint_x;
  191171. int_y_blue = (png_fixed_point)uint_y;
  191172. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191173. white_x = (float)int_x_white / (float)100000.0;
  191174. white_y = (float)int_y_white / (float)100000.0;
  191175. red_x = (float)int_x_red / (float)100000.0;
  191176. red_y = (float)int_y_red / (float)100000.0;
  191177. green_x = (float)int_x_green / (float)100000.0;
  191178. green_y = (float)int_y_green / (float)100000.0;
  191179. blue_x = (float)int_x_blue / (float)100000.0;
  191180. blue_y = (float)int_y_blue / (float)100000.0;
  191181. #endif
  191182. #if defined(PNG_READ_sRGB_SUPPORTED)
  191183. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  191184. {
  191185. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  191186. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  191187. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  191188. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  191189. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  191190. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  191191. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  191192. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  191193. {
  191194. png_warning(png_ptr,
  191195. "Ignoring incorrect cHRM value when sRGB is also present");
  191196. #ifndef PNG_NO_CONSOLE_IO
  191197. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191198. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  191199. white_x, white_y, red_x, red_y);
  191200. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  191201. green_x, green_y, blue_x, blue_y);
  191202. #else
  191203. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  191204. int_x_white, int_y_white, int_x_red, int_y_red);
  191205. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  191206. int_x_green, int_y_green, int_x_blue, int_y_blue);
  191207. #endif
  191208. #endif /* PNG_NO_CONSOLE_IO */
  191209. }
  191210. png_crc_finish(png_ptr, 0);
  191211. return;
  191212. }
  191213. #endif /* PNG_READ_sRGB_SUPPORTED */
  191214. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191215. png_set_cHRM(png_ptr, info_ptr,
  191216. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191217. #endif
  191218. #ifdef PNG_FIXED_POINT_SUPPORTED
  191219. png_set_cHRM_fixed(png_ptr, info_ptr,
  191220. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191221. int_y_green, int_x_blue, int_y_blue);
  191222. #endif
  191223. if (png_crc_finish(png_ptr, 0))
  191224. return;
  191225. }
  191226. #endif
  191227. #if defined(PNG_READ_sRGB_SUPPORTED)
  191228. void /* PRIVATE */
  191229. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191230. {
  191231. int intent;
  191232. png_byte buf[1];
  191233. png_debug(1, "in png_handle_sRGB\n");
  191234. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191235. png_error(png_ptr, "Missing IHDR before sRGB");
  191236. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191237. {
  191238. png_warning(png_ptr, "Invalid sRGB after IDAT");
  191239. png_crc_finish(png_ptr, length);
  191240. return;
  191241. }
  191242. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191243. /* Should be an error, but we can cope with it */
  191244. png_warning(png_ptr, "Out of place sRGB chunk");
  191245. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191246. {
  191247. png_warning(png_ptr, "Duplicate sRGB chunk");
  191248. png_crc_finish(png_ptr, length);
  191249. return;
  191250. }
  191251. if (length != 1)
  191252. {
  191253. png_warning(png_ptr, "Incorrect sRGB chunk length");
  191254. png_crc_finish(png_ptr, length);
  191255. return;
  191256. }
  191257. png_crc_read(png_ptr, buf, 1);
  191258. if (png_crc_finish(png_ptr, 0))
  191259. return;
  191260. intent = buf[0];
  191261. /* check for bad intent */
  191262. if (intent >= PNG_sRGB_INTENT_LAST)
  191263. {
  191264. png_warning(png_ptr, "Unknown sRGB intent");
  191265. return;
  191266. }
  191267. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  191268. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  191269. {
  191270. png_fixed_point igamma;
  191271. #ifdef PNG_FIXED_POINT_SUPPORTED
  191272. igamma=info_ptr->int_gamma;
  191273. #else
  191274. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191275. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  191276. # endif
  191277. #endif
  191278. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191279. {
  191280. png_warning(png_ptr,
  191281. "Ignoring incorrect gAMA value when sRGB is also present");
  191282. #ifndef PNG_NO_CONSOLE_IO
  191283. # ifdef PNG_FIXED_POINT_SUPPORTED
  191284. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  191285. # else
  191286. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191287. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  191288. # endif
  191289. # endif
  191290. #endif
  191291. }
  191292. }
  191293. #endif /* PNG_READ_gAMA_SUPPORTED */
  191294. #ifdef PNG_READ_cHRM_SUPPORTED
  191295. #ifdef PNG_FIXED_POINT_SUPPORTED
  191296. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  191297. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  191298. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  191299. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  191300. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  191301. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  191302. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  191303. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  191304. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  191305. {
  191306. png_warning(png_ptr,
  191307. "Ignoring incorrect cHRM value when sRGB is also present");
  191308. }
  191309. #endif /* PNG_FIXED_POINT_SUPPORTED */
  191310. #endif /* PNG_READ_cHRM_SUPPORTED */
  191311. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  191312. }
  191313. #endif /* PNG_READ_sRGB_SUPPORTED */
  191314. #if defined(PNG_READ_iCCP_SUPPORTED)
  191315. void /* PRIVATE */
  191316. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191317. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191318. {
  191319. png_charp chunkdata;
  191320. png_byte compression_type;
  191321. png_bytep pC;
  191322. png_charp profile;
  191323. png_uint_32 skip = 0;
  191324. png_uint_32 profile_size, profile_length;
  191325. png_size_t slength, prefix_length, data_length;
  191326. png_debug(1, "in png_handle_iCCP\n");
  191327. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191328. png_error(png_ptr, "Missing IHDR before iCCP");
  191329. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191330. {
  191331. png_warning(png_ptr, "Invalid iCCP after IDAT");
  191332. png_crc_finish(png_ptr, length);
  191333. return;
  191334. }
  191335. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191336. /* Should be an error, but we can cope with it */
  191337. png_warning(png_ptr, "Out of place iCCP chunk");
  191338. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  191339. {
  191340. png_warning(png_ptr, "Duplicate iCCP chunk");
  191341. png_crc_finish(png_ptr, length);
  191342. return;
  191343. }
  191344. #ifdef PNG_MAX_MALLOC_64K
  191345. if (length > (png_uint_32)65535L)
  191346. {
  191347. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  191348. skip = length - (png_uint_32)65535L;
  191349. length = (png_uint_32)65535L;
  191350. }
  191351. #endif
  191352. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  191353. slength = (png_size_t)length;
  191354. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191355. if (png_crc_finish(png_ptr, skip))
  191356. {
  191357. png_free(png_ptr, chunkdata);
  191358. return;
  191359. }
  191360. chunkdata[slength] = 0x00;
  191361. for (profile = chunkdata; *profile; profile++)
  191362. /* empty loop to find end of name */ ;
  191363. ++profile;
  191364. /* there should be at least one zero (the compression type byte)
  191365. following the separator, and we should be on it */
  191366. if ( profile >= chunkdata + slength - 1)
  191367. {
  191368. png_free(png_ptr, chunkdata);
  191369. png_warning(png_ptr, "Malformed iCCP chunk");
  191370. return;
  191371. }
  191372. /* compression_type should always be zero */
  191373. compression_type = *profile++;
  191374. if (compression_type)
  191375. {
  191376. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  191377. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  191378. wrote nonzero) */
  191379. }
  191380. prefix_length = profile - chunkdata;
  191381. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  191382. slength, prefix_length, &data_length);
  191383. profile_length = data_length - prefix_length;
  191384. if ( prefix_length > data_length || profile_length < 4)
  191385. {
  191386. png_free(png_ptr, chunkdata);
  191387. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  191388. return;
  191389. }
  191390. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  191391. pC = (png_bytep)(chunkdata+prefix_length);
  191392. profile_size = ((*(pC ))<<24) |
  191393. ((*(pC+1))<<16) |
  191394. ((*(pC+2))<< 8) |
  191395. ((*(pC+3)) );
  191396. if(profile_size < profile_length)
  191397. profile_length = profile_size;
  191398. if(profile_size > profile_length)
  191399. {
  191400. png_free(png_ptr, chunkdata);
  191401. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  191402. return;
  191403. }
  191404. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  191405. chunkdata + prefix_length, profile_length);
  191406. png_free(png_ptr, chunkdata);
  191407. }
  191408. #endif /* PNG_READ_iCCP_SUPPORTED */
  191409. #if defined(PNG_READ_sPLT_SUPPORTED)
  191410. void /* PRIVATE */
  191411. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191412. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191413. {
  191414. png_bytep chunkdata;
  191415. png_bytep entry_start;
  191416. png_sPLT_t new_palette;
  191417. #ifdef PNG_NO_POINTER_INDEXING
  191418. png_sPLT_entryp pp;
  191419. #endif
  191420. int data_length, entry_size, i;
  191421. png_uint_32 skip = 0;
  191422. png_size_t slength;
  191423. png_debug(1, "in png_handle_sPLT\n");
  191424. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191425. png_error(png_ptr, "Missing IHDR before sPLT");
  191426. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191427. {
  191428. png_warning(png_ptr, "Invalid sPLT after IDAT");
  191429. png_crc_finish(png_ptr, length);
  191430. return;
  191431. }
  191432. #ifdef PNG_MAX_MALLOC_64K
  191433. if (length > (png_uint_32)65535L)
  191434. {
  191435. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  191436. skip = length - (png_uint_32)65535L;
  191437. length = (png_uint_32)65535L;
  191438. }
  191439. #endif
  191440. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  191441. slength = (png_size_t)length;
  191442. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191443. if (png_crc_finish(png_ptr, skip))
  191444. {
  191445. png_free(png_ptr, chunkdata);
  191446. return;
  191447. }
  191448. chunkdata[slength] = 0x00;
  191449. for (entry_start = chunkdata; *entry_start; entry_start++)
  191450. /* empty loop to find end of name */ ;
  191451. ++entry_start;
  191452. /* a sample depth should follow the separator, and we should be on it */
  191453. if (entry_start > chunkdata + slength - 2)
  191454. {
  191455. png_free(png_ptr, chunkdata);
  191456. png_warning(png_ptr, "malformed sPLT chunk");
  191457. return;
  191458. }
  191459. new_palette.depth = *entry_start++;
  191460. entry_size = (new_palette.depth == 8 ? 6 : 10);
  191461. data_length = (slength - (entry_start - chunkdata));
  191462. /* integrity-check the data length */
  191463. if (data_length % entry_size)
  191464. {
  191465. png_free(png_ptr, chunkdata);
  191466. png_warning(png_ptr, "sPLT chunk has bad length");
  191467. return;
  191468. }
  191469. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  191470. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  191471. png_sizeof(png_sPLT_entry)))
  191472. {
  191473. png_warning(png_ptr, "sPLT chunk too long");
  191474. return;
  191475. }
  191476. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  191477. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  191478. if (new_palette.entries == NULL)
  191479. {
  191480. png_warning(png_ptr, "sPLT chunk requires too much memory");
  191481. return;
  191482. }
  191483. #ifndef PNG_NO_POINTER_INDEXING
  191484. for (i = 0; i < new_palette.nentries; i++)
  191485. {
  191486. png_sPLT_entryp pp = new_palette.entries + i;
  191487. if (new_palette.depth == 8)
  191488. {
  191489. pp->red = *entry_start++;
  191490. pp->green = *entry_start++;
  191491. pp->blue = *entry_start++;
  191492. pp->alpha = *entry_start++;
  191493. }
  191494. else
  191495. {
  191496. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  191497. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  191498. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  191499. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  191500. }
  191501. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  191502. }
  191503. #else
  191504. pp = new_palette.entries;
  191505. for (i = 0; i < new_palette.nentries; i++)
  191506. {
  191507. if (new_palette.depth == 8)
  191508. {
  191509. pp[i].red = *entry_start++;
  191510. pp[i].green = *entry_start++;
  191511. pp[i].blue = *entry_start++;
  191512. pp[i].alpha = *entry_start++;
  191513. }
  191514. else
  191515. {
  191516. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  191517. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  191518. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  191519. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  191520. }
  191521. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  191522. }
  191523. #endif
  191524. /* discard all chunk data except the name and stash that */
  191525. new_palette.name = (png_charp)chunkdata;
  191526. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  191527. png_free(png_ptr, chunkdata);
  191528. png_free(png_ptr, new_palette.entries);
  191529. }
  191530. #endif /* PNG_READ_sPLT_SUPPORTED */
  191531. #if defined(PNG_READ_tRNS_SUPPORTED)
  191532. void /* PRIVATE */
  191533. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191534. {
  191535. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  191536. int bit_mask;
  191537. png_debug(1, "in png_handle_tRNS\n");
  191538. /* For non-indexed color, mask off any bits in the tRNS value that
  191539. * exceed the bit depth. Some creators were writing extra bits there.
  191540. * This is not needed for indexed color. */
  191541. bit_mask = (1 << png_ptr->bit_depth) - 1;
  191542. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191543. png_error(png_ptr, "Missing IHDR before tRNS");
  191544. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191545. {
  191546. png_warning(png_ptr, "Invalid tRNS after IDAT");
  191547. png_crc_finish(png_ptr, length);
  191548. return;
  191549. }
  191550. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  191551. {
  191552. png_warning(png_ptr, "Duplicate tRNS chunk");
  191553. png_crc_finish(png_ptr, length);
  191554. return;
  191555. }
  191556. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  191557. {
  191558. png_byte buf[2];
  191559. if (length != 2)
  191560. {
  191561. png_warning(png_ptr, "Incorrect tRNS chunk length");
  191562. png_crc_finish(png_ptr, length);
  191563. return;
  191564. }
  191565. png_crc_read(png_ptr, buf, 2);
  191566. png_ptr->num_trans = 1;
  191567. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  191568. }
  191569. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191570. {
  191571. png_byte buf[6];
  191572. if (length != 6)
  191573. {
  191574. png_warning(png_ptr, "Incorrect tRNS chunk length");
  191575. png_crc_finish(png_ptr, length);
  191576. return;
  191577. }
  191578. png_crc_read(png_ptr, buf, (png_size_t)length);
  191579. png_ptr->num_trans = 1;
  191580. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  191581. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  191582. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  191583. }
  191584. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191585. {
  191586. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  191587. {
  191588. /* Should be an error, but we can cope with it. */
  191589. png_warning(png_ptr, "Missing PLTE before tRNS");
  191590. }
  191591. if (length > (png_uint_32)png_ptr->num_palette ||
  191592. length > PNG_MAX_PALETTE_LENGTH)
  191593. {
  191594. png_warning(png_ptr, "Incorrect tRNS chunk length");
  191595. png_crc_finish(png_ptr, length);
  191596. return;
  191597. }
  191598. if (length == 0)
  191599. {
  191600. png_warning(png_ptr, "Zero length tRNS chunk");
  191601. png_crc_finish(png_ptr, length);
  191602. return;
  191603. }
  191604. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  191605. png_ptr->num_trans = (png_uint_16)length;
  191606. }
  191607. else
  191608. {
  191609. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  191610. png_crc_finish(png_ptr, length);
  191611. return;
  191612. }
  191613. if (png_crc_finish(png_ptr, 0))
  191614. {
  191615. png_ptr->num_trans = 0;
  191616. return;
  191617. }
  191618. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  191619. &(png_ptr->trans_values));
  191620. }
  191621. #endif
  191622. #if defined(PNG_READ_bKGD_SUPPORTED)
  191623. void /* PRIVATE */
  191624. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191625. {
  191626. png_size_t truelen;
  191627. png_byte buf[6];
  191628. png_debug(1, "in png_handle_bKGD\n");
  191629. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191630. png_error(png_ptr, "Missing IHDR before bKGD");
  191631. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191632. {
  191633. png_warning(png_ptr, "Invalid bKGD after IDAT");
  191634. png_crc_finish(png_ptr, length);
  191635. return;
  191636. }
  191637. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  191638. !(png_ptr->mode & PNG_HAVE_PLTE))
  191639. {
  191640. png_warning(png_ptr, "Missing PLTE before bKGD");
  191641. png_crc_finish(png_ptr, length);
  191642. return;
  191643. }
  191644. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  191645. {
  191646. png_warning(png_ptr, "Duplicate bKGD chunk");
  191647. png_crc_finish(png_ptr, length);
  191648. return;
  191649. }
  191650. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191651. truelen = 1;
  191652. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191653. truelen = 6;
  191654. else
  191655. truelen = 2;
  191656. if (length != truelen)
  191657. {
  191658. png_warning(png_ptr, "Incorrect bKGD chunk length");
  191659. png_crc_finish(png_ptr, length);
  191660. return;
  191661. }
  191662. png_crc_read(png_ptr, buf, truelen);
  191663. if (png_crc_finish(png_ptr, 0))
  191664. return;
  191665. /* We convert the index value into RGB components so that we can allow
  191666. * arbitrary RGB values for background when we have transparency, and
  191667. * so it is easy to determine the RGB values of the background color
  191668. * from the info_ptr struct. */
  191669. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191670. {
  191671. png_ptr->background.index = buf[0];
  191672. if(info_ptr->num_palette)
  191673. {
  191674. if(buf[0] > info_ptr->num_palette)
  191675. {
  191676. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  191677. return;
  191678. }
  191679. png_ptr->background.red =
  191680. (png_uint_16)png_ptr->palette[buf[0]].red;
  191681. png_ptr->background.green =
  191682. (png_uint_16)png_ptr->palette[buf[0]].green;
  191683. png_ptr->background.blue =
  191684. (png_uint_16)png_ptr->palette[buf[0]].blue;
  191685. }
  191686. }
  191687. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  191688. {
  191689. png_ptr->background.red =
  191690. png_ptr->background.green =
  191691. png_ptr->background.blue =
  191692. png_ptr->background.gray = png_get_uint_16(buf);
  191693. }
  191694. else
  191695. {
  191696. png_ptr->background.red = png_get_uint_16(buf);
  191697. png_ptr->background.green = png_get_uint_16(buf + 2);
  191698. png_ptr->background.blue = png_get_uint_16(buf + 4);
  191699. }
  191700. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  191701. }
  191702. #endif
  191703. #if defined(PNG_READ_hIST_SUPPORTED)
  191704. void /* PRIVATE */
  191705. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191706. {
  191707. unsigned int num, i;
  191708. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  191709. png_debug(1, "in png_handle_hIST\n");
  191710. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191711. png_error(png_ptr, "Missing IHDR before hIST");
  191712. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191713. {
  191714. png_warning(png_ptr, "Invalid hIST after IDAT");
  191715. png_crc_finish(png_ptr, length);
  191716. return;
  191717. }
  191718. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  191719. {
  191720. png_warning(png_ptr, "Missing PLTE before hIST");
  191721. png_crc_finish(png_ptr, length);
  191722. return;
  191723. }
  191724. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  191725. {
  191726. png_warning(png_ptr, "Duplicate hIST chunk");
  191727. png_crc_finish(png_ptr, length);
  191728. return;
  191729. }
  191730. num = length / 2 ;
  191731. if (num != (unsigned int) png_ptr->num_palette || num >
  191732. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  191733. {
  191734. png_warning(png_ptr, "Incorrect hIST chunk length");
  191735. png_crc_finish(png_ptr, length);
  191736. return;
  191737. }
  191738. for (i = 0; i < num; i++)
  191739. {
  191740. png_byte buf[2];
  191741. png_crc_read(png_ptr, buf, 2);
  191742. readbuf[i] = png_get_uint_16(buf);
  191743. }
  191744. if (png_crc_finish(png_ptr, 0))
  191745. return;
  191746. png_set_hIST(png_ptr, info_ptr, readbuf);
  191747. }
  191748. #endif
  191749. #if defined(PNG_READ_pHYs_SUPPORTED)
  191750. void /* PRIVATE */
  191751. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191752. {
  191753. png_byte buf[9];
  191754. png_uint_32 res_x, res_y;
  191755. int unit_type;
  191756. png_debug(1, "in png_handle_pHYs\n");
  191757. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191758. png_error(png_ptr, "Missing IHDR before pHYs");
  191759. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191760. {
  191761. png_warning(png_ptr, "Invalid pHYs after IDAT");
  191762. png_crc_finish(png_ptr, length);
  191763. return;
  191764. }
  191765. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  191766. {
  191767. png_warning(png_ptr, "Duplicate pHYs chunk");
  191768. png_crc_finish(png_ptr, length);
  191769. return;
  191770. }
  191771. if (length != 9)
  191772. {
  191773. png_warning(png_ptr, "Incorrect pHYs chunk length");
  191774. png_crc_finish(png_ptr, length);
  191775. return;
  191776. }
  191777. png_crc_read(png_ptr, buf, 9);
  191778. if (png_crc_finish(png_ptr, 0))
  191779. return;
  191780. res_x = png_get_uint_32(buf);
  191781. res_y = png_get_uint_32(buf + 4);
  191782. unit_type = buf[8];
  191783. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  191784. }
  191785. #endif
  191786. #if defined(PNG_READ_oFFs_SUPPORTED)
  191787. void /* PRIVATE */
  191788. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191789. {
  191790. png_byte buf[9];
  191791. png_int_32 offset_x, offset_y;
  191792. int unit_type;
  191793. png_debug(1, "in png_handle_oFFs\n");
  191794. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191795. png_error(png_ptr, "Missing IHDR before oFFs");
  191796. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191797. {
  191798. png_warning(png_ptr, "Invalid oFFs after IDAT");
  191799. png_crc_finish(png_ptr, length);
  191800. return;
  191801. }
  191802. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  191803. {
  191804. png_warning(png_ptr, "Duplicate oFFs chunk");
  191805. png_crc_finish(png_ptr, length);
  191806. return;
  191807. }
  191808. if (length != 9)
  191809. {
  191810. png_warning(png_ptr, "Incorrect oFFs chunk length");
  191811. png_crc_finish(png_ptr, length);
  191812. return;
  191813. }
  191814. png_crc_read(png_ptr, buf, 9);
  191815. if (png_crc_finish(png_ptr, 0))
  191816. return;
  191817. offset_x = png_get_int_32(buf);
  191818. offset_y = png_get_int_32(buf + 4);
  191819. unit_type = buf[8];
  191820. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  191821. }
  191822. #endif
  191823. #if defined(PNG_READ_pCAL_SUPPORTED)
  191824. /* read the pCAL chunk (described in the PNG Extensions document) */
  191825. void /* PRIVATE */
  191826. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191827. {
  191828. png_charp purpose;
  191829. png_int_32 X0, X1;
  191830. png_byte type, nparams;
  191831. png_charp buf, units, endptr;
  191832. png_charpp params;
  191833. png_size_t slength;
  191834. int i;
  191835. png_debug(1, "in png_handle_pCAL\n");
  191836. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191837. png_error(png_ptr, "Missing IHDR before pCAL");
  191838. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191839. {
  191840. png_warning(png_ptr, "Invalid pCAL after IDAT");
  191841. png_crc_finish(png_ptr, length);
  191842. return;
  191843. }
  191844. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  191845. {
  191846. png_warning(png_ptr, "Duplicate pCAL chunk");
  191847. png_crc_finish(png_ptr, length);
  191848. return;
  191849. }
  191850. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  191851. length + 1);
  191852. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191853. if (purpose == NULL)
  191854. {
  191855. png_warning(png_ptr, "No memory for pCAL purpose.");
  191856. return;
  191857. }
  191858. slength = (png_size_t)length;
  191859. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  191860. if (png_crc_finish(png_ptr, 0))
  191861. {
  191862. png_free(png_ptr, purpose);
  191863. return;
  191864. }
  191865. purpose[slength] = 0x00; /* null terminate the last string */
  191866. png_debug(3, "Finding end of pCAL purpose string\n");
  191867. for (buf = purpose; *buf; buf++)
  191868. /* empty loop */ ;
  191869. endptr = purpose + slength;
  191870. /* We need to have at least 12 bytes after the purpose string
  191871. in order to get the parameter information. */
  191872. if (endptr <= buf + 12)
  191873. {
  191874. png_warning(png_ptr, "Invalid pCAL data");
  191875. png_free(png_ptr, purpose);
  191876. return;
  191877. }
  191878. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  191879. X0 = png_get_int_32((png_bytep)buf+1);
  191880. X1 = png_get_int_32((png_bytep)buf+5);
  191881. type = buf[9];
  191882. nparams = buf[10];
  191883. units = buf + 11;
  191884. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  191885. /* Check that we have the right number of parameters for known
  191886. equation types. */
  191887. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  191888. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  191889. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  191890. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  191891. {
  191892. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  191893. png_free(png_ptr, purpose);
  191894. return;
  191895. }
  191896. else if (type >= PNG_EQUATION_LAST)
  191897. {
  191898. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  191899. }
  191900. for (buf = units; *buf; buf++)
  191901. /* Empty loop to move past the units string. */ ;
  191902. png_debug(3, "Allocating pCAL parameters array\n");
  191903. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  191904. *png_sizeof(png_charp))) ;
  191905. if (params == NULL)
  191906. {
  191907. png_free(png_ptr, purpose);
  191908. png_warning(png_ptr, "No memory for pCAL params.");
  191909. return;
  191910. }
  191911. /* Get pointers to the start of each parameter string. */
  191912. for (i = 0; i < (int)nparams; i++)
  191913. {
  191914. buf++; /* Skip the null string terminator from previous parameter. */
  191915. png_debug1(3, "Reading pCAL parameter %d\n", i);
  191916. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  191917. /* Empty loop to move past each parameter string */ ;
  191918. /* Make sure we haven't run out of data yet */
  191919. if (buf > endptr)
  191920. {
  191921. png_warning(png_ptr, "Invalid pCAL data");
  191922. png_free(png_ptr, purpose);
  191923. png_free(png_ptr, params);
  191924. return;
  191925. }
  191926. }
  191927. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  191928. units, params);
  191929. png_free(png_ptr, purpose);
  191930. png_free(png_ptr, params);
  191931. }
  191932. #endif
  191933. #if defined(PNG_READ_sCAL_SUPPORTED)
  191934. /* read the sCAL chunk */
  191935. void /* PRIVATE */
  191936. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191937. {
  191938. png_charp buffer, ep;
  191939. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191940. double width, height;
  191941. png_charp vp;
  191942. #else
  191943. #ifdef PNG_FIXED_POINT_SUPPORTED
  191944. png_charp swidth, sheight;
  191945. #endif
  191946. #endif
  191947. png_size_t slength;
  191948. png_debug(1, "in png_handle_sCAL\n");
  191949. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191950. png_error(png_ptr, "Missing IHDR before sCAL");
  191951. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191952. {
  191953. png_warning(png_ptr, "Invalid sCAL after IDAT");
  191954. png_crc_finish(png_ptr, length);
  191955. return;
  191956. }
  191957. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  191958. {
  191959. png_warning(png_ptr, "Duplicate sCAL chunk");
  191960. png_crc_finish(png_ptr, length);
  191961. return;
  191962. }
  191963. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  191964. length + 1);
  191965. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191966. if (buffer == NULL)
  191967. {
  191968. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  191969. return;
  191970. }
  191971. slength = (png_size_t)length;
  191972. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  191973. if (png_crc_finish(png_ptr, 0))
  191974. {
  191975. png_free(png_ptr, buffer);
  191976. return;
  191977. }
  191978. buffer[slength] = 0x00; /* null terminate the last string */
  191979. ep = buffer + 1; /* skip unit byte */
  191980. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191981. width = png_strtod(png_ptr, ep, &vp);
  191982. if (*vp)
  191983. {
  191984. png_warning(png_ptr, "malformed width string in sCAL chunk");
  191985. return;
  191986. }
  191987. #else
  191988. #ifdef PNG_FIXED_POINT_SUPPORTED
  191989. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191990. if (swidth == NULL)
  191991. {
  191992. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  191993. return;
  191994. }
  191995. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  191996. #endif
  191997. #endif
  191998. for (ep = buffer; *ep; ep++)
  191999. /* empty loop */ ;
  192000. ep++;
  192001. if (buffer + slength < ep)
  192002. {
  192003. png_warning(png_ptr, "Truncated sCAL chunk");
  192004. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  192005. !defined(PNG_FLOATING_POINT_SUPPORTED)
  192006. png_free(png_ptr, swidth);
  192007. #endif
  192008. png_free(png_ptr, buffer);
  192009. return;
  192010. }
  192011. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192012. height = png_strtod(png_ptr, ep, &vp);
  192013. if (*vp)
  192014. {
  192015. png_warning(png_ptr, "malformed height string in sCAL chunk");
  192016. return;
  192017. }
  192018. #else
  192019. #ifdef PNG_FIXED_POINT_SUPPORTED
  192020. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  192021. if (swidth == NULL)
  192022. {
  192023. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  192024. return;
  192025. }
  192026. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  192027. #endif
  192028. #endif
  192029. if (buffer + slength < ep
  192030. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192031. || width <= 0. || height <= 0.
  192032. #endif
  192033. )
  192034. {
  192035. png_warning(png_ptr, "Invalid sCAL data");
  192036. png_free(png_ptr, buffer);
  192037. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192038. png_free(png_ptr, swidth);
  192039. png_free(png_ptr, sheight);
  192040. #endif
  192041. return;
  192042. }
  192043. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192044. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  192045. #else
  192046. #ifdef PNG_FIXED_POINT_SUPPORTED
  192047. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  192048. #endif
  192049. #endif
  192050. png_free(png_ptr, buffer);
  192051. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192052. png_free(png_ptr, swidth);
  192053. png_free(png_ptr, sheight);
  192054. #endif
  192055. }
  192056. #endif
  192057. #if defined(PNG_READ_tIME_SUPPORTED)
  192058. void /* PRIVATE */
  192059. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192060. {
  192061. png_byte buf[7];
  192062. png_time mod_time;
  192063. png_debug(1, "in png_handle_tIME\n");
  192064. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192065. png_error(png_ptr, "Out of place tIME chunk");
  192066. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  192067. {
  192068. png_warning(png_ptr, "Duplicate tIME chunk");
  192069. png_crc_finish(png_ptr, length);
  192070. return;
  192071. }
  192072. if (png_ptr->mode & PNG_HAVE_IDAT)
  192073. png_ptr->mode |= PNG_AFTER_IDAT;
  192074. if (length != 7)
  192075. {
  192076. png_warning(png_ptr, "Incorrect tIME chunk length");
  192077. png_crc_finish(png_ptr, length);
  192078. return;
  192079. }
  192080. png_crc_read(png_ptr, buf, 7);
  192081. if (png_crc_finish(png_ptr, 0))
  192082. return;
  192083. mod_time.second = buf[6];
  192084. mod_time.minute = buf[5];
  192085. mod_time.hour = buf[4];
  192086. mod_time.day = buf[3];
  192087. mod_time.month = buf[2];
  192088. mod_time.year = png_get_uint_16(buf);
  192089. png_set_tIME(png_ptr, info_ptr, &mod_time);
  192090. }
  192091. #endif
  192092. #if defined(PNG_READ_tEXt_SUPPORTED)
  192093. /* Note: this does not properly handle chunks that are > 64K under DOS */
  192094. void /* PRIVATE */
  192095. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192096. {
  192097. png_textp text_ptr;
  192098. png_charp key;
  192099. png_charp text;
  192100. png_uint_32 skip = 0;
  192101. png_size_t slength;
  192102. int ret;
  192103. png_debug(1, "in png_handle_tEXt\n");
  192104. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192105. png_error(png_ptr, "Missing IHDR before tEXt");
  192106. if (png_ptr->mode & PNG_HAVE_IDAT)
  192107. png_ptr->mode |= PNG_AFTER_IDAT;
  192108. #ifdef PNG_MAX_MALLOC_64K
  192109. if (length > (png_uint_32)65535L)
  192110. {
  192111. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  192112. skip = length - (png_uint_32)65535L;
  192113. length = (png_uint_32)65535L;
  192114. }
  192115. #endif
  192116. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192117. if (key == NULL)
  192118. {
  192119. png_warning(png_ptr, "No memory to process text chunk.");
  192120. return;
  192121. }
  192122. slength = (png_size_t)length;
  192123. png_crc_read(png_ptr, (png_bytep)key, slength);
  192124. if (png_crc_finish(png_ptr, skip))
  192125. {
  192126. png_free(png_ptr, key);
  192127. return;
  192128. }
  192129. key[slength] = 0x00;
  192130. for (text = key; *text; text++)
  192131. /* empty loop to find end of key */ ;
  192132. if (text != key + slength)
  192133. text++;
  192134. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192135. (png_uint_32)png_sizeof(png_text));
  192136. if (text_ptr == NULL)
  192137. {
  192138. png_warning(png_ptr, "Not enough memory to process text chunk.");
  192139. png_free(png_ptr, key);
  192140. return;
  192141. }
  192142. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  192143. text_ptr->key = key;
  192144. #ifdef PNG_iTXt_SUPPORTED
  192145. text_ptr->lang = NULL;
  192146. text_ptr->lang_key = NULL;
  192147. text_ptr->itxt_length = 0;
  192148. #endif
  192149. text_ptr->text = text;
  192150. text_ptr->text_length = png_strlen(text);
  192151. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192152. png_free(png_ptr, key);
  192153. png_free(png_ptr, text_ptr);
  192154. if (ret)
  192155. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  192156. }
  192157. #endif
  192158. #if defined(PNG_READ_zTXt_SUPPORTED)
  192159. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192160. void /* PRIVATE */
  192161. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192162. {
  192163. png_textp text_ptr;
  192164. png_charp chunkdata;
  192165. png_charp text;
  192166. int comp_type;
  192167. int ret;
  192168. png_size_t slength, prefix_len, data_len;
  192169. png_debug(1, "in png_handle_zTXt\n");
  192170. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192171. png_error(png_ptr, "Missing IHDR before zTXt");
  192172. if (png_ptr->mode & PNG_HAVE_IDAT)
  192173. png_ptr->mode |= PNG_AFTER_IDAT;
  192174. #ifdef PNG_MAX_MALLOC_64K
  192175. /* We will no doubt have problems with chunks even half this size, but
  192176. there is no hard and fast rule to tell us where to stop. */
  192177. if (length > (png_uint_32)65535L)
  192178. {
  192179. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  192180. png_crc_finish(png_ptr, length);
  192181. return;
  192182. }
  192183. #endif
  192184. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192185. if (chunkdata == NULL)
  192186. {
  192187. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  192188. return;
  192189. }
  192190. slength = (png_size_t)length;
  192191. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192192. if (png_crc_finish(png_ptr, 0))
  192193. {
  192194. png_free(png_ptr, chunkdata);
  192195. return;
  192196. }
  192197. chunkdata[slength] = 0x00;
  192198. for (text = chunkdata; *text; text++)
  192199. /* empty loop */ ;
  192200. /* zTXt must have some text after the chunkdataword */
  192201. if (text >= chunkdata + slength - 2)
  192202. {
  192203. png_warning(png_ptr, "Truncated zTXt chunk");
  192204. png_free(png_ptr, chunkdata);
  192205. return;
  192206. }
  192207. else
  192208. {
  192209. comp_type = *(++text);
  192210. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  192211. {
  192212. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  192213. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  192214. }
  192215. text++; /* skip the compression_method byte */
  192216. }
  192217. prefix_len = text - chunkdata;
  192218. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192219. (png_size_t)length, prefix_len, &data_len);
  192220. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192221. (png_uint_32)png_sizeof(png_text));
  192222. if (text_ptr == NULL)
  192223. {
  192224. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  192225. png_free(png_ptr, chunkdata);
  192226. return;
  192227. }
  192228. text_ptr->compression = comp_type;
  192229. text_ptr->key = chunkdata;
  192230. #ifdef PNG_iTXt_SUPPORTED
  192231. text_ptr->lang = NULL;
  192232. text_ptr->lang_key = NULL;
  192233. text_ptr->itxt_length = 0;
  192234. #endif
  192235. text_ptr->text = chunkdata + prefix_len;
  192236. text_ptr->text_length = data_len;
  192237. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192238. png_free(png_ptr, text_ptr);
  192239. png_free(png_ptr, chunkdata);
  192240. if (ret)
  192241. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  192242. }
  192243. #endif
  192244. #if defined(PNG_READ_iTXt_SUPPORTED)
  192245. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192246. void /* PRIVATE */
  192247. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192248. {
  192249. png_textp text_ptr;
  192250. png_charp chunkdata;
  192251. png_charp key, lang, text, lang_key;
  192252. int comp_flag;
  192253. int comp_type = 0;
  192254. int ret;
  192255. png_size_t slength, prefix_len, data_len;
  192256. png_debug(1, "in png_handle_iTXt\n");
  192257. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192258. png_error(png_ptr, "Missing IHDR before iTXt");
  192259. if (png_ptr->mode & PNG_HAVE_IDAT)
  192260. png_ptr->mode |= PNG_AFTER_IDAT;
  192261. #ifdef PNG_MAX_MALLOC_64K
  192262. /* We will no doubt have problems with chunks even half this size, but
  192263. there is no hard and fast rule to tell us where to stop. */
  192264. if (length > (png_uint_32)65535L)
  192265. {
  192266. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  192267. png_crc_finish(png_ptr, length);
  192268. return;
  192269. }
  192270. #endif
  192271. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192272. if (chunkdata == NULL)
  192273. {
  192274. png_warning(png_ptr, "No memory to process iTXt chunk.");
  192275. return;
  192276. }
  192277. slength = (png_size_t)length;
  192278. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192279. if (png_crc_finish(png_ptr, 0))
  192280. {
  192281. png_free(png_ptr, chunkdata);
  192282. return;
  192283. }
  192284. chunkdata[slength] = 0x00;
  192285. for (lang = chunkdata; *lang; lang++)
  192286. /* empty loop */ ;
  192287. lang++; /* skip NUL separator */
  192288. /* iTXt must have a language tag (possibly empty), two compression bytes,
  192289. translated keyword (possibly empty), and possibly some text after the
  192290. keyword */
  192291. if (lang >= chunkdata + slength - 3)
  192292. {
  192293. png_warning(png_ptr, "Truncated iTXt chunk");
  192294. png_free(png_ptr, chunkdata);
  192295. return;
  192296. }
  192297. else
  192298. {
  192299. comp_flag = *lang++;
  192300. comp_type = *lang++;
  192301. }
  192302. for (lang_key = lang; *lang_key; lang_key++)
  192303. /* empty loop */ ;
  192304. lang_key++; /* skip NUL separator */
  192305. if (lang_key >= chunkdata + slength)
  192306. {
  192307. png_warning(png_ptr, "Truncated iTXt chunk");
  192308. png_free(png_ptr, chunkdata);
  192309. return;
  192310. }
  192311. for (text = lang_key; *text; text++)
  192312. /* empty loop */ ;
  192313. text++; /* skip NUL separator */
  192314. if (text >= chunkdata + slength)
  192315. {
  192316. png_warning(png_ptr, "Malformed iTXt chunk");
  192317. png_free(png_ptr, chunkdata);
  192318. return;
  192319. }
  192320. prefix_len = text - chunkdata;
  192321. key=chunkdata;
  192322. if (comp_flag)
  192323. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192324. (size_t)length, prefix_len, &data_len);
  192325. else
  192326. data_len=png_strlen(chunkdata + prefix_len);
  192327. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192328. (png_uint_32)png_sizeof(png_text));
  192329. if (text_ptr == NULL)
  192330. {
  192331. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  192332. png_free(png_ptr, chunkdata);
  192333. return;
  192334. }
  192335. text_ptr->compression = (int)comp_flag + 1;
  192336. text_ptr->lang_key = chunkdata+(lang_key-key);
  192337. text_ptr->lang = chunkdata+(lang-key);
  192338. text_ptr->itxt_length = data_len;
  192339. text_ptr->text_length = 0;
  192340. text_ptr->key = chunkdata;
  192341. text_ptr->text = chunkdata + prefix_len;
  192342. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192343. png_free(png_ptr, text_ptr);
  192344. png_free(png_ptr, chunkdata);
  192345. if (ret)
  192346. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  192347. }
  192348. #endif
  192349. /* This function is called when we haven't found a handler for a
  192350. chunk. If there isn't a problem with the chunk itself (ie bad
  192351. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  192352. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  192353. case it will be saved away to be written out later. */
  192354. void /* PRIVATE */
  192355. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192356. {
  192357. png_uint_32 skip = 0;
  192358. png_debug(1, "in png_handle_unknown\n");
  192359. if (png_ptr->mode & PNG_HAVE_IDAT)
  192360. {
  192361. #ifdef PNG_USE_LOCAL_ARRAYS
  192362. PNG_CONST PNG_IDAT;
  192363. #endif
  192364. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  192365. png_ptr->mode |= PNG_AFTER_IDAT;
  192366. }
  192367. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  192368. if (!(png_ptr->chunk_name[0] & 0x20))
  192369. {
  192370. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  192371. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  192372. PNG_HANDLE_CHUNK_ALWAYS
  192373. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192374. && png_ptr->read_user_chunk_fn == NULL
  192375. #endif
  192376. )
  192377. #endif
  192378. png_chunk_error(png_ptr, "unknown critical chunk");
  192379. }
  192380. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  192381. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  192382. (png_ptr->read_user_chunk_fn != NULL))
  192383. {
  192384. #ifdef PNG_MAX_MALLOC_64K
  192385. if (length > (png_uint_32)65535L)
  192386. {
  192387. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  192388. skip = length - (png_uint_32)65535L;
  192389. length = (png_uint_32)65535L;
  192390. }
  192391. #endif
  192392. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  192393. (png_charp)png_ptr->chunk_name, 5);
  192394. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  192395. png_ptr->unknown_chunk.size = (png_size_t)length;
  192396. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  192397. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192398. if(png_ptr->read_user_chunk_fn != NULL)
  192399. {
  192400. /* callback to user unknown chunk handler */
  192401. int ret;
  192402. ret = (*(png_ptr->read_user_chunk_fn))
  192403. (png_ptr, &png_ptr->unknown_chunk);
  192404. if (ret < 0)
  192405. png_chunk_error(png_ptr, "error in user chunk");
  192406. if (ret == 0)
  192407. {
  192408. if (!(png_ptr->chunk_name[0] & 0x20))
  192409. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  192410. PNG_HANDLE_CHUNK_ALWAYS)
  192411. png_chunk_error(png_ptr, "unknown critical chunk");
  192412. png_set_unknown_chunks(png_ptr, info_ptr,
  192413. &png_ptr->unknown_chunk, 1);
  192414. }
  192415. }
  192416. #else
  192417. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  192418. #endif
  192419. png_free(png_ptr, png_ptr->unknown_chunk.data);
  192420. png_ptr->unknown_chunk.data = NULL;
  192421. }
  192422. else
  192423. #endif
  192424. skip = length;
  192425. png_crc_finish(png_ptr, skip);
  192426. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192427. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  192428. #endif
  192429. }
  192430. /* This function is called to verify that a chunk name is valid.
  192431. This function can't have the "critical chunk check" incorporated
  192432. into it, since in the future we will need to be able to call user
  192433. functions to handle unknown critical chunks after we check that
  192434. the chunk name itself is valid. */
  192435. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  192436. void /* PRIVATE */
  192437. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  192438. {
  192439. png_debug(1, "in png_check_chunk_name\n");
  192440. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  192441. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  192442. {
  192443. png_chunk_error(png_ptr, "invalid chunk type");
  192444. }
  192445. }
  192446. /* Combines the row recently read in with the existing pixels in the
  192447. row. This routine takes care of alpha and transparency if requested.
  192448. This routine also handles the two methods of progressive display
  192449. of interlaced images, depending on the mask value.
  192450. The mask value describes which pixels are to be combined with
  192451. the row. The pattern always repeats every 8 pixels, so just 8
  192452. bits are needed. A one indicates the pixel is to be combined,
  192453. a zero indicates the pixel is to be skipped. This is in addition
  192454. to any alpha or transparency value associated with the pixel. If
  192455. you want all pixels to be combined, pass 0xff (255) in mask. */
  192456. void /* PRIVATE */
  192457. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  192458. {
  192459. png_debug(1,"in png_combine_row\n");
  192460. if (mask == 0xff)
  192461. {
  192462. png_memcpy(row, png_ptr->row_buf + 1,
  192463. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  192464. }
  192465. else
  192466. {
  192467. switch (png_ptr->row_info.pixel_depth)
  192468. {
  192469. case 1:
  192470. {
  192471. png_bytep sp = png_ptr->row_buf + 1;
  192472. png_bytep dp = row;
  192473. int s_inc, s_start, s_end;
  192474. int m = 0x80;
  192475. int shift;
  192476. png_uint_32 i;
  192477. png_uint_32 row_width = png_ptr->width;
  192478. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192479. if (png_ptr->transformations & PNG_PACKSWAP)
  192480. {
  192481. s_start = 0;
  192482. s_end = 7;
  192483. s_inc = 1;
  192484. }
  192485. else
  192486. #endif
  192487. {
  192488. s_start = 7;
  192489. s_end = 0;
  192490. s_inc = -1;
  192491. }
  192492. shift = s_start;
  192493. for (i = 0; i < row_width; i++)
  192494. {
  192495. if (m & mask)
  192496. {
  192497. int value;
  192498. value = (*sp >> shift) & 0x01;
  192499. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192500. *dp |= (png_byte)(value << shift);
  192501. }
  192502. if (shift == s_end)
  192503. {
  192504. shift = s_start;
  192505. sp++;
  192506. dp++;
  192507. }
  192508. else
  192509. shift += s_inc;
  192510. if (m == 1)
  192511. m = 0x80;
  192512. else
  192513. m >>= 1;
  192514. }
  192515. break;
  192516. }
  192517. case 2:
  192518. {
  192519. png_bytep sp = png_ptr->row_buf + 1;
  192520. png_bytep dp = row;
  192521. int s_start, s_end, s_inc;
  192522. int m = 0x80;
  192523. int shift;
  192524. png_uint_32 i;
  192525. png_uint_32 row_width = png_ptr->width;
  192526. int value;
  192527. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192528. if (png_ptr->transformations & PNG_PACKSWAP)
  192529. {
  192530. s_start = 0;
  192531. s_end = 6;
  192532. s_inc = 2;
  192533. }
  192534. else
  192535. #endif
  192536. {
  192537. s_start = 6;
  192538. s_end = 0;
  192539. s_inc = -2;
  192540. }
  192541. shift = s_start;
  192542. for (i = 0; i < row_width; i++)
  192543. {
  192544. if (m & mask)
  192545. {
  192546. value = (*sp >> shift) & 0x03;
  192547. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192548. *dp |= (png_byte)(value << shift);
  192549. }
  192550. if (shift == s_end)
  192551. {
  192552. shift = s_start;
  192553. sp++;
  192554. dp++;
  192555. }
  192556. else
  192557. shift += s_inc;
  192558. if (m == 1)
  192559. m = 0x80;
  192560. else
  192561. m >>= 1;
  192562. }
  192563. break;
  192564. }
  192565. case 4:
  192566. {
  192567. png_bytep sp = png_ptr->row_buf + 1;
  192568. png_bytep dp = row;
  192569. int s_start, s_end, s_inc;
  192570. int m = 0x80;
  192571. int shift;
  192572. png_uint_32 i;
  192573. png_uint_32 row_width = png_ptr->width;
  192574. int value;
  192575. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192576. if (png_ptr->transformations & PNG_PACKSWAP)
  192577. {
  192578. s_start = 0;
  192579. s_end = 4;
  192580. s_inc = 4;
  192581. }
  192582. else
  192583. #endif
  192584. {
  192585. s_start = 4;
  192586. s_end = 0;
  192587. s_inc = -4;
  192588. }
  192589. shift = s_start;
  192590. for (i = 0; i < row_width; i++)
  192591. {
  192592. if (m & mask)
  192593. {
  192594. value = (*sp >> shift) & 0xf;
  192595. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192596. *dp |= (png_byte)(value << shift);
  192597. }
  192598. if (shift == s_end)
  192599. {
  192600. shift = s_start;
  192601. sp++;
  192602. dp++;
  192603. }
  192604. else
  192605. shift += s_inc;
  192606. if (m == 1)
  192607. m = 0x80;
  192608. else
  192609. m >>= 1;
  192610. }
  192611. break;
  192612. }
  192613. default:
  192614. {
  192615. png_bytep sp = png_ptr->row_buf + 1;
  192616. png_bytep dp = row;
  192617. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  192618. png_uint_32 i;
  192619. png_uint_32 row_width = png_ptr->width;
  192620. png_byte m = 0x80;
  192621. for (i = 0; i < row_width; i++)
  192622. {
  192623. if (m & mask)
  192624. {
  192625. png_memcpy(dp, sp, pixel_bytes);
  192626. }
  192627. sp += pixel_bytes;
  192628. dp += pixel_bytes;
  192629. if (m == 1)
  192630. m = 0x80;
  192631. else
  192632. m >>= 1;
  192633. }
  192634. break;
  192635. }
  192636. }
  192637. }
  192638. }
  192639. #ifdef PNG_READ_INTERLACING_SUPPORTED
  192640. /* OLD pre-1.0.9 interface:
  192641. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  192642. png_uint_32 transformations)
  192643. */
  192644. void /* PRIVATE */
  192645. png_do_read_interlace(png_structp png_ptr)
  192646. {
  192647. png_row_infop row_info = &(png_ptr->row_info);
  192648. png_bytep row = png_ptr->row_buf + 1;
  192649. int pass = png_ptr->pass;
  192650. png_uint_32 transformations = png_ptr->transformations;
  192651. #ifdef PNG_USE_LOCAL_ARRAYS
  192652. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192653. /* offset to next interlace block */
  192654. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192655. #endif
  192656. png_debug(1,"in png_do_read_interlace\n");
  192657. if (row != NULL && row_info != NULL)
  192658. {
  192659. png_uint_32 final_width;
  192660. final_width = row_info->width * png_pass_inc[pass];
  192661. switch (row_info->pixel_depth)
  192662. {
  192663. case 1:
  192664. {
  192665. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  192666. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  192667. int sshift, dshift;
  192668. int s_start, s_end, s_inc;
  192669. int jstop = png_pass_inc[pass];
  192670. png_byte v;
  192671. png_uint_32 i;
  192672. int j;
  192673. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192674. if (transformations & PNG_PACKSWAP)
  192675. {
  192676. sshift = (int)((row_info->width + 7) & 0x07);
  192677. dshift = (int)((final_width + 7) & 0x07);
  192678. s_start = 7;
  192679. s_end = 0;
  192680. s_inc = -1;
  192681. }
  192682. else
  192683. #endif
  192684. {
  192685. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  192686. dshift = 7 - (int)((final_width + 7) & 0x07);
  192687. s_start = 0;
  192688. s_end = 7;
  192689. s_inc = 1;
  192690. }
  192691. for (i = 0; i < row_info->width; i++)
  192692. {
  192693. v = (png_byte)((*sp >> sshift) & 0x01);
  192694. for (j = 0; j < jstop; j++)
  192695. {
  192696. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  192697. *dp |= (png_byte)(v << dshift);
  192698. if (dshift == s_end)
  192699. {
  192700. dshift = s_start;
  192701. dp--;
  192702. }
  192703. else
  192704. dshift += s_inc;
  192705. }
  192706. if (sshift == s_end)
  192707. {
  192708. sshift = s_start;
  192709. sp--;
  192710. }
  192711. else
  192712. sshift += s_inc;
  192713. }
  192714. break;
  192715. }
  192716. case 2:
  192717. {
  192718. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  192719. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  192720. int sshift, dshift;
  192721. int s_start, s_end, s_inc;
  192722. int jstop = png_pass_inc[pass];
  192723. png_uint_32 i;
  192724. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192725. if (transformations & PNG_PACKSWAP)
  192726. {
  192727. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  192728. dshift = (int)(((final_width + 3) & 0x03) << 1);
  192729. s_start = 6;
  192730. s_end = 0;
  192731. s_inc = -2;
  192732. }
  192733. else
  192734. #endif
  192735. {
  192736. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  192737. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  192738. s_start = 0;
  192739. s_end = 6;
  192740. s_inc = 2;
  192741. }
  192742. for (i = 0; i < row_info->width; i++)
  192743. {
  192744. png_byte v;
  192745. int j;
  192746. v = (png_byte)((*sp >> sshift) & 0x03);
  192747. for (j = 0; j < jstop; j++)
  192748. {
  192749. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  192750. *dp |= (png_byte)(v << dshift);
  192751. if (dshift == s_end)
  192752. {
  192753. dshift = s_start;
  192754. dp--;
  192755. }
  192756. else
  192757. dshift += s_inc;
  192758. }
  192759. if (sshift == s_end)
  192760. {
  192761. sshift = s_start;
  192762. sp--;
  192763. }
  192764. else
  192765. sshift += s_inc;
  192766. }
  192767. break;
  192768. }
  192769. case 4:
  192770. {
  192771. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  192772. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  192773. int sshift, dshift;
  192774. int s_start, s_end, s_inc;
  192775. png_uint_32 i;
  192776. int jstop = png_pass_inc[pass];
  192777. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192778. if (transformations & PNG_PACKSWAP)
  192779. {
  192780. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  192781. dshift = (int)(((final_width + 1) & 0x01) << 2);
  192782. s_start = 4;
  192783. s_end = 0;
  192784. s_inc = -4;
  192785. }
  192786. else
  192787. #endif
  192788. {
  192789. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  192790. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  192791. s_start = 0;
  192792. s_end = 4;
  192793. s_inc = 4;
  192794. }
  192795. for (i = 0; i < row_info->width; i++)
  192796. {
  192797. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  192798. int j;
  192799. for (j = 0; j < jstop; j++)
  192800. {
  192801. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  192802. *dp |= (png_byte)(v << dshift);
  192803. if (dshift == s_end)
  192804. {
  192805. dshift = s_start;
  192806. dp--;
  192807. }
  192808. else
  192809. dshift += s_inc;
  192810. }
  192811. if (sshift == s_end)
  192812. {
  192813. sshift = s_start;
  192814. sp--;
  192815. }
  192816. else
  192817. sshift += s_inc;
  192818. }
  192819. break;
  192820. }
  192821. default:
  192822. {
  192823. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  192824. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  192825. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  192826. int jstop = png_pass_inc[pass];
  192827. png_uint_32 i;
  192828. for (i = 0; i < row_info->width; i++)
  192829. {
  192830. png_byte v[8];
  192831. int j;
  192832. png_memcpy(v, sp, pixel_bytes);
  192833. for (j = 0; j < jstop; j++)
  192834. {
  192835. png_memcpy(dp, v, pixel_bytes);
  192836. dp -= pixel_bytes;
  192837. }
  192838. sp -= pixel_bytes;
  192839. }
  192840. break;
  192841. }
  192842. }
  192843. row_info->width = final_width;
  192844. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  192845. }
  192846. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  192847. transformations = transformations; /* silence compiler warning */
  192848. #endif
  192849. }
  192850. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  192851. void /* PRIVATE */
  192852. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  192853. png_bytep prev_row, int filter)
  192854. {
  192855. png_debug(1, "in png_read_filter_row\n");
  192856. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  192857. switch (filter)
  192858. {
  192859. case PNG_FILTER_VALUE_NONE:
  192860. break;
  192861. case PNG_FILTER_VALUE_SUB:
  192862. {
  192863. png_uint_32 i;
  192864. png_uint_32 istop = row_info->rowbytes;
  192865. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192866. png_bytep rp = row + bpp;
  192867. png_bytep lp = row;
  192868. for (i = bpp; i < istop; i++)
  192869. {
  192870. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  192871. rp++;
  192872. }
  192873. break;
  192874. }
  192875. case PNG_FILTER_VALUE_UP:
  192876. {
  192877. png_uint_32 i;
  192878. png_uint_32 istop = row_info->rowbytes;
  192879. png_bytep rp = row;
  192880. png_bytep pp = prev_row;
  192881. for (i = 0; i < istop; i++)
  192882. {
  192883. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192884. rp++;
  192885. }
  192886. break;
  192887. }
  192888. case PNG_FILTER_VALUE_AVG:
  192889. {
  192890. png_uint_32 i;
  192891. png_bytep rp = row;
  192892. png_bytep pp = prev_row;
  192893. png_bytep lp = row;
  192894. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192895. png_uint_32 istop = row_info->rowbytes - bpp;
  192896. for (i = 0; i < bpp; i++)
  192897. {
  192898. *rp = (png_byte)(((int)(*rp) +
  192899. ((int)(*pp++) / 2 )) & 0xff);
  192900. rp++;
  192901. }
  192902. for (i = 0; i < istop; i++)
  192903. {
  192904. *rp = (png_byte)(((int)(*rp) +
  192905. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  192906. rp++;
  192907. }
  192908. break;
  192909. }
  192910. case PNG_FILTER_VALUE_PAETH:
  192911. {
  192912. png_uint_32 i;
  192913. png_bytep rp = row;
  192914. png_bytep pp = prev_row;
  192915. png_bytep lp = row;
  192916. png_bytep cp = prev_row;
  192917. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192918. png_uint_32 istop=row_info->rowbytes - bpp;
  192919. for (i = 0; i < bpp; i++)
  192920. {
  192921. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192922. rp++;
  192923. }
  192924. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  192925. {
  192926. int a, b, c, pa, pb, pc, p;
  192927. a = *lp++;
  192928. b = *pp++;
  192929. c = *cp++;
  192930. p = b - c;
  192931. pc = a - c;
  192932. #ifdef PNG_USE_ABS
  192933. pa = abs(p);
  192934. pb = abs(pc);
  192935. pc = abs(p + pc);
  192936. #else
  192937. pa = p < 0 ? -p : p;
  192938. pb = pc < 0 ? -pc : pc;
  192939. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  192940. #endif
  192941. /*
  192942. if (pa <= pb && pa <= pc)
  192943. p = a;
  192944. else if (pb <= pc)
  192945. p = b;
  192946. else
  192947. p = c;
  192948. */
  192949. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  192950. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  192951. rp++;
  192952. }
  192953. break;
  192954. }
  192955. default:
  192956. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  192957. *row=0;
  192958. break;
  192959. }
  192960. }
  192961. void /* PRIVATE */
  192962. png_read_finish_row(png_structp png_ptr)
  192963. {
  192964. #ifdef PNG_USE_LOCAL_ARRAYS
  192965. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192966. /* start of interlace block */
  192967. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192968. /* offset to next interlace block */
  192969. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192970. /* start of interlace block in the y direction */
  192971. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192972. /* offset to next interlace block in the y direction */
  192973. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192974. #endif
  192975. png_debug(1, "in png_read_finish_row\n");
  192976. png_ptr->row_number++;
  192977. if (png_ptr->row_number < png_ptr->num_rows)
  192978. return;
  192979. if (png_ptr->interlaced)
  192980. {
  192981. png_ptr->row_number = 0;
  192982. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  192983. png_ptr->rowbytes + 1);
  192984. do
  192985. {
  192986. png_ptr->pass++;
  192987. if (png_ptr->pass >= 7)
  192988. break;
  192989. png_ptr->iwidth = (png_ptr->width +
  192990. png_pass_inc[png_ptr->pass] - 1 -
  192991. png_pass_start[png_ptr->pass]) /
  192992. png_pass_inc[png_ptr->pass];
  192993. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  192994. png_ptr->iwidth) + 1;
  192995. if (!(png_ptr->transformations & PNG_INTERLACE))
  192996. {
  192997. png_ptr->num_rows = (png_ptr->height +
  192998. png_pass_yinc[png_ptr->pass] - 1 -
  192999. png_pass_ystart[png_ptr->pass]) /
  193000. png_pass_yinc[png_ptr->pass];
  193001. if (!(png_ptr->num_rows))
  193002. continue;
  193003. }
  193004. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  193005. break;
  193006. } while (png_ptr->iwidth == 0);
  193007. if (png_ptr->pass < 7)
  193008. return;
  193009. }
  193010. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  193011. {
  193012. #ifdef PNG_USE_LOCAL_ARRAYS
  193013. PNG_CONST PNG_IDAT;
  193014. #endif
  193015. char extra;
  193016. int ret;
  193017. png_ptr->zstream.next_out = (Bytef *)&extra;
  193018. png_ptr->zstream.avail_out = (uInt)1;
  193019. for(;;)
  193020. {
  193021. if (!(png_ptr->zstream.avail_in))
  193022. {
  193023. while (!png_ptr->idat_size)
  193024. {
  193025. png_byte chunk_length[4];
  193026. png_crc_finish(png_ptr, 0);
  193027. png_read_data(png_ptr, chunk_length, 4);
  193028. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  193029. png_reset_crc(png_ptr);
  193030. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  193031. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  193032. png_error(png_ptr, "Not enough image data");
  193033. }
  193034. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  193035. png_ptr->zstream.next_in = png_ptr->zbuf;
  193036. if (png_ptr->zbuf_size > png_ptr->idat_size)
  193037. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  193038. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  193039. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  193040. }
  193041. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193042. if (ret == Z_STREAM_END)
  193043. {
  193044. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  193045. png_ptr->idat_size)
  193046. png_warning(png_ptr, "Extra compressed data");
  193047. png_ptr->mode |= PNG_AFTER_IDAT;
  193048. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193049. break;
  193050. }
  193051. if (ret != Z_OK)
  193052. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  193053. "Decompression Error");
  193054. if (!(png_ptr->zstream.avail_out))
  193055. {
  193056. png_warning(png_ptr, "Extra compressed data.");
  193057. png_ptr->mode |= PNG_AFTER_IDAT;
  193058. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193059. break;
  193060. }
  193061. }
  193062. png_ptr->zstream.avail_out = 0;
  193063. }
  193064. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  193065. png_warning(png_ptr, "Extra compression data");
  193066. inflateReset(&png_ptr->zstream);
  193067. png_ptr->mode |= PNG_AFTER_IDAT;
  193068. }
  193069. void /* PRIVATE */
  193070. png_read_start_row(png_structp png_ptr)
  193071. {
  193072. #ifdef PNG_USE_LOCAL_ARRAYS
  193073. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193074. /* start of interlace block */
  193075. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  193076. /* offset to next interlace block */
  193077. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193078. /* start of interlace block in the y direction */
  193079. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  193080. /* offset to next interlace block in the y direction */
  193081. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  193082. #endif
  193083. int max_pixel_depth;
  193084. png_uint_32 row_bytes;
  193085. png_debug(1, "in png_read_start_row\n");
  193086. png_ptr->zstream.avail_in = 0;
  193087. png_init_read_transformations(png_ptr);
  193088. if (png_ptr->interlaced)
  193089. {
  193090. if (!(png_ptr->transformations & PNG_INTERLACE))
  193091. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  193092. png_pass_ystart[0]) / png_pass_yinc[0];
  193093. else
  193094. png_ptr->num_rows = png_ptr->height;
  193095. png_ptr->iwidth = (png_ptr->width +
  193096. png_pass_inc[png_ptr->pass] - 1 -
  193097. png_pass_start[png_ptr->pass]) /
  193098. png_pass_inc[png_ptr->pass];
  193099. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  193100. png_ptr->irowbytes = (png_size_t)row_bytes;
  193101. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  193102. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  193103. }
  193104. else
  193105. {
  193106. png_ptr->num_rows = png_ptr->height;
  193107. png_ptr->iwidth = png_ptr->width;
  193108. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  193109. }
  193110. max_pixel_depth = png_ptr->pixel_depth;
  193111. #if defined(PNG_READ_PACK_SUPPORTED)
  193112. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  193113. max_pixel_depth = 8;
  193114. #endif
  193115. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193116. if (png_ptr->transformations & PNG_EXPAND)
  193117. {
  193118. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193119. {
  193120. if (png_ptr->num_trans)
  193121. max_pixel_depth = 32;
  193122. else
  193123. max_pixel_depth = 24;
  193124. }
  193125. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193126. {
  193127. if (max_pixel_depth < 8)
  193128. max_pixel_depth = 8;
  193129. if (png_ptr->num_trans)
  193130. max_pixel_depth *= 2;
  193131. }
  193132. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193133. {
  193134. if (png_ptr->num_trans)
  193135. {
  193136. max_pixel_depth *= 4;
  193137. max_pixel_depth /= 3;
  193138. }
  193139. }
  193140. }
  193141. #endif
  193142. #if defined(PNG_READ_FILLER_SUPPORTED)
  193143. if (png_ptr->transformations & (PNG_FILLER))
  193144. {
  193145. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193146. max_pixel_depth = 32;
  193147. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193148. {
  193149. if (max_pixel_depth <= 8)
  193150. max_pixel_depth = 16;
  193151. else
  193152. max_pixel_depth = 32;
  193153. }
  193154. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193155. {
  193156. if (max_pixel_depth <= 32)
  193157. max_pixel_depth = 32;
  193158. else
  193159. max_pixel_depth = 64;
  193160. }
  193161. }
  193162. #endif
  193163. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  193164. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  193165. {
  193166. if (
  193167. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193168. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  193169. #endif
  193170. #if defined(PNG_READ_FILLER_SUPPORTED)
  193171. (png_ptr->transformations & (PNG_FILLER)) ||
  193172. #endif
  193173. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193174. {
  193175. if (max_pixel_depth <= 16)
  193176. max_pixel_depth = 32;
  193177. else
  193178. max_pixel_depth = 64;
  193179. }
  193180. else
  193181. {
  193182. if (max_pixel_depth <= 8)
  193183. {
  193184. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193185. max_pixel_depth = 32;
  193186. else
  193187. max_pixel_depth = 24;
  193188. }
  193189. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193190. max_pixel_depth = 64;
  193191. else
  193192. max_pixel_depth = 48;
  193193. }
  193194. }
  193195. #endif
  193196. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  193197. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193198. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  193199. {
  193200. int user_pixel_depth=png_ptr->user_transform_depth*
  193201. png_ptr->user_transform_channels;
  193202. if(user_pixel_depth > max_pixel_depth)
  193203. max_pixel_depth=user_pixel_depth;
  193204. }
  193205. #endif
  193206. /* align the width on the next larger 8 pixels. Mainly used
  193207. for interlacing */
  193208. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  193209. /* calculate the maximum bytes needed, adding a byte and a pixel
  193210. for safety's sake */
  193211. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  193212. 1 + ((max_pixel_depth + 7) >> 3);
  193213. #ifdef PNG_MAX_MALLOC_64K
  193214. if (row_bytes > (png_uint_32)65536L)
  193215. png_error(png_ptr, "This image requires a row greater than 64KB");
  193216. #endif
  193217. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  193218. png_ptr->row_buf = png_ptr->big_row_buf+32;
  193219. #ifdef PNG_MAX_MALLOC_64K
  193220. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  193221. png_error(png_ptr, "This image requires a row greater than 64KB");
  193222. #endif
  193223. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  193224. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  193225. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  193226. png_ptr->rowbytes + 1));
  193227. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  193228. png_debug1(3, "width = %lu,\n", png_ptr->width);
  193229. png_debug1(3, "height = %lu,\n", png_ptr->height);
  193230. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  193231. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  193232. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  193233. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  193234. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  193235. }
  193236. #endif /* PNG_READ_SUPPORTED */
  193237. /*** End of inlined file: pngrutil.c ***/
  193238. /*** Start of inlined file: pngset.c ***/
  193239. /* pngset.c - storage of image information into info struct
  193240. *
  193241. * Last changed in libpng 1.2.21 [October 4, 2007]
  193242. * For conditions of distribution and use, see copyright notice in png.h
  193243. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193244. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193245. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193246. *
  193247. * The functions here are used during reads to store data from the file
  193248. * into the info struct, and during writes to store application data
  193249. * into the info struct for writing into the file. This abstracts the
  193250. * info struct and allows us to change the structure in the future.
  193251. */
  193252. #define PNG_INTERNAL
  193253. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193254. #if defined(PNG_bKGD_SUPPORTED)
  193255. void PNGAPI
  193256. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  193257. {
  193258. png_debug1(1, "in %s storage function\n", "bKGD");
  193259. if (png_ptr == NULL || info_ptr == NULL)
  193260. return;
  193261. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  193262. info_ptr->valid |= PNG_INFO_bKGD;
  193263. }
  193264. #endif
  193265. #if defined(PNG_cHRM_SUPPORTED)
  193266. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193267. void PNGAPI
  193268. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  193269. double white_x, double white_y, double red_x, double red_y,
  193270. double green_x, double green_y, double blue_x, double blue_y)
  193271. {
  193272. png_debug1(1, "in %s storage function\n", "cHRM");
  193273. if (png_ptr == NULL || info_ptr == NULL)
  193274. return;
  193275. if (white_x < 0.0 || white_y < 0.0 ||
  193276. red_x < 0.0 || red_y < 0.0 ||
  193277. green_x < 0.0 || green_y < 0.0 ||
  193278. blue_x < 0.0 || blue_y < 0.0)
  193279. {
  193280. png_warning(png_ptr,
  193281. "Ignoring attempt to set negative chromaticity value");
  193282. return;
  193283. }
  193284. if (white_x > 21474.83 || white_y > 21474.83 ||
  193285. red_x > 21474.83 || red_y > 21474.83 ||
  193286. green_x > 21474.83 || green_y > 21474.83 ||
  193287. blue_x > 21474.83 || blue_y > 21474.83)
  193288. {
  193289. png_warning(png_ptr,
  193290. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193291. return;
  193292. }
  193293. info_ptr->x_white = (float)white_x;
  193294. info_ptr->y_white = (float)white_y;
  193295. info_ptr->x_red = (float)red_x;
  193296. info_ptr->y_red = (float)red_y;
  193297. info_ptr->x_green = (float)green_x;
  193298. info_ptr->y_green = (float)green_y;
  193299. info_ptr->x_blue = (float)blue_x;
  193300. info_ptr->y_blue = (float)blue_y;
  193301. #ifdef PNG_FIXED_POINT_SUPPORTED
  193302. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  193303. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  193304. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  193305. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  193306. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  193307. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  193308. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  193309. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  193310. #endif
  193311. info_ptr->valid |= PNG_INFO_cHRM;
  193312. }
  193313. #endif
  193314. #ifdef PNG_FIXED_POINT_SUPPORTED
  193315. void PNGAPI
  193316. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  193317. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  193318. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  193319. png_fixed_point blue_x, png_fixed_point blue_y)
  193320. {
  193321. png_debug1(1, "in %s storage function\n", "cHRM");
  193322. if (png_ptr == NULL || info_ptr == NULL)
  193323. return;
  193324. if (white_x < 0 || white_y < 0 ||
  193325. red_x < 0 || red_y < 0 ||
  193326. green_x < 0 || green_y < 0 ||
  193327. blue_x < 0 || blue_y < 0)
  193328. {
  193329. png_warning(png_ptr,
  193330. "Ignoring attempt to set negative chromaticity value");
  193331. return;
  193332. }
  193333. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193334. if (white_x > (double) PNG_UINT_31_MAX ||
  193335. white_y > (double) PNG_UINT_31_MAX ||
  193336. red_x > (double) PNG_UINT_31_MAX ||
  193337. red_y > (double) PNG_UINT_31_MAX ||
  193338. green_x > (double) PNG_UINT_31_MAX ||
  193339. green_y > (double) PNG_UINT_31_MAX ||
  193340. blue_x > (double) PNG_UINT_31_MAX ||
  193341. blue_y > (double) PNG_UINT_31_MAX)
  193342. #else
  193343. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193344. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193345. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193346. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193347. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193348. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193349. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193350. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  193351. #endif
  193352. {
  193353. png_warning(png_ptr,
  193354. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193355. return;
  193356. }
  193357. info_ptr->int_x_white = white_x;
  193358. info_ptr->int_y_white = white_y;
  193359. info_ptr->int_x_red = red_x;
  193360. info_ptr->int_y_red = red_y;
  193361. info_ptr->int_x_green = green_x;
  193362. info_ptr->int_y_green = green_y;
  193363. info_ptr->int_x_blue = blue_x;
  193364. info_ptr->int_y_blue = blue_y;
  193365. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193366. info_ptr->x_white = (float)(white_x/100000.);
  193367. info_ptr->y_white = (float)(white_y/100000.);
  193368. info_ptr->x_red = (float)( red_x/100000.);
  193369. info_ptr->y_red = (float)( red_y/100000.);
  193370. info_ptr->x_green = (float)(green_x/100000.);
  193371. info_ptr->y_green = (float)(green_y/100000.);
  193372. info_ptr->x_blue = (float)( blue_x/100000.);
  193373. info_ptr->y_blue = (float)( blue_y/100000.);
  193374. #endif
  193375. info_ptr->valid |= PNG_INFO_cHRM;
  193376. }
  193377. #endif
  193378. #endif
  193379. #if defined(PNG_gAMA_SUPPORTED)
  193380. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193381. void PNGAPI
  193382. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  193383. {
  193384. double gamma;
  193385. png_debug1(1, "in %s storage function\n", "gAMA");
  193386. if (png_ptr == NULL || info_ptr == NULL)
  193387. return;
  193388. /* Check for overflow */
  193389. if (file_gamma > 21474.83)
  193390. {
  193391. png_warning(png_ptr, "Limiting gamma to 21474.83");
  193392. gamma=21474.83;
  193393. }
  193394. else
  193395. gamma=file_gamma;
  193396. info_ptr->gamma = (float)gamma;
  193397. #ifdef PNG_FIXED_POINT_SUPPORTED
  193398. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  193399. #endif
  193400. info_ptr->valid |= PNG_INFO_gAMA;
  193401. if(gamma == 0.0)
  193402. png_warning(png_ptr, "Setting gamma=0");
  193403. }
  193404. #endif
  193405. void PNGAPI
  193406. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  193407. int_gamma)
  193408. {
  193409. png_fixed_point gamma;
  193410. png_debug1(1, "in %s storage function\n", "gAMA");
  193411. if (png_ptr == NULL || info_ptr == NULL)
  193412. return;
  193413. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  193414. {
  193415. png_warning(png_ptr, "Limiting gamma to 21474.83");
  193416. gamma=PNG_UINT_31_MAX;
  193417. }
  193418. else
  193419. {
  193420. if (int_gamma < 0)
  193421. {
  193422. png_warning(png_ptr, "Setting negative gamma to zero");
  193423. gamma=0;
  193424. }
  193425. else
  193426. gamma=int_gamma;
  193427. }
  193428. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193429. info_ptr->gamma = (float)(gamma/100000.);
  193430. #endif
  193431. #ifdef PNG_FIXED_POINT_SUPPORTED
  193432. info_ptr->int_gamma = gamma;
  193433. #endif
  193434. info_ptr->valid |= PNG_INFO_gAMA;
  193435. if(gamma == 0)
  193436. png_warning(png_ptr, "Setting gamma=0");
  193437. }
  193438. #endif
  193439. #if defined(PNG_hIST_SUPPORTED)
  193440. void PNGAPI
  193441. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  193442. {
  193443. int i;
  193444. png_debug1(1, "in %s storage function\n", "hIST");
  193445. if (png_ptr == NULL || info_ptr == NULL)
  193446. return;
  193447. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  193448. > PNG_MAX_PALETTE_LENGTH)
  193449. {
  193450. png_warning(png_ptr,
  193451. "Invalid palette size, hIST allocation skipped.");
  193452. return;
  193453. }
  193454. #ifdef PNG_FREE_ME_SUPPORTED
  193455. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  193456. #endif
  193457. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  193458. 1.2.1 */
  193459. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  193460. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  193461. if (png_ptr->hist == NULL)
  193462. {
  193463. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  193464. return;
  193465. }
  193466. for (i = 0; i < info_ptr->num_palette; i++)
  193467. png_ptr->hist[i] = hist[i];
  193468. info_ptr->hist = png_ptr->hist;
  193469. info_ptr->valid |= PNG_INFO_hIST;
  193470. #ifdef PNG_FREE_ME_SUPPORTED
  193471. info_ptr->free_me |= PNG_FREE_HIST;
  193472. #else
  193473. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  193474. #endif
  193475. }
  193476. #endif
  193477. void PNGAPI
  193478. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  193479. png_uint_32 width, png_uint_32 height, int bit_depth,
  193480. int color_type, int interlace_type, int compression_type,
  193481. int filter_type)
  193482. {
  193483. png_debug1(1, "in %s storage function\n", "IHDR");
  193484. if (png_ptr == NULL || info_ptr == NULL)
  193485. return;
  193486. /* check for width and height valid values */
  193487. if (width == 0 || height == 0)
  193488. png_error(png_ptr, "Image width or height is zero in IHDR");
  193489. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193490. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  193491. png_error(png_ptr, "image size exceeds user limits in IHDR");
  193492. #else
  193493. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  193494. png_error(png_ptr, "image size exceeds user limits in IHDR");
  193495. #endif
  193496. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  193497. png_error(png_ptr, "Invalid image size in IHDR");
  193498. if ( width > (PNG_UINT_32_MAX
  193499. >> 3) /* 8-byte RGBA pixels */
  193500. - 64 /* bigrowbuf hack */
  193501. - 1 /* filter byte */
  193502. - 7*8 /* rounding of width to multiple of 8 pixels */
  193503. - 8) /* extra max_pixel_depth pad */
  193504. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  193505. /* check other values */
  193506. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  193507. bit_depth != 8 && bit_depth != 16)
  193508. png_error(png_ptr, "Invalid bit depth in IHDR");
  193509. if (color_type < 0 || color_type == 1 ||
  193510. color_type == 5 || color_type > 6)
  193511. png_error(png_ptr, "Invalid color type in IHDR");
  193512. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  193513. ((color_type == PNG_COLOR_TYPE_RGB ||
  193514. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  193515. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  193516. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  193517. if (interlace_type >= PNG_INTERLACE_LAST)
  193518. png_error(png_ptr, "Unknown interlace method in IHDR");
  193519. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  193520. png_error(png_ptr, "Unknown compression method in IHDR");
  193521. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193522. /* Accept filter_method 64 (intrapixel differencing) only if
  193523. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  193524. * 2. Libpng did not read a PNG signature (this filter_method is only
  193525. * used in PNG datastreams that are embedded in MNG datastreams) and
  193526. * 3. The application called png_permit_mng_features with a mask that
  193527. * included PNG_FLAG_MNG_FILTER_64 and
  193528. * 4. The filter_method is 64 and
  193529. * 5. The color_type is RGB or RGBA
  193530. */
  193531. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  193532. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  193533. if(filter_type != PNG_FILTER_TYPE_BASE)
  193534. {
  193535. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193536. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  193537. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  193538. (color_type == PNG_COLOR_TYPE_RGB ||
  193539. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  193540. png_error(png_ptr, "Unknown filter method in IHDR");
  193541. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  193542. png_warning(png_ptr, "Invalid filter method in IHDR");
  193543. }
  193544. #else
  193545. if(filter_type != PNG_FILTER_TYPE_BASE)
  193546. png_error(png_ptr, "Unknown filter method in IHDR");
  193547. #endif
  193548. info_ptr->width = width;
  193549. info_ptr->height = height;
  193550. info_ptr->bit_depth = (png_byte)bit_depth;
  193551. info_ptr->color_type =(png_byte) color_type;
  193552. info_ptr->compression_type = (png_byte)compression_type;
  193553. info_ptr->filter_type = (png_byte)filter_type;
  193554. info_ptr->interlace_type = (png_byte)interlace_type;
  193555. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193556. info_ptr->channels = 1;
  193557. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193558. info_ptr->channels = 3;
  193559. else
  193560. info_ptr->channels = 1;
  193561. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  193562. info_ptr->channels++;
  193563. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  193564. /* check for potential overflow */
  193565. if (width > (PNG_UINT_32_MAX
  193566. >> 3) /* 8-byte RGBA pixels */
  193567. - 64 /* bigrowbuf hack */
  193568. - 1 /* filter byte */
  193569. - 7*8 /* rounding of width to multiple of 8 pixels */
  193570. - 8) /* extra max_pixel_depth pad */
  193571. info_ptr->rowbytes = (png_size_t)0;
  193572. else
  193573. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  193574. }
  193575. #if defined(PNG_oFFs_SUPPORTED)
  193576. void PNGAPI
  193577. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  193578. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  193579. {
  193580. png_debug1(1, "in %s storage function\n", "oFFs");
  193581. if (png_ptr == NULL || info_ptr == NULL)
  193582. return;
  193583. info_ptr->x_offset = offset_x;
  193584. info_ptr->y_offset = offset_y;
  193585. info_ptr->offset_unit_type = (png_byte)unit_type;
  193586. info_ptr->valid |= PNG_INFO_oFFs;
  193587. }
  193588. #endif
  193589. #if defined(PNG_pCAL_SUPPORTED)
  193590. void PNGAPI
  193591. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  193592. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  193593. png_charp units, png_charpp params)
  193594. {
  193595. png_uint_32 length;
  193596. int i;
  193597. png_debug1(1, "in %s storage function\n", "pCAL");
  193598. if (png_ptr == NULL || info_ptr == NULL)
  193599. return;
  193600. length = png_strlen(purpose) + 1;
  193601. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  193602. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  193603. if (info_ptr->pcal_purpose == NULL)
  193604. {
  193605. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  193606. return;
  193607. }
  193608. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  193609. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  193610. info_ptr->pcal_X0 = X0;
  193611. info_ptr->pcal_X1 = X1;
  193612. info_ptr->pcal_type = (png_byte)type;
  193613. info_ptr->pcal_nparams = (png_byte)nparams;
  193614. length = png_strlen(units) + 1;
  193615. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  193616. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  193617. if (info_ptr->pcal_units == NULL)
  193618. {
  193619. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  193620. return;
  193621. }
  193622. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  193623. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  193624. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  193625. if (info_ptr->pcal_params == NULL)
  193626. {
  193627. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  193628. return;
  193629. }
  193630. info_ptr->pcal_params[nparams] = NULL;
  193631. for (i = 0; i < nparams; i++)
  193632. {
  193633. length = png_strlen(params[i]) + 1;
  193634. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  193635. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  193636. if (info_ptr->pcal_params[i] == NULL)
  193637. {
  193638. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  193639. return;
  193640. }
  193641. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  193642. }
  193643. info_ptr->valid |= PNG_INFO_pCAL;
  193644. #ifdef PNG_FREE_ME_SUPPORTED
  193645. info_ptr->free_me |= PNG_FREE_PCAL;
  193646. #endif
  193647. }
  193648. #endif
  193649. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  193650. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193651. void PNGAPI
  193652. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  193653. int unit, double width, double height)
  193654. {
  193655. png_debug1(1, "in %s storage function\n", "sCAL");
  193656. if (png_ptr == NULL || info_ptr == NULL)
  193657. return;
  193658. info_ptr->scal_unit = (png_byte)unit;
  193659. info_ptr->scal_pixel_width = width;
  193660. info_ptr->scal_pixel_height = height;
  193661. info_ptr->valid |= PNG_INFO_sCAL;
  193662. }
  193663. #else
  193664. #ifdef PNG_FIXED_POINT_SUPPORTED
  193665. void PNGAPI
  193666. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  193667. int unit, png_charp swidth, png_charp sheight)
  193668. {
  193669. png_uint_32 length;
  193670. png_debug1(1, "in %s storage function\n", "sCAL");
  193671. if (png_ptr == NULL || info_ptr == NULL)
  193672. return;
  193673. info_ptr->scal_unit = (png_byte)unit;
  193674. length = png_strlen(swidth) + 1;
  193675. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  193676. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  193677. if (info_ptr->scal_s_width == NULL)
  193678. {
  193679. png_warning(png_ptr,
  193680. "Memory allocation failed while processing sCAL.");
  193681. }
  193682. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  193683. length = png_strlen(sheight) + 1;
  193684. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  193685. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  193686. if (info_ptr->scal_s_height == NULL)
  193687. {
  193688. png_free (png_ptr, info_ptr->scal_s_width);
  193689. png_warning(png_ptr,
  193690. "Memory allocation failed while processing sCAL.");
  193691. }
  193692. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  193693. info_ptr->valid |= PNG_INFO_sCAL;
  193694. #ifdef PNG_FREE_ME_SUPPORTED
  193695. info_ptr->free_me |= PNG_FREE_SCAL;
  193696. #endif
  193697. }
  193698. #endif
  193699. #endif
  193700. #endif
  193701. #if defined(PNG_pHYs_SUPPORTED)
  193702. void PNGAPI
  193703. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  193704. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  193705. {
  193706. png_debug1(1, "in %s storage function\n", "pHYs");
  193707. if (png_ptr == NULL || info_ptr == NULL)
  193708. return;
  193709. info_ptr->x_pixels_per_unit = res_x;
  193710. info_ptr->y_pixels_per_unit = res_y;
  193711. info_ptr->phys_unit_type = (png_byte)unit_type;
  193712. info_ptr->valid |= PNG_INFO_pHYs;
  193713. }
  193714. #endif
  193715. void PNGAPI
  193716. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  193717. png_colorp palette, int num_palette)
  193718. {
  193719. png_debug1(1, "in %s storage function\n", "PLTE");
  193720. if (png_ptr == NULL || info_ptr == NULL)
  193721. return;
  193722. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  193723. {
  193724. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193725. png_error(png_ptr, "Invalid palette length");
  193726. else
  193727. {
  193728. png_warning(png_ptr, "Invalid palette length");
  193729. return;
  193730. }
  193731. }
  193732. /*
  193733. * It may not actually be necessary to set png_ptr->palette here;
  193734. * we do it for backward compatibility with the way the png_handle_tRNS
  193735. * function used to do the allocation.
  193736. */
  193737. #ifdef PNG_FREE_ME_SUPPORTED
  193738. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  193739. #endif
  193740. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  193741. of num_palette entries,
  193742. in case of an invalid PNG file that has too-large sample values. */
  193743. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  193744. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  193745. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  193746. png_sizeof(png_color));
  193747. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  193748. info_ptr->palette = png_ptr->palette;
  193749. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  193750. #ifdef PNG_FREE_ME_SUPPORTED
  193751. info_ptr->free_me |= PNG_FREE_PLTE;
  193752. #else
  193753. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  193754. #endif
  193755. info_ptr->valid |= PNG_INFO_PLTE;
  193756. }
  193757. #if defined(PNG_sBIT_SUPPORTED)
  193758. void PNGAPI
  193759. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  193760. png_color_8p sig_bit)
  193761. {
  193762. png_debug1(1, "in %s storage function\n", "sBIT");
  193763. if (png_ptr == NULL || info_ptr == NULL)
  193764. return;
  193765. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  193766. info_ptr->valid |= PNG_INFO_sBIT;
  193767. }
  193768. #endif
  193769. #if defined(PNG_sRGB_SUPPORTED)
  193770. void PNGAPI
  193771. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  193772. {
  193773. png_debug1(1, "in %s storage function\n", "sRGB");
  193774. if (png_ptr == NULL || info_ptr == NULL)
  193775. return;
  193776. info_ptr->srgb_intent = (png_byte)intent;
  193777. info_ptr->valid |= PNG_INFO_sRGB;
  193778. }
  193779. void PNGAPI
  193780. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  193781. int intent)
  193782. {
  193783. #if defined(PNG_gAMA_SUPPORTED)
  193784. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193785. float file_gamma;
  193786. #endif
  193787. #ifdef PNG_FIXED_POINT_SUPPORTED
  193788. png_fixed_point int_file_gamma;
  193789. #endif
  193790. #endif
  193791. #if defined(PNG_cHRM_SUPPORTED)
  193792. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193793. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193794. #endif
  193795. #ifdef PNG_FIXED_POINT_SUPPORTED
  193796. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  193797. int_green_y, int_blue_x, int_blue_y;
  193798. #endif
  193799. #endif
  193800. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  193801. if (png_ptr == NULL || info_ptr == NULL)
  193802. return;
  193803. png_set_sRGB(png_ptr, info_ptr, intent);
  193804. #if defined(PNG_gAMA_SUPPORTED)
  193805. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193806. file_gamma = (float).45455;
  193807. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193808. #endif
  193809. #ifdef PNG_FIXED_POINT_SUPPORTED
  193810. int_file_gamma = 45455L;
  193811. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  193812. #endif
  193813. #endif
  193814. #if defined(PNG_cHRM_SUPPORTED)
  193815. #ifdef PNG_FIXED_POINT_SUPPORTED
  193816. int_white_x = 31270L;
  193817. int_white_y = 32900L;
  193818. int_red_x = 64000L;
  193819. int_red_y = 33000L;
  193820. int_green_x = 30000L;
  193821. int_green_y = 60000L;
  193822. int_blue_x = 15000L;
  193823. int_blue_y = 6000L;
  193824. png_set_cHRM_fixed(png_ptr, info_ptr,
  193825. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  193826. int_blue_x, int_blue_y);
  193827. #endif
  193828. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193829. white_x = (float).3127;
  193830. white_y = (float).3290;
  193831. red_x = (float).64;
  193832. red_y = (float).33;
  193833. green_x = (float).30;
  193834. green_y = (float).60;
  193835. blue_x = (float).15;
  193836. blue_y = (float).06;
  193837. png_set_cHRM(png_ptr, info_ptr,
  193838. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193839. #endif
  193840. #endif
  193841. }
  193842. #endif
  193843. #if defined(PNG_iCCP_SUPPORTED)
  193844. void PNGAPI
  193845. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  193846. png_charp name, int compression_type,
  193847. png_charp profile, png_uint_32 proflen)
  193848. {
  193849. png_charp new_iccp_name;
  193850. png_charp new_iccp_profile;
  193851. png_debug1(1, "in %s storage function\n", "iCCP");
  193852. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  193853. return;
  193854. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  193855. if (new_iccp_name == NULL)
  193856. {
  193857. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  193858. return;
  193859. }
  193860. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  193861. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  193862. if (new_iccp_profile == NULL)
  193863. {
  193864. png_free (png_ptr, new_iccp_name);
  193865. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  193866. return;
  193867. }
  193868. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  193869. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  193870. info_ptr->iccp_proflen = proflen;
  193871. info_ptr->iccp_name = new_iccp_name;
  193872. info_ptr->iccp_profile = new_iccp_profile;
  193873. /* Compression is always zero but is here so the API and info structure
  193874. * does not have to change if we introduce multiple compression types */
  193875. info_ptr->iccp_compression = (png_byte)compression_type;
  193876. #ifdef PNG_FREE_ME_SUPPORTED
  193877. info_ptr->free_me |= PNG_FREE_ICCP;
  193878. #endif
  193879. info_ptr->valid |= PNG_INFO_iCCP;
  193880. }
  193881. #endif
  193882. #if defined(PNG_TEXT_SUPPORTED)
  193883. void PNGAPI
  193884. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193885. int num_text)
  193886. {
  193887. int ret;
  193888. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  193889. if (ret)
  193890. png_error(png_ptr, "Insufficient memory to store text");
  193891. }
  193892. int /* PRIVATE */
  193893. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193894. int num_text)
  193895. {
  193896. int i;
  193897. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  193898. "text" : (png_const_charp)png_ptr->chunk_name));
  193899. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  193900. return(0);
  193901. /* Make sure we have enough space in the "text" array in info_struct
  193902. * to hold all of the incoming text_ptr objects.
  193903. */
  193904. if (info_ptr->num_text + num_text > info_ptr->max_text)
  193905. {
  193906. if (info_ptr->text != NULL)
  193907. {
  193908. png_textp old_text;
  193909. int old_max;
  193910. old_max = info_ptr->max_text;
  193911. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  193912. old_text = info_ptr->text;
  193913. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193914. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193915. if (info_ptr->text == NULL)
  193916. {
  193917. png_free(png_ptr, old_text);
  193918. return(1);
  193919. }
  193920. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  193921. png_sizeof(png_text)));
  193922. png_free(png_ptr, old_text);
  193923. }
  193924. else
  193925. {
  193926. info_ptr->max_text = num_text + 8;
  193927. info_ptr->num_text = 0;
  193928. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193929. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193930. if (info_ptr->text == NULL)
  193931. return(1);
  193932. #ifdef PNG_FREE_ME_SUPPORTED
  193933. info_ptr->free_me |= PNG_FREE_TEXT;
  193934. #endif
  193935. }
  193936. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  193937. info_ptr->max_text);
  193938. }
  193939. for (i = 0; i < num_text; i++)
  193940. {
  193941. png_size_t text_length,key_len;
  193942. png_size_t lang_len,lang_key_len;
  193943. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  193944. if (text_ptr[i].key == NULL)
  193945. continue;
  193946. key_len = png_strlen(text_ptr[i].key);
  193947. if(text_ptr[i].compression <= 0)
  193948. {
  193949. lang_len = 0;
  193950. lang_key_len = 0;
  193951. }
  193952. else
  193953. #ifdef PNG_iTXt_SUPPORTED
  193954. {
  193955. /* set iTXt data */
  193956. if (text_ptr[i].lang != NULL)
  193957. lang_len = png_strlen(text_ptr[i].lang);
  193958. else
  193959. lang_len = 0;
  193960. if (text_ptr[i].lang_key != NULL)
  193961. lang_key_len = png_strlen(text_ptr[i].lang_key);
  193962. else
  193963. lang_key_len = 0;
  193964. }
  193965. #else
  193966. {
  193967. png_warning(png_ptr, "iTXt chunk not supported.");
  193968. continue;
  193969. }
  193970. #endif
  193971. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  193972. {
  193973. text_length = 0;
  193974. #ifdef PNG_iTXt_SUPPORTED
  193975. if(text_ptr[i].compression > 0)
  193976. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  193977. else
  193978. #endif
  193979. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  193980. }
  193981. else
  193982. {
  193983. text_length = png_strlen(text_ptr[i].text);
  193984. textp->compression = text_ptr[i].compression;
  193985. }
  193986. textp->key = (png_charp)png_malloc_warn(png_ptr,
  193987. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  193988. if (textp->key == NULL)
  193989. return(1);
  193990. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  193991. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  193992. (int)textp->key);
  193993. png_memcpy(textp->key, text_ptr[i].key,
  193994. (png_size_t)(key_len));
  193995. *(textp->key+key_len) = '\0';
  193996. #ifdef PNG_iTXt_SUPPORTED
  193997. if (text_ptr[i].compression > 0)
  193998. {
  193999. textp->lang=textp->key + key_len + 1;
  194000. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  194001. *(textp->lang+lang_len) = '\0';
  194002. textp->lang_key=textp->lang + lang_len + 1;
  194003. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  194004. *(textp->lang_key+lang_key_len) = '\0';
  194005. textp->text=textp->lang_key + lang_key_len + 1;
  194006. }
  194007. else
  194008. #endif
  194009. {
  194010. #ifdef PNG_iTXt_SUPPORTED
  194011. textp->lang=NULL;
  194012. textp->lang_key=NULL;
  194013. #endif
  194014. textp->text=textp->key + key_len + 1;
  194015. }
  194016. if(text_length)
  194017. png_memcpy(textp->text, text_ptr[i].text,
  194018. (png_size_t)(text_length));
  194019. *(textp->text+text_length) = '\0';
  194020. #ifdef PNG_iTXt_SUPPORTED
  194021. if(textp->compression > 0)
  194022. {
  194023. textp->text_length = 0;
  194024. textp->itxt_length = text_length;
  194025. }
  194026. else
  194027. #endif
  194028. {
  194029. textp->text_length = text_length;
  194030. #ifdef PNG_iTXt_SUPPORTED
  194031. textp->itxt_length = 0;
  194032. #endif
  194033. }
  194034. info_ptr->num_text++;
  194035. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  194036. }
  194037. return(0);
  194038. }
  194039. #endif
  194040. #if defined(PNG_tIME_SUPPORTED)
  194041. void PNGAPI
  194042. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  194043. {
  194044. png_debug1(1, "in %s storage function\n", "tIME");
  194045. if (png_ptr == NULL || info_ptr == NULL ||
  194046. (png_ptr->mode & PNG_WROTE_tIME))
  194047. return;
  194048. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  194049. info_ptr->valid |= PNG_INFO_tIME;
  194050. }
  194051. #endif
  194052. #if defined(PNG_tRNS_SUPPORTED)
  194053. void PNGAPI
  194054. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  194055. png_bytep trans, int num_trans, png_color_16p trans_values)
  194056. {
  194057. png_debug1(1, "in %s storage function\n", "tRNS");
  194058. if (png_ptr == NULL || info_ptr == NULL)
  194059. return;
  194060. if (trans != NULL)
  194061. {
  194062. /*
  194063. * It may not actually be necessary to set png_ptr->trans here;
  194064. * we do it for backward compatibility with the way the png_handle_tRNS
  194065. * function used to do the allocation.
  194066. */
  194067. #ifdef PNG_FREE_ME_SUPPORTED
  194068. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  194069. #endif
  194070. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  194071. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  194072. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  194073. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  194074. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  194075. #ifdef PNG_FREE_ME_SUPPORTED
  194076. info_ptr->free_me |= PNG_FREE_TRNS;
  194077. #else
  194078. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  194079. #endif
  194080. }
  194081. if (trans_values != NULL)
  194082. {
  194083. png_memcpy(&(info_ptr->trans_values), trans_values,
  194084. png_sizeof(png_color_16));
  194085. if (num_trans == 0)
  194086. num_trans = 1;
  194087. }
  194088. info_ptr->num_trans = (png_uint_16)num_trans;
  194089. info_ptr->valid |= PNG_INFO_tRNS;
  194090. }
  194091. #endif
  194092. #if defined(PNG_sPLT_SUPPORTED)
  194093. void PNGAPI
  194094. png_set_sPLT(png_structp png_ptr,
  194095. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  194096. {
  194097. png_sPLT_tp np;
  194098. int i;
  194099. if (png_ptr == NULL || info_ptr == NULL)
  194100. return;
  194101. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  194102. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  194103. if (np == NULL)
  194104. {
  194105. png_warning(png_ptr, "No memory for sPLT palettes.");
  194106. return;
  194107. }
  194108. png_memcpy(np, info_ptr->splt_palettes,
  194109. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  194110. png_free(png_ptr, info_ptr->splt_palettes);
  194111. info_ptr->splt_palettes=NULL;
  194112. for (i = 0; i < nentries; i++)
  194113. {
  194114. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  194115. png_sPLT_tp from = entries + i;
  194116. to->name = (png_charp)png_malloc_warn(png_ptr,
  194117. png_strlen(from->name) + 1);
  194118. if (to->name == NULL)
  194119. {
  194120. png_warning(png_ptr,
  194121. "Out of memory while processing sPLT chunk");
  194122. }
  194123. /* TODO: use png_malloc_warn */
  194124. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  194125. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  194126. from->nentries * png_sizeof(png_sPLT_entry));
  194127. /* TODO: use png_malloc_warn */
  194128. png_memcpy(to->entries, from->entries,
  194129. from->nentries * png_sizeof(png_sPLT_entry));
  194130. if (to->entries == NULL)
  194131. {
  194132. png_warning(png_ptr,
  194133. "Out of memory while processing sPLT chunk");
  194134. png_free(png_ptr,to->name);
  194135. to->name = NULL;
  194136. }
  194137. to->nentries = from->nentries;
  194138. to->depth = from->depth;
  194139. }
  194140. info_ptr->splt_palettes = np;
  194141. info_ptr->splt_palettes_num += nentries;
  194142. info_ptr->valid |= PNG_INFO_sPLT;
  194143. #ifdef PNG_FREE_ME_SUPPORTED
  194144. info_ptr->free_me |= PNG_FREE_SPLT;
  194145. #endif
  194146. }
  194147. #endif /* PNG_sPLT_SUPPORTED */
  194148. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194149. void PNGAPI
  194150. png_set_unknown_chunks(png_structp png_ptr,
  194151. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  194152. {
  194153. png_unknown_chunkp np;
  194154. int i;
  194155. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  194156. return;
  194157. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  194158. (info_ptr->unknown_chunks_num + num_unknowns) *
  194159. png_sizeof(png_unknown_chunk));
  194160. if (np == NULL)
  194161. {
  194162. png_warning(png_ptr,
  194163. "Out of memory while processing unknown chunk.");
  194164. return;
  194165. }
  194166. png_memcpy(np, info_ptr->unknown_chunks,
  194167. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  194168. png_free(png_ptr, info_ptr->unknown_chunks);
  194169. info_ptr->unknown_chunks=NULL;
  194170. for (i = 0; i < num_unknowns; i++)
  194171. {
  194172. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  194173. png_unknown_chunkp from = unknowns + i;
  194174. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  194175. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  194176. if (to->data == NULL)
  194177. {
  194178. png_warning(png_ptr,
  194179. "Out of memory while processing unknown chunk.");
  194180. }
  194181. else
  194182. {
  194183. png_memcpy(to->data, from->data, from->size);
  194184. to->size = from->size;
  194185. /* note our location in the read or write sequence */
  194186. to->location = (png_byte)(png_ptr->mode & 0xff);
  194187. }
  194188. }
  194189. info_ptr->unknown_chunks = np;
  194190. info_ptr->unknown_chunks_num += num_unknowns;
  194191. #ifdef PNG_FREE_ME_SUPPORTED
  194192. info_ptr->free_me |= PNG_FREE_UNKN;
  194193. #endif
  194194. }
  194195. void PNGAPI
  194196. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  194197. int chunk, int location)
  194198. {
  194199. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  194200. (int)info_ptr->unknown_chunks_num)
  194201. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  194202. }
  194203. #endif
  194204. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194205. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  194206. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  194207. void PNGAPI
  194208. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  194209. {
  194210. /* This function is deprecated in favor of png_permit_mng_features()
  194211. and will be removed from libpng-1.3.0 */
  194212. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  194213. if (png_ptr == NULL)
  194214. return;
  194215. png_ptr->mng_features_permitted = (png_byte)
  194216. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  194217. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  194218. }
  194219. #endif
  194220. #endif
  194221. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194222. png_uint_32 PNGAPI
  194223. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  194224. {
  194225. png_debug(1, "in png_permit_mng_features\n");
  194226. if (png_ptr == NULL)
  194227. return (png_uint_32)0;
  194228. png_ptr->mng_features_permitted =
  194229. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  194230. return (png_uint_32)png_ptr->mng_features_permitted;
  194231. }
  194232. #endif
  194233. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194234. void PNGAPI
  194235. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  194236. chunk_list, int num_chunks)
  194237. {
  194238. png_bytep new_list, p;
  194239. int i, old_num_chunks;
  194240. if (png_ptr == NULL)
  194241. return;
  194242. if (num_chunks == 0)
  194243. {
  194244. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  194245. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194246. else
  194247. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194248. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  194249. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194250. else
  194251. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194252. return;
  194253. }
  194254. if (chunk_list == NULL)
  194255. return;
  194256. old_num_chunks=png_ptr->num_chunk_list;
  194257. new_list=(png_bytep)png_malloc(png_ptr,
  194258. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  194259. if(png_ptr->chunk_list != NULL)
  194260. {
  194261. png_memcpy(new_list, png_ptr->chunk_list,
  194262. (png_size_t)(5*old_num_chunks));
  194263. png_free(png_ptr, png_ptr->chunk_list);
  194264. png_ptr->chunk_list=NULL;
  194265. }
  194266. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  194267. (png_size_t)(5*num_chunks));
  194268. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  194269. *p=(png_byte)keep;
  194270. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  194271. png_ptr->chunk_list=new_list;
  194272. #ifdef PNG_FREE_ME_SUPPORTED
  194273. png_ptr->free_me |= PNG_FREE_LIST;
  194274. #endif
  194275. }
  194276. #endif
  194277. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194278. void PNGAPI
  194279. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  194280. png_user_chunk_ptr read_user_chunk_fn)
  194281. {
  194282. png_debug(1, "in png_set_read_user_chunk_fn\n");
  194283. if (png_ptr == NULL)
  194284. return;
  194285. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  194286. png_ptr->user_chunk_ptr = user_chunk_ptr;
  194287. }
  194288. #endif
  194289. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194290. void PNGAPI
  194291. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  194292. {
  194293. png_debug1(1, "in %s storage function\n", "rows");
  194294. if (png_ptr == NULL || info_ptr == NULL)
  194295. return;
  194296. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  194297. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  194298. info_ptr->row_pointers = row_pointers;
  194299. if(row_pointers)
  194300. info_ptr->valid |= PNG_INFO_IDAT;
  194301. }
  194302. #endif
  194303. #ifdef PNG_WRITE_SUPPORTED
  194304. void PNGAPI
  194305. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  194306. {
  194307. if (png_ptr == NULL)
  194308. return;
  194309. if(png_ptr->zbuf)
  194310. png_free(png_ptr, png_ptr->zbuf);
  194311. png_ptr->zbuf_size = (png_size_t)size;
  194312. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  194313. png_ptr->zstream.next_out = png_ptr->zbuf;
  194314. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194315. }
  194316. #endif
  194317. void PNGAPI
  194318. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  194319. {
  194320. if (png_ptr && info_ptr)
  194321. info_ptr->valid &= ~(mask);
  194322. }
  194323. #ifndef PNG_1_0_X
  194324. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  194325. /* function was added to libpng 1.2.0 and should always exist by default */
  194326. void PNGAPI
  194327. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  194328. {
  194329. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194330. if (png_ptr != NULL)
  194331. png_ptr->asm_flags = 0;
  194332. }
  194333. /* this function was added to libpng 1.2.0 */
  194334. void PNGAPI
  194335. png_set_mmx_thresholds (png_structp png_ptr,
  194336. png_byte,
  194337. png_uint_32)
  194338. {
  194339. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194340. if (png_ptr == NULL)
  194341. return;
  194342. }
  194343. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  194344. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194345. /* this function was added to libpng 1.2.6 */
  194346. void PNGAPI
  194347. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  194348. png_uint_32 user_height_max)
  194349. {
  194350. /* Images with dimensions larger than these limits will be
  194351. * rejected by png_set_IHDR(). To accept any PNG datastream
  194352. * regardless of dimensions, set both limits to 0x7ffffffL.
  194353. */
  194354. if(png_ptr == NULL) return;
  194355. png_ptr->user_width_max = user_width_max;
  194356. png_ptr->user_height_max = user_height_max;
  194357. }
  194358. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  194359. #endif /* ?PNG_1_0_X */
  194360. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194361. /*** End of inlined file: pngset.c ***/
  194362. /*** Start of inlined file: pngtrans.c ***/
  194363. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  194364. *
  194365. * Last changed in libpng 1.2.17 May 15, 2007
  194366. * For conditions of distribution and use, see copyright notice in png.h
  194367. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194368. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194369. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194370. */
  194371. #define PNG_INTERNAL
  194372. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  194373. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194374. /* turn on BGR-to-RGB mapping */
  194375. void PNGAPI
  194376. png_set_bgr(png_structp png_ptr)
  194377. {
  194378. png_debug(1, "in png_set_bgr\n");
  194379. if(png_ptr == NULL) return;
  194380. png_ptr->transformations |= PNG_BGR;
  194381. }
  194382. #endif
  194383. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  194384. /* turn on 16 bit byte swapping */
  194385. void PNGAPI
  194386. png_set_swap(png_structp png_ptr)
  194387. {
  194388. png_debug(1, "in png_set_swap\n");
  194389. if(png_ptr == NULL) return;
  194390. if (png_ptr->bit_depth == 16)
  194391. png_ptr->transformations |= PNG_SWAP_BYTES;
  194392. }
  194393. #endif
  194394. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  194395. /* turn on pixel packing */
  194396. void PNGAPI
  194397. png_set_packing(png_structp png_ptr)
  194398. {
  194399. png_debug(1, "in png_set_packing\n");
  194400. if(png_ptr == NULL) return;
  194401. if (png_ptr->bit_depth < 8)
  194402. {
  194403. png_ptr->transformations |= PNG_PACK;
  194404. png_ptr->usr_bit_depth = 8;
  194405. }
  194406. }
  194407. #endif
  194408. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194409. /* turn on packed pixel swapping */
  194410. void PNGAPI
  194411. png_set_packswap(png_structp png_ptr)
  194412. {
  194413. png_debug(1, "in png_set_packswap\n");
  194414. if(png_ptr == NULL) return;
  194415. if (png_ptr->bit_depth < 8)
  194416. png_ptr->transformations |= PNG_PACKSWAP;
  194417. }
  194418. #endif
  194419. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  194420. void PNGAPI
  194421. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  194422. {
  194423. png_debug(1, "in png_set_shift\n");
  194424. if(png_ptr == NULL) return;
  194425. png_ptr->transformations |= PNG_SHIFT;
  194426. png_ptr->shift = *true_bits;
  194427. }
  194428. #endif
  194429. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  194430. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194431. int PNGAPI
  194432. png_set_interlace_handling(png_structp png_ptr)
  194433. {
  194434. png_debug(1, "in png_set_interlace handling\n");
  194435. if (png_ptr && png_ptr->interlaced)
  194436. {
  194437. png_ptr->transformations |= PNG_INTERLACE;
  194438. return (7);
  194439. }
  194440. return (1);
  194441. }
  194442. #endif
  194443. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  194444. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  194445. * The filler type has changed in v0.95 to allow future 2-byte fillers
  194446. * for 48-bit input data, as well as to avoid problems with some compilers
  194447. * that don't like bytes as parameters.
  194448. */
  194449. void PNGAPI
  194450. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  194451. {
  194452. png_debug(1, "in png_set_filler\n");
  194453. if(png_ptr == NULL) return;
  194454. png_ptr->transformations |= PNG_FILLER;
  194455. png_ptr->filler = (png_byte)filler;
  194456. if (filler_loc == PNG_FILLER_AFTER)
  194457. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  194458. else
  194459. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  194460. /* This should probably go in the "do_read_filler" routine.
  194461. * I attempted to do that in libpng-1.0.1a but that caused problems
  194462. * so I restored it in libpng-1.0.2a
  194463. */
  194464. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194465. {
  194466. png_ptr->usr_channels = 4;
  194467. }
  194468. /* Also I added this in libpng-1.0.2a (what happens when we expand
  194469. * a less-than-8-bit grayscale to GA? */
  194470. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  194471. {
  194472. png_ptr->usr_channels = 2;
  194473. }
  194474. }
  194475. #if !defined(PNG_1_0_X)
  194476. /* Added to libpng-1.2.7 */
  194477. void PNGAPI
  194478. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  194479. {
  194480. png_debug(1, "in png_set_add_alpha\n");
  194481. if(png_ptr == NULL) return;
  194482. png_set_filler(png_ptr, filler, filler_loc);
  194483. png_ptr->transformations |= PNG_ADD_ALPHA;
  194484. }
  194485. #endif
  194486. #endif
  194487. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  194488. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194489. void PNGAPI
  194490. png_set_swap_alpha(png_structp png_ptr)
  194491. {
  194492. png_debug(1, "in png_set_swap_alpha\n");
  194493. if(png_ptr == NULL) return;
  194494. png_ptr->transformations |= PNG_SWAP_ALPHA;
  194495. }
  194496. #endif
  194497. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  194498. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194499. void PNGAPI
  194500. png_set_invert_alpha(png_structp png_ptr)
  194501. {
  194502. png_debug(1, "in png_set_invert_alpha\n");
  194503. if(png_ptr == NULL) return;
  194504. png_ptr->transformations |= PNG_INVERT_ALPHA;
  194505. }
  194506. #endif
  194507. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  194508. void PNGAPI
  194509. png_set_invert_mono(png_structp png_ptr)
  194510. {
  194511. png_debug(1, "in png_set_invert_mono\n");
  194512. if(png_ptr == NULL) return;
  194513. png_ptr->transformations |= PNG_INVERT_MONO;
  194514. }
  194515. /* invert monochrome grayscale data */
  194516. void /* PRIVATE */
  194517. png_do_invert(png_row_infop row_info, png_bytep row)
  194518. {
  194519. png_debug(1, "in png_do_invert\n");
  194520. /* This test removed from libpng version 1.0.13 and 1.2.0:
  194521. * if (row_info->bit_depth == 1 &&
  194522. */
  194523. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194524. if (row == NULL || row_info == NULL)
  194525. return;
  194526. #endif
  194527. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  194528. {
  194529. png_bytep rp = row;
  194530. png_uint_32 i;
  194531. png_uint_32 istop = row_info->rowbytes;
  194532. for (i = 0; i < istop; i++)
  194533. {
  194534. *rp = (png_byte)(~(*rp));
  194535. rp++;
  194536. }
  194537. }
  194538. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194539. row_info->bit_depth == 8)
  194540. {
  194541. png_bytep rp = row;
  194542. png_uint_32 i;
  194543. png_uint_32 istop = row_info->rowbytes;
  194544. for (i = 0; i < istop; i+=2)
  194545. {
  194546. *rp = (png_byte)(~(*rp));
  194547. rp+=2;
  194548. }
  194549. }
  194550. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194551. row_info->bit_depth == 16)
  194552. {
  194553. png_bytep rp = row;
  194554. png_uint_32 i;
  194555. png_uint_32 istop = row_info->rowbytes;
  194556. for (i = 0; i < istop; i+=4)
  194557. {
  194558. *rp = (png_byte)(~(*rp));
  194559. *(rp+1) = (png_byte)(~(*(rp+1)));
  194560. rp+=4;
  194561. }
  194562. }
  194563. }
  194564. #endif
  194565. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  194566. /* swaps byte order on 16 bit depth images */
  194567. void /* PRIVATE */
  194568. png_do_swap(png_row_infop row_info, png_bytep row)
  194569. {
  194570. png_debug(1, "in png_do_swap\n");
  194571. if (
  194572. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194573. row != NULL && row_info != NULL &&
  194574. #endif
  194575. row_info->bit_depth == 16)
  194576. {
  194577. png_bytep rp = row;
  194578. png_uint_32 i;
  194579. png_uint_32 istop= row_info->width * row_info->channels;
  194580. for (i = 0; i < istop; i++, rp += 2)
  194581. {
  194582. png_byte t = *rp;
  194583. *rp = *(rp + 1);
  194584. *(rp + 1) = t;
  194585. }
  194586. }
  194587. }
  194588. #endif
  194589. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194590. static PNG_CONST png_byte onebppswaptable[256] = {
  194591. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  194592. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  194593. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  194594. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  194595. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  194596. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  194597. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  194598. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  194599. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  194600. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  194601. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  194602. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  194603. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  194604. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  194605. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  194606. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  194607. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  194608. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  194609. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  194610. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  194611. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  194612. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  194613. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  194614. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  194615. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  194616. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  194617. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  194618. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  194619. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  194620. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  194621. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  194622. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  194623. };
  194624. static PNG_CONST png_byte twobppswaptable[256] = {
  194625. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  194626. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  194627. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  194628. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  194629. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  194630. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  194631. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  194632. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  194633. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  194634. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  194635. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  194636. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  194637. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  194638. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  194639. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  194640. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  194641. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  194642. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  194643. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  194644. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  194645. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  194646. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  194647. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  194648. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  194649. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  194650. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  194651. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  194652. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  194653. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  194654. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  194655. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  194656. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  194657. };
  194658. static PNG_CONST png_byte fourbppswaptable[256] = {
  194659. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  194660. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  194661. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  194662. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  194663. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  194664. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  194665. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  194666. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  194667. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  194668. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  194669. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  194670. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  194671. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  194672. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  194673. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  194674. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  194675. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  194676. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  194677. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  194678. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  194679. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  194680. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  194681. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  194682. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  194683. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  194684. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  194685. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  194686. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  194687. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  194688. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  194689. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  194690. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  194691. };
  194692. /* swaps pixel packing order within bytes */
  194693. void /* PRIVATE */
  194694. png_do_packswap(png_row_infop row_info, png_bytep row)
  194695. {
  194696. png_debug(1, "in png_do_packswap\n");
  194697. if (
  194698. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194699. row != NULL && row_info != NULL &&
  194700. #endif
  194701. row_info->bit_depth < 8)
  194702. {
  194703. png_bytep rp, end, table;
  194704. end = row + row_info->rowbytes;
  194705. if (row_info->bit_depth == 1)
  194706. table = (png_bytep)onebppswaptable;
  194707. else if (row_info->bit_depth == 2)
  194708. table = (png_bytep)twobppswaptable;
  194709. else if (row_info->bit_depth == 4)
  194710. table = (png_bytep)fourbppswaptable;
  194711. else
  194712. return;
  194713. for (rp = row; rp < end; rp++)
  194714. *rp = table[*rp];
  194715. }
  194716. }
  194717. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  194718. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  194719. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  194720. /* remove filler or alpha byte(s) */
  194721. void /* PRIVATE */
  194722. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  194723. {
  194724. png_debug(1, "in png_do_strip_filler\n");
  194725. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194726. if (row != NULL && row_info != NULL)
  194727. #endif
  194728. {
  194729. png_bytep sp=row;
  194730. png_bytep dp=row;
  194731. png_uint_32 row_width=row_info->width;
  194732. png_uint_32 i;
  194733. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  194734. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  194735. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  194736. row_info->channels == 4)
  194737. {
  194738. if (row_info->bit_depth == 8)
  194739. {
  194740. /* This converts from RGBX or RGBA to RGB */
  194741. if (flags & PNG_FLAG_FILLER_AFTER)
  194742. {
  194743. dp+=3; sp+=4;
  194744. for (i = 1; i < row_width; i++)
  194745. {
  194746. *dp++ = *sp++;
  194747. *dp++ = *sp++;
  194748. *dp++ = *sp++;
  194749. sp++;
  194750. }
  194751. }
  194752. /* This converts from XRGB or ARGB to RGB */
  194753. else
  194754. {
  194755. for (i = 0; i < row_width; i++)
  194756. {
  194757. sp++;
  194758. *dp++ = *sp++;
  194759. *dp++ = *sp++;
  194760. *dp++ = *sp++;
  194761. }
  194762. }
  194763. row_info->pixel_depth = 24;
  194764. row_info->rowbytes = row_width * 3;
  194765. }
  194766. else /* if (row_info->bit_depth == 16) */
  194767. {
  194768. if (flags & PNG_FLAG_FILLER_AFTER)
  194769. {
  194770. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  194771. sp += 8; dp += 6;
  194772. for (i = 1; i < row_width; i++)
  194773. {
  194774. /* This could be (although png_memcpy is probably slower):
  194775. png_memcpy(dp, sp, 6);
  194776. sp += 8;
  194777. dp += 6;
  194778. */
  194779. *dp++ = *sp++;
  194780. *dp++ = *sp++;
  194781. *dp++ = *sp++;
  194782. *dp++ = *sp++;
  194783. *dp++ = *sp++;
  194784. *dp++ = *sp++;
  194785. sp += 2;
  194786. }
  194787. }
  194788. else
  194789. {
  194790. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  194791. for (i = 0; i < row_width; i++)
  194792. {
  194793. /* This could be (although png_memcpy is probably slower):
  194794. png_memcpy(dp, sp, 6);
  194795. sp += 8;
  194796. dp += 6;
  194797. */
  194798. sp+=2;
  194799. *dp++ = *sp++;
  194800. *dp++ = *sp++;
  194801. *dp++ = *sp++;
  194802. *dp++ = *sp++;
  194803. *dp++ = *sp++;
  194804. *dp++ = *sp++;
  194805. }
  194806. }
  194807. row_info->pixel_depth = 48;
  194808. row_info->rowbytes = row_width * 6;
  194809. }
  194810. row_info->channels = 3;
  194811. }
  194812. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  194813. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194814. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  194815. row_info->channels == 2)
  194816. {
  194817. if (row_info->bit_depth == 8)
  194818. {
  194819. /* This converts from GX or GA to G */
  194820. if (flags & PNG_FLAG_FILLER_AFTER)
  194821. {
  194822. for (i = 0; i < row_width; i++)
  194823. {
  194824. *dp++ = *sp++;
  194825. sp++;
  194826. }
  194827. }
  194828. /* This converts from XG or AG to G */
  194829. else
  194830. {
  194831. for (i = 0; i < row_width; i++)
  194832. {
  194833. sp++;
  194834. *dp++ = *sp++;
  194835. }
  194836. }
  194837. row_info->pixel_depth = 8;
  194838. row_info->rowbytes = row_width;
  194839. }
  194840. else /* if (row_info->bit_depth == 16) */
  194841. {
  194842. if (flags & PNG_FLAG_FILLER_AFTER)
  194843. {
  194844. /* This converts from GGXX or GGAA to GG */
  194845. sp += 4; dp += 2;
  194846. for (i = 1; i < row_width; i++)
  194847. {
  194848. *dp++ = *sp++;
  194849. *dp++ = *sp++;
  194850. sp += 2;
  194851. }
  194852. }
  194853. else
  194854. {
  194855. /* This converts from XXGG or AAGG to GG */
  194856. for (i = 0; i < row_width; i++)
  194857. {
  194858. sp += 2;
  194859. *dp++ = *sp++;
  194860. *dp++ = *sp++;
  194861. }
  194862. }
  194863. row_info->pixel_depth = 16;
  194864. row_info->rowbytes = row_width * 2;
  194865. }
  194866. row_info->channels = 1;
  194867. }
  194868. if (flags & PNG_FLAG_STRIP_ALPHA)
  194869. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  194870. }
  194871. }
  194872. #endif
  194873. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194874. /* swaps red and blue bytes within a pixel */
  194875. void /* PRIVATE */
  194876. png_do_bgr(png_row_infop row_info, png_bytep row)
  194877. {
  194878. png_debug(1, "in png_do_bgr\n");
  194879. if (
  194880. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194881. row != NULL && row_info != NULL &&
  194882. #endif
  194883. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194884. {
  194885. png_uint_32 row_width = row_info->width;
  194886. if (row_info->bit_depth == 8)
  194887. {
  194888. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194889. {
  194890. png_bytep rp;
  194891. png_uint_32 i;
  194892. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  194893. {
  194894. png_byte save = *rp;
  194895. *rp = *(rp + 2);
  194896. *(rp + 2) = save;
  194897. }
  194898. }
  194899. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194900. {
  194901. png_bytep rp;
  194902. png_uint_32 i;
  194903. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  194904. {
  194905. png_byte save = *rp;
  194906. *rp = *(rp + 2);
  194907. *(rp + 2) = save;
  194908. }
  194909. }
  194910. }
  194911. else if (row_info->bit_depth == 16)
  194912. {
  194913. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194914. {
  194915. png_bytep rp;
  194916. png_uint_32 i;
  194917. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  194918. {
  194919. png_byte save = *rp;
  194920. *rp = *(rp + 4);
  194921. *(rp + 4) = save;
  194922. save = *(rp + 1);
  194923. *(rp + 1) = *(rp + 5);
  194924. *(rp + 5) = save;
  194925. }
  194926. }
  194927. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194928. {
  194929. png_bytep rp;
  194930. png_uint_32 i;
  194931. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  194932. {
  194933. png_byte save = *rp;
  194934. *rp = *(rp + 4);
  194935. *(rp + 4) = save;
  194936. save = *(rp + 1);
  194937. *(rp + 1) = *(rp + 5);
  194938. *(rp + 5) = save;
  194939. }
  194940. }
  194941. }
  194942. }
  194943. }
  194944. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  194945. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  194946. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  194947. defined(PNG_LEGACY_SUPPORTED)
  194948. void PNGAPI
  194949. png_set_user_transform_info(png_structp png_ptr, png_voidp
  194950. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  194951. {
  194952. png_debug(1, "in png_set_user_transform_info\n");
  194953. if(png_ptr == NULL) return;
  194954. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194955. png_ptr->user_transform_ptr = user_transform_ptr;
  194956. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  194957. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  194958. #else
  194959. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  194960. png_warning(png_ptr,
  194961. "This version of libpng does not support user transform info");
  194962. #endif
  194963. }
  194964. #endif
  194965. /* This function returns a pointer to the user_transform_ptr associated with
  194966. * the user transform functions. The application should free any memory
  194967. * associated with this pointer before png_write_destroy and png_read_destroy
  194968. * are called.
  194969. */
  194970. png_voidp PNGAPI
  194971. png_get_user_transform_ptr(png_structp png_ptr)
  194972. {
  194973. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194974. if (png_ptr == NULL) return (NULL);
  194975. return ((png_voidp)png_ptr->user_transform_ptr);
  194976. #else
  194977. return (NULL);
  194978. #endif
  194979. }
  194980. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194981. /*** End of inlined file: pngtrans.c ***/
  194982. /*** Start of inlined file: pngwio.c ***/
  194983. /* pngwio.c - functions for data output
  194984. *
  194985. * Last changed in libpng 1.2.13 November 13, 2006
  194986. * For conditions of distribution and use, see copyright notice in png.h
  194987. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194988. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194989. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194990. *
  194991. * This file provides a location for all output. Users who need
  194992. * special handling are expected to write functions that have the same
  194993. * arguments as these and perform similar functions, but that possibly
  194994. * use different output methods. Note that you shouldn't change these
  194995. * functions, but rather write replacement functions and then change
  194996. * them at run time with png_set_write_fn(...).
  194997. */
  194998. #define PNG_INTERNAL
  194999. #ifdef PNG_WRITE_SUPPORTED
  195000. /* Write the data to whatever output you are using. The default routine
  195001. writes to a file pointer. Note that this routine sometimes gets called
  195002. with very small lengths, so you should implement some kind of simple
  195003. buffering if you are using unbuffered writes. This should never be asked
  195004. to write more than 64K on a 16 bit machine. */
  195005. void /* PRIVATE */
  195006. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195007. {
  195008. if (png_ptr->write_data_fn != NULL )
  195009. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  195010. else
  195011. png_error(png_ptr, "Call to NULL write function");
  195012. }
  195013. #if !defined(PNG_NO_STDIO)
  195014. /* This is the function that does the actual writing of data. If you are
  195015. not writing to a standard C stream, you should create a replacement
  195016. write_data function and use it at run time with png_set_write_fn(), rather
  195017. than changing the library. */
  195018. #ifndef USE_FAR_KEYWORD
  195019. void PNGAPI
  195020. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195021. {
  195022. png_uint_32 check;
  195023. if(png_ptr == NULL) return;
  195024. #if defined(_WIN32_WCE)
  195025. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  195026. check = 0;
  195027. #else
  195028. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  195029. #endif
  195030. if (check != length)
  195031. png_error(png_ptr, "Write Error");
  195032. }
  195033. #else
  195034. /* this is the model-independent version. Since the standard I/O library
  195035. can't handle far buffers in the medium and small models, we have to copy
  195036. the data.
  195037. */
  195038. #define NEAR_BUF_SIZE 1024
  195039. #define MIN(a,b) (a <= b ? a : b)
  195040. void PNGAPI
  195041. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195042. {
  195043. png_uint_32 check;
  195044. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  195045. png_FILE_p io_ptr;
  195046. if(png_ptr == NULL) return;
  195047. /* Check if data really is near. If so, use usual code. */
  195048. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  195049. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  195050. if ((png_bytep)near_data == data)
  195051. {
  195052. #if defined(_WIN32_WCE)
  195053. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  195054. check = 0;
  195055. #else
  195056. check = fwrite(near_data, 1, length, io_ptr);
  195057. #endif
  195058. }
  195059. else
  195060. {
  195061. png_byte buf[NEAR_BUF_SIZE];
  195062. png_size_t written, remaining, err;
  195063. check = 0;
  195064. remaining = length;
  195065. do
  195066. {
  195067. written = MIN(NEAR_BUF_SIZE, remaining);
  195068. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  195069. #if defined(_WIN32_WCE)
  195070. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  195071. err = 0;
  195072. #else
  195073. err = fwrite(buf, 1, written, io_ptr);
  195074. #endif
  195075. if (err != written)
  195076. break;
  195077. else
  195078. check += err;
  195079. data += written;
  195080. remaining -= written;
  195081. }
  195082. while (remaining != 0);
  195083. }
  195084. if (check != length)
  195085. png_error(png_ptr, "Write Error");
  195086. }
  195087. #endif
  195088. #endif
  195089. /* This function is called to output any data pending writing (normally
  195090. to disk). After png_flush is called, there should be no data pending
  195091. writing in any buffers. */
  195092. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195093. void /* PRIVATE */
  195094. png_flush(png_structp png_ptr)
  195095. {
  195096. if (png_ptr->output_flush_fn != NULL)
  195097. (*(png_ptr->output_flush_fn))(png_ptr);
  195098. }
  195099. #if !defined(PNG_NO_STDIO)
  195100. void PNGAPI
  195101. png_default_flush(png_structp png_ptr)
  195102. {
  195103. #if !defined(_WIN32_WCE)
  195104. png_FILE_p io_ptr;
  195105. #endif
  195106. if(png_ptr == NULL) return;
  195107. #if !defined(_WIN32_WCE)
  195108. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  195109. if (io_ptr != NULL)
  195110. fflush(io_ptr);
  195111. #endif
  195112. }
  195113. #endif
  195114. #endif
  195115. /* This function allows the application to supply new output functions for
  195116. libpng if standard C streams aren't being used.
  195117. This function takes as its arguments:
  195118. png_ptr - pointer to a png output data structure
  195119. io_ptr - pointer to user supplied structure containing info about
  195120. the output functions. May be NULL.
  195121. write_data_fn - pointer to a new output function that takes as its
  195122. arguments a pointer to a png_struct, a pointer to
  195123. data to be written, and a 32-bit unsigned int that is
  195124. the number of bytes to be written. The new write
  195125. function should call png_error(png_ptr, "Error msg")
  195126. to exit and output any fatal error messages.
  195127. flush_data_fn - pointer to a new flush function that takes as its
  195128. arguments a pointer to a png_struct. After a call to
  195129. the flush function, there should be no data in any buffers
  195130. or pending transmission. If the output method doesn't do
  195131. any buffering of ouput, a function prototype must still be
  195132. supplied although it doesn't have to do anything. If
  195133. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  195134. time, output_flush_fn will be ignored, although it must be
  195135. supplied for compatibility. */
  195136. void PNGAPI
  195137. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  195138. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  195139. {
  195140. if(png_ptr == NULL) return;
  195141. png_ptr->io_ptr = io_ptr;
  195142. #if !defined(PNG_NO_STDIO)
  195143. if (write_data_fn != NULL)
  195144. png_ptr->write_data_fn = write_data_fn;
  195145. else
  195146. png_ptr->write_data_fn = png_default_write_data;
  195147. #else
  195148. png_ptr->write_data_fn = write_data_fn;
  195149. #endif
  195150. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195151. #if !defined(PNG_NO_STDIO)
  195152. if (output_flush_fn != NULL)
  195153. png_ptr->output_flush_fn = output_flush_fn;
  195154. else
  195155. png_ptr->output_flush_fn = png_default_flush;
  195156. #else
  195157. png_ptr->output_flush_fn = output_flush_fn;
  195158. #endif
  195159. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195160. /* It is an error to read while writing a png file */
  195161. if (png_ptr->read_data_fn != NULL)
  195162. {
  195163. png_ptr->read_data_fn = NULL;
  195164. png_warning(png_ptr,
  195165. "Attempted to set both read_data_fn and write_data_fn in");
  195166. png_warning(png_ptr,
  195167. "the same structure. Resetting read_data_fn to NULL.");
  195168. }
  195169. }
  195170. #if defined(USE_FAR_KEYWORD)
  195171. #if defined(_MSC_VER)
  195172. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195173. {
  195174. void *near_ptr;
  195175. void FAR *far_ptr;
  195176. FP_OFF(near_ptr) = FP_OFF(ptr);
  195177. far_ptr = (void FAR *)near_ptr;
  195178. if(check != 0)
  195179. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  195180. png_error(png_ptr,"segment lost in conversion");
  195181. return(near_ptr);
  195182. }
  195183. # else
  195184. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195185. {
  195186. void *near_ptr;
  195187. void FAR *far_ptr;
  195188. near_ptr = (void FAR *)ptr;
  195189. far_ptr = (void FAR *)near_ptr;
  195190. if(check != 0)
  195191. if(far_ptr != ptr)
  195192. png_error(png_ptr,"segment lost in conversion");
  195193. return(near_ptr);
  195194. }
  195195. # endif
  195196. # endif
  195197. #endif /* PNG_WRITE_SUPPORTED */
  195198. /*** End of inlined file: pngwio.c ***/
  195199. /*** Start of inlined file: pngwrite.c ***/
  195200. /* pngwrite.c - general routines to write a PNG file
  195201. *
  195202. * Last changed in libpng 1.2.15 January 5, 2007
  195203. * For conditions of distribution and use, see copyright notice in png.h
  195204. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195205. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195206. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195207. */
  195208. /* get internal access to png.h */
  195209. #define PNG_INTERNAL
  195210. #ifdef PNG_WRITE_SUPPORTED
  195211. /* Writes all the PNG information. This is the suggested way to use the
  195212. * library. If you have a new chunk to add, make a function to write it,
  195213. * and put it in the correct location here. If you want the chunk written
  195214. * after the image data, put it in png_write_end(). I strongly encourage
  195215. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  195216. * the chunk, as that will keep the code from breaking if you want to just
  195217. * write a plain PNG file. If you have long comments, I suggest writing
  195218. * them in png_write_end(), and compressing them.
  195219. */
  195220. void PNGAPI
  195221. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  195222. {
  195223. png_debug(1, "in png_write_info_before_PLTE\n");
  195224. if (png_ptr == NULL || info_ptr == NULL)
  195225. return;
  195226. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195227. {
  195228. png_write_sig(png_ptr); /* write PNG signature */
  195229. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195230. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  195231. {
  195232. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  195233. png_ptr->mng_features_permitted=0;
  195234. }
  195235. #endif
  195236. /* write IHDR information. */
  195237. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  195238. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  195239. info_ptr->filter_type,
  195240. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195241. info_ptr->interlace_type);
  195242. #else
  195243. 0);
  195244. #endif
  195245. /* the rest of these check to see if the valid field has the appropriate
  195246. flag set, and if it does, writes the chunk. */
  195247. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195248. if (info_ptr->valid & PNG_INFO_gAMA)
  195249. {
  195250. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195251. png_write_gAMA(png_ptr, info_ptr->gamma);
  195252. #else
  195253. #ifdef PNG_FIXED_POINT_SUPPORTED
  195254. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  195255. # endif
  195256. #endif
  195257. }
  195258. #endif
  195259. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195260. if (info_ptr->valid & PNG_INFO_sRGB)
  195261. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  195262. #endif
  195263. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195264. if (info_ptr->valid & PNG_INFO_iCCP)
  195265. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  195266. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  195267. #endif
  195268. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195269. if (info_ptr->valid & PNG_INFO_sBIT)
  195270. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  195271. #endif
  195272. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195273. if (info_ptr->valid & PNG_INFO_cHRM)
  195274. {
  195275. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195276. png_write_cHRM(png_ptr,
  195277. info_ptr->x_white, info_ptr->y_white,
  195278. info_ptr->x_red, info_ptr->y_red,
  195279. info_ptr->x_green, info_ptr->y_green,
  195280. info_ptr->x_blue, info_ptr->y_blue);
  195281. #else
  195282. # ifdef PNG_FIXED_POINT_SUPPORTED
  195283. png_write_cHRM_fixed(png_ptr,
  195284. info_ptr->int_x_white, info_ptr->int_y_white,
  195285. info_ptr->int_x_red, info_ptr->int_y_red,
  195286. info_ptr->int_x_green, info_ptr->int_y_green,
  195287. info_ptr->int_x_blue, info_ptr->int_y_blue);
  195288. # endif
  195289. #endif
  195290. }
  195291. #endif
  195292. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195293. if (info_ptr->unknown_chunks_num)
  195294. {
  195295. png_unknown_chunk *up;
  195296. png_debug(5, "writing extra chunks\n");
  195297. for (up = info_ptr->unknown_chunks;
  195298. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195299. up++)
  195300. {
  195301. int keep=png_handle_as_unknown(png_ptr, up->name);
  195302. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195303. up->location && !(up->location & PNG_HAVE_PLTE) &&
  195304. !(up->location & PNG_HAVE_IDAT) &&
  195305. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195306. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195307. {
  195308. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195309. }
  195310. }
  195311. }
  195312. #endif
  195313. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  195314. }
  195315. }
  195316. void PNGAPI
  195317. png_write_info(png_structp png_ptr, png_infop info_ptr)
  195318. {
  195319. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195320. int i;
  195321. #endif
  195322. png_debug(1, "in png_write_info\n");
  195323. if (png_ptr == NULL || info_ptr == NULL)
  195324. return;
  195325. png_write_info_before_PLTE(png_ptr, info_ptr);
  195326. if (info_ptr->valid & PNG_INFO_PLTE)
  195327. png_write_PLTE(png_ptr, info_ptr->palette,
  195328. (png_uint_32)info_ptr->num_palette);
  195329. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195330. png_error(png_ptr, "Valid palette required for paletted images");
  195331. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195332. if (info_ptr->valid & PNG_INFO_tRNS)
  195333. {
  195334. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195335. /* invert the alpha channel (in tRNS) */
  195336. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  195337. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195338. {
  195339. int j;
  195340. for (j=0; j<(int)info_ptr->num_trans; j++)
  195341. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  195342. }
  195343. #endif
  195344. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  195345. info_ptr->num_trans, info_ptr->color_type);
  195346. }
  195347. #endif
  195348. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195349. if (info_ptr->valid & PNG_INFO_bKGD)
  195350. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  195351. #endif
  195352. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195353. if (info_ptr->valid & PNG_INFO_hIST)
  195354. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  195355. #endif
  195356. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195357. if (info_ptr->valid & PNG_INFO_oFFs)
  195358. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  195359. info_ptr->offset_unit_type);
  195360. #endif
  195361. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195362. if (info_ptr->valid & PNG_INFO_pCAL)
  195363. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  195364. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  195365. info_ptr->pcal_units, info_ptr->pcal_params);
  195366. #endif
  195367. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  195368. if (info_ptr->valid & PNG_INFO_sCAL)
  195369. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  195370. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  195371. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  195372. #else
  195373. #ifdef PNG_FIXED_POINT_SUPPORTED
  195374. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  195375. info_ptr->scal_s_width, info_ptr->scal_s_height);
  195376. #else
  195377. png_warning(png_ptr,
  195378. "png_write_sCAL not supported; sCAL chunk not written.");
  195379. #endif
  195380. #endif
  195381. #endif
  195382. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  195383. if (info_ptr->valid & PNG_INFO_pHYs)
  195384. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  195385. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  195386. #endif
  195387. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195388. if (info_ptr->valid & PNG_INFO_tIME)
  195389. {
  195390. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  195391. png_ptr->mode |= PNG_WROTE_tIME;
  195392. }
  195393. #endif
  195394. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  195395. if (info_ptr->valid & PNG_INFO_sPLT)
  195396. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  195397. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  195398. #endif
  195399. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195400. /* Check to see if we need to write text chunks */
  195401. for (i = 0; i < info_ptr->num_text; i++)
  195402. {
  195403. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  195404. info_ptr->text[i].compression);
  195405. /* an internationalized chunk? */
  195406. if (info_ptr->text[i].compression > 0)
  195407. {
  195408. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195409. /* write international chunk */
  195410. png_write_iTXt(png_ptr,
  195411. info_ptr->text[i].compression,
  195412. info_ptr->text[i].key,
  195413. info_ptr->text[i].lang,
  195414. info_ptr->text[i].lang_key,
  195415. info_ptr->text[i].text);
  195416. #else
  195417. png_warning(png_ptr, "Unable to write international text");
  195418. #endif
  195419. /* Mark this chunk as written */
  195420. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195421. }
  195422. /* If we want a compressed text chunk */
  195423. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  195424. {
  195425. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195426. /* write compressed chunk */
  195427. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  195428. info_ptr->text[i].text, 0,
  195429. info_ptr->text[i].compression);
  195430. #else
  195431. png_warning(png_ptr, "Unable to write compressed text");
  195432. #endif
  195433. /* Mark this chunk as written */
  195434. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  195435. }
  195436. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  195437. {
  195438. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195439. /* write uncompressed chunk */
  195440. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  195441. info_ptr->text[i].text,
  195442. 0);
  195443. #else
  195444. png_warning(png_ptr, "Unable to write uncompressed text");
  195445. #endif
  195446. /* Mark this chunk as written */
  195447. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195448. }
  195449. }
  195450. #endif
  195451. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195452. if (info_ptr->unknown_chunks_num)
  195453. {
  195454. png_unknown_chunk *up;
  195455. png_debug(5, "writing extra chunks\n");
  195456. for (up = info_ptr->unknown_chunks;
  195457. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195458. up++)
  195459. {
  195460. int keep=png_handle_as_unknown(png_ptr, up->name);
  195461. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195462. up->location && (up->location & PNG_HAVE_PLTE) &&
  195463. !(up->location & PNG_HAVE_IDAT) &&
  195464. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195465. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195466. {
  195467. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195468. }
  195469. }
  195470. }
  195471. #endif
  195472. }
  195473. /* Writes the end of the PNG file. If you don't want to write comments or
  195474. * time information, you can pass NULL for info. If you already wrote these
  195475. * in png_write_info(), do not write them again here. If you have long
  195476. * comments, I suggest writing them here, and compressing them.
  195477. */
  195478. void PNGAPI
  195479. png_write_end(png_structp png_ptr, png_infop info_ptr)
  195480. {
  195481. png_debug(1, "in png_write_end\n");
  195482. if (png_ptr == NULL)
  195483. return;
  195484. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  195485. png_error(png_ptr, "No IDATs written into file");
  195486. /* see if user wants us to write information chunks */
  195487. if (info_ptr != NULL)
  195488. {
  195489. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195490. int i; /* local index variable */
  195491. #endif
  195492. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195493. /* check to see if user has supplied a time chunk */
  195494. if ((info_ptr->valid & PNG_INFO_tIME) &&
  195495. !(png_ptr->mode & PNG_WROTE_tIME))
  195496. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  195497. #endif
  195498. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195499. /* loop through comment chunks */
  195500. for (i = 0; i < info_ptr->num_text; i++)
  195501. {
  195502. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  195503. info_ptr->text[i].compression);
  195504. /* an internationalized chunk? */
  195505. if (info_ptr->text[i].compression > 0)
  195506. {
  195507. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195508. /* write international chunk */
  195509. png_write_iTXt(png_ptr,
  195510. info_ptr->text[i].compression,
  195511. info_ptr->text[i].key,
  195512. info_ptr->text[i].lang,
  195513. info_ptr->text[i].lang_key,
  195514. info_ptr->text[i].text);
  195515. #else
  195516. png_warning(png_ptr, "Unable to write international text");
  195517. #endif
  195518. /* Mark this chunk as written */
  195519. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195520. }
  195521. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  195522. {
  195523. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195524. /* write compressed chunk */
  195525. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  195526. info_ptr->text[i].text, 0,
  195527. info_ptr->text[i].compression);
  195528. #else
  195529. png_warning(png_ptr, "Unable to write compressed text");
  195530. #endif
  195531. /* Mark this chunk as written */
  195532. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  195533. }
  195534. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  195535. {
  195536. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195537. /* write uncompressed chunk */
  195538. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  195539. info_ptr->text[i].text, 0);
  195540. #else
  195541. png_warning(png_ptr, "Unable to write uncompressed text");
  195542. #endif
  195543. /* Mark this chunk as written */
  195544. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195545. }
  195546. }
  195547. #endif
  195548. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195549. if (info_ptr->unknown_chunks_num)
  195550. {
  195551. png_unknown_chunk *up;
  195552. png_debug(5, "writing extra chunks\n");
  195553. for (up = info_ptr->unknown_chunks;
  195554. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195555. up++)
  195556. {
  195557. int keep=png_handle_as_unknown(png_ptr, up->name);
  195558. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195559. up->location && (up->location & PNG_AFTER_IDAT) &&
  195560. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195561. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195562. {
  195563. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195564. }
  195565. }
  195566. }
  195567. #endif
  195568. }
  195569. png_ptr->mode |= PNG_AFTER_IDAT;
  195570. /* write end of PNG file */
  195571. png_write_IEND(png_ptr);
  195572. }
  195573. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195574. #if !defined(_WIN32_WCE)
  195575. /* "time.h" functions are not supported on WindowsCE */
  195576. void PNGAPI
  195577. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  195578. {
  195579. png_debug(1, "in png_convert_from_struct_tm\n");
  195580. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  195581. ptime->month = (png_byte)(ttime->tm_mon + 1);
  195582. ptime->day = (png_byte)ttime->tm_mday;
  195583. ptime->hour = (png_byte)ttime->tm_hour;
  195584. ptime->minute = (png_byte)ttime->tm_min;
  195585. ptime->second = (png_byte)ttime->tm_sec;
  195586. }
  195587. void PNGAPI
  195588. png_convert_from_time_t(png_timep ptime, time_t ttime)
  195589. {
  195590. struct tm *tbuf;
  195591. png_debug(1, "in png_convert_from_time_t\n");
  195592. tbuf = gmtime(&ttime);
  195593. png_convert_from_struct_tm(ptime, tbuf);
  195594. }
  195595. #endif
  195596. #endif
  195597. /* Initialize png_ptr structure, and allocate any memory needed */
  195598. png_structp PNGAPI
  195599. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  195600. png_error_ptr error_fn, png_error_ptr warn_fn)
  195601. {
  195602. #ifdef PNG_USER_MEM_SUPPORTED
  195603. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  195604. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  195605. }
  195606. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  195607. png_structp PNGAPI
  195608. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  195609. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  195610. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  195611. {
  195612. #endif /* PNG_USER_MEM_SUPPORTED */
  195613. png_structp png_ptr;
  195614. #ifdef PNG_SETJMP_SUPPORTED
  195615. #ifdef USE_FAR_KEYWORD
  195616. jmp_buf jmpbuf;
  195617. #endif
  195618. #endif
  195619. int i;
  195620. png_debug(1, "in png_create_write_struct\n");
  195621. #ifdef PNG_USER_MEM_SUPPORTED
  195622. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  195623. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  195624. #else
  195625. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  195626. #endif /* PNG_USER_MEM_SUPPORTED */
  195627. if (png_ptr == NULL)
  195628. return (NULL);
  195629. /* added at libpng-1.2.6 */
  195630. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195631. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  195632. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  195633. #endif
  195634. #ifdef PNG_SETJMP_SUPPORTED
  195635. #ifdef USE_FAR_KEYWORD
  195636. if (setjmp(jmpbuf))
  195637. #else
  195638. if (setjmp(png_ptr->jmpbuf))
  195639. #endif
  195640. {
  195641. png_free(png_ptr, png_ptr->zbuf);
  195642. png_ptr->zbuf=NULL;
  195643. png_destroy_struct(png_ptr);
  195644. return (NULL);
  195645. }
  195646. #ifdef USE_FAR_KEYWORD
  195647. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  195648. #endif
  195649. #endif
  195650. #ifdef PNG_USER_MEM_SUPPORTED
  195651. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  195652. #endif /* PNG_USER_MEM_SUPPORTED */
  195653. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  195654. i=0;
  195655. do
  195656. {
  195657. if(user_png_ver[i] != png_libpng_ver[i])
  195658. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  195659. } while (png_libpng_ver[i++]);
  195660. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  195661. {
  195662. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  195663. * we must recompile any applications that use any older library version.
  195664. * For versions after libpng 1.0, we will be compatible, so we need
  195665. * only check the first digit.
  195666. */
  195667. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  195668. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  195669. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  195670. {
  195671. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195672. char msg[80];
  195673. if (user_png_ver)
  195674. {
  195675. png_snprintf(msg, 80,
  195676. "Application was compiled with png.h from libpng-%.20s",
  195677. user_png_ver);
  195678. png_warning(png_ptr, msg);
  195679. }
  195680. png_snprintf(msg, 80,
  195681. "Application is running with png.c from libpng-%.20s",
  195682. png_libpng_ver);
  195683. png_warning(png_ptr, msg);
  195684. #endif
  195685. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  195686. png_ptr->flags=0;
  195687. #endif
  195688. png_error(png_ptr,
  195689. "Incompatible libpng version in application and library");
  195690. }
  195691. }
  195692. /* initialize zbuf - compression buffer */
  195693. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  195694. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  195695. (png_uint_32)png_ptr->zbuf_size);
  195696. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  195697. png_flush_ptr_NULL);
  195698. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195699. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  195700. 1, png_doublep_NULL, png_doublep_NULL);
  195701. #endif
  195702. #ifdef PNG_SETJMP_SUPPORTED
  195703. /* Applications that neglect to set up their own setjmp() and then encounter
  195704. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  195705. abort instead of returning. */
  195706. #ifdef USE_FAR_KEYWORD
  195707. if (setjmp(jmpbuf))
  195708. PNG_ABORT();
  195709. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  195710. #else
  195711. if (setjmp(png_ptr->jmpbuf))
  195712. PNG_ABORT();
  195713. #endif
  195714. #endif
  195715. return (png_ptr);
  195716. }
  195717. /* Initialize png_ptr structure, and allocate any memory needed */
  195718. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  195719. /* Deprecated. */
  195720. #undef png_write_init
  195721. void PNGAPI
  195722. png_write_init(png_structp png_ptr)
  195723. {
  195724. /* We only come here via pre-1.0.7-compiled applications */
  195725. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  195726. }
  195727. void PNGAPI
  195728. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  195729. png_size_t png_struct_size, png_size_t png_info_size)
  195730. {
  195731. /* We only come here via pre-1.0.12-compiled applications */
  195732. if(png_ptr == NULL) return;
  195733. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195734. if(png_sizeof(png_struct) > png_struct_size ||
  195735. png_sizeof(png_info) > png_info_size)
  195736. {
  195737. char msg[80];
  195738. png_ptr->warning_fn=NULL;
  195739. if (user_png_ver)
  195740. {
  195741. png_snprintf(msg, 80,
  195742. "Application was compiled with png.h from libpng-%.20s",
  195743. user_png_ver);
  195744. png_warning(png_ptr, msg);
  195745. }
  195746. png_snprintf(msg, 80,
  195747. "Application is running with png.c from libpng-%.20s",
  195748. png_libpng_ver);
  195749. png_warning(png_ptr, msg);
  195750. }
  195751. #endif
  195752. if(png_sizeof(png_struct) > png_struct_size)
  195753. {
  195754. png_ptr->error_fn=NULL;
  195755. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  195756. png_ptr->flags=0;
  195757. #endif
  195758. png_error(png_ptr,
  195759. "The png struct allocated by the application for writing is too small.");
  195760. }
  195761. if(png_sizeof(png_info) > png_info_size)
  195762. {
  195763. png_ptr->error_fn=NULL;
  195764. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  195765. png_ptr->flags=0;
  195766. #endif
  195767. png_error(png_ptr,
  195768. "The info struct allocated by the application for writing is too small.");
  195769. }
  195770. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  195771. }
  195772. #endif /* PNG_1_0_X || PNG_1_2_X */
  195773. void PNGAPI
  195774. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  195775. png_size_t png_struct_size)
  195776. {
  195777. png_structp png_ptr=*ptr_ptr;
  195778. #ifdef PNG_SETJMP_SUPPORTED
  195779. jmp_buf tmp_jmp; /* to save current jump buffer */
  195780. #endif
  195781. int i = 0;
  195782. if (png_ptr == NULL)
  195783. return;
  195784. do
  195785. {
  195786. if (user_png_ver[i] != png_libpng_ver[i])
  195787. {
  195788. #ifdef PNG_LEGACY_SUPPORTED
  195789. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  195790. #else
  195791. png_ptr->warning_fn=NULL;
  195792. png_warning(png_ptr,
  195793. "Application uses deprecated png_write_init() and should be recompiled.");
  195794. break;
  195795. #endif
  195796. }
  195797. } while (png_libpng_ver[i++]);
  195798. png_debug(1, "in png_write_init_3\n");
  195799. #ifdef PNG_SETJMP_SUPPORTED
  195800. /* save jump buffer and error functions */
  195801. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195802. #endif
  195803. if (png_sizeof(png_struct) > png_struct_size)
  195804. {
  195805. png_destroy_struct(png_ptr);
  195806. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  195807. *ptr_ptr = png_ptr;
  195808. }
  195809. /* reset all variables to 0 */
  195810. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195811. /* added at libpng-1.2.6 */
  195812. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195813. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  195814. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  195815. #endif
  195816. #ifdef PNG_SETJMP_SUPPORTED
  195817. /* restore jump buffer */
  195818. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195819. #endif
  195820. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  195821. png_flush_ptr_NULL);
  195822. /* initialize zbuf - compression buffer */
  195823. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  195824. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  195825. (png_uint_32)png_ptr->zbuf_size);
  195826. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195827. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  195828. 1, png_doublep_NULL, png_doublep_NULL);
  195829. #endif
  195830. }
  195831. /* Write a few rows of image data. If the image is interlaced,
  195832. * either you will have to write the 7 sub images, or, if you
  195833. * have called png_set_interlace_handling(), you will have to
  195834. * "write" the image seven times.
  195835. */
  195836. void PNGAPI
  195837. png_write_rows(png_structp png_ptr, png_bytepp row,
  195838. png_uint_32 num_rows)
  195839. {
  195840. png_uint_32 i; /* row counter */
  195841. png_bytepp rp; /* row pointer */
  195842. png_debug(1, "in png_write_rows\n");
  195843. if (png_ptr == NULL)
  195844. return;
  195845. /* loop through the rows */
  195846. for (i = 0, rp = row; i < num_rows; i++, rp++)
  195847. {
  195848. png_write_row(png_ptr, *rp);
  195849. }
  195850. }
  195851. /* Write the image. You only need to call this function once, even
  195852. * if you are writing an interlaced image.
  195853. */
  195854. void PNGAPI
  195855. png_write_image(png_structp png_ptr, png_bytepp image)
  195856. {
  195857. png_uint_32 i; /* row index */
  195858. int pass, num_pass; /* pass variables */
  195859. png_bytepp rp; /* points to current row */
  195860. if (png_ptr == NULL)
  195861. return;
  195862. png_debug(1, "in png_write_image\n");
  195863. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195864. /* intialize interlace handling. If image is not interlaced,
  195865. this will set pass to 1 */
  195866. num_pass = png_set_interlace_handling(png_ptr);
  195867. #else
  195868. num_pass = 1;
  195869. #endif
  195870. /* loop through passes */
  195871. for (pass = 0; pass < num_pass; pass++)
  195872. {
  195873. /* loop through image */
  195874. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  195875. {
  195876. png_write_row(png_ptr, *rp);
  195877. }
  195878. }
  195879. }
  195880. /* called by user to write a row of image data */
  195881. void PNGAPI
  195882. png_write_row(png_structp png_ptr, png_bytep row)
  195883. {
  195884. if (png_ptr == NULL)
  195885. return;
  195886. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  195887. png_ptr->row_number, png_ptr->pass);
  195888. /* initialize transformations and other stuff if first time */
  195889. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  195890. {
  195891. /* make sure we wrote the header info */
  195892. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195893. png_error(png_ptr,
  195894. "png_write_info was never called before png_write_row.");
  195895. /* check for transforms that have been set but were defined out */
  195896. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  195897. if (png_ptr->transformations & PNG_INVERT_MONO)
  195898. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  195899. #endif
  195900. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  195901. if (png_ptr->transformations & PNG_FILLER)
  195902. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  195903. #endif
  195904. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  195905. if (png_ptr->transformations & PNG_PACKSWAP)
  195906. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  195907. #endif
  195908. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  195909. if (png_ptr->transformations & PNG_PACK)
  195910. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  195911. #endif
  195912. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  195913. if (png_ptr->transformations & PNG_SHIFT)
  195914. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  195915. #endif
  195916. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  195917. if (png_ptr->transformations & PNG_BGR)
  195918. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  195919. #endif
  195920. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  195921. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195922. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  195923. #endif
  195924. png_write_start_row(png_ptr);
  195925. }
  195926. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195927. /* if interlaced and not interested in row, return */
  195928. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  195929. {
  195930. switch (png_ptr->pass)
  195931. {
  195932. case 0:
  195933. if (png_ptr->row_number & 0x07)
  195934. {
  195935. png_write_finish_row(png_ptr);
  195936. return;
  195937. }
  195938. break;
  195939. case 1:
  195940. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  195941. {
  195942. png_write_finish_row(png_ptr);
  195943. return;
  195944. }
  195945. break;
  195946. case 2:
  195947. if ((png_ptr->row_number & 0x07) != 4)
  195948. {
  195949. png_write_finish_row(png_ptr);
  195950. return;
  195951. }
  195952. break;
  195953. case 3:
  195954. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  195955. {
  195956. png_write_finish_row(png_ptr);
  195957. return;
  195958. }
  195959. break;
  195960. case 4:
  195961. if ((png_ptr->row_number & 0x03) != 2)
  195962. {
  195963. png_write_finish_row(png_ptr);
  195964. return;
  195965. }
  195966. break;
  195967. case 5:
  195968. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  195969. {
  195970. png_write_finish_row(png_ptr);
  195971. return;
  195972. }
  195973. break;
  195974. case 6:
  195975. if (!(png_ptr->row_number & 0x01))
  195976. {
  195977. png_write_finish_row(png_ptr);
  195978. return;
  195979. }
  195980. break;
  195981. }
  195982. }
  195983. #endif
  195984. /* set up row info for transformations */
  195985. png_ptr->row_info.color_type = png_ptr->color_type;
  195986. png_ptr->row_info.width = png_ptr->usr_width;
  195987. png_ptr->row_info.channels = png_ptr->usr_channels;
  195988. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  195989. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  195990. png_ptr->row_info.channels);
  195991. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  195992. png_ptr->row_info.width);
  195993. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  195994. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  195995. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  195996. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  195997. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  195998. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  195999. /* Copy user's row into buffer, leaving room for filter byte. */
  196000. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  196001. png_ptr->row_info.rowbytes);
  196002. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196003. /* handle interlacing */
  196004. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  196005. (png_ptr->transformations & PNG_INTERLACE))
  196006. {
  196007. png_do_write_interlace(&(png_ptr->row_info),
  196008. png_ptr->row_buf + 1, png_ptr->pass);
  196009. /* this should always get caught above, but still ... */
  196010. if (!(png_ptr->row_info.width))
  196011. {
  196012. png_write_finish_row(png_ptr);
  196013. return;
  196014. }
  196015. }
  196016. #endif
  196017. /* handle other transformations */
  196018. if (png_ptr->transformations)
  196019. png_do_write_transformations(png_ptr);
  196020. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196021. /* Write filter_method 64 (intrapixel differencing) only if
  196022. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196023. * 2. Libpng did not write a PNG signature (this filter_method is only
  196024. * used in PNG datastreams that are embedded in MNG datastreams) and
  196025. * 3. The application called png_permit_mng_features with a mask that
  196026. * included PNG_FLAG_MNG_FILTER_64 and
  196027. * 4. The filter_method is 64 and
  196028. * 5. The color_type is RGB or RGBA
  196029. */
  196030. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196031. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  196032. {
  196033. /* Intrapixel differencing */
  196034. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196035. }
  196036. #endif
  196037. /* Find a filter if necessary, filter the row and write it out. */
  196038. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  196039. if (png_ptr->write_row_fn != NULL)
  196040. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  196041. }
  196042. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  196043. /* Set the automatic flush interval or 0 to turn flushing off */
  196044. void PNGAPI
  196045. png_set_flush(png_structp png_ptr, int nrows)
  196046. {
  196047. png_debug(1, "in png_set_flush\n");
  196048. if (png_ptr == NULL)
  196049. return;
  196050. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  196051. }
  196052. /* flush the current output buffers now */
  196053. void PNGAPI
  196054. png_write_flush(png_structp png_ptr)
  196055. {
  196056. int wrote_IDAT;
  196057. png_debug(1, "in png_write_flush\n");
  196058. if (png_ptr == NULL)
  196059. return;
  196060. /* We have already written out all of the data */
  196061. if (png_ptr->row_number >= png_ptr->num_rows)
  196062. return;
  196063. do
  196064. {
  196065. int ret;
  196066. /* compress the data */
  196067. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  196068. wrote_IDAT = 0;
  196069. /* check for compression errors */
  196070. if (ret != Z_OK)
  196071. {
  196072. if (png_ptr->zstream.msg != NULL)
  196073. png_error(png_ptr, png_ptr->zstream.msg);
  196074. else
  196075. png_error(png_ptr, "zlib error");
  196076. }
  196077. if (!(png_ptr->zstream.avail_out))
  196078. {
  196079. /* write the IDAT and reset the zlib output buffer */
  196080. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196081. png_ptr->zbuf_size);
  196082. png_ptr->zstream.next_out = png_ptr->zbuf;
  196083. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196084. wrote_IDAT = 1;
  196085. }
  196086. } while(wrote_IDAT == 1);
  196087. /* If there is any data left to be output, write it into a new IDAT */
  196088. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  196089. {
  196090. /* write the IDAT and reset the zlib output buffer */
  196091. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196092. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196093. png_ptr->zstream.next_out = png_ptr->zbuf;
  196094. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196095. }
  196096. png_ptr->flush_rows = 0;
  196097. png_flush(png_ptr);
  196098. }
  196099. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  196100. /* free all memory used by the write */
  196101. void PNGAPI
  196102. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  196103. {
  196104. png_structp png_ptr = NULL;
  196105. png_infop info_ptr = NULL;
  196106. #ifdef PNG_USER_MEM_SUPPORTED
  196107. png_free_ptr free_fn = NULL;
  196108. png_voidp mem_ptr = NULL;
  196109. #endif
  196110. png_debug(1, "in png_destroy_write_struct\n");
  196111. if (png_ptr_ptr != NULL)
  196112. {
  196113. png_ptr = *png_ptr_ptr;
  196114. #ifdef PNG_USER_MEM_SUPPORTED
  196115. free_fn = png_ptr->free_fn;
  196116. mem_ptr = png_ptr->mem_ptr;
  196117. #endif
  196118. }
  196119. if (info_ptr_ptr != NULL)
  196120. info_ptr = *info_ptr_ptr;
  196121. if (info_ptr != NULL)
  196122. {
  196123. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  196124. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196125. if (png_ptr->num_chunk_list)
  196126. {
  196127. png_free(png_ptr, png_ptr->chunk_list);
  196128. png_ptr->chunk_list=NULL;
  196129. png_ptr->num_chunk_list=0;
  196130. }
  196131. #endif
  196132. #ifdef PNG_USER_MEM_SUPPORTED
  196133. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  196134. (png_voidp)mem_ptr);
  196135. #else
  196136. png_destroy_struct((png_voidp)info_ptr);
  196137. #endif
  196138. *info_ptr_ptr = NULL;
  196139. }
  196140. if (png_ptr != NULL)
  196141. {
  196142. png_write_destroy(png_ptr);
  196143. #ifdef PNG_USER_MEM_SUPPORTED
  196144. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  196145. (png_voidp)mem_ptr);
  196146. #else
  196147. png_destroy_struct((png_voidp)png_ptr);
  196148. #endif
  196149. *png_ptr_ptr = NULL;
  196150. }
  196151. }
  196152. /* Free any memory used in png_ptr struct (old method) */
  196153. void /* PRIVATE */
  196154. png_write_destroy(png_structp png_ptr)
  196155. {
  196156. #ifdef PNG_SETJMP_SUPPORTED
  196157. jmp_buf tmp_jmp; /* save jump buffer */
  196158. #endif
  196159. png_error_ptr error_fn;
  196160. png_error_ptr warning_fn;
  196161. png_voidp error_ptr;
  196162. #ifdef PNG_USER_MEM_SUPPORTED
  196163. png_free_ptr free_fn;
  196164. #endif
  196165. png_debug(1, "in png_write_destroy\n");
  196166. /* free any memory zlib uses */
  196167. deflateEnd(&png_ptr->zstream);
  196168. /* free our memory. png_free checks NULL for us. */
  196169. png_free(png_ptr, png_ptr->zbuf);
  196170. png_free(png_ptr, png_ptr->row_buf);
  196171. png_free(png_ptr, png_ptr->prev_row);
  196172. png_free(png_ptr, png_ptr->sub_row);
  196173. png_free(png_ptr, png_ptr->up_row);
  196174. png_free(png_ptr, png_ptr->avg_row);
  196175. png_free(png_ptr, png_ptr->paeth_row);
  196176. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  196177. png_free(png_ptr, png_ptr->time_buffer);
  196178. #endif
  196179. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196180. png_free(png_ptr, png_ptr->prev_filters);
  196181. png_free(png_ptr, png_ptr->filter_weights);
  196182. png_free(png_ptr, png_ptr->inv_filter_weights);
  196183. png_free(png_ptr, png_ptr->filter_costs);
  196184. png_free(png_ptr, png_ptr->inv_filter_costs);
  196185. #endif
  196186. #ifdef PNG_SETJMP_SUPPORTED
  196187. /* reset structure */
  196188. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  196189. #endif
  196190. error_fn = png_ptr->error_fn;
  196191. warning_fn = png_ptr->warning_fn;
  196192. error_ptr = png_ptr->error_ptr;
  196193. #ifdef PNG_USER_MEM_SUPPORTED
  196194. free_fn = png_ptr->free_fn;
  196195. #endif
  196196. png_memset(png_ptr, 0, png_sizeof (png_struct));
  196197. png_ptr->error_fn = error_fn;
  196198. png_ptr->warning_fn = warning_fn;
  196199. png_ptr->error_ptr = error_ptr;
  196200. #ifdef PNG_USER_MEM_SUPPORTED
  196201. png_ptr->free_fn = free_fn;
  196202. #endif
  196203. #ifdef PNG_SETJMP_SUPPORTED
  196204. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  196205. #endif
  196206. }
  196207. /* Allow the application to select one or more row filters to use. */
  196208. void PNGAPI
  196209. png_set_filter(png_structp png_ptr, int method, int filters)
  196210. {
  196211. png_debug(1, "in png_set_filter\n");
  196212. if (png_ptr == NULL)
  196213. return;
  196214. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196215. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196216. (method == PNG_INTRAPIXEL_DIFFERENCING))
  196217. method = PNG_FILTER_TYPE_BASE;
  196218. #endif
  196219. if (method == PNG_FILTER_TYPE_BASE)
  196220. {
  196221. switch (filters & (PNG_ALL_FILTERS | 0x07))
  196222. {
  196223. #ifndef PNG_NO_WRITE_FILTER
  196224. case 5:
  196225. case 6:
  196226. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  196227. #endif /* PNG_NO_WRITE_FILTER */
  196228. case PNG_FILTER_VALUE_NONE:
  196229. png_ptr->do_filter=PNG_FILTER_NONE; break;
  196230. #ifndef PNG_NO_WRITE_FILTER
  196231. case PNG_FILTER_VALUE_SUB:
  196232. png_ptr->do_filter=PNG_FILTER_SUB; break;
  196233. case PNG_FILTER_VALUE_UP:
  196234. png_ptr->do_filter=PNG_FILTER_UP; break;
  196235. case PNG_FILTER_VALUE_AVG:
  196236. png_ptr->do_filter=PNG_FILTER_AVG; break;
  196237. case PNG_FILTER_VALUE_PAETH:
  196238. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  196239. default: png_ptr->do_filter = (png_byte)filters; break;
  196240. #else
  196241. default: png_warning(png_ptr, "Unknown row filter for method 0");
  196242. #endif /* PNG_NO_WRITE_FILTER */
  196243. }
  196244. /* If we have allocated the row_buf, this means we have already started
  196245. * with the image and we should have allocated all of the filter buffers
  196246. * that have been selected. If prev_row isn't already allocated, then
  196247. * it is too late to start using the filters that need it, since we
  196248. * will be missing the data in the previous row. If an application
  196249. * wants to start and stop using particular filters during compression,
  196250. * it should start out with all of the filters, and then add and
  196251. * remove them after the start of compression.
  196252. */
  196253. if (png_ptr->row_buf != NULL)
  196254. {
  196255. #ifndef PNG_NO_WRITE_FILTER
  196256. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  196257. {
  196258. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196259. (png_ptr->rowbytes + 1));
  196260. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196261. }
  196262. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  196263. {
  196264. if (png_ptr->prev_row == NULL)
  196265. {
  196266. png_warning(png_ptr, "Can't add Up filter after starting");
  196267. png_ptr->do_filter &= ~PNG_FILTER_UP;
  196268. }
  196269. else
  196270. {
  196271. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196272. (png_ptr->rowbytes + 1));
  196273. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196274. }
  196275. }
  196276. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  196277. {
  196278. if (png_ptr->prev_row == NULL)
  196279. {
  196280. png_warning(png_ptr, "Can't add Average filter after starting");
  196281. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  196282. }
  196283. else
  196284. {
  196285. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196286. (png_ptr->rowbytes + 1));
  196287. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196288. }
  196289. }
  196290. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  196291. png_ptr->paeth_row == NULL)
  196292. {
  196293. if (png_ptr->prev_row == NULL)
  196294. {
  196295. png_warning(png_ptr, "Can't add Paeth filter after starting");
  196296. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  196297. }
  196298. else
  196299. {
  196300. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196301. (png_ptr->rowbytes + 1));
  196302. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196303. }
  196304. }
  196305. if (png_ptr->do_filter == PNG_NO_FILTERS)
  196306. #endif /* PNG_NO_WRITE_FILTER */
  196307. png_ptr->do_filter = PNG_FILTER_NONE;
  196308. }
  196309. }
  196310. else
  196311. png_error(png_ptr, "Unknown custom filter method");
  196312. }
  196313. /* This allows us to influence the way in which libpng chooses the "best"
  196314. * filter for the current scanline. While the "minimum-sum-of-absolute-
  196315. * differences metric is relatively fast and effective, there is some
  196316. * question as to whether it can be improved upon by trying to keep the
  196317. * filtered data going to zlib more consistent, hopefully resulting in
  196318. * better compression.
  196319. */
  196320. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  196321. void PNGAPI
  196322. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  196323. int num_weights, png_doublep filter_weights,
  196324. png_doublep filter_costs)
  196325. {
  196326. int i;
  196327. png_debug(1, "in png_set_filter_heuristics\n");
  196328. if (png_ptr == NULL)
  196329. return;
  196330. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  196331. {
  196332. png_warning(png_ptr, "Unknown filter heuristic method");
  196333. return;
  196334. }
  196335. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  196336. {
  196337. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  196338. }
  196339. if (num_weights < 0 || filter_weights == NULL ||
  196340. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  196341. {
  196342. num_weights = 0;
  196343. }
  196344. png_ptr->num_prev_filters = (png_byte)num_weights;
  196345. png_ptr->heuristic_method = (png_byte)heuristic_method;
  196346. if (num_weights > 0)
  196347. {
  196348. if (png_ptr->prev_filters == NULL)
  196349. {
  196350. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  196351. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  196352. /* To make sure that the weighting starts out fairly */
  196353. for (i = 0; i < num_weights; i++)
  196354. {
  196355. png_ptr->prev_filters[i] = 255;
  196356. }
  196357. }
  196358. if (png_ptr->filter_weights == NULL)
  196359. {
  196360. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  196361. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  196362. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  196363. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  196364. for (i = 0; i < num_weights; i++)
  196365. {
  196366. png_ptr->inv_filter_weights[i] =
  196367. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  196368. }
  196369. }
  196370. for (i = 0; i < num_weights; i++)
  196371. {
  196372. if (filter_weights[i] < 0.0)
  196373. {
  196374. png_ptr->inv_filter_weights[i] =
  196375. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  196376. }
  196377. else
  196378. {
  196379. png_ptr->inv_filter_weights[i] =
  196380. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  196381. png_ptr->filter_weights[i] =
  196382. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  196383. }
  196384. }
  196385. }
  196386. /* If, in the future, there are other filter methods, this would
  196387. * need to be based on png_ptr->filter.
  196388. */
  196389. if (png_ptr->filter_costs == NULL)
  196390. {
  196391. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  196392. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  196393. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  196394. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  196395. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  196396. {
  196397. png_ptr->inv_filter_costs[i] =
  196398. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  196399. }
  196400. }
  196401. /* Here is where we set the relative costs of the different filters. We
  196402. * should take the desired compression level into account when setting
  196403. * the costs, so that Paeth, for instance, has a high relative cost at low
  196404. * compression levels, while it has a lower relative cost at higher
  196405. * compression settings. The filter types are in order of increasing
  196406. * relative cost, so it would be possible to do this with an algorithm.
  196407. */
  196408. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  196409. {
  196410. if (filter_costs == NULL || filter_costs[i] < 0.0)
  196411. {
  196412. png_ptr->inv_filter_costs[i] =
  196413. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  196414. }
  196415. else if (filter_costs[i] >= 1.0)
  196416. {
  196417. png_ptr->inv_filter_costs[i] =
  196418. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  196419. png_ptr->filter_costs[i] =
  196420. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  196421. }
  196422. }
  196423. }
  196424. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  196425. void PNGAPI
  196426. png_set_compression_level(png_structp png_ptr, int level)
  196427. {
  196428. png_debug(1, "in png_set_compression_level\n");
  196429. if (png_ptr == NULL)
  196430. return;
  196431. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  196432. png_ptr->zlib_level = level;
  196433. }
  196434. void PNGAPI
  196435. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  196436. {
  196437. png_debug(1, "in png_set_compression_mem_level\n");
  196438. if (png_ptr == NULL)
  196439. return;
  196440. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  196441. png_ptr->zlib_mem_level = mem_level;
  196442. }
  196443. void PNGAPI
  196444. png_set_compression_strategy(png_structp png_ptr, int strategy)
  196445. {
  196446. png_debug(1, "in png_set_compression_strategy\n");
  196447. if (png_ptr == NULL)
  196448. return;
  196449. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  196450. png_ptr->zlib_strategy = strategy;
  196451. }
  196452. void PNGAPI
  196453. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  196454. {
  196455. if (png_ptr == NULL)
  196456. return;
  196457. if (window_bits > 15)
  196458. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  196459. else if (window_bits < 8)
  196460. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  196461. #ifndef WBITS_8_OK
  196462. /* avoid libpng bug with 256-byte windows */
  196463. if (window_bits == 8)
  196464. {
  196465. png_warning(png_ptr, "Compression window is being reset to 512");
  196466. window_bits=9;
  196467. }
  196468. #endif
  196469. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  196470. png_ptr->zlib_window_bits = window_bits;
  196471. }
  196472. void PNGAPI
  196473. png_set_compression_method(png_structp png_ptr, int method)
  196474. {
  196475. png_debug(1, "in png_set_compression_method\n");
  196476. if (png_ptr == NULL)
  196477. return;
  196478. if (method != 8)
  196479. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  196480. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  196481. png_ptr->zlib_method = method;
  196482. }
  196483. void PNGAPI
  196484. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  196485. {
  196486. if (png_ptr == NULL)
  196487. return;
  196488. png_ptr->write_row_fn = write_row_fn;
  196489. }
  196490. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  196491. void PNGAPI
  196492. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  196493. write_user_transform_fn)
  196494. {
  196495. png_debug(1, "in png_set_write_user_transform_fn\n");
  196496. if (png_ptr == NULL)
  196497. return;
  196498. png_ptr->transformations |= PNG_USER_TRANSFORM;
  196499. png_ptr->write_user_transform_fn = write_user_transform_fn;
  196500. }
  196501. #endif
  196502. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  196503. void PNGAPI
  196504. png_write_png(png_structp png_ptr, png_infop info_ptr,
  196505. int transforms, voidp params)
  196506. {
  196507. if (png_ptr == NULL || info_ptr == NULL)
  196508. return;
  196509. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196510. /* invert the alpha channel from opacity to transparency */
  196511. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  196512. png_set_invert_alpha(png_ptr);
  196513. #endif
  196514. /* Write the file header information. */
  196515. png_write_info(png_ptr, info_ptr);
  196516. /* ------ these transformations don't touch the info structure ------- */
  196517. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  196518. /* invert monochrome pixels */
  196519. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  196520. png_set_invert_mono(png_ptr);
  196521. #endif
  196522. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  196523. /* Shift the pixels up to a legal bit depth and fill in
  196524. * as appropriate to correctly scale the image.
  196525. */
  196526. if ((transforms & PNG_TRANSFORM_SHIFT)
  196527. && (info_ptr->valid & PNG_INFO_sBIT))
  196528. png_set_shift(png_ptr, &info_ptr->sig_bit);
  196529. #endif
  196530. #if defined(PNG_WRITE_PACK_SUPPORTED)
  196531. /* pack pixels into bytes */
  196532. if (transforms & PNG_TRANSFORM_PACKING)
  196533. png_set_packing(png_ptr);
  196534. #endif
  196535. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196536. /* swap location of alpha bytes from ARGB to RGBA */
  196537. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  196538. png_set_swap_alpha(png_ptr);
  196539. #endif
  196540. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  196541. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  196542. * RGB (4 channels -> 3 channels). The second parameter is not used.
  196543. */
  196544. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  196545. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  196546. #endif
  196547. #if defined(PNG_WRITE_BGR_SUPPORTED)
  196548. /* flip BGR pixels to RGB */
  196549. if (transforms & PNG_TRANSFORM_BGR)
  196550. png_set_bgr(png_ptr);
  196551. #endif
  196552. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  196553. /* swap bytes of 16-bit files to most significant byte first */
  196554. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  196555. png_set_swap(png_ptr);
  196556. #endif
  196557. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196558. /* swap bits of 1, 2, 4 bit packed pixel formats */
  196559. if (transforms & PNG_TRANSFORM_PACKSWAP)
  196560. png_set_packswap(png_ptr);
  196561. #endif
  196562. /* ----------------------- end of transformations ------------------- */
  196563. /* write the bits */
  196564. if (info_ptr->valid & PNG_INFO_IDAT)
  196565. png_write_image(png_ptr, info_ptr->row_pointers);
  196566. /* It is REQUIRED to call this to finish writing the rest of the file */
  196567. png_write_end(png_ptr, info_ptr);
  196568. transforms = transforms; /* quiet compiler warnings */
  196569. params = params;
  196570. }
  196571. #endif
  196572. #endif /* PNG_WRITE_SUPPORTED */
  196573. /*** End of inlined file: pngwrite.c ***/
  196574. /*** Start of inlined file: pngwtran.c ***/
  196575. /* pngwtran.c - transforms the data in a row for PNG writers
  196576. *
  196577. * Last changed in libpng 1.2.9 April 14, 2006
  196578. * For conditions of distribution and use, see copyright notice in png.h
  196579. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  196580. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196581. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196582. */
  196583. #define PNG_INTERNAL
  196584. #ifdef PNG_WRITE_SUPPORTED
  196585. /* Transform the data according to the user's wishes. The order of
  196586. * transformations is significant.
  196587. */
  196588. void /* PRIVATE */
  196589. png_do_write_transformations(png_structp png_ptr)
  196590. {
  196591. png_debug(1, "in png_do_write_transformations\n");
  196592. if (png_ptr == NULL)
  196593. return;
  196594. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  196595. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  196596. if(png_ptr->write_user_transform_fn != NULL)
  196597. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  196598. (png_ptr, /* png_ptr */
  196599. &(png_ptr->row_info), /* row_info: */
  196600. /* png_uint_32 width; width of row */
  196601. /* png_uint_32 rowbytes; number of bytes in row */
  196602. /* png_byte color_type; color type of pixels */
  196603. /* png_byte bit_depth; bit depth of samples */
  196604. /* png_byte channels; number of channels (1-4) */
  196605. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  196606. png_ptr->row_buf + 1); /* start of pixel data for row */
  196607. #endif
  196608. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  196609. if (png_ptr->transformations & PNG_FILLER)
  196610. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  196611. png_ptr->flags);
  196612. #endif
  196613. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196614. if (png_ptr->transformations & PNG_PACKSWAP)
  196615. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196616. #endif
  196617. #if defined(PNG_WRITE_PACK_SUPPORTED)
  196618. if (png_ptr->transformations & PNG_PACK)
  196619. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  196620. (png_uint_32)png_ptr->bit_depth);
  196621. #endif
  196622. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  196623. if (png_ptr->transformations & PNG_SWAP_BYTES)
  196624. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196625. #endif
  196626. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  196627. if (png_ptr->transformations & PNG_SHIFT)
  196628. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  196629. &(png_ptr->shift));
  196630. #endif
  196631. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196632. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  196633. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196634. #endif
  196635. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196636. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  196637. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196638. #endif
  196639. #if defined(PNG_WRITE_BGR_SUPPORTED)
  196640. if (png_ptr->transformations & PNG_BGR)
  196641. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196642. #endif
  196643. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  196644. if (png_ptr->transformations & PNG_INVERT_MONO)
  196645. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196646. #endif
  196647. }
  196648. #if defined(PNG_WRITE_PACK_SUPPORTED)
  196649. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  196650. * row_info bit depth should be 8 (one pixel per byte). The channels
  196651. * should be 1 (this only happens on grayscale and paletted images).
  196652. */
  196653. void /* PRIVATE */
  196654. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  196655. {
  196656. png_debug(1, "in png_do_pack\n");
  196657. if (row_info->bit_depth == 8 &&
  196658. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196659. row != NULL && row_info != NULL &&
  196660. #endif
  196661. row_info->channels == 1)
  196662. {
  196663. switch ((int)bit_depth)
  196664. {
  196665. case 1:
  196666. {
  196667. png_bytep sp, dp;
  196668. int mask, v;
  196669. png_uint_32 i;
  196670. png_uint_32 row_width = row_info->width;
  196671. sp = row;
  196672. dp = row;
  196673. mask = 0x80;
  196674. v = 0;
  196675. for (i = 0; i < row_width; i++)
  196676. {
  196677. if (*sp != 0)
  196678. v |= mask;
  196679. sp++;
  196680. if (mask > 1)
  196681. mask >>= 1;
  196682. else
  196683. {
  196684. mask = 0x80;
  196685. *dp = (png_byte)v;
  196686. dp++;
  196687. v = 0;
  196688. }
  196689. }
  196690. if (mask != 0x80)
  196691. *dp = (png_byte)v;
  196692. break;
  196693. }
  196694. case 2:
  196695. {
  196696. png_bytep sp, dp;
  196697. int shift, v;
  196698. png_uint_32 i;
  196699. png_uint_32 row_width = row_info->width;
  196700. sp = row;
  196701. dp = row;
  196702. shift = 6;
  196703. v = 0;
  196704. for (i = 0; i < row_width; i++)
  196705. {
  196706. png_byte value;
  196707. value = (png_byte)(*sp & 0x03);
  196708. v |= (value << shift);
  196709. if (shift == 0)
  196710. {
  196711. shift = 6;
  196712. *dp = (png_byte)v;
  196713. dp++;
  196714. v = 0;
  196715. }
  196716. else
  196717. shift -= 2;
  196718. sp++;
  196719. }
  196720. if (shift != 6)
  196721. *dp = (png_byte)v;
  196722. break;
  196723. }
  196724. case 4:
  196725. {
  196726. png_bytep sp, dp;
  196727. int shift, v;
  196728. png_uint_32 i;
  196729. png_uint_32 row_width = row_info->width;
  196730. sp = row;
  196731. dp = row;
  196732. shift = 4;
  196733. v = 0;
  196734. for (i = 0; i < row_width; i++)
  196735. {
  196736. png_byte value;
  196737. value = (png_byte)(*sp & 0x0f);
  196738. v |= (value << shift);
  196739. if (shift == 0)
  196740. {
  196741. shift = 4;
  196742. *dp = (png_byte)v;
  196743. dp++;
  196744. v = 0;
  196745. }
  196746. else
  196747. shift -= 4;
  196748. sp++;
  196749. }
  196750. if (shift != 4)
  196751. *dp = (png_byte)v;
  196752. break;
  196753. }
  196754. }
  196755. row_info->bit_depth = (png_byte)bit_depth;
  196756. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  196757. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  196758. row_info->width);
  196759. }
  196760. }
  196761. #endif
  196762. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  196763. /* Shift pixel values to take advantage of whole range. Pass the
  196764. * true number of bits in bit_depth. The row should be packed
  196765. * according to row_info->bit_depth. Thus, if you had a row of
  196766. * bit depth 4, but the pixels only had values from 0 to 7, you
  196767. * would pass 3 as bit_depth, and this routine would translate the
  196768. * data to 0 to 15.
  196769. */
  196770. void /* PRIVATE */
  196771. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  196772. {
  196773. png_debug(1, "in png_do_shift\n");
  196774. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196775. if (row != NULL && row_info != NULL &&
  196776. #else
  196777. if (
  196778. #endif
  196779. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  196780. {
  196781. int shift_start[4], shift_dec[4];
  196782. int channels = 0;
  196783. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  196784. {
  196785. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  196786. shift_dec[channels] = bit_depth->red;
  196787. channels++;
  196788. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  196789. shift_dec[channels] = bit_depth->green;
  196790. channels++;
  196791. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  196792. shift_dec[channels] = bit_depth->blue;
  196793. channels++;
  196794. }
  196795. else
  196796. {
  196797. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  196798. shift_dec[channels] = bit_depth->gray;
  196799. channels++;
  196800. }
  196801. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  196802. {
  196803. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  196804. shift_dec[channels] = bit_depth->alpha;
  196805. channels++;
  196806. }
  196807. /* with low row depths, could only be grayscale, so one channel */
  196808. if (row_info->bit_depth < 8)
  196809. {
  196810. png_bytep bp = row;
  196811. png_uint_32 i;
  196812. png_byte mask;
  196813. png_uint_32 row_bytes = row_info->rowbytes;
  196814. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  196815. mask = 0x55;
  196816. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  196817. mask = 0x11;
  196818. else
  196819. mask = 0xff;
  196820. for (i = 0; i < row_bytes; i++, bp++)
  196821. {
  196822. png_uint_16 v;
  196823. int j;
  196824. v = *bp;
  196825. *bp = 0;
  196826. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  196827. {
  196828. if (j > 0)
  196829. *bp |= (png_byte)((v << j) & 0xff);
  196830. else
  196831. *bp |= (png_byte)((v >> (-j)) & mask);
  196832. }
  196833. }
  196834. }
  196835. else if (row_info->bit_depth == 8)
  196836. {
  196837. png_bytep bp = row;
  196838. png_uint_32 i;
  196839. png_uint_32 istop = channels * row_info->width;
  196840. for (i = 0; i < istop; i++, bp++)
  196841. {
  196842. png_uint_16 v;
  196843. int j;
  196844. int c = (int)(i%channels);
  196845. v = *bp;
  196846. *bp = 0;
  196847. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196848. {
  196849. if (j > 0)
  196850. *bp |= (png_byte)((v << j) & 0xff);
  196851. else
  196852. *bp |= (png_byte)((v >> (-j)) & 0xff);
  196853. }
  196854. }
  196855. }
  196856. else
  196857. {
  196858. png_bytep bp;
  196859. png_uint_32 i;
  196860. png_uint_32 istop = channels * row_info->width;
  196861. for (bp = row, i = 0; i < istop; i++)
  196862. {
  196863. int c = (int)(i%channels);
  196864. png_uint_16 value, v;
  196865. int j;
  196866. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  196867. value = 0;
  196868. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196869. {
  196870. if (j > 0)
  196871. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  196872. else
  196873. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  196874. }
  196875. *bp++ = (png_byte)(value >> 8);
  196876. *bp++ = (png_byte)(value & 0xff);
  196877. }
  196878. }
  196879. }
  196880. }
  196881. #endif
  196882. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196883. void /* PRIVATE */
  196884. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  196885. {
  196886. png_debug(1, "in png_do_write_swap_alpha\n");
  196887. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196888. if (row != NULL && row_info != NULL)
  196889. #endif
  196890. {
  196891. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196892. {
  196893. /* This converts from ARGB to RGBA */
  196894. if (row_info->bit_depth == 8)
  196895. {
  196896. png_bytep sp, dp;
  196897. png_uint_32 i;
  196898. png_uint_32 row_width = row_info->width;
  196899. for (i = 0, sp = dp = row; i < row_width; i++)
  196900. {
  196901. png_byte save = *(sp++);
  196902. *(dp++) = *(sp++);
  196903. *(dp++) = *(sp++);
  196904. *(dp++) = *(sp++);
  196905. *(dp++) = save;
  196906. }
  196907. }
  196908. /* This converts from AARRGGBB to RRGGBBAA */
  196909. else
  196910. {
  196911. png_bytep sp, dp;
  196912. png_uint_32 i;
  196913. png_uint_32 row_width = row_info->width;
  196914. for (i = 0, sp = dp = row; i < row_width; i++)
  196915. {
  196916. png_byte save[2];
  196917. save[0] = *(sp++);
  196918. save[1] = *(sp++);
  196919. *(dp++) = *(sp++);
  196920. *(dp++) = *(sp++);
  196921. *(dp++) = *(sp++);
  196922. *(dp++) = *(sp++);
  196923. *(dp++) = *(sp++);
  196924. *(dp++) = *(sp++);
  196925. *(dp++) = save[0];
  196926. *(dp++) = save[1];
  196927. }
  196928. }
  196929. }
  196930. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196931. {
  196932. /* This converts from AG to GA */
  196933. if (row_info->bit_depth == 8)
  196934. {
  196935. png_bytep sp, dp;
  196936. png_uint_32 i;
  196937. png_uint_32 row_width = row_info->width;
  196938. for (i = 0, sp = dp = row; i < row_width; i++)
  196939. {
  196940. png_byte save = *(sp++);
  196941. *(dp++) = *(sp++);
  196942. *(dp++) = save;
  196943. }
  196944. }
  196945. /* This converts from AAGG to GGAA */
  196946. else
  196947. {
  196948. png_bytep sp, dp;
  196949. png_uint_32 i;
  196950. png_uint_32 row_width = row_info->width;
  196951. for (i = 0, sp = dp = row; i < row_width; i++)
  196952. {
  196953. png_byte save[2];
  196954. save[0] = *(sp++);
  196955. save[1] = *(sp++);
  196956. *(dp++) = *(sp++);
  196957. *(dp++) = *(sp++);
  196958. *(dp++) = save[0];
  196959. *(dp++) = save[1];
  196960. }
  196961. }
  196962. }
  196963. }
  196964. }
  196965. #endif
  196966. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196967. void /* PRIVATE */
  196968. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  196969. {
  196970. png_debug(1, "in png_do_write_invert_alpha\n");
  196971. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196972. if (row != NULL && row_info != NULL)
  196973. #endif
  196974. {
  196975. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196976. {
  196977. /* This inverts the alpha channel in RGBA */
  196978. if (row_info->bit_depth == 8)
  196979. {
  196980. png_bytep sp, dp;
  196981. png_uint_32 i;
  196982. png_uint_32 row_width = row_info->width;
  196983. for (i = 0, sp = dp = row; i < row_width; i++)
  196984. {
  196985. /* does nothing
  196986. *(dp++) = *(sp++);
  196987. *(dp++) = *(sp++);
  196988. *(dp++) = *(sp++);
  196989. */
  196990. sp+=3; dp = sp;
  196991. *(dp++) = (png_byte)(255 - *(sp++));
  196992. }
  196993. }
  196994. /* This inverts the alpha channel in RRGGBBAA */
  196995. else
  196996. {
  196997. png_bytep sp, dp;
  196998. png_uint_32 i;
  196999. png_uint_32 row_width = row_info->width;
  197000. for (i = 0, sp = dp = row; i < row_width; i++)
  197001. {
  197002. /* does nothing
  197003. *(dp++) = *(sp++);
  197004. *(dp++) = *(sp++);
  197005. *(dp++) = *(sp++);
  197006. *(dp++) = *(sp++);
  197007. *(dp++) = *(sp++);
  197008. *(dp++) = *(sp++);
  197009. */
  197010. sp+=6; dp = sp;
  197011. *(dp++) = (png_byte)(255 - *(sp++));
  197012. *(dp++) = (png_byte)(255 - *(sp++));
  197013. }
  197014. }
  197015. }
  197016. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197017. {
  197018. /* This inverts the alpha channel in GA */
  197019. if (row_info->bit_depth == 8)
  197020. {
  197021. png_bytep sp, dp;
  197022. png_uint_32 i;
  197023. png_uint_32 row_width = row_info->width;
  197024. for (i = 0, sp = dp = row; i < row_width; i++)
  197025. {
  197026. *(dp++) = *(sp++);
  197027. *(dp++) = (png_byte)(255 - *(sp++));
  197028. }
  197029. }
  197030. /* This inverts the alpha channel in GGAA */
  197031. else
  197032. {
  197033. png_bytep sp, dp;
  197034. png_uint_32 i;
  197035. png_uint_32 row_width = row_info->width;
  197036. for (i = 0, sp = dp = row; i < row_width; i++)
  197037. {
  197038. /* does nothing
  197039. *(dp++) = *(sp++);
  197040. *(dp++) = *(sp++);
  197041. */
  197042. sp+=2; dp = sp;
  197043. *(dp++) = (png_byte)(255 - *(sp++));
  197044. *(dp++) = (png_byte)(255 - *(sp++));
  197045. }
  197046. }
  197047. }
  197048. }
  197049. }
  197050. #endif
  197051. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197052. /* undoes intrapixel differencing */
  197053. void /* PRIVATE */
  197054. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  197055. {
  197056. png_debug(1, "in png_do_write_intrapixel\n");
  197057. if (
  197058. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197059. row != NULL && row_info != NULL &&
  197060. #endif
  197061. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197062. {
  197063. int bytes_per_pixel;
  197064. png_uint_32 row_width = row_info->width;
  197065. if (row_info->bit_depth == 8)
  197066. {
  197067. png_bytep rp;
  197068. png_uint_32 i;
  197069. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197070. bytes_per_pixel = 3;
  197071. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197072. bytes_per_pixel = 4;
  197073. else
  197074. return;
  197075. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197076. {
  197077. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  197078. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  197079. }
  197080. }
  197081. else if (row_info->bit_depth == 16)
  197082. {
  197083. png_bytep rp;
  197084. png_uint_32 i;
  197085. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197086. bytes_per_pixel = 6;
  197087. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197088. bytes_per_pixel = 8;
  197089. else
  197090. return;
  197091. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197092. {
  197093. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  197094. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  197095. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  197096. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  197097. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  197098. *(rp ) = (png_byte)((red >> 8) & 0xff);
  197099. *(rp+1) = (png_byte)(red & 0xff);
  197100. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  197101. *(rp+5) = (png_byte)(blue & 0xff);
  197102. }
  197103. }
  197104. }
  197105. }
  197106. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  197107. #endif /* PNG_WRITE_SUPPORTED */
  197108. /*** End of inlined file: pngwtran.c ***/
  197109. /*** Start of inlined file: pngwutil.c ***/
  197110. /* pngwutil.c - utilities to write a PNG file
  197111. *
  197112. * Last changed in libpng 1.2.20 Septhember 3, 2007
  197113. * For conditions of distribution and use, see copyright notice in png.h
  197114. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197115. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197116. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197117. */
  197118. #define PNG_INTERNAL
  197119. #ifdef PNG_WRITE_SUPPORTED
  197120. /* Place a 32-bit number into a buffer in PNG byte order. We work
  197121. * with unsigned numbers for convenience, although one supported
  197122. * ancillary chunk uses signed (two's complement) numbers.
  197123. */
  197124. void PNGAPI
  197125. png_save_uint_32(png_bytep buf, png_uint_32 i)
  197126. {
  197127. buf[0] = (png_byte)((i >> 24) & 0xff);
  197128. buf[1] = (png_byte)((i >> 16) & 0xff);
  197129. buf[2] = (png_byte)((i >> 8) & 0xff);
  197130. buf[3] = (png_byte)(i & 0xff);
  197131. }
  197132. /* The png_save_int_32 function assumes integers are stored in two's
  197133. * complement format. If this isn't the case, then this routine needs to
  197134. * be modified to write data in two's complement format.
  197135. */
  197136. void PNGAPI
  197137. png_save_int_32(png_bytep buf, png_int_32 i)
  197138. {
  197139. buf[0] = (png_byte)((i >> 24) & 0xff);
  197140. buf[1] = (png_byte)((i >> 16) & 0xff);
  197141. buf[2] = (png_byte)((i >> 8) & 0xff);
  197142. buf[3] = (png_byte)(i & 0xff);
  197143. }
  197144. /* Place a 16-bit number into a buffer in PNG byte order.
  197145. * The parameter is declared unsigned int, not png_uint_16,
  197146. * just to avoid potential problems on pre-ANSI C compilers.
  197147. */
  197148. void PNGAPI
  197149. png_save_uint_16(png_bytep buf, unsigned int i)
  197150. {
  197151. buf[0] = (png_byte)((i >> 8) & 0xff);
  197152. buf[1] = (png_byte)(i & 0xff);
  197153. }
  197154. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  197155. * representing the chunk name. The array must be at least 4 bytes in
  197156. * length, and does not need to be null terminated. To be safe, pass the
  197157. * pre-defined chunk names here, and if you need a new one, define it
  197158. * where the others are defined. The length is the length of the data.
  197159. * All the data must be present. If that is not possible, use the
  197160. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  197161. * functions instead.
  197162. */
  197163. void PNGAPI
  197164. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  197165. png_bytep data, png_size_t length)
  197166. {
  197167. if(png_ptr == NULL) return;
  197168. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  197169. png_write_chunk_data(png_ptr, data, length);
  197170. png_write_chunk_end(png_ptr);
  197171. }
  197172. /* Write the start of a PNG chunk. The type is the chunk type.
  197173. * The total_length is the sum of the lengths of all the data you will be
  197174. * passing in png_write_chunk_data().
  197175. */
  197176. void PNGAPI
  197177. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  197178. png_uint_32 length)
  197179. {
  197180. png_byte buf[4];
  197181. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  197182. if(png_ptr == NULL) return;
  197183. /* write the length */
  197184. png_save_uint_32(buf, length);
  197185. png_write_data(png_ptr, buf, (png_size_t)4);
  197186. /* write the chunk name */
  197187. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  197188. /* reset the crc and run it over the chunk name */
  197189. png_reset_crc(png_ptr);
  197190. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  197191. }
  197192. /* Write the data of a PNG chunk started with png_write_chunk_start().
  197193. * Note that multiple calls to this function are allowed, and that the
  197194. * sum of the lengths from these calls *must* add up to the total_length
  197195. * given to png_write_chunk_start().
  197196. */
  197197. void PNGAPI
  197198. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197199. {
  197200. /* write the data, and run the CRC over it */
  197201. if(png_ptr == NULL) return;
  197202. if (data != NULL && length > 0)
  197203. {
  197204. png_calculate_crc(png_ptr, data, length);
  197205. png_write_data(png_ptr, data, length);
  197206. }
  197207. }
  197208. /* Finish a chunk started with png_write_chunk_start(). */
  197209. void PNGAPI
  197210. png_write_chunk_end(png_structp png_ptr)
  197211. {
  197212. png_byte buf[4];
  197213. if(png_ptr == NULL) return;
  197214. /* write the crc */
  197215. png_save_uint_32(buf, png_ptr->crc);
  197216. png_write_data(png_ptr, buf, (png_size_t)4);
  197217. }
  197218. /* Simple function to write the signature. If we have already written
  197219. * the magic bytes of the signature, or more likely, the PNG stream is
  197220. * being embedded into another stream and doesn't need its own signature,
  197221. * we should call png_set_sig_bytes() to tell libpng how many of the
  197222. * bytes have already been written.
  197223. */
  197224. void /* PRIVATE */
  197225. png_write_sig(png_structp png_ptr)
  197226. {
  197227. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  197228. /* write the rest of the 8 byte signature */
  197229. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  197230. (png_size_t)8 - png_ptr->sig_bytes);
  197231. if(png_ptr->sig_bytes < 3)
  197232. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  197233. }
  197234. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  197235. /*
  197236. * This pair of functions encapsulates the operation of (a) compressing a
  197237. * text string, and (b) issuing it later as a series of chunk data writes.
  197238. * The compression_state structure is shared context for these functions
  197239. * set up by the caller in order to make the whole mess thread-safe.
  197240. */
  197241. typedef struct
  197242. {
  197243. char *input; /* the uncompressed input data */
  197244. int input_len; /* its length */
  197245. int num_output_ptr; /* number of output pointers used */
  197246. int max_output_ptr; /* size of output_ptr */
  197247. png_charpp output_ptr; /* array of pointers to output */
  197248. } compression_state;
  197249. /* compress given text into storage in the png_ptr structure */
  197250. static int /* PRIVATE */
  197251. png_text_compress(png_structp png_ptr,
  197252. png_charp text, png_size_t text_len, int compression,
  197253. compression_state *comp)
  197254. {
  197255. int ret;
  197256. comp->num_output_ptr = 0;
  197257. comp->max_output_ptr = 0;
  197258. comp->output_ptr = NULL;
  197259. comp->input = NULL;
  197260. comp->input_len = 0;
  197261. /* we may just want to pass the text right through */
  197262. if (compression == PNG_TEXT_COMPRESSION_NONE)
  197263. {
  197264. comp->input = text;
  197265. comp->input_len = text_len;
  197266. return((int)text_len);
  197267. }
  197268. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  197269. {
  197270. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197271. char msg[50];
  197272. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  197273. png_warning(png_ptr, msg);
  197274. #else
  197275. png_warning(png_ptr, "Unknown compression type");
  197276. #endif
  197277. }
  197278. /* We can't write the chunk until we find out how much data we have,
  197279. * which means we need to run the compressor first and save the
  197280. * output. This shouldn't be a problem, as the vast majority of
  197281. * comments should be reasonable, but we will set up an array of
  197282. * malloc'd pointers to be sure.
  197283. *
  197284. * If we knew the application was well behaved, we could simplify this
  197285. * greatly by assuming we can always malloc an output buffer large
  197286. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  197287. * and malloc this directly. The only time this would be a bad idea is
  197288. * if we can't malloc more than 64K and we have 64K of random input
  197289. * data, or if the input string is incredibly large (although this
  197290. * wouldn't cause a failure, just a slowdown due to swapping).
  197291. */
  197292. /* set up the compression buffers */
  197293. png_ptr->zstream.avail_in = (uInt)text_len;
  197294. png_ptr->zstream.next_in = (Bytef *)text;
  197295. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197296. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  197297. /* this is the same compression loop as in png_write_row() */
  197298. do
  197299. {
  197300. /* compress the data */
  197301. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197302. if (ret != Z_OK)
  197303. {
  197304. /* error */
  197305. if (png_ptr->zstream.msg != NULL)
  197306. png_error(png_ptr, png_ptr->zstream.msg);
  197307. else
  197308. png_error(png_ptr, "zlib error");
  197309. }
  197310. /* check to see if we need more room */
  197311. if (!(png_ptr->zstream.avail_out))
  197312. {
  197313. /* make sure the output array has room */
  197314. if (comp->num_output_ptr >= comp->max_output_ptr)
  197315. {
  197316. int old_max;
  197317. old_max = comp->max_output_ptr;
  197318. comp->max_output_ptr = comp->num_output_ptr + 4;
  197319. if (comp->output_ptr != NULL)
  197320. {
  197321. png_charpp old_ptr;
  197322. old_ptr = comp->output_ptr;
  197323. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197324. (png_uint_32)(comp->max_output_ptr *
  197325. png_sizeof (png_charpp)));
  197326. png_memcpy(comp->output_ptr, old_ptr, old_max
  197327. * png_sizeof (png_charp));
  197328. png_free(png_ptr, old_ptr);
  197329. }
  197330. else
  197331. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197332. (png_uint_32)(comp->max_output_ptr *
  197333. png_sizeof (png_charp)));
  197334. }
  197335. /* save the data */
  197336. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  197337. (png_uint_32)png_ptr->zbuf_size);
  197338. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197339. png_ptr->zbuf_size);
  197340. comp->num_output_ptr++;
  197341. /* and reset the buffer */
  197342. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197343. png_ptr->zstream.next_out = png_ptr->zbuf;
  197344. }
  197345. /* continue until we don't have any more to compress */
  197346. } while (png_ptr->zstream.avail_in);
  197347. /* finish the compression */
  197348. do
  197349. {
  197350. /* tell zlib we are finished */
  197351. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197352. if (ret == Z_OK)
  197353. {
  197354. /* check to see if we need more room */
  197355. if (!(png_ptr->zstream.avail_out))
  197356. {
  197357. /* check to make sure our output array has room */
  197358. if (comp->num_output_ptr >= comp->max_output_ptr)
  197359. {
  197360. int old_max;
  197361. old_max = comp->max_output_ptr;
  197362. comp->max_output_ptr = comp->num_output_ptr + 4;
  197363. if (comp->output_ptr != NULL)
  197364. {
  197365. png_charpp old_ptr;
  197366. old_ptr = comp->output_ptr;
  197367. /* This could be optimized to realloc() */
  197368. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197369. (png_uint_32)(comp->max_output_ptr *
  197370. png_sizeof (png_charpp)));
  197371. png_memcpy(comp->output_ptr, old_ptr,
  197372. old_max * png_sizeof (png_charp));
  197373. png_free(png_ptr, old_ptr);
  197374. }
  197375. else
  197376. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197377. (png_uint_32)(comp->max_output_ptr *
  197378. png_sizeof (png_charp)));
  197379. }
  197380. /* save off the data */
  197381. comp->output_ptr[comp->num_output_ptr] =
  197382. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  197383. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197384. png_ptr->zbuf_size);
  197385. comp->num_output_ptr++;
  197386. /* and reset the buffer pointers */
  197387. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197388. png_ptr->zstream.next_out = png_ptr->zbuf;
  197389. }
  197390. }
  197391. else if (ret != Z_STREAM_END)
  197392. {
  197393. /* we got an error */
  197394. if (png_ptr->zstream.msg != NULL)
  197395. png_error(png_ptr, png_ptr->zstream.msg);
  197396. else
  197397. png_error(png_ptr, "zlib error");
  197398. }
  197399. } while (ret != Z_STREAM_END);
  197400. /* text length is number of buffers plus last buffer */
  197401. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  197402. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197403. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  197404. return((int)text_len);
  197405. }
  197406. /* ship the compressed text out via chunk writes */
  197407. static void /* PRIVATE */
  197408. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  197409. {
  197410. int i;
  197411. /* handle the no-compression case */
  197412. if (comp->input)
  197413. {
  197414. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  197415. (png_size_t)comp->input_len);
  197416. return;
  197417. }
  197418. /* write saved output buffers, if any */
  197419. for (i = 0; i < comp->num_output_ptr; i++)
  197420. {
  197421. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  197422. png_ptr->zbuf_size);
  197423. png_free(png_ptr, comp->output_ptr[i]);
  197424. comp->output_ptr[i]=NULL;
  197425. }
  197426. if (comp->max_output_ptr != 0)
  197427. png_free(png_ptr, comp->output_ptr);
  197428. comp->output_ptr=NULL;
  197429. /* write anything left in zbuf */
  197430. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  197431. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  197432. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  197433. /* reset zlib for another zTXt/iTXt or image data */
  197434. deflateReset(&png_ptr->zstream);
  197435. png_ptr->zstream.data_type = Z_BINARY;
  197436. }
  197437. #endif
  197438. /* Write the IHDR chunk, and update the png_struct with the necessary
  197439. * information. Note that the rest of this code depends upon this
  197440. * information being correct.
  197441. */
  197442. void /* PRIVATE */
  197443. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  197444. int bit_depth, int color_type, int compression_type, int filter_type,
  197445. int interlace_type)
  197446. {
  197447. #ifdef PNG_USE_LOCAL_ARRAYS
  197448. PNG_IHDR;
  197449. #endif
  197450. png_byte buf[13]; /* buffer to store the IHDR info */
  197451. png_debug(1, "in png_write_IHDR\n");
  197452. /* Check that we have valid input data from the application info */
  197453. switch (color_type)
  197454. {
  197455. case PNG_COLOR_TYPE_GRAY:
  197456. switch (bit_depth)
  197457. {
  197458. case 1:
  197459. case 2:
  197460. case 4:
  197461. case 8:
  197462. case 16: png_ptr->channels = 1; break;
  197463. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  197464. }
  197465. break;
  197466. case PNG_COLOR_TYPE_RGB:
  197467. if (bit_depth != 8 && bit_depth != 16)
  197468. png_error(png_ptr, "Invalid bit depth for RGB image");
  197469. png_ptr->channels = 3;
  197470. break;
  197471. case PNG_COLOR_TYPE_PALETTE:
  197472. switch (bit_depth)
  197473. {
  197474. case 1:
  197475. case 2:
  197476. case 4:
  197477. case 8: png_ptr->channels = 1; break;
  197478. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  197479. }
  197480. break;
  197481. case PNG_COLOR_TYPE_GRAY_ALPHA:
  197482. if (bit_depth != 8 && bit_depth != 16)
  197483. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  197484. png_ptr->channels = 2;
  197485. break;
  197486. case PNG_COLOR_TYPE_RGB_ALPHA:
  197487. if (bit_depth != 8 && bit_depth != 16)
  197488. png_error(png_ptr, "Invalid bit depth for RGBA image");
  197489. png_ptr->channels = 4;
  197490. break;
  197491. default:
  197492. png_error(png_ptr, "Invalid image color type specified");
  197493. }
  197494. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197495. {
  197496. png_warning(png_ptr, "Invalid compression type specified");
  197497. compression_type = PNG_COMPRESSION_TYPE_BASE;
  197498. }
  197499. /* Write filter_method 64 (intrapixel differencing) only if
  197500. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197501. * 2. Libpng did not write a PNG signature (this filter_method is only
  197502. * used in PNG datastreams that are embedded in MNG datastreams) and
  197503. * 3. The application called png_permit_mng_features with a mask that
  197504. * included PNG_FLAG_MNG_FILTER_64 and
  197505. * 4. The filter_method is 64 and
  197506. * 5. The color_type is RGB or RGBA
  197507. */
  197508. if (
  197509. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197510. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197511. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197512. (color_type == PNG_COLOR_TYPE_RGB ||
  197513. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  197514. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  197515. #endif
  197516. filter_type != PNG_FILTER_TYPE_BASE)
  197517. {
  197518. png_warning(png_ptr, "Invalid filter type specified");
  197519. filter_type = PNG_FILTER_TYPE_BASE;
  197520. }
  197521. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197522. if (interlace_type != PNG_INTERLACE_NONE &&
  197523. interlace_type != PNG_INTERLACE_ADAM7)
  197524. {
  197525. png_warning(png_ptr, "Invalid interlace type specified");
  197526. interlace_type = PNG_INTERLACE_ADAM7;
  197527. }
  197528. #else
  197529. interlace_type=PNG_INTERLACE_NONE;
  197530. #endif
  197531. /* save off the relevent information */
  197532. png_ptr->bit_depth = (png_byte)bit_depth;
  197533. png_ptr->color_type = (png_byte)color_type;
  197534. png_ptr->interlaced = (png_byte)interlace_type;
  197535. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197536. png_ptr->filter_type = (png_byte)filter_type;
  197537. #endif
  197538. png_ptr->compression_type = (png_byte)compression_type;
  197539. png_ptr->width = width;
  197540. png_ptr->height = height;
  197541. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  197542. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  197543. /* set the usr info, so any transformations can modify it */
  197544. png_ptr->usr_width = png_ptr->width;
  197545. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  197546. png_ptr->usr_channels = png_ptr->channels;
  197547. /* pack the header information into the buffer */
  197548. png_save_uint_32(buf, width);
  197549. png_save_uint_32(buf + 4, height);
  197550. buf[8] = (png_byte)bit_depth;
  197551. buf[9] = (png_byte)color_type;
  197552. buf[10] = (png_byte)compression_type;
  197553. buf[11] = (png_byte)filter_type;
  197554. buf[12] = (png_byte)interlace_type;
  197555. /* write the chunk */
  197556. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  197557. /* initialize zlib with PNG info */
  197558. png_ptr->zstream.zalloc = png_zalloc;
  197559. png_ptr->zstream.zfree = png_zfree;
  197560. png_ptr->zstream.opaque = (voidpf)png_ptr;
  197561. if (!(png_ptr->do_filter))
  197562. {
  197563. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  197564. png_ptr->bit_depth < 8)
  197565. png_ptr->do_filter = PNG_FILTER_NONE;
  197566. else
  197567. png_ptr->do_filter = PNG_ALL_FILTERS;
  197568. }
  197569. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  197570. {
  197571. if (png_ptr->do_filter != PNG_FILTER_NONE)
  197572. png_ptr->zlib_strategy = Z_FILTERED;
  197573. else
  197574. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  197575. }
  197576. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  197577. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  197578. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  197579. png_ptr->zlib_mem_level = 8;
  197580. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  197581. png_ptr->zlib_window_bits = 15;
  197582. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  197583. png_ptr->zlib_method = 8;
  197584. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  197585. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  197586. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  197587. png_error(png_ptr, "zlib failed to initialize compressor");
  197588. png_ptr->zstream.next_out = png_ptr->zbuf;
  197589. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197590. /* libpng is not interested in zstream.data_type */
  197591. /* set it to a predefined value, to avoid its evaluation inside zlib */
  197592. png_ptr->zstream.data_type = Z_BINARY;
  197593. png_ptr->mode = PNG_HAVE_IHDR;
  197594. }
  197595. /* write the palette. We are careful not to trust png_color to be in the
  197596. * correct order for PNG, so people can redefine it to any convenient
  197597. * structure.
  197598. */
  197599. void /* PRIVATE */
  197600. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  197601. {
  197602. #ifdef PNG_USE_LOCAL_ARRAYS
  197603. PNG_PLTE;
  197604. #endif
  197605. png_uint_32 i;
  197606. png_colorp pal_ptr;
  197607. png_byte buf[3];
  197608. png_debug(1, "in png_write_PLTE\n");
  197609. if ((
  197610. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197611. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  197612. #endif
  197613. num_pal == 0) || num_pal > 256)
  197614. {
  197615. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197616. {
  197617. png_error(png_ptr, "Invalid number of colors in palette");
  197618. }
  197619. else
  197620. {
  197621. png_warning(png_ptr, "Invalid number of colors in palette");
  197622. return;
  197623. }
  197624. }
  197625. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  197626. {
  197627. png_warning(png_ptr,
  197628. "Ignoring request to write a PLTE chunk in grayscale PNG");
  197629. return;
  197630. }
  197631. png_ptr->num_palette = (png_uint_16)num_pal;
  197632. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  197633. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  197634. #ifndef PNG_NO_POINTER_INDEXING
  197635. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  197636. {
  197637. buf[0] = pal_ptr->red;
  197638. buf[1] = pal_ptr->green;
  197639. buf[2] = pal_ptr->blue;
  197640. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  197641. }
  197642. #else
  197643. /* This is a little slower but some buggy compilers need to do this instead */
  197644. pal_ptr=palette;
  197645. for (i = 0; i < num_pal; i++)
  197646. {
  197647. buf[0] = pal_ptr[i].red;
  197648. buf[1] = pal_ptr[i].green;
  197649. buf[2] = pal_ptr[i].blue;
  197650. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  197651. }
  197652. #endif
  197653. png_write_chunk_end(png_ptr);
  197654. png_ptr->mode |= PNG_HAVE_PLTE;
  197655. }
  197656. /* write an IDAT chunk */
  197657. void /* PRIVATE */
  197658. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  197659. {
  197660. #ifdef PNG_USE_LOCAL_ARRAYS
  197661. PNG_IDAT;
  197662. #endif
  197663. png_debug(1, "in png_write_IDAT\n");
  197664. /* Optimize the CMF field in the zlib stream. */
  197665. /* This hack of the zlib stream is compliant to the stream specification. */
  197666. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  197667. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  197668. {
  197669. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  197670. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  197671. {
  197672. /* Avoid memory underflows and multiplication overflows. */
  197673. /* The conditions below are practically always satisfied;
  197674. however, they still must be checked. */
  197675. if (length >= 2 &&
  197676. png_ptr->height < 16384 && png_ptr->width < 16384)
  197677. {
  197678. png_uint_32 uncompressed_idat_size = png_ptr->height *
  197679. ((png_ptr->width *
  197680. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  197681. unsigned int z_cinfo = z_cmf >> 4;
  197682. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  197683. while (uncompressed_idat_size <= half_z_window_size &&
  197684. half_z_window_size >= 256)
  197685. {
  197686. z_cinfo--;
  197687. half_z_window_size >>= 1;
  197688. }
  197689. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  197690. if (data[0] != (png_byte)z_cmf)
  197691. {
  197692. data[0] = (png_byte)z_cmf;
  197693. data[1] &= 0xe0;
  197694. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  197695. }
  197696. }
  197697. }
  197698. else
  197699. png_error(png_ptr,
  197700. "Invalid zlib compression method or flags in IDAT");
  197701. }
  197702. png_write_chunk(png_ptr, png_IDAT, data, length);
  197703. png_ptr->mode |= PNG_HAVE_IDAT;
  197704. }
  197705. /* write an IEND chunk */
  197706. void /* PRIVATE */
  197707. png_write_IEND(png_structp png_ptr)
  197708. {
  197709. #ifdef PNG_USE_LOCAL_ARRAYS
  197710. PNG_IEND;
  197711. #endif
  197712. png_debug(1, "in png_write_IEND\n");
  197713. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  197714. (png_size_t)0);
  197715. png_ptr->mode |= PNG_HAVE_IEND;
  197716. }
  197717. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  197718. /* write a gAMA chunk */
  197719. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197720. void /* PRIVATE */
  197721. png_write_gAMA(png_structp png_ptr, double file_gamma)
  197722. {
  197723. #ifdef PNG_USE_LOCAL_ARRAYS
  197724. PNG_gAMA;
  197725. #endif
  197726. png_uint_32 igamma;
  197727. png_byte buf[4];
  197728. png_debug(1, "in png_write_gAMA\n");
  197729. /* file_gamma is saved in 1/100,000ths */
  197730. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  197731. png_save_uint_32(buf, igamma);
  197732. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  197733. }
  197734. #endif
  197735. #ifdef PNG_FIXED_POINT_SUPPORTED
  197736. void /* PRIVATE */
  197737. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  197738. {
  197739. #ifdef PNG_USE_LOCAL_ARRAYS
  197740. PNG_gAMA;
  197741. #endif
  197742. png_byte buf[4];
  197743. png_debug(1, "in png_write_gAMA\n");
  197744. /* file_gamma is saved in 1/100,000ths */
  197745. png_save_uint_32(buf, (png_uint_32)file_gamma);
  197746. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  197747. }
  197748. #endif
  197749. #endif
  197750. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  197751. /* write a sRGB chunk */
  197752. void /* PRIVATE */
  197753. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  197754. {
  197755. #ifdef PNG_USE_LOCAL_ARRAYS
  197756. PNG_sRGB;
  197757. #endif
  197758. png_byte buf[1];
  197759. png_debug(1, "in png_write_sRGB\n");
  197760. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  197761. png_warning(png_ptr,
  197762. "Invalid sRGB rendering intent specified");
  197763. buf[0]=(png_byte)srgb_intent;
  197764. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  197765. }
  197766. #endif
  197767. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  197768. /* write an iCCP chunk */
  197769. void /* PRIVATE */
  197770. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  197771. png_charp profile, int profile_len)
  197772. {
  197773. #ifdef PNG_USE_LOCAL_ARRAYS
  197774. PNG_iCCP;
  197775. #endif
  197776. png_size_t name_len;
  197777. png_charp new_name;
  197778. compression_state comp;
  197779. int embedded_profile_len = 0;
  197780. png_debug(1, "in png_write_iCCP\n");
  197781. comp.num_output_ptr = 0;
  197782. comp.max_output_ptr = 0;
  197783. comp.output_ptr = NULL;
  197784. comp.input = NULL;
  197785. comp.input_len = 0;
  197786. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  197787. &new_name)) == 0)
  197788. {
  197789. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  197790. return;
  197791. }
  197792. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197793. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  197794. if (profile == NULL)
  197795. profile_len = 0;
  197796. if (profile_len > 3)
  197797. embedded_profile_len =
  197798. ((*( (png_bytep)profile ))<<24) |
  197799. ((*( (png_bytep)profile+1))<<16) |
  197800. ((*( (png_bytep)profile+2))<< 8) |
  197801. ((*( (png_bytep)profile+3)) );
  197802. if (profile_len < embedded_profile_len)
  197803. {
  197804. png_warning(png_ptr,
  197805. "Embedded profile length too large in iCCP chunk");
  197806. return;
  197807. }
  197808. if (profile_len > embedded_profile_len)
  197809. {
  197810. png_warning(png_ptr,
  197811. "Truncating profile to actual length in iCCP chunk");
  197812. profile_len = embedded_profile_len;
  197813. }
  197814. if (profile_len)
  197815. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  197816. PNG_COMPRESSION_TYPE_BASE, &comp);
  197817. /* make sure we include the NULL after the name and the compression type */
  197818. png_write_chunk_start(png_ptr, png_iCCP,
  197819. (png_uint_32)name_len+profile_len+2);
  197820. new_name[name_len+1]=0x00;
  197821. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  197822. if (profile_len)
  197823. png_write_compressed_data_out(png_ptr, &comp);
  197824. png_write_chunk_end(png_ptr);
  197825. png_free(png_ptr, new_name);
  197826. }
  197827. #endif
  197828. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  197829. /* write a sPLT chunk */
  197830. void /* PRIVATE */
  197831. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  197832. {
  197833. #ifdef PNG_USE_LOCAL_ARRAYS
  197834. PNG_sPLT;
  197835. #endif
  197836. png_size_t name_len;
  197837. png_charp new_name;
  197838. png_byte entrybuf[10];
  197839. int entry_size = (spalette->depth == 8 ? 6 : 10);
  197840. int palette_size = entry_size * spalette->nentries;
  197841. png_sPLT_entryp ep;
  197842. #ifdef PNG_NO_POINTER_INDEXING
  197843. int i;
  197844. #endif
  197845. png_debug(1, "in png_write_sPLT\n");
  197846. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  197847. spalette->name, &new_name))==0)
  197848. {
  197849. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  197850. return;
  197851. }
  197852. /* make sure we include the NULL after the name */
  197853. png_write_chunk_start(png_ptr, png_sPLT,
  197854. (png_uint_32)(name_len + 2 + palette_size));
  197855. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  197856. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  197857. /* loop through each palette entry, writing appropriately */
  197858. #ifndef PNG_NO_POINTER_INDEXING
  197859. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  197860. {
  197861. if (spalette->depth == 8)
  197862. {
  197863. entrybuf[0] = (png_byte)ep->red;
  197864. entrybuf[1] = (png_byte)ep->green;
  197865. entrybuf[2] = (png_byte)ep->blue;
  197866. entrybuf[3] = (png_byte)ep->alpha;
  197867. png_save_uint_16(entrybuf + 4, ep->frequency);
  197868. }
  197869. else
  197870. {
  197871. png_save_uint_16(entrybuf + 0, ep->red);
  197872. png_save_uint_16(entrybuf + 2, ep->green);
  197873. png_save_uint_16(entrybuf + 4, ep->blue);
  197874. png_save_uint_16(entrybuf + 6, ep->alpha);
  197875. png_save_uint_16(entrybuf + 8, ep->frequency);
  197876. }
  197877. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  197878. }
  197879. #else
  197880. ep=spalette->entries;
  197881. for (i=0; i>spalette->nentries; i++)
  197882. {
  197883. if (spalette->depth == 8)
  197884. {
  197885. entrybuf[0] = (png_byte)ep[i].red;
  197886. entrybuf[1] = (png_byte)ep[i].green;
  197887. entrybuf[2] = (png_byte)ep[i].blue;
  197888. entrybuf[3] = (png_byte)ep[i].alpha;
  197889. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  197890. }
  197891. else
  197892. {
  197893. png_save_uint_16(entrybuf + 0, ep[i].red);
  197894. png_save_uint_16(entrybuf + 2, ep[i].green);
  197895. png_save_uint_16(entrybuf + 4, ep[i].blue);
  197896. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  197897. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  197898. }
  197899. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  197900. }
  197901. #endif
  197902. png_write_chunk_end(png_ptr);
  197903. png_free(png_ptr, new_name);
  197904. }
  197905. #endif
  197906. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197907. /* write the sBIT chunk */
  197908. void /* PRIVATE */
  197909. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  197910. {
  197911. #ifdef PNG_USE_LOCAL_ARRAYS
  197912. PNG_sBIT;
  197913. #endif
  197914. png_byte buf[4];
  197915. png_size_t size;
  197916. png_debug(1, "in png_write_sBIT\n");
  197917. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  197918. if (color_type & PNG_COLOR_MASK_COLOR)
  197919. {
  197920. png_byte maxbits;
  197921. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  197922. png_ptr->usr_bit_depth);
  197923. if (sbit->red == 0 || sbit->red > maxbits ||
  197924. sbit->green == 0 || sbit->green > maxbits ||
  197925. sbit->blue == 0 || sbit->blue > maxbits)
  197926. {
  197927. png_warning(png_ptr, "Invalid sBIT depth specified");
  197928. return;
  197929. }
  197930. buf[0] = sbit->red;
  197931. buf[1] = sbit->green;
  197932. buf[2] = sbit->blue;
  197933. size = 3;
  197934. }
  197935. else
  197936. {
  197937. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  197938. {
  197939. png_warning(png_ptr, "Invalid sBIT depth specified");
  197940. return;
  197941. }
  197942. buf[0] = sbit->gray;
  197943. size = 1;
  197944. }
  197945. if (color_type & PNG_COLOR_MASK_ALPHA)
  197946. {
  197947. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  197948. {
  197949. png_warning(png_ptr, "Invalid sBIT depth specified");
  197950. return;
  197951. }
  197952. buf[size++] = sbit->alpha;
  197953. }
  197954. png_write_chunk(png_ptr, png_sBIT, buf, size);
  197955. }
  197956. #endif
  197957. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197958. /* write the cHRM chunk */
  197959. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197960. void /* PRIVATE */
  197961. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  197962. double red_x, double red_y, double green_x, double green_y,
  197963. double blue_x, double blue_y)
  197964. {
  197965. #ifdef PNG_USE_LOCAL_ARRAYS
  197966. PNG_cHRM;
  197967. #endif
  197968. png_byte buf[32];
  197969. png_uint_32 itemp;
  197970. png_debug(1, "in png_write_cHRM\n");
  197971. /* each value is saved in 1/100,000ths */
  197972. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  197973. white_x + white_y > 1.0)
  197974. {
  197975. png_warning(png_ptr, "Invalid cHRM white point specified");
  197976. #if !defined(PNG_NO_CONSOLE_IO)
  197977. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  197978. #endif
  197979. return;
  197980. }
  197981. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  197982. png_save_uint_32(buf, itemp);
  197983. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  197984. png_save_uint_32(buf + 4, itemp);
  197985. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  197986. {
  197987. png_warning(png_ptr, "Invalid cHRM red point specified");
  197988. return;
  197989. }
  197990. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  197991. png_save_uint_32(buf + 8, itemp);
  197992. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  197993. png_save_uint_32(buf + 12, itemp);
  197994. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  197995. {
  197996. png_warning(png_ptr, "Invalid cHRM green point specified");
  197997. return;
  197998. }
  197999. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  198000. png_save_uint_32(buf + 16, itemp);
  198001. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  198002. png_save_uint_32(buf + 20, itemp);
  198003. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  198004. {
  198005. png_warning(png_ptr, "Invalid cHRM blue point specified");
  198006. return;
  198007. }
  198008. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  198009. png_save_uint_32(buf + 24, itemp);
  198010. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  198011. png_save_uint_32(buf + 28, itemp);
  198012. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198013. }
  198014. #endif
  198015. #ifdef PNG_FIXED_POINT_SUPPORTED
  198016. void /* PRIVATE */
  198017. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  198018. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  198019. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  198020. png_fixed_point blue_y)
  198021. {
  198022. #ifdef PNG_USE_LOCAL_ARRAYS
  198023. PNG_cHRM;
  198024. #endif
  198025. png_byte buf[32];
  198026. png_debug(1, "in png_write_cHRM\n");
  198027. /* each value is saved in 1/100,000ths */
  198028. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  198029. {
  198030. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  198031. #if !defined(PNG_NO_CONSOLE_IO)
  198032. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  198033. #endif
  198034. return;
  198035. }
  198036. png_save_uint_32(buf, (png_uint_32)white_x);
  198037. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  198038. if (red_x + red_y > 100000L)
  198039. {
  198040. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  198041. return;
  198042. }
  198043. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  198044. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  198045. if (green_x + green_y > 100000L)
  198046. {
  198047. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  198048. return;
  198049. }
  198050. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  198051. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  198052. if (blue_x + blue_y > 100000L)
  198053. {
  198054. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  198055. return;
  198056. }
  198057. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  198058. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  198059. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198060. }
  198061. #endif
  198062. #endif
  198063. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198064. /* write the tRNS chunk */
  198065. void /* PRIVATE */
  198066. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  198067. int num_trans, int color_type)
  198068. {
  198069. #ifdef PNG_USE_LOCAL_ARRAYS
  198070. PNG_tRNS;
  198071. #endif
  198072. png_byte buf[6];
  198073. png_debug(1, "in png_write_tRNS\n");
  198074. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198075. {
  198076. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  198077. {
  198078. png_warning(png_ptr,"Invalid number of transparent colors specified");
  198079. return;
  198080. }
  198081. /* write the chunk out as it is */
  198082. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  198083. }
  198084. else if (color_type == PNG_COLOR_TYPE_GRAY)
  198085. {
  198086. /* one 16 bit value */
  198087. if(tran->gray >= (1 << png_ptr->bit_depth))
  198088. {
  198089. png_warning(png_ptr,
  198090. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  198091. return;
  198092. }
  198093. png_save_uint_16(buf, tran->gray);
  198094. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  198095. }
  198096. else if (color_type == PNG_COLOR_TYPE_RGB)
  198097. {
  198098. /* three 16 bit values */
  198099. png_save_uint_16(buf, tran->red);
  198100. png_save_uint_16(buf + 2, tran->green);
  198101. png_save_uint_16(buf + 4, tran->blue);
  198102. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198103. {
  198104. png_warning(png_ptr,
  198105. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  198106. return;
  198107. }
  198108. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  198109. }
  198110. else
  198111. {
  198112. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  198113. }
  198114. }
  198115. #endif
  198116. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198117. /* write the background chunk */
  198118. void /* PRIVATE */
  198119. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  198120. {
  198121. #ifdef PNG_USE_LOCAL_ARRAYS
  198122. PNG_bKGD;
  198123. #endif
  198124. png_byte buf[6];
  198125. png_debug(1, "in png_write_bKGD\n");
  198126. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198127. {
  198128. if (
  198129. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198130. (png_ptr->num_palette ||
  198131. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  198132. #endif
  198133. back->index > png_ptr->num_palette)
  198134. {
  198135. png_warning(png_ptr, "Invalid background palette index");
  198136. return;
  198137. }
  198138. buf[0] = back->index;
  198139. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  198140. }
  198141. else if (color_type & PNG_COLOR_MASK_COLOR)
  198142. {
  198143. png_save_uint_16(buf, back->red);
  198144. png_save_uint_16(buf + 2, back->green);
  198145. png_save_uint_16(buf + 4, back->blue);
  198146. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198147. {
  198148. png_warning(png_ptr,
  198149. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  198150. return;
  198151. }
  198152. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  198153. }
  198154. else
  198155. {
  198156. if(back->gray >= (1 << png_ptr->bit_depth))
  198157. {
  198158. png_warning(png_ptr,
  198159. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  198160. return;
  198161. }
  198162. png_save_uint_16(buf, back->gray);
  198163. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  198164. }
  198165. }
  198166. #endif
  198167. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198168. /* write the histogram */
  198169. void /* PRIVATE */
  198170. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  198171. {
  198172. #ifdef PNG_USE_LOCAL_ARRAYS
  198173. PNG_hIST;
  198174. #endif
  198175. int i;
  198176. png_byte buf[3];
  198177. png_debug(1, "in png_write_hIST\n");
  198178. if (num_hist > (int)png_ptr->num_palette)
  198179. {
  198180. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  198181. png_ptr->num_palette);
  198182. png_warning(png_ptr, "Invalid number of histogram entries specified");
  198183. return;
  198184. }
  198185. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  198186. for (i = 0; i < num_hist; i++)
  198187. {
  198188. png_save_uint_16(buf, hist[i]);
  198189. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  198190. }
  198191. png_write_chunk_end(png_ptr);
  198192. }
  198193. #endif
  198194. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  198195. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198196. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  198197. * and if invalid, correct the keyword rather than discarding the entire
  198198. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  198199. * length, forbids leading or trailing whitespace, multiple internal spaces,
  198200. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  198201. *
  198202. * The new_key is allocated to hold the corrected keyword and must be freed
  198203. * by the calling routine. This avoids problems with trying to write to
  198204. * static keywords without having to have duplicate copies of the strings.
  198205. */
  198206. png_size_t /* PRIVATE */
  198207. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  198208. {
  198209. png_size_t key_len;
  198210. png_charp kp, dp;
  198211. int kflag;
  198212. int kwarn=0;
  198213. png_debug(1, "in png_check_keyword\n");
  198214. *new_key = NULL;
  198215. if (key == NULL || (key_len = png_strlen(key)) == 0)
  198216. {
  198217. png_warning(png_ptr, "zero length keyword");
  198218. return ((png_size_t)0);
  198219. }
  198220. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  198221. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  198222. if (*new_key == NULL)
  198223. {
  198224. png_warning(png_ptr, "Out of memory while procesing keyword");
  198225. return ((png_size_t)0);
  198226. }
  198227. /* Replace non-printing characters with a blank and print a warning */
  198228. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  198229. {
  198230. if ((png_byte)*kp < 0x20 ||
  198231. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  198232. {
  198233. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198234. char msg[40];
  198235. png_snprintf(msg, 40,
  198236. "invalid keyword character 0x%02X", (png_byte)*kp);
  198237. png_warning(png_ptr, msg);
  198238. #else
  198239. png_warning(png_ptr, "invalid character in keyword");
  198240. #endif
  198241. *dp = ' ';
  198242. }
  198243. else
  198244. {
  198245. *dp = *kp;
  198246. }
  198247. }
  198248. *dp = '\0';
  198249. /* Remove any trailing white space. */
  198250. kp = *new_key + key_len - 1;
  198251. if (*kp == ' ')
  198252. {
  198253. png_warning(png_ptr, "trailing spaces removed from keyword");
  198254. while (*kp == ' ')
  198255. {
  198256. *(kp--) = '\0';
  198257. key_len--;
  198258. }
  198259. }
  198260. /* Remove any leading white space. */
  198261. kp = *new_key;
  198262. if (*kp == ' ')
  198263. {
  198264. png_warning(png_ptr, "leading spaces removed from keyword");
  198265. while (*kp == ' ')
  198266. {
  198267. kp++;
  198268. key_len--;
  198269. }
  198270. }
  198271. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  198272. /* Remove multiple internal spaces. */
  198273. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  198274. {
  198275. if (*kp == ' ' && kflag == 0)
  198276. {
  198277. *(dp++) = *kp;
  198278. kflag = 1;
  198279. }
  198280. else if (*kp == ' ')
  198281. {
  198282. key_len--;
  198283. kwarn=1;
  198284. }
  198285. else
  198286. {
  198287. *(dp++) = *kp;
  198288. kflag = 0;
  198289. }
  198290. }
  198291. *dp = '\0';
  198292. if(kwarn)
  198293. png_warning(png_ptr, "extra interior spaces removed from keyword");
  198294. if (key_len == 0)
  198295. {
  198296. png_free(png_ptr, *new_key);
  198297. *new_key=NULL;
  198298. png_warning(png_ptr, "Zero length keyword");
  198299. }
  198300. if (key_len > 79)
  198301. {
  198302. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  198303. new_key[79] = '\0';
  198304. key_len = 79;
  198305. }
  198306. return (key_len);
  198307. }
  198308. #endif
  198309. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198310. /* write a tEXt chunk */
  198311. void /* PRIVATE */
  198312. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  198313. png_size_t text_len)
  198314. {
  198315. #ifdef PNG_USE_LOCAL_ARRAYS
  198316. PNG_tEXt;
  198317. #endif
  198318. png_size_t key_len;
  198319. png_charp new_key;
  198320. png_debug(1, "in png_write_tEXt\n");
  198321. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198322. {
  198323. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  198324. return;
  198325. }
  198326. if (text == NULL || *text == '\0')
  198327. text_len = 0;
  198328. else
  198329. text_len = png_strlen(text);
  198330. /* make sure we include the 0 after the key */
  198331. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  198332. /*
  198333. * We leave it to the application to meet PNG-1.0 requirements on the
  198334. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198335. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198336. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198337. */
  198338. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198339. if (text_len)
  198340. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  198341. png_write_chunk_end(png_ptr);
  198342. png_free(png_ptr, new_key);
  198343. }
  198344. #endif
  198345. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198346. /* write a compressed text chunk */
  198347. void /* PRIVATE */
  198348. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  198349. png_size_t text_len, int compression)
  198350. {
  198351. #ifdef PNG_USE_LOCAL_ARRAYS
  198352. PNG_zTXt;
  198353. #endif
  198354. png_size_t key_len;
  198355. char buf[1];
  198356. png_charp new_key;
  198357. compression_state comp;
  198358. png_debug(1, "in png_write_zTXt\n");
  198359. comp.num_output_ptr = 0;
  198360. comp.max_output_ptr = 0;
  198361. comp.output_ptr = NULL;
  198362. comp.input = NULL;
  198363. comp.input_len = 0;
  198364. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198365. {
  198366. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  198367. return;
  198368. }
  198369. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  198370. {
  198371. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  198372. png_free(png_ptr, new_key);
  198373. return;
  198374. }
  198375. text_len = png_strlen(text);
  198376. /* compute the compressed data; do it now for the length */
  198377. text_len = png_text_compress(png_ptr, text, text_len, compression,
  198378. &comp);
  198379. /* write start of chunk */
  198380. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  198381. (key_len+text_len+2));
  198382. /* write key */
  198383. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198384. png_free(png_ptr, new_key);
  198385. buf[0] = (png_byte)compression;
  198386. /* write compression */
  198387. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  198388. /* write the compressed data */
  198389. png_write_compressed_data_out(png_ptr, &comp);
  198390. /* close the chunk */
  198391. png_write_chunk_end(png_ptr);
  198392. }
  198393. #endif
  198394. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198395. /* write an iTXt chunk */
  198396. void /* PRIVATE */
  198397. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  198398. png_charp lang, png_charp lang_key, png_charp text)
  198399. {
  198400. #ifdef PNG_USE_LOCAL_ARRAYS
  198401. PNG_iTXt;
  198402. #endif
  198403. png_size_t lang_len, key_len, lang_key_len, text_len;
  198404. png_charp new_lang, new_key;
  198405. png_byte cbuf[2];
  198406. compression_state comp;
  198407. png_debug(1, "in png_write_iTXt\n");
  198408. comp.num_output_ptr = 0;
  198409. comp.max_output_ptr = 0;
  198410. comp.output_ptr = NULL;
  198411. comp.input = NULL;
  198412. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198413. {
  198414. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  198415. return;
  198416. }
  198417. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  198418. {
  198419. png_warning(png_ptr, "Empty language field in iTXt chunk");
  198420. new_lang = NULL;
  198421. lang_len = 0;
  198422. }
  198423. if (lang_key == NULL)
  198424. lang_key_len = 0;
  198425. else
  198426. lang_key_len = png_strlen(lang_key);
  198427. if (text == NULL)
  198428. text_len = 0;
  198429. else
  198430. text_len = png_strlen(text);
  198431. /* compute the compressed data; do it now for the length */
  198432. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  198433. &comp);
  198434. /* make sure we include the compression flag, the compression byte,
  198435. * and the NULs after the key, lang, and lang_key parts */
  198436. png_write_chunk_start(png_ptr, png_iTXt,
  198437. (png_uint_32)(
  198438. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  198439. + key_len
  198440. + lang_len
  198441. + lang_key_len
  198442. + text_len));
  198443. /*
  198444. * We leave it to the application to meet PNG-1.0 requirements on the
  198445. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198446. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198447. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198448. */
  198449. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198450. /* set the compression flag */
  198451. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  198452. compression == PNG_TEXT_COMPRESSION_NONE)
  198453. cbuf[0] = 0;
  198454. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  198455. cbuf[0] = 1;
  198456. /* set the compression method */
  198457. cbuf[1] = 0;
  198458. png_write_chunk_data(png_ptr, cbuf, 2);
  198459. cbuf[0] = 0;
  198460. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  198461. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  198462. png_write_compressed_data_out(png_ptr, &comp);
  198463. png_write_chunk_end(png_ptr);
  198464. png_free(png_ptr, new_key);
  198465. if (new_lang)
  198466. png_free(png_ptr, new_lang);
  198467. }
  198468. #endif
  198469. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198470. /* write the oFFs chunk */
  198471. void /* PRIVATE */
  198472. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  198473. int unit_type)
  198474. {
  198475. #ifdef PNG_USE_LOCAL_ARRAYS
  198476. PNG_oFFs;
  198477. #endif
  198478. png_byte buf[9];
  198479. png_debug(1, "in png_write_oFFs\n");
  198480. if (unit_type >= PNG_OFFSET_LAST)
  198481. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  198482. png_save_int_32(buf, x_offset);
  198483. png_save_int_32(buf + 4, y_offset);
  198484. buf[8] = (png_byte)unit_type;
  198485. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  198486. }
  198487. #endif
  198488. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198489. /* write the pCAL chunk (described in the PNG extensions document) */
  198490. void /* PRIVATE */
  198491. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  198492. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  198493. {
  198494. #ifdef PNG_USE_LOCAL_ARRAYS
  198495. PNG_pCAL;
  198496. #endif
  198497. png_size_t purpose_len, units_len, total_len;
  198498. png_uint_32p params_len;
  198499. png_byte buf[10];
  198500. png_charp new_purpose;
  198501. int i;
  198502. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  198503. if (type >= PNG_EQUATION_LAST)
  198504. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  198505. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  198506. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  198507. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  198508. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  198509. total_len = purpose_len + units_len + 10;
  198510. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  198511. *png_sizeof(png_uint_32)));
  198512. /* Find the length of each parameter, making sure we don't count the
  198513. null terminator for the last parameter. */
  198514. for (i = 0; i < nparams; i++)
  198515. {
  198516. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  198517. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  198518. total_len += (png_size_t)params_len[i];
  198519. }
  198520. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  198521. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  198522. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  198523. png_save_int_32(buf, X0);
  198524. png_save_int_32(buf + 4, X1);
  198525. buf[8] = (png_byte)type;
  198526. buf[9] = (png_byte)nparams;
  198527. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  198528. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  198529. png_free(png_ptr, new_purpose);
  198530. for (i = 0; i < nparams; i++)
  198531. {
  198532. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  198533. (png_size_t)params_len[i]);
  198534. }
  198535. png_free(png_ptr, params_len);
  198536. png_write_chunk_end(png_ptr);
  198537. }
  198538. #endif
  198539. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198540. /* write the sCAL chunk */
  198541. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198542. void /* PRIVATE */
  198543. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  198544. {
  198545. #ifdef PNG_USE_LOCAL_ARRAYS
  198546. PNG_sCAL;
  198547. #endif
  198548. char buf[64];
  198549. png_size_t total_len;
  198550. png_debug(1, "in png_write_sCAL\n");
  198551. buf[0] = (char)unit;
  198552. #if defined(_WIN32_WCE)
  198553. /* sprintf() function is not supported on WindowsCE */
  198554. {
  198555. wchar_t wc_buf[32];
  198556. size_t wc_len;
  198557. swprintf(wc_buf, TEXT("%12.12e"), width);
  198558. wc_len = wcslen(wc_buf);
  198559. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  198560. total_len = wc_len + 2;
  198561. swprintf(wc_buf, TEXT("%12.12e"), height);
  198562. wc_len = wcslen(wc_buf);
  198563. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  198564. NULL, NULL);
  198565. total_len += wc_len;
  198566. }
  198567. #else
  198568. png_snprintf(buf + 1, 63, "%12.12e", width);
  198569. total_len = 1 + png_strlen(buf + 1) + 1;
  198570. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  198571. total_len += png_strlen(buf + total_len);
  198572. #endif
  198573. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  198574. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  198575. }
  198576. #else
  198577. #ifdef PNG_FIXED_POINT_SUPPORTED
  198578. void /* PRIVATE */
  198579. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  198580. png_charp height)
  198581. {
  198582. #ifdef PNG_USE_LOCAL_ARRAYS
  198583. PNG_sCAL;
  198584. #endif
  198585. png_byte buf[64];
  198586. png_size_t wlen, hlen, total_len;
  198587. png_debug(1, "in png_write_sCAL_s\n");
  198588. wlen = png_strlen(width);
  198589. hlen = png_strlen(height);
  198590. total_len = wlen + hlen + 2;
  198591. if (total_len > 64)
  198592. {
  198593. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  198594. return;
  198595. }
  198596. buf[0] = (png_byte)unit;
  198597. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  198598. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  198599. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  198600. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  198601. }
  198602. #endif
  198603. #endif
  198604. #endif
  198605. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198606. /* write the pHYs chunk */
  198607. void /* PRIVATE */
  198608. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  198609. png_uint_32 y_pixels_per_unit,
  198610. int unit_type)
  198611. {
  198612. #ifdef PNG_USE_LOCAL_ARRAYS
  198613. PNG_pHYs;
  198614. #endif
  198615. png_byte buf[9];
  198616. png_debug(1, "in png_write_pHYs\n");
  198617. if (unit_type >= PNG_RESOLUTION_LAST)
  198618. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  198619. png_save_uint_32(buf, x_pixels_per_unit);
  198620. png_save_uint_32(buf + 4, y_pixels_per_unit);
  198621. buf[8] = (png_byte)unit_type;
  198622. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  198623. }
  198624. #endif
  198625. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198626. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  198627. * or png_convert_from_time_t(), or fill in the structure yourself.
  198628. */
  198629. void /* PRIVATE */
  198630. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  198631. {
  198632. #ifdef PNG_USE_LOCAL_ARRAYS
  198633. PNG_tIME;
  198634. #endif
  198635. png_byte buf[7];
  198636. png_debug(1, "in png_write_tIME\n");
  198637. if (mod_time->month > 12 || mod_time->month < 1 ||
  198638. mod_time->day > 31 || mod_time->day < 1 ||
  198639. mod_time->hour > 23 || mod_time->second > 60)
  198640. {
  198641. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  198642. return;
  198643. }
  198644. png_save_uint_16(buf, mod_time->year);
  198645. buf[2] = mod_time->month;
  198646. buf[3] = mod_time->day;
  198647. buf[4] = mod_time->hour;
  198648. buf[5] = mod_time->minute;
  198649. buf[6] = mod_time->second;
  198650. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  198651. }
  198652. #endif
  198653. /* initializes the row writing capability of libpng */
  198654. void /* PRIVATE */
  198655. png_write_start_row(png_structp png_ptr)
  198656. {
  198657. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198658. #ifdef PNG_USE_LOCAL_ARRAYS
  198659. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198660. /* start of interlace block */
  198661. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198662. /* offset to next interlace block */
  198663. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198664. /* start of interlace block in the y direction */
  198665. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  198666. /* offset to next interlace block in the y direction */
  198667. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  198668. #endif
  198669. #endif
  198670. png_size_t buf_size;
  198671. png_debug(1, "in png_write_start_row\n");
  198672. buf_size = (png_size_t)(PNG_ROWBYTES(
  198673. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  198674. /* set up row buffer */
  198675. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  198676. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  198677. #ifndef PNG_NO_WRITE_FILTERING
  198678. /* set up filtering buffer, if using this filter */
  198679. if (png_ptr->do_filter & PNG_FILTER_SUB)
  198680. {
  198681. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  198682. (png_ptr->rowbytes + 1));
  198683. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  198684. }
  198685. /* We only need to keep the previous row if we are using one of these. */
  198686. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  198687. {
  198688. /* set up previous row buffer */
  198689. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  198690. png_memset(png_ptr->prev_row, 0, buf_size);
  198691. if (png_ptr->do_filter & PNG_FILTER_UP)
  198692. {
  198693. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  198694. (png_ptr->rowbytes + 1));
  198695. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  198696. }
  198697. if (png_ptr->do_filter & PNG_FILTER_AVG)
  198698. {
  198699. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  198700. (png_ptr->rowbytes + 1));
  198701. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  198702. }
  198703. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  198704. {
  198705. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  198706. (png_ptr->rowbytes + 1));
  198707. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  198708. }
  198709. #endif /* PNG_NO_WRITE_FILTERING */
  198710. }
  198711. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198712. /* if interlaced, we need to set up width and height of pass */
  198713. if (png_ptr->interlaced)
  198714. {
  198715. if (!(png_ptr->transformations & PNG_INTERLACE))
  198716. {
  198717. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  198718. png_pass_ystart[0]) / png_pass_yinc[0];
  198719. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  198720. png_pass_start[0]) / png_pass_inc[0];
  198721. }
  198722. else
  198723. {
  198724. png_ptr->num_rows = png_ptr->height;
  198725. png_ptr->usr_width = png_ptr->width;
  198726. }
  198727. }
  198728. else
  198729. #endif
  198730. {
  198731. png_ptr->num_rows = png_ptr->height;
  198732. png_ptr->usr_width = png_ptr->width;
  198733. }
  198734. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198735. png_ptr->zstream.next_out = png_ptr->zbuf;
  198736. }
  198737. /* Internal use only. Called when finished processing a row of data. */
  198738. void /* PRIVATE */
  198739. png_write_finish_row(png_structp png_ptr)
  198740. {
  198741. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198742. #ifdef PNG_USE_LOCAL_ARRAYS
  198743. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198744. /* start of interlace block */
  198745. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198746. /* offset to next interlace block */
  198747. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198748. /* start of interlace block in the y direction */
  198749. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  198750. /* offset to next interlace block in the y direction */
  198751. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  198752. #endif
  198753. #endif
  198754. int ret;
  198755. png_debug(1, "in png_write_finish_row\n");
  198756. /* next row */
  198757. png_ptr->row_number++;
  198758. /* see if we are done */
  198759. if (png_ptr->row_number < png_ptr->num_rows)
  198760. return;
  198761. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198762. /* if interlaced, go to next pass */
  198763. if (png_ptr->interlaced)
  198764. {
  198765. png_ptr->row_number = 0;
  198766. if (png_ptr->transformations & PNG_INTERLACE)
  198767. {
  198768. png_ptr->pass++;
  198769. }
  198770. else
  198771. {
  198772. /* loop until we find a non-zero width or height pass */
  198773. do
  198774. {
  198775. png_ptr->pass++;
  198776. if (png_ptr->pass >= 7)
  198777. break;
  198778. png_ptr->usr_width = (png_ptr->width +
  198779. png_pass_inc[png_ptr->pass] - 1 -
  198780. png_pass_start[png_ptr->pass]) /
  198781. png_pass_inc[png_ptr->pass];
  198782. png_ptr->num_rows = (png_ptr->height +
  198783. png_pass_yinc[png_ptr->pass] - 1 -
  198784. png_pass_ystart[png_ptr->pass]) /
  198785. png_pass_yinc[png_ptr->pass];
  198786. if (png_ptr->transformations & PNG_INTERLACE)
  198787. break;
  198788. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  198789. }
  198790. /* reset the row above the image for the next pass */
  198791. if (png_ptr->pass < 7)
  198792. {
  198793. if (png_ptr->prev_row != NULL)
  198794. png_memset(png_ptr->prev_row, 0,
  198795. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  198796. png_ptr->usr_bit_depth,png_ptr->width))+1);
  198797. return;
  198798. }
  198799. }
  198800. #endif
  198801. /* if we get here, we've just written the last row, so we need
  198802. to flush the compressor */
  198803. do
  198804. {
  198805. /* tell the compressor we are done */
  198806. ret = deflate(&png_ptr->zstream, Z_FINISH);
  198807. /* check for an error */
  198808. if (ret == Z_OK)
  198809. {
  198810. /* check to see if we need more room */
  198811. if (!(png_ptr->zstream.avail_out))
  198812. {
  198813. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198814. png_ptr->zstream.next_out = png_ptr->zbuf;
  198815. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198816. }
  198817. }
  198818. else if (ret != Z_STREAM_END)
  198819. {
  198820. if (png_ptr->zstream.msg != NULL)
  198821. png_error(png_ptr, png_ptr->zstream.msg);
  198822. else
  198823. png_error(png_ptr, "zlib error");
  198824. }
  198825. } while (ret != Z_STREAM_END);
  198826. /* write any extra space */
  198827. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  198828. {
  198829. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  198830. png_ptr->zstream.avail_out);
  198831. }
  198832. deflateReset(&png_ptr->zstream);
  198833. png_ptr->zstream.data_type = Z_BINARY;
  198834. }
  198835. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198836. /* Pick out the correct pixels for the interlace pass.
  198837. * The basic idea here is to go through the row with a source
  198838. * pointer and a destination pointer (sp and dp), and copy the
  198839. * correct pixels for the pass. As the row gets compacted,
  198840. * sp will always be >= dp, so we should never overwrite anything.
  198841. * See the default: case for the easiest code to understand.
  198842. */
  198843. void /* PRIVATE */
  198844. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  198845. {
  198846. #ifdef PNG_USE_LOCAL_ARRAYS
  198847. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198848. /* start of interlace block */
  198849. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198850. /* offset to next interlace block */
  198851. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198852. #endif
  198853. png_debug(1, "in png_do_write_interlace\n");
  198854. /* we don't have to do anything on the last pass (6) */
  198855. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198856. if (row != NULL && row_info != NULL && pass < 6)
  198857. #else
  198858. if (pass < 6)
  198859. #endif
  198860. {
  198861. /* each pixel depth is handled separately */
  198862. switch (row_info->pixel_depth)
  198863. {
  198864. case 1:
  198865. {
  198866. png_bytep sp;
  198867. png_bytep dp;
  198868. int shift;
  198869. int d;
  198870. int value;
  198871. png_uint_32 i;
  198872. png_uint_32 row_width = row_info->width;
  198873. dp = row;
  198874. d = 0;
  198875. shift = 7;
  198876. for (i = png_pass_start[pass]; i < row_width;
  198877. i += png_pass_inc[pass])
  198878. {
  198879. sp = row + (png_size_t)(i >> 3);
  198880. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  198881. d |= (value << shift);
  198882. if (shift == 0)
  198883. {
  198884. shift = 7;
  198885. *dp++ = (png_byte)d;
  198886. d = 0;
  198887. }
  198888. else
  198889. shift--;
  198890. }
  198891. if (shift != 7)
  198892. *dp = (png_byte)d;
  198893. break;
  198894. }
  198895. case 2:
  198896. {
  198897. png_bytep sp;
  198898. png_bytep dp;
  198899. int shift;
  198900. int d;
  198901. int value;
  198902. png_uint_32 i;
  198903. png_uint_32 row_width = row_info->width;
  198904. dp = row;
  198905. shift = 6;
  198906. d = 0;
  198907. for (i = png_pass_start[pass]; i < row_width;
  198908. i += png_pass_inc[pass])
  198909. {
  198910. sp = row + (png_size_t)(i >> 2);
  198911. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  198912. d |= (value << shift);
  198913. if (shift == 0)
  198914. {
  198915. shift = 6;
  198916. *dp++ = (png_byte)d;
  198917. d = 0;
  198918. }
  198919. else
  198920. shift -= 2;
  198921. }
  198922. if (shift != 6)
  198923. *dp = (png_byte)d;
  198924. break;
  198925. }
  198926. case 4:
  198927. {
  198928. png_bytep sp;
  198929. png_bytep dp;
  198930. int shift;
  198931. int d;
  198932. int value;
  198933. png_uint_32 i;
  198934. png_uint_32 row_width = row_info->width;
  198935. dp = row;
  198936. shift = 4;
  198937. d = 0;
  198938. for (i = png_pass_start[pass]; i < row_width;
  198939. i += png_pass_inc[pass])
  198940. {
  198941. sp = row + (png_size_t)(i >> 1);
  198942. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  198943. d |= (value << shift);
  198944. if (shift == 0)
  198945. {
  198946. shift = 4;
  198947. *dp++ = (png_byte)d;
  198948. d = 0;
  198949. }
  198950. else
  198951. shift -= 4;
  198952. }
  198953. if (shift != 4)
  198954. *dp = (png_byte)d;
  198955. break;
  198956. }
  198957. default:
  198958. {
  198959. png_bytep sp;
  198960. png_bytep dp;
  198961. png_uint_32 i;
  198962. png_uint_32 row_width = row_info->width;
  198963. png_size_t pixel_bytes;
  198964. /* start at the beginning */
  198965. dp = row;
  198966. /* find out how many bytes each pixel takes up */
  198967. pixel_bytes = (row_info->pixel_depth >> 3);
  198968. /* loop through the row, only looking at the pixels that
  198969. matter */
  198970. for (i = png_pass_start[pass]; i < row_width;
  198971. i += png_pass_inc[pass])
  198972. {
  198973. /* find out where the original pixel is */
  198974. sp = row + (png_size_t)i * pixel_bytes;
  198975. /* move the pixel */
  198976. if (dp != sp)
  198977. png_memcpy(dp, sp, pixel_bytes);
  198978. /* next pixel */
  198979. dp += pixel_bytes;
  198980. }
  198981. break;
  198982. }
  198983. }
  198984. /* set new row width */
  198985. row_info->width = (row_info->width +
  198986. png_pass_inc[pass] - 1 -
  198987. png_pass_start[pass]) /
  198988. png_pass_inc[pass];
  198989. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  198990. row_info->width);
  198991. }
  198992. }
  198993. #endif
  198994. /* This filters the row, chooses which filter to use, if it has not already
  198995. * been specified by the application, and then writes the row out with the
  198996. * chosen filter.
  198997. */
  198998. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  198999. #define PNG_HISHIFT 10
  199000. #define PNG_LOMASK ((png_uint_32)0xffffL)
  199001. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  199002. void /* PRIVATE */
  199003. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  199004. {
  199005. png_bytep best_row;
  199006. #ifndef PNG_NO_WRITE_FILTER
  199007. png_bytep prev_row, row_buf;
  199008. png_uint_32 mins, bpp;
  199009. png_byte filter_to_do = png_ptr->do_filter;
  199010. png_uint_32 row_bytes = row_info->rowbytes;
  199011. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199012. int num_p_filters = (int)png_ptr->num_prev_filters;
  199013. #endif
  199014. png_debug(1, "in png_write_find_filter\n");
  199015. /* find out how many bytes offset each pixel is */
  199016. bpp = (row_info->pixel_depth + 7) >> 3;
  199017. prev_row = png_ptr->prev_row;
  199018. #endif
  199019. best_row = png_ptr->row_buf;
  199020. #ifndef PNG_NO_WRITE_FILTER
  199021. row_buf = best_row;
  199022. mins = PNG_MAXSUM;
  199023. /* The prediction method we use is to find which method provides the
  199024. * smallest value when summing the absolute values of the distances
  199025. * from zero, using anything >= 128 as negative numbers. This is known
  199026. * as the "minimum sum of absolute differences" heuristic. Other
  199027. * heuristics are the "weighted minimum sum of absolute differences"
  199028. * (experimental and can in theory improve compression), and the "zlib
  199029. * predictive" method (not implemented yet), which does test compressions
  199030. * of lines using different filter methods, and then chooses the
  199031. * (series of) filter(s) that give minimum compressed data size (VERY
  199032. * computationally expensive).
  199033. *
  199034. * GRR 980525: consider also
  199035. * (1) minimum sum of absolute differences from running average (i.e.,
  199036. * keep running sum of non-absolute differences & count of bytes)
  199037. * [track dispersion, too? restart average if dispersion too large?]
  199038. * (1b) minimum sum of absolute differences from sliding average, probably
  199039. * with window size <= deflate window (usually 32K)
  199040. * (2) minimum sum of squared differences from zero or running average
  199041. * (i.e., ~ root-mean-square approach)
  199042. */
  199043. /* We don't need to test the 'no filter' case if this is the only filter
  199044. * that has been chosen, as it doesn't actually do anything to the data.
  199045. */
  199046. if ((filter_to_do & PNG_FILTER_NONE) &&
  199047. filter_to_do != PNG_FILTER_NONE)
  199048. {
  199049. png_bytep rp;
  199050. png_uint_32 sum = 0;
  199051. png_uint_32 i;
  199052. int v;
  199053. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  199054. {
  199055. v = *rp;
  199056. sum += (v < 128) ? v : 256 - v;
  199057. }
  199058. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199059. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199060. {
  199061. png_uint_32 sumhi, sumlo;
  199062. int j;
  199063. sumlo = sum & PNG_LOMASK;
  199064. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  199065. /* Reduce the sum if we match any of the previous rows */
  199066. for (j = 0; j < num_p_filters; j++)
  199067. {
  199068. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199069. {
  199070. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199071. PNG_WEIGHT_SHIFT;
  199072. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199073. PNG_WEIGHT_SHIFT;
  199074. }
  199075. }
  199076. /* Factor in the cost of this filter (this is here for completeness,
  199077. * but it makes no sense to have a "cost" for the NONE filter, as
  199078. * it has the minimum possible computational cost - none).
  199079. */
  199080. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199081. PNG_COST_SHIFT;
  199082. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199083. PNG_COST_SHIFT;
  199084. if (sumhi > PNG_HIMASK)
  199085. sum = PNG_MAXSUM;
  199086. else
  199087. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199088. }
  199089. #endif
  199090. mins = sum;
  199091. }
  199092. /* sub filter */
  199093. if (filter_to_do == PNG_FILTER_SUB)
  199094. /* it's the only filter so no testing is needed */
  199095. {
  199096. png_bytep rp, lp, dp;
  199097. png_uint_32 i;
  199098. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199099. i++, rp++, dp++)
  199100. {
  199101. *dp = *rp;
  199102. }
  199103. for (lp = row_buf + 1; i < row_bytes;
  199104. i++, rp++, lp++, dp++)
  199105. {
  199106. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199107. }
  199108. best_row = png_ptr->sub_row;
  199109. }
  199110. else if (filter_to_do & PNG_FILTER_SUB)
  199111. {
  199112. png_bytep rp, dp, lp;
  199113. png_uint_32 sum = 0, lmins = mins;
  199114. png_uint_32 i;
  199115. int v;
  199116. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199117. /* We temporarily increase the "minimum sum" by the factor we
  199118. * would reduce the sum of this filter, so that we can do the
  199119. * early exit comparison without scaling the sum each time.
  199120. */
  199121. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199122. {
  199123. int j;
  199124. png_uint_32 lmhi, lmlo;
  199125. lmlo = lmins & PNG_LOMASK;
  199126. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199127. for (j = 0; j < num_p_filters; j++)
  199128. {
  199129. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199130. {
  199131. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199132. PNG_WEIGHT_SHIFT;
  199133. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199134. PNG_WEIGHT_SHIFT;
  199135. }
  199136. }
  199137. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199138. PNG_COST_SHIFT;
  199139. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199140. PNG_COST_SHIFT;
  199141. if (lmhi > PNG_HIMASK)
  199142. lmins = PNG_MAXSUM;
  199143. else
  199144. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199145. }
  199146. #endif
  199147. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199148. i++, rp++, dp++)
  199149. {
  199150. v = *dp = *rp;
  199151. sum += (v < 128) ? v : 256 - v;
  199152. }
  199153. for (lp = row_buf + 1; i < row_bytes;
  199154. i++, rp++, lp++, dp++)
  199155. {
  199156. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199157. sum += (v < 128) ? v : 256 - v;
  199158. if (sum > lmins) /* We are already worse, don't continue. */
  199159. break;
  199160. }
  199161. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199162. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199163. {
  199164. int j;
  199165. png_uint_32 sumhi, sumlo;
  199166. sumlo = sum & PNG_LOMASK;
  199167. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199168. for (j = 0; j < num_p_filters; j++)
  199169. {
  199170. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199171. {
  199172. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  199173. PNG_WEIGHT_SHIFT;
  199174. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  199175. PNG_WEIGHT_SHIFT;
  199176. }
  199177. }
  199178. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199179. PNG_COST_SHIFT;
  199180. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199181. PNG_COST_SHIFT;
  199182. if (sumhi > PNG_HIMASK)
  199183. sum = PNG_MAXSUM;
  199184. else
  199185. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199186. }
  199187. #endif
  199188. if (sum < mins)
  199189. {
  199190. mins = sum;
  199191. best_row = png_ptr->sub_row;
  199192. }
  199193. }
  199194. /* up filter */
  199195. if (filter_to_do == PNG_FILTER_UP)
  199196. {
  199197. png_bytep rp, dp, pp;
  199198. png_uint_32 i;
  199199. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199200. pp = prev_row + 1; i < row_bytes;
  199201. i++, rp++, pp++, dp++)
  199202. {
  199203. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  199204. }
  199205. best_row = png_ptr->up_row;
  199206. }
  199207. else if (filter_to_do & PNG_FILTER_UP)
  199208. {
  199209. png_bytep rp, dp, pp;
  199210. png_uint_32 sum = 0, lmins = mins;
  199211. png_uint_32 i;
  199212. int v;
  199213. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199214. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199215. {
  199216. int j;
  199217. png_uint_32 lmhi, lmlo;
  199218. lmlo = lmins & PNG_LOMASK;
  199219. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199220. for (j = 0; j < num_p_filters; j++)
  199221. {
  199222. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199223. {
  199224. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199225. PNG_WEIGHT_SHIFT;
  199226. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199227. PNG_WEIGHT_SHIFT;
  199228. }
  199229. }
  199230. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199231. PNG_COST_SHIFT;
  199232. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199233. PNG_COST_SHIFT;
  199234. if (lmhi > PNG_HIMASK)
  199235. lmins = PNG_MAXSUM;
  199236. else
  199237. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199238. }
  199239. #endif
  199240. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199241. pp = prev_row + 1; i < row_bytes; i++)
  199242. {
  199243. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199244. sum += (v < 128) ? v : 256 - v;
  199245. if (sum > lmins) /* We are already worse, don't continue. */
  199246. break;
  199247. }
  199248. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199249. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199250. {
  199251. int j;
  199252. png_uint_32 sumhi, sumlo;
  199253. sumlo = sum & PNG_LOMASK;
  199254. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199255. for (j = 0; j < num_p_filters; j++)
  199256. {
  199257. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199258. {
  199259. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199260. PNG_WEIGHT_SHIFT;
  199261. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199262. PNG_WEIGHT_SHIFT;
  199263. }
  199264. }
  199265. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199266. PNG_COST_SHIFT;
  199267. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199268. PNG_COST_SHIFT;
  199269. if (sumhi > PNG_HIMASK)
  199270. sum = PNG_MAXSUM;
  199271. else
  199272. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199273. }
  199274. #endif
  199275. if (sum < mins)
  199276. {
  199277. mins = sum;
  199278. best_row = png_ptr->up_row;
  199279. }
  199280. }
  199281. /* avg filter */
  199282. if (filter_to_do == PNG_FILTER_AVG)
  199283. {
  199284. png_bytep rp, dp, pp, lp;
  199285. png_uint_32 i;
  199286. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199287. pp = prev_row + 1; i < bpp; i++)
  199288. {
  199289. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199290. }
  199291. for (lp = row_buf + 1; i < row_bytes; i++)
  199292. {
  199293. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  199294. & 0xff);
  199295. }
  199296. best_row = png_ptr->avg_row;
  199297. }
  199298. else if (filter_to_do & PNG_FILTER_AVG)
  199299. {
  199300. png_bytep rp, dp, pp, lp;
  199301. png_uint_32 sum = 0, lmins = mins;
  199302. png_uint_32 i;
  199303. int v;
  199304. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199305. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199306. {
  199307. int j;
  199308. png_uint_32 lmhi, lmlo;
  199309. lmlo = lmins & PNG_LOMASK;
  199310. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199311. for (j = 0; j < num_p_filters; j++)
  199312. {
  199313. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  199314. {
  199315. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199316. PNG_WEIGHT_SHIFT;
  199317. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199318. PNG_WEIGHT_SHIFT;
  199319. }
  199320. }
  199321. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199322. PNG_COST_SHIFT;
  199323. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199324. PNG_COST_SHIFT;
  199325. if (lmhi > PNG_HIMASK)
  199326. lmins = PNG_MAXSUM;
  199327. else
  199328. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199329. }
  199330. #endif
  199331. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199332. pp = prev_row + 1; i < bpp; i++)
  199333. {
  199334. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199335. sum += (v < 128) ? v : 256 - v;
  199336. }
  199337. for (lp = row_buf + 1; i < row_bytes; i++)
  199338. {
  199339. v = *dp++ =
  199340. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  199341. sum += (v < 128) ? v : 256 - v;
  199342. if (sum > lmins) /* We are already worse, don't continue. */
  199343. break;
  199344. }
  199345. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199346. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199347. {
  199348. int j;
  199349. png_uint_32 sumhi, sumlo;
  199350. sumlo = sum & PNG_LOMASK;
  199351. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199352. for (j = 0; j < num_p_filters; j++)
  199353. {
  199354. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199355. {
  199356. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199357. PNG_WEIGHT_SHIFT;
  199358. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199359. PNG_WEIGHT_SHIFT;
  199360. }
  199361. }
  199362. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199363. PNG_COST_SHIFT;
  199364. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199365. PNG_COST_SHIFT;
  199366. if (sumhi > PNG_HIMASK)
  199367. sum = PNG_MAXSUM;
  199368. else
  199369. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199370. }
  199371. #endif
  199372. if (sum < mins)
  199373. {
  199374. mins = sum;
  199375. best_row = png_ptr->avg_row;
  199376. }
  199377. }
  199378. /* Paeth filter */
  199379. if (filter_to_do == PNG_FILTER_PAETH)
  199380. {
  199381. png_bytep rp, dp, pp, cp, lp;
  199382. png_uint_32 i;
  199383. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  199384. pp = prev_row + 1; i < bpp; i++)
  199385. {
  199386. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199387. }
  199388. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  199389. {
  199390. int a, b, c, pa, pb, pc, p;
  199391. b = *pp++;
  199392. c = *cp++;
  199393. a = *lp++;
  199394. p = b - c;
  199395. pc = a - c;
  199396. #ifdef PNG_USE_ABS
  199397. pa = abs(p);
  199398. pb = abs(pc);
  199399. pc = abs(p + pc);
  199400. #else
  199401. pa = p < 0 ? -p : p;
  199402. pb = pc < 0 ? -pc : pc;
  199403. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  199404. #endif
  199405. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  199406. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  199407. }
  199408. best_row = png_ptr->paeth_row;
  199409. }
  199410. else if (filter_to_do & PNG_FILTER_PAETH)
  199411. {
  199412. png_bytep rp, dp, pp, cp, lp;
  199413. png_uint_32 sum = 0, lmins = mins;
  199414. png_uint_32 i;
  199415. int v;
  199416. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199417. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199418. {
  199419. int j;
  199420. png_uint_32 lmhi, lmlo;
  199421. lmlo = lmins & PNG_LOMASK;
  199422. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199423. for (j = 0; j < num_p_filters; j++)
  199424. {
  199425. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  199426. {
  199427. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199428. PNG_WEIGHT_SHIFT;
  199429. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199430. PNG_WEIGHT_SHIFT;
  199431. }
  199432. }
  199433. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199434. PNG_COST_SHIFT;
  199435. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199436. PNG_COST_SHIFT;
  199437. if (lmhi > PNG_HIMASK)
  199438. lmins = PNG_MAXSUM;
  199439. else
  199440. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199441. }
  199442. #endif
  199443. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  199444. pp = prev_row + 1; i < bpp; i++)
  199445. {
  199446. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199447. sum += (v < 128) ? v : 256 - v;
  199448. }
  199449. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  199450. {
  199451. int a, b, c, pa, pb, pc, p;
  199452. b = *pp++;
  199453. c = *cp++;
  199454. a = *lp++;
  199455. #ifndef PNG_SLOW_PAETH
  199456. p = b - c;
  199457. pc = a - c;
  199458. #ifdef PNG_USE_ABS
  199459. pa = abs(p);
  199460. pb = abs(pc);
  199461. pc = abs(p + pc);
  199462. #else
  199463. pa = p < 0 ? -p : p;
  199464. pb = pc < 0 ? -pc : pc;
  199465. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  199466. #endif
  199467. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  199468. #else /* PNG_SLOW_PAETH */
  199469. p = a + b - c;
  199470. pa = abs(p - a);
  199471. pb = abs(p - b);
  199472. pc = abs(p - c);
  199473. if (pa <= pb && pa <= pc)
  199474. p = a;
  199475. else if (pb <= pc)
  199476. p = b;
  199477. else
  199478. p = c;
  199479. #endif /* PNG_SLOW_PAETH */
  199480. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  199481. sum += (v < 128) ? v : 256 - v;
  199482. if (sum > lmins) /* We are already worse, don't continue. */
  199483. break;
  199484. }
  199485. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199486. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199487. {
  199488. int j;
  199489. png_uint_32 sumhi, sumlo;
  199490. sumlo = sum & PNG_LOMASK;
  199491. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199492. for (j = 0; j < num_p_filters; j++)
  199493. {
  199494. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  199495. {
  199496. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199497. PNG_WEIGHT_SHIFT;
  199498. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199499. PNG_WEIGHT_SHIFT;
  199500. }
  199501. }
  199502. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199503. PNG_COST_SHIFT;
  199504. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199505. PNG_COST_SHIFT;
  199506. if (sumhi > PNG_HIMASK)
  199507. sum = PNG_MAXSUM;
  199508. else
  199509. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199510. }
  199511. #endif
  199512. if (sum < mins)
  199513. {
  199514. best_row = png_ptr->paeth_row;
  199515. }
  199516. }
  199517. #endif /* PNG_NO_WRITE_FILTER */
  199518. /* Do the actual writing of the filtered row data from the chosen filter. */
  199519. png_write_filtered_row(png_ptr, best_row);
  199520. #ifndef PNG_NO_WRITE_FILTER
  199521. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199522. /* Save the type of filter we picked this time for future calculations */
  199523. if (png_ptr->num_prev_filters > 0)
  199524. {
  199525. int j;
  199526. for (j = 1; j < num_p_filters; j++)
  199527. {
  199528. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  199529. }
  199530. png_ptr->prev_filters[j] = best_row[0];
  199531. }
  199532. #endif
  199533. #endif /* PNG_NO_WRITE_FILTER */
  199534. }
  199535. /* Do the actual writing of a previously filtered row. */
  199536. void /* PRIVATE */
  199537. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  199538. {
  199539. png_debug(1, "in png_write_filtered_row\n");
  199540. png_debug1(2, "filter = %d\n", filtered_row[0]);
  199541. /* set up the zlib input buffer */
  199542. png_ptr->zstream.next_in = filtered_row;
  199543. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  199544. /* repeat until we have compressed all the data */
  199545. do
  199546. {
  199547. int ret; /* return of zlib */
  199548. /* compress the data */
  199549. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  199550. /* check for compression errors */
  199551. if (ret != Z_OK)
  199552. {
  199553. if (png_ptr->zstream.msg != NULL)
  199554. png_error(png_ptr, png_ptr->zstream.msg);
  199555. else
  199556. png_error(png_ptr, "zlib error");
  199557. }
  199558. /* see if it is time to write another IDAT */
  199559. if (!(png_ptr->zstream.avail_out))
  199560. {
  199561. /* write the IDAT and reset the zlib output buffer */
  199562. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  199563. png_ptr->zstream.next_out = png_ptr->zbuf;
  199564. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199565. }
  199566. /* repeat until all data has been compressed */
  199567. } while (png_ptr->zstream.avail_in);
  199568. /* swap the current and previous rows */
  199569. if (png_ptr->prev_row != NULL)
  199570. {
  199571. png_bytep tptr;
  199572. tptr = png_ptr->prev_row;
  199573. png_ptr->prev_row = png_ptr->row_buf;
  199574. png_ptr->row_buf = tptr;
  199575. }
  199576. /* finish row - updates counters and flushes zlib if last row */
  199577. png_write_finish_row(png_ptr);
  199578. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199579. png_ptr->flush_rows++;
  199580. if (png_ptr->flush_dist > 0 &&
  199581. png_ptr->flush_rows >= png_ptr->flush_dist)
  199582. {
  199583. png_write_flush(png_ptr);
  199584. }
  199585. #endif
  199586. }
  199587. #endif /* PNG_WRITE_SUPPORTED */
  199588. /*** End of inlined file: pngwutil.c ***/
  199589. }
  199590. #else
  199591. extern "C"
  199592. {
  199593. #include <png.h>
  199594. #include <pngconf.h>
  199595. }
  199596. #endif
  199597. }
  199598. #undef max
  199599. #undef min
  199600. #ifdef _MSC_VER
  199601. #pragma warning (pop)
  199602. #endif
  199603. BEGIN_JUCE_NAMESPACE
  199604. using ::calloc;
  199605. using ::malloc;
  199606. using ::free;
  199607. namespace PNGHelpers
  199608. {
  199609. using namespace pnglibNamespace;
  199610. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  199611. {
  199612. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  199613. }
  199614. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  199615. {
  199616. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  199617. }
  199618. struct PNGErrorStruct {};
  199619. static void errorCallback (png_structp, png_const_charp)
  199620. {
  199621. throw PNGErrorStruct();
  199622. }
  199623. }
  199624. PNGImageFormat::PNGImageFormat() {}
  199625. PNGImageFormat::~PNGImageFormat() {}
  199626. const String PNGImageFormat::getFormatName()
  199627. {
  199628. return "PNG";
  199629. }
  199630. bool PNGImageFormat::canUnderstand (InputStream& in)
  199631. {
  199632. const int bytesNeeded = 4;
  199633. char header [bytesNeeded];
  199634. return in.read (header, bytesNeeded) == bytesNeeded
  199635. && header[1] == 'P'
  199636. && header[2] == 'N'
  199637. && header[3] == 'G';
  199638. }
  199639. Image* PNGImageFormat::decodeImage (InputStream& in)
  199640. {
  199641. using namespace pnglibNamespace;
  199642. Image* image = 0;
  199643. png_structp pngReadStruct;
  199644. png_infop pngInfoStruct;
  199645. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  199646. if (pngReadStruct != 0)
  199647. {
  199648. pngInfoStruct = png_create_info_struct (pngReadStruct);
  199649. if (pngInfoStruct == 0)
  199650. {
  199651. png_destroy_read_struct (&pngReadStruct, 0, 0);
  199652. return 0;
  199653. }
  199654. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  199655. // read the header..
  199656. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  199657. png_uint_32 width, height;
  199658. int bitDepth, colorType, interlaceType;
  199659. png_read_info (pngReadStruct, pngInfoStruct);
  199660. png_get_IHDR (pngReadStruct, pngInfoStruct,
  199661. &width, &height,
  199662. &bitDepth, &colorType,
  199663. &interlaceType, 0, 0);
  199664. if (bitDepth == 16)
  199665. png_set_strip_16 (pngReadStruct);
  199666. if (colorType == PNG_COLOR_TYPE_PALETTE)
  199667. png_set_expand (pngReadStruct);
  199668. if (bitDepth < 8)
  199669. png_set_expand (pngReadStruct);
  199670. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  199671. png_set_expand (pngReadStruct);
  199672. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  199673. png_set_gray_to_rgb (pngReadStruct);
  199674. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  199675. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  199676. || pngInfoStruct->num_trans > 0;
  199677. // Load the image into a temp buffer in the pnglib format..
  199678. HeapBlock <uint8> tempBuffer (height * (width << 2));
  199679. {
  199680. HeapBlock <png_bytep> rows (height);
  199681. for (int y = (int) height; --y >= 0;)
  199682. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  199683. png_read_image (pngReadStruct, rows);
  199684. png_read_end (pngReadStruct, pngInfoStruct);
  199685. }
  199686. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  199687. // now convert the data to a juce image format..
  199688. image = Image::createNativeImage (hasAlphaChan ? Image::ARGB : Image::RGB,
  199689. (int) width, (int) height, hasAlphaChan);
  199690. hasAlphaChan = image->hasAlphaChannel(); // (the native image creator may not give back what we expect)
  199691. const Image::BitmapData destData (*image, 0, 0, (int) width, (int) height, true);
  199692. uint8* srcRow = tempBuffer;
  199693. uint8* destRow = destData.data;
  199694. for (int y = 0; y < (int) height; ++y)
  199695. {
  199696. const uint8* src = srcRow;
  199697. srcRow += (width << 2);
  199698. uint8* dest = destRow;
  199699. destRow += destData.lineStride;
  199700. if (hasAlphaChan)
  199701. {
  199702. for (int i = (int) width; --i >= 0;)
  199703. {
  199704. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  199705. ((PixelARGB*) dest)->premultiply();
  199706. dest += destData.pixelStride;
  199707. src += 4;
  199708. }
  199709. }
  199710. else
  199711. {
  199712. for (int i = (int) width; --i >= 0;)
  199713. {
  199714. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  199715. dest += destData.pixelStride;
  199716. src += 4;
  199717. }
  199718. }
  199719. }
  199720. }
  199721. return image;
  199722. }
  199723. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  199724. {
  199725. using namespace pnglibNamespace;
  199726. const int width = image.getWidth();
  199727. const int height = image.getHeight();
  199728. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  199729. if (pngWriteStruct == 0)
  199730. return false;
  199731. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  199732. if (pngInfoStruct == 0)
  199733. {
  199734. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  199735. return false;
  199736. }
  199737. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  199738. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  199739. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  199740. : PNG_COLOR_TYPE_RGB,
  199741. PNG_INTERLACE_NONE,
  199742. PNG_COMPRESSION_TYPE_BASE,
  199743. PNG_FILTER_TYPE_BASE);
  199744. HeapBlock <uint8> rowData (width * 4);
  199745. png_color_8 sig_bit;
  199746. sig_bit.red = 8;
  199747. sig_bit.green = 8;
  199748. sig_bit.blue = 8;
  199749. sig_bit.alpha = 8;
  199750. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  199751. png_write_info (pngWriteStruct, pngInfoStruct);
  199752. png_set_shift (pngWriteStruct, &sig_bit);
  199753. png_set_packing (pngWriteStruct);
  199754. const Image::BitmapData srcData (image, 0, 0, width, height);
  199755. for (int y = 0; y < height; ++y)
  199756. {
  199757. uint8* dst = rowData;
  199758. const uint8* src = srcData.getLinePointer (y);
  199759. if (image.hasAlphaChannel())
  199760. {
  199761. for (int i = width; --i >= 0;)
  199762. {
  199763. PixelARGB p (*(const PixelARGB*) src);
  199764. p.unpremultiply();
  199765. *dst++ = p.getRed();
  199766. *dst++ = p.getGreen();
  199767. *dst++ = p.getBlue();
  199768. *dst++ = p.getAlpha();
  199769. src += srcData.pixelStride;
  199770. }
  199771. }
  199772. else
  199773. {
  199774. for (int i = width; --i >= 0;)
  199775. {
  199776. *dst++ = ((const PixelRGB*) src)->getRed();
  199777. *dst++ = ((const PixelRGB*) src)->getGreen();
  199778. *dst++ = ((const PixelRGB*) src)->getBlue();
  199779. src += srcData.pixelStride;
  199780. }
  199781. }
  199782. png_write_rows (pngWriteStruct, &rowData, 1);
  199783. }
  199784. png_write_end (pngWriteStruct, pngInfoStruct);
  199785. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  199786. out.flush();
  199787. return true;
  199788. }
  199789. END_JUCE_NAMESPACE
  199790. /*** End of inlined file: juce_PNGLoader.cpp ***/
  199791. #endif
  199792. //==============================================================================
  199793. #if JUCE_BUILD_NATIVE
  199794. #if JUCE_WINDOWS
  199795. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  199796. /*
  199797. This file wraps together all the win32-specific code, so that
  199798. we can include all the native headers just once, and compile all our
  199799. platform-specific stuff in one big lump, keeping it out of the way of
  199800. the rest of the codebase.
  199801. */
  199802. #if JUCE_WINDOWS
  199803. BEGIN_JUCE_NAMESPACE
  199804. #define JUCE_INCLUDED_FILE 1
  199805. // Now include the actual code files..
  199806. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  199807. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199808. // compiled on its own).
  199809. #if JUCE_INCLUDED_FILE
  199810. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  199811. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199812. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199813. #ifndef DOXYGEN
  199814. // use with DynamicLibraryLoader to simplify importing functions
  199815. //
  199816. // functionName: function to import
  199817. // localFunctionName: name you want to use to actually call it (must be different)
  199818. // returnType: the return type
  199819. // object: the DynamicLibraryLoader to use
  199820. // params: list of params (bracketed)
  199821. //
  199822. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  199823. typedef returnType (WINAPI *type##localFunctionName) params; \
  199824. type##localFunctionName localFunctionName \
  199825. = (type##localFunctionName)object.findProcAddress (#functionName);
  199826. // loads and unloads a DLL automatically
  199827. class JUCE_API DynamicLibraryLoader
  199828. {
  199829. public:
  199830. DynamicLibraryLoader (const String& name);
  199831. ~DynamicLibraryLoader();
  199832. void* findProcAddress (const String& functionName);
  199833. private:
  199834. void* libHandle;
  199835. };
  199836. #endif
  199837. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199838. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  199839. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199840. {
  199841. libHandle = LoadLibrary (name);
  199842. }
  199843. DynamicLibraryLoader::~DynamicLibraryLoader()
  199844. {
  199845. FreeLibrary ((HMODULE) libHandle);
  199846. }
  199847. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199848. {
  199849. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  199850. }
  199851. #endif
  199852. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  199853. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  199854. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199855. // compiled on its own).
  199856. #if JUCE_INCLUDED_FILE
  199857. extern void juce_initialiseThreadEvents();
  199858. void Logger::outputDebugString (const String& text) throw()
  199859. {
  199860. OutputDebugString (text + "\n");
  199861. }
  199862. static int64 hiResTicksPerSecond;
  199863. static double hiResTicksScaleFactor;
  199864. #if JUCE_USE_INTRINSICS
  199865. // CPU info functions using intrinsics...
  199866. #pragma intrinsic (__cpuid)
  199867. #pragma intrinsic (__rdtsc)
  199868. const String SystemStats::getCpuVendor() throw()
  199869. {
  199870. int info [4];
  199871. __cpuid (info, 0);
  199872. char v [12];
  199873. memcpy (v, info + 1, 4);
  199874. memcpy (v + 4, info + 3, 4);
  199875. memcpy (v + 8, info + 2, 4);
  199876. return String (v, 12);
  199877. }
  199878. #else
  199879. // CPU info functions using old fashioned inline asm...
  199880. static void juce_getCpuVendor (char* const v)
  199881. {
  199882. int vendor[4];
  199883. zeromem (vendor, 16);
  199884. #ifdef JUCE_64BIT
  199885. #else
  199886. #ifndef __MINGW32__
  199887. __try
  199888. #endif
  199889. {
  199890. #if JUCE_GCC
  199891. unsigned int dummy = 0;
  199892. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  199893. #else
  199894. __asm
  199895. {
  199896. mov eax, 0
  199897. cpuid
  199898. mov [vendor], ebx
  199899. mov [vendor + 4], edx
  199900. mov [vendor + 8], ecx
  199901. }
  199902. #endif
  199903. }
  199904. #ifndef __MINGW32__
  199905. __except (EXCEPTION_EXECUTE_HANDLER)
  199906. {
  199907. *v = 0;
  199908. }
  199909. #endif
  199910. #endif
  199911. memcpy (v, vendor, 16);
  199912. }
  199913. const String SystemStats::getCpuVendor() throw()
  199914. {
  199915. char v [16];
  199916. juce_getCpuVendor (v);
  199917. return String (v, 16);
  199918. }
  199919. #endif
  199920. struct CPUFlags
  199921. {
  199922. bool hasMMX : 1;
  199923. bool hasSSE : 1;
  199924. bool hasSSE2 : 1;
  199925. bool has3DNow : 1;
  199926. };
  199927. static CPUFlags cpuFlags;
  199928. bool SystemStats::hasMMX() throw()
  199929. {
  199930. return cpuFlags.hasMMX;
  199931. }
  199932. bool SystemStats::hasSSE() throw()
  199933. {
  199934. return cpuFlags.hasSSE;
  199935. }
  199936. bool SystemStats::hasSSE2() throw()
  199937. {
  199938. return cpuFlags.hasSSE2;
  199939. }
  199940. bool SystemStats::has3DNow() throw()
  199941. {
  199942. return cpuFlags.has3DNow;
  199943. }
  199944. void SystemStats::initialiseStats() throw()
  199945. {
  199946. juce_initialiseThreadEvents();
  199947. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  199948. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  199949. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  199950. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  199951. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  199952. #else
  199953. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  199954. #endif
  199955. LARGE_INTEGER f;
  199956. QueryPerformanceFrequency (&f);
  199957. hiResTicksPerSecond = f.QuadPart;
  199958. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  199959. String s (SystemStats::getJUCEVersion());
  199960. #if JUCE_DEBUG
  199961. const MMRESULT res = timeBeginPeriod (1);
  199962. jassert (res == TIMERR_NOERROR);
  199963. #else
  199964. timeBeginPeriod (1);
  199965. #endif
  199966. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199967. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  199968. #endif
  199969. }
  199970. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  199971. {
  199972. OSVERSIONINFO info;
  199973. info.dwOSVersionInfoSize = sizeof (info);
  199974. GetVersionEx (&info);
  199975. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  199976. {
  199977. switch (info.dwMajorVersion)
  199978. {
  199979. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  199980. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  199981. default: jassertfalse; break; // !! not a supported OS!
  199982. }
  199983. }
  199984. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  199985. {
  199986. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  199987. return Win98;
  199988. }
  199989. return UnknownOS;
  199990. }
  199991. const String SystemStats::getOperatingSystemName() throw()
  199992. {
  199993. const char* name = "Unknown OS";
  199994. switch (getOperatingSystemType())
  199995. {
  199996. case Windows7: name = "Windows 7"; break;
  199997. case WinVista: name = "Windows Vista"; break;
  199998. case WinXP: name = "Windows XP"; break;
  199999. case Win2000: name = "Windows 2000"; break;
  200000. case Win98: name = "Windows 98"; break;
  200001. default: jassertfalse; break; // !! new type of OS?
  200002. }
  200003. return name;
  200004. }
  200005. bool SystemStats::isOperatingSystem64Bit() throw()
  200006. {
  200007. #ifdef _WIN64
  200008. return true;
  200009. #else
  200010. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  200011. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  200012. BOOL isWow64 = FALSE;
  200013. return (fnIsWow64Process != 0)
  200014. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  200015. && (isWow64 != FALSE);
  200016. #endif
  200017. }
  200018. int SystemStats::getMemorySizeInMegabytes() throw()
  200019. {
  200020. MEMORYSTATUSEX mem;
  200021. mem.dwLength = sizeof (mem);
  200022. GlobalMemoryStatusEx (&mem);
  200023. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  200024. }
  200025. int SystemStats::getNumCpus() throw()
  200026. {
  200027. SYSTEM_INFO systemInfo;
  200028. GetSystemInfo (&systemInfo);
  200029. return systemInfo.dwNumberOfProcessors;
  200030. }
  200031. uint32 juce_millisecondsSinceStartup() throw()
  200032. {
  200033. return (uint32) GetTickCount();
  200034. }
  200035. int64 Time::getHighResolutionTicks() throw()
  200036. {
  200037. LARGE_INTEGER ticks;
  200038. QueryPerformanceCounter (&ticks);
  200039. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  200040. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  200041. // fix for a very obscure PCI hardware bug that can make the counter
  200042. // sometimes jump forwards by a few seconds..
  200043. static int64 hiResTicksOffset = 0;
  200044. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  200045. if (offsetDrift > (hiResTicksPerSecond >> 1))
  200046. hiResTicksOffset = newOffset;
  200047. return ticks.QuadPart + hiResTicksOffset;
  200048. }
  200049. double Time::getMillisecondCounterHiRes() throw()
  200050. {
  200051. return getHighResolutionTicks() * hiResTicksScaleFactor;
  200052. }
  200053. int64 Time::getHighResolutionTicksPerSecond() throw()
  200054. {
  200055. return hiResTicksPerSecond;
  200056. }
  200057. int64 SystemStats::getClockCycleCounter() throw()
  200058. {
  200059. #if JUCE_USE_INTRINSICS
  200060. // MS intrinsics version...
  200061. return __rdtsc();
  200062. #elif JUCE_GCC
  200063. // GNU inline asm version...
  200064. unsigned int hi = 0, lo = 0;
  200065. __asm__ __volatile__ (
  200066. "xor %%eax, %%eax \n\
  200067. xor %%edx, %%edx \n\
  200068. rdtsc \n\
  200069. movl %%eax, %[lo] \n\
  200070. movl %%edx, %[hi]"
  200071. :
  200072. : [hi] "m" (hi),
  200073. [lo] "m" (lo)
  200074. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  200075. return (int64) ((((uint64) hi) << 32) | lo);
  200076. #else
  200077. // MSVC inline asm version...
  200078. unsigned int hi = 0, lo = 0;
  200079. __asm
  200080. {
  200081. xor eax, eax
  200082. xor edx, edx
  200083. rdtsc
  200084. mov lo, eax
  200085. mov hi, edx
  200086. }
  200087. return (int64) ((((uint64) hi) << 32) | lo);
  200088. #endif
  200089. }
  200090. int SystemStats::getCpuSpeedInMegaherz() throw()
  200091. {
  200092. const int64 cycles = SystemStats::getClockCycleCounter();
  200093. const uint32 millis = Time::getMillisecondCounter();
  200094. int lastResult = 0;
  200095. for (;;)
  200096. {
  200097. int n = 1000000;
  200098. while (--n > 0) {}
  200099. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  200100. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  200101. if (millisElapsed > 80)
  200102. {
  200103. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  200104. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  200105. return newResult;
  200106. lastResult = newResult;
  200107. }
  200108. }
  200109. }
  200110. bool Time::setSystemTimeToThisTime() const throw()
  200111. {
  200112. SYSTEMTIME st;
  200113. st.wDayOfWeek = 0;
  200114. st.wYear = (WORD) getYear();
  200115. st.wMonth = (WORD) (getMonth() + 1);
  200116. st.wDay = (WORD) getDayOfMonth();
  200117. st.wHour = (WORD) getHours();
  200118. st.wMinute = (WORD) getMinutes();
  200119. st.wSecond = (WORD) getSeconds();
  200120. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  200121. // do this twice because of daylight saving conversion problems - the
  200122. // first one sets it up, the second one kicks it in.
  200123. return SetLocalTime (&st) != 0
  200124. && SetLocalTime (&st) != 0;
  200125. }
  200126. int SystemStats::getPageSize() throw()
  200127. {
  200128. SYSTEM_INFO systemInfo;
  200129. GetSystemInfo (&systemInfo);
  200130. return systemInfo.dwPageSize;
  200131. }
  200132. const String SystemStats::getLogonName()
  200133. {
  200134. TCHAR text [256];
  200135. DWORD len = numElementsInArray (text) - 2;
  200136. zerostruct (text);
  200137. GetUserName (text, &len);
  200138. return String (text, len);
  200139. }
  200140. const String SystemStats::getFullUserName()
  200141. {
  200142. return getLogonName();
  200143. }
  200144. #endif
  200145. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  200146. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  200147. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200148. // compiled on its own).
  200149. #if JUCE_INCLUDED_FILE
  200150. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200151. extern HWND juce_messageWindowHandle;
  200152. #endif
  200153. #if ! JUCE_USE_INTRINSICS
  200154. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  200155. // older ones we have to actually call the ops as win32 functions..
  200156. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  200157. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  200158. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  200159. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  200160. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  200161. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  200162. {
  200163. jassertfalse; // This operation isn't available in old MS compiler versions!
  200164. __int64 oldValue = *value;
  200165. if (oldValue == valueToCompare)
  200166. *value = newValue;
  200167. return oldValue;
  200168. }
  200169. #endif
  200170. CriticalSection::CriticalSection() throw()
  200171. {
  200172. // (just to check the MS haven't changed this structure and broken things...)
  200173. #if _MSC_VER >= 1400
  200174. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  200175. #else
  200176. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  200177. #endif
  200178. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  200179. }
  200180. CriticalSection::~CriticalSection() throw()
  200181. {
  200182. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  200183. }
  200184. void CriticalSection::enter() const throw()
  200185. {
  200186. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  200187. }
  200188. bool CriticalSection::tryEnter() const throw()
  200189. {
  200190. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  200191. }
  200192. void CriticalSection::exit() const throw()
  200193. {
  200194. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  200195. }
  200196. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  200197. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  200198. {
  200199. }
  200200. WaitableEvent::~WaitableEvent() throw()
  200201. {
  200202. CloseHandle (internal);
  200203. }
  200204. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  200205. {
  200206. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  200207. }
  200208. void WaitableEvent::signal() const throw()
  200209. {
  200210. SetEvent (internal);
  200211. }
  200212. void WaitableEvent::reset() const throw()
  200213. {
  200214. ResetEvent (internal);
  200215. }
  200216. void JUCE_API juce_threadEntryPoint (void*);
  200217. static unsigned int __stdcall threadEntryProc (void* userData)
  200218. {
  200219. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200220. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  200221. GetCurrentThreadId(), TRUE);
  200222. #endif
  200223. juce_threadEntryPoint (userData);
  200224. _endthreadex (0);
  200225. return 0;
  200226. }
  200227. void juce_CloseThreadHandle (void* handle)
  200228. {
  200229. CloseHandle ((HANDLE) handle);
  200230. }
  200231. void* juce_createThread (void* userData)
  200232. {
  200233. unsigned int threadId;
  200234. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  200235. }
  200236. void juce_killThread (void* handle)
  200237. {
  200238. if (handle != 0)
  200239. {
  200240. #if JUCE_DEBUG
  200241. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  200242. #endif
  200243. TerminateThread (handle, 0);
  200244. }
  200245. }
  200246. void juce_setCurrentThreadName (const String& name)
  200247. {
  200248. #if JUCE_DEBUG && JUCE_MSVC
  200249. struct
  200250. {
  200251. DWORD dwType;
  200252. LPCSTR szName;
  200253. DWORD dwThreadID;
  200254. DWORD dwFlags;
  200255. } info;
  200256. info.dwType = 0x1000;
  200257. info.szName = name.toCString();
  200258. info.dwThreadID = GetCurrentThreadId();
  200259. info.dwFlags = 0;
  200260. __try
  200261. {
  200262. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  200263. }
  200264. __except (EXCEPTION_CONTINUE_EXECUTION)
  200265. {}
  200266. #else
  200267. (void) name;
  200268. #endif
  200269. }
  200270. Thread::ThreadID Thread::getCurrentThreadId()
  200271. {
  200272. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  200273. }
  200274. // priority 1 to 10 where 5=normal, 1=low
  200275. bool juce_setThreadPriority (void* threadHandle, int priority)
  200276. {
  200277. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  200278. if (priority < 1)
  200279. pri = THREAD_PRIORITY_IDLE;
  200280. else if (priority < 2)
  200281. pri = THREAD_PRIORITY_LOWEST;
  200282. else if (priority < 5)
  200283. pri = THREAD_PRIORITY_BELOW_NORMAL;
  200284. else if (priority < 7)
  200285. pri = THREAD_PRIORITY_NORMAL;
  200286. else if (priority < 9)
  200287. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  200288. else if (priority < 10)
  200289. pri = THREAD_PRIORITY_HIGHEST;
  200290. if (threadHandle == 0)
  200291. threadHandle = GetCurrentThread();
  200292. return SetThreadPriority (threadHandle, pri) != FALSE;
  200293. }
  200294. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  200295. {
  200296. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  200297. }
  200298. static HANDLE sleepEvent = 0;
  200299. void juce_initialiseThreadEvents()
  200300. {
  200301. if (sleepEvent == 0)
  200302. #if JUCE_DEBUG
  200303. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  200304. #else
  200305. sleepEvent = CreateEvent (0, 0, 0, 0);
  200306. #endif
  200307. }
  200308. void Thread::yield()
  200309. {
  200310. Sleep (0);
  200311. }
  200312. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  200313. {
  200314. if (millisecs >= 10)
  200315. {
  200316. Sleep (millisecs);
  200317. }
  200318. else
  200319. {
  200320. jassert (sleepEvent != 0);
  200321. // unlike Sleep() this is guaranteed to return to the current thread after
  200322. // the time expires, so we'll use this for short waits, which are more likely
  200323. // to need to be accurate
  200324. WaitForSingleObject (sleepEvent, millisecs);
  200325. }
  200326. }
  200327. static int lastProcessPriority = -1;
  200328. // called by WindowDriver because Windows does wierd things to process priority
  200329. // when you swap apps, and this forces an update when the app is brought to the front.
  200330. void juce_repeatLastProcessPriority()
  200331. {
  200332. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  200333. {
  200334. DWORD p;
  200335. switch (lastProcessPriority)
  200336. {
  200337. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  200338. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  200339. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  200340. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  200341. default: jassertfalse; return; // bad priority value
  200342. }
  200343. SetPriorityClass (GetCurrentProcess(), p);
  200344. }
  200345. }
  200346. void Process::setPriority (ProcessPriority prior)
  200347. {
  200348. if (lastProcessPriority != (int) prior)
  200349. {
  200350. lastProcessPriority = (int) prior;
  200351. juce_repeatLastProcessPriority();
  200352. }
  200353. }
  200354. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  200355. {
  200356. return IsDebuggerPresent() != FALSE;
  200357. }
  200358. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  200359. {
  200360. return juce_isRunningUnderDebugger();
  200361. }
  200362. void Process::raisePrivilege()
  200363. {
  200364. jassertfalse // xxx not implemented
  200365. }
  200366. void Process::lowerPrivilege()
  200367. {
  200368. jassertfalse // xxx not implemented
  200369. }
  200370. void Process::terminate()
  200371. {
  200372. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  200373. _CrtDumpMemoryLeaks();
  200374. #endif
  200375. // bullet in the head in case there's a problem shutting down..
  200376. ExitProcess (0);
  200377. }
  200378. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  200379. {
  200380. void* result = 0;
  200381. JUCE_TRY
  200382. {
  200383. result = LoadLibrary (name);
  200384. }
  200385. JUCE_CATCH_ALL
  200386. return result;
  200387. }
  200388. void PlatformUtilities::freeDynamicLibrary (void* h)
  200389. {
  200390. JUCE_TRY
  200391. {
  200392. if (h != 0)
  200393. FreeLibrary ((HMODULE) h);
  200394. }
  200395. JUCE_CATCH_ALL
  200396. }
  200397. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  200398. {
  200399. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  200400. }
  200401. class InterProcessLock::Pimpl
  200402. {
  200403. public:
  200404. Pimpl (const String& name, const int timeOutMillisecs)
  200405. : handle (0), refCount (1)
  200406. {
  200407. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  200408. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  200409. {
  200410. if (timeOutMillisecs == 0)
  200411. {
  200412. close();
  200413. return;
  200414. }
  200415. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  200416. {
  200417. case WAIT_OBJECT_0:
  200418. case WAIT_ABANDONED:
  200419. break;
  200420. case WAIT_TIMEOUT:
  200421. default:
  200422. close();
  200423. break;
  200424. }
  200425. }
  200426. }
  200427. ~Pimpl()
  200428. {
  200429. close();
  200430. }
  200431. void close()
  200432. {
  200433. if (handle != 0)
  200434. {
  200435. ReleaseMutex (handle);
  200436. CloseHandle (handle);
  200437. handle = 0;
  200438. }
  200439. }
  200440. HANDLE handle;
  200441. int refCount;
  200442. };
  200443. InterProcessLock::InterProcessLock (const String& name_)
  200444. : name (name_)
  200445. {
  200446. }
  200447. InterProcessLock::~InterProcessLock()
  200448. {
  200449. }
  200450. bool InterProcessLock::enter (const int timeOutMillisecs)
  200451. {
  200452. const ScopedLock sl (lock);
  200453. if (pimpl == 0)
  200454. {
  200455. pimpl = new Pimpl (name, timeOutMillisecs);
  200456. if (pimpl->handle == 0)
  200457. pimpl = 0;
  200458. }
  200459. else
  200460. {
  200461. pimpl->refCount++;
  200462. }
  200463. return pimpl != 0;
  200464. }
  200465. void InterProcessLock::exit()
  200466. {
  200467. const ScopedLock sl (lock);
  200468. // Trying to release the lock too many times!
  200469. jassert (pimpl != 0);
  200470. if (pimpl != 0 && --(pimpl->refCount) == 0)
  200471. pimpl = 0;
  200472. }
  200473. #endif
  200474. /*** End of inlined file: juce_win32_Threads.cpp ***/
  200475. /*** Start of inlined file: juce_win32_Files.cpp ***/
  200476. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200477. // compiled on its own).
  200478. #if JUCE_INCLUDED_FILE
  200479. #ifndef CSIDL_MYMUSIC
  200480. #define CSIDL_MYMUSIC 0x000d
  200481. #endif
  200482. #ifndef CSIDL_MYVIDEO
  200483. #define CSIDL_MYVIDEO 0x000e
  200484. #endif
  200485. #ifndef INVALID_FILE_ATTRIBUTES
  200486. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  200487. #endif
  200488. const juce_wchar File::separator = '\\';
  200489. const String File::separatorString ("\\");
  200490. bool File::exists() const
  200491. {
  200492. return fullPath.isNotEmpty()
  200493. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  200494. }
  200495. bool File::existsAsFile() const
  200496. {
  200497. return fullPath.isNotEmpty()
  200498. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  200499. }
  200500. bool File::isDirectory() const
  200501. {
  200502. const DWORD attr = GetFileAttributes (fullPath);
  200503. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  200504. }
  200505. bool File::hasWriteAccess() const
  200506. {
  200507. if (exists())
  200508. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  200509. // on windows, it seems that even read-only directories can still be written into,
  200510. // so checking the parent directory's permissions would return the wrong result..
  200511. return true;
  200512. }
  200513. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  200514. {
  200515. DWORD attr = GetFileAttributes (fullPath);
  200516. if (attr == INVALID_FILE_ATTRIBUTES)
  200517. return false;
  200518. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  200519. return true;
  200520. if (shouldBeReadOnly)
  200521. attr |= FILE_ATTRIBUTE_READONLY;
  200522. else
  200523. attr &= ~FILE_ATTRIBUTE_READONLY;
  200524. return SetFileAttributes (fullPath, attr) != FALSE;
  200525. }
  200526. bool File::isHidden() const
  200527. {
  200528. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  200529. }
  200530. bool File::deleteFile() const
  200531. {
  200532. if (! exists())
  200533. return true;
  200534. else if (isDirectory())
  200535. return RemoveDirectory (fullPath) != 0;
  200536. else
  200537. return DeleteFile (fullPath) != 0;
  200538. }
  200539. bool File::moveToTrash() const
  200540. {
  200541. if (! exists())
  200542. return true;
  200543. SHFILEOPSTRUCT fos;
  200544. zerostruct (fos);
  200545. // The string we pass in must be double null terminated..
  200546. String doubleNullTermPath (getFullPathName() + " ");
  200547. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  200548. p [getFullPathName().length()] = 0;
  200549. fos.wFunc = FO_DELETE;
  200550. fos.pFrom = p;
  200551. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  200552. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  200553. return SHFileOperation (&fos) == 0;
  200554. }
  200555. bool File::copyInternal (const File& dest) const
  200556. {
  200557. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  200558. }
  200559. bool File::moveInternal (const File& dest) const
  200560. {
  200561. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  200562. }
  200563. void File::createDirectoryInternal (const String& fileName) const
  200564. {
  200565. CreateDirectory (fileName, 0);
  200566. }
  200567. // return 0 if not possible
  200568. void* juce_fileOpen (const File& file, bool forWriting)
  200569. {
  200570. HANDLE h;
  200571. if (forWriting)
  200572. {
  200573. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  200574. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  200575. if (h != INVALID_HANDLE_VALUE)
  200576. SetFilePointer (h, 0, 0, FILE_END);
  200577. else
  200578. h = 0;
  200579. }
  200580. else
  200581. {
  200582. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  200583. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  200584. if (h == INVALID_HANDLE_VALUE)
  200585. h = 0;
  200586. }
  200587. return h;
  200588. }
  200589. void juce_fileClose (void* handle)
  200590. {
  200591. CloseHandle (handle);
  200592. }
  200593. int juce_fileRead (void* handle, void* buffer, int size)
  200594. {
  200595. DWORD num = 0;
  200596. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  200597. return (int) num;
  200598. }
  200599. int juce_fileWrite (void* handle, const void* buffer, int size)
  200600. {
  200601. DWORD num;
  200602. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  200603. return (int) num;
  200604. }
  200605. int64 juce_fileSetPosition (void* handle, int64 pos)
  200606. {
  200607. LARGE_INTEGER li;
  200608. li.QuadPart = pos;
  200609. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  200610. return li.QuadPart;
  200611. }
  200612. int64 FileOutputStream::getPositionInternal() const
  200613. {
  200614. if (fileHandle == 0)
  200615. return -1;
  200616. LARGE_INTEGER li;
  200617. li.QuadPart = 0;
  200618. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  200619. return jmax ((int64) 0, li.QuadPart);
  200620. }
  200621. void FileOutputStream::flushInternal()
  200622. {
  200623. if (fileHandle != 0)
  200624. FlushFileBuffers ((HANDLE) fileHandle);
  200625. }
  200626. int64 File::getSize() const
  200627. {
  200628. WIN32_FILE_ATTRIBUTE_DATA attributes;
  200629. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  200630. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  200631. return 0;
  200632. }
  200633. static int64 fileTimeToTime (const FILETIME* const ft)
  200634. {
  200635. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  200636. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  200637. }
  200638. static void timeToFileTime (const int64 time, FILETIME* const ft)
  200639. {
  200640. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  200641. }
  200642. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  200643. {
  200644. WIN32_FILE_ATTRIBUTE_DATA attributes;
  200645. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  200646. {
  200647. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  200648. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  200649. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  200650. }
  200651. else
  200652. {
  200653. creationTime = accessTime = modificationTime = 0;
  200654. }
  200655. }
  200656. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  200657. {
  200658. void* const h = juce_fileOpen (fullPath, true);
  200659. bool ok = false;
  200660. if (h != 0)
  200661. {
  200662. FILETIME m, a, c;
  200663. timeToFileTime (modificationTime, &m);
  200664. timeToFileTime (accessTime, &a);
  200665. timeToFileTime (creationTime, &c);
  200666. ok = SetFileTime ((HANDLE) h,
  200667. creationTime > 0 ? &c : 0,
  200668. accessTime > 0 ? &a : 0,
  200669. modificationTime > 0 ? &m : 0) != 0;
  200670. juce_fileClose (h);
  200671. }
  200672. return ok;
  200673. }
  200674. void File::findFileSystemRoots (Array<File>& destArray)
  200675. {
  200676. TCHAR buffer [2048];
  200677. buffer[0] = 0;
  200678. buffer[1] = 0;
  200679. GetLogicalDriveStrings (2048, buffer);
  200680. const TCHAR* n = buffer;
  200681. StringArray roots;
  200682. while (*n != 0)
  200683. {
  200684. roots.add (String (n));
  200685. while (*n++ != 0)
  200686. {}
  200687. }
  200688. roots.sort (true);
  200689. for (int i = 0; i < roots.size(); ++i)
  200690. destArray.add (roots [i]);
  200691. }
  200692. static const String getDriveFromPath (const String& path)
  200693. {
  200694. if (path.isNotEmpty() && path[1] == ':')
  200695. return path.substring (0, 2) + '\\';
  200696. return path;
  200697. }
  200698. const String File::getVolumeLabel() const
  200699. {
  200700. TCHAR dest[64];
  200701. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  200702. numElementsInArray (dest), 0, 0, 0, 0, 0))
  200703. dest[0] = 0;
  200704. return dest;
  200705. }
  200706. int File::getVolumeSerialNumber() const
  200707. {
  200708. TCHAR dest[64];
  200709. DWORD serialNum;
  200710. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  200711. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  200712. return 0;
  200713. return (int) serialNum;
  200714. }
  200715. static int64 getDiskSpaceInfo (const String& path, const bool total)
  200716. {
  200717. ULARGE_INTEGER spc, tot, totFree;
  200718. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  200719. return total ? (int64) tot.QuadPart
  200720. : (int64) spc.QuadPart;
  200721. return 0;
  200722. }
  200723. int64 File::getBytesFreeOnVolume() const
  200724. {
  200725. return getDiskSpaceInfo (getFullPathName(), false);
  200726. }
  200727. int64 File::getVolumeTotalSize() const
  200728. {
  200729. return getDiskSpaceInfo (getFullPathName(), true);
  200730. }
  200731. static unsigned int getWindowsDriveType (const String& path)
  200732. {
  200733. return GetDriveType (getDriveFromPath (path));
  200734. }
  200735. bool File::isOnCDRomDrive() const
  200736. {
  200737. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  200738. }
  200739. bool File::isOnHardDisk() const
  200740. {
  200741. if (fullPath.isEmpty())
  200742. return false;
  200743. const unsigned int n = getWindowsDriveType (getFullPathName());
  200744. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  200745. return n != DRIVE_REMOVABLE;
  200746. else
  200747. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  200748. }
  200749. bool File::isOnRemovableDrive() const
  200750. {
  200751. if (fullPath.isEmpty())
  200752. return false;
  200753. const unsigned int n = getWindowsDriveType (getFullPathName());
  200754. return n == DRIVE_CDROM
  200755. || n == DRIVE_REMOTE
  200756. || n == DRIVE_REMOVABLE
  200757. || n == DRIVE_RAMDISK;
  200758. }
  200759. static const File juce_getSpecialFolderPath (int type)
  200760. {
  200761. WCHAR path [MAX_PATH + 256];
  200762. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  200763. return File (String (path));
  200764. return File::nonexistent;
  200765. }
  200766. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  200767. {
  200768. int csidlType = 0;
  200769. switch (type)
  200770. {
  200771. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  200772. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  200773. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  200774. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  200775. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  200776. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  200777. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  200778. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  200779. case tempDirectory:
  200780. {
  200781. WCHAR dest [2048];
  200782. dest[0] = 0;
  200783. GetTempPath (numElementsInArray (dest), dest);
  200784. return File (String (dest));
  200785. }
  200786. case invokedExecutableFile:
  200787. case currentExecutableFile:
  200788. case currentApplicationFile:
  200789. {
  200790. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200791. WCHAR dest [MAX_PATH + 256];
  200792. dest[0] = 0;
  200793. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  200794. return File (String (dest));
  200795. }
  200796. break;
  200797. default:
  200798. jassertfalse // unknown type?
  200799. return File::nonexistent;
  200800. }
  200801. return juce_getSpecialFolderPath (csidlType);
  200802. }
  200803. const File File::getCurrentWorkingDirectory()
  200804. {
  200805. WCHAR dest [MAX_PATH + 256];
  200806. dest[0] = 0;
  200807. GetCurrentDirectory (numElementsInArray (dest), dest);
  200808. return File (String (dest));
  200809. }
  200810. bool File::setAsCurrentWorkingDirectory() const
  200811. {
  200812. return SetCurrentDirectory (getFullPathName()) != FALSE;
  200813. }
  200814. const String File::getVersion() const
  200815. {
  200816. String result;
  200817. DWORD handle = 0;
  200818. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  200819. HeapBlock<char> buffer;
  200820. buffer.calloc (bufferSize);
  200821. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  200822. {
  200823. VS_FIXEDFILEINFO* vffi;
  200824. UINT len = 0;
  200825. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  200826. {
  200827. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  200828. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  200829. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  200830. << (int) LOWORD (vffi->dwFileVersionLS);
  200831. }
  200832. }
  200833. return result;
  200834. }
  200835. const File File::getLinkedTarget() const
  200836. {
  200837. File result (*this);
  200838. String p (getFullPathName());
  200839. if (! exists())
  200840. p += ".lnk";
  200841. else if (getFileExtension() != ".lnk")
  200842. return result;
  200843. ComSmartPtr <IShellLink> shellLink;
  200844. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  200845. {
  200846. ComSmartPtr <IPersistFile> persistFile;
  200847. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  200848. {
  200849. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  200850. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  200851. {
  200852. WIN32_FIND_DATA winFindData;
  200853. WCHAR resolvedPath [MAX_PATH];
  200854. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  200855. result = File (resolvedPath);
  200856. }
  200857. }
  200858. }
  200859. return result;
  200860. }
  200861. class DirectoryIterator::NativeIterator::Pimpl
  200862. {
  200863. public:
  200864. Pimpl (const File& directory, const String& wildCard)
  200865. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  200866. handle (INVALID_HANDLE_VALUE)
  200867. {
  200868. }
  200869. ~Pimpl()
  200870. {
  200871. if (handle != INVALID_HANDLE_VALUE)
  200872. FindClose (handle);
  200873. }
  200874. bool next (String& filenameFound,
  200875. bool* const isDir, bool* const isHidden, int64* const fileSize,
  200876. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  200877. {
  200878. WIN32_FIND_DATA findData;
  200879. if (handle == INVALID_HANDLE_VALUE)
  200880. {
  200881. handle = FindFirstFile (directoryWithWildCard, &findData);
  200882. if (handle == INVALID_HANDLE_VALUE)
  200883. return false;
  200884. }
  200885. else
  200886. {
  200887. if (FindNextFile (handle, &findData) == 0)
  200888. return false;
  200889. }
  200890. filenameFound = findData.cFileName;
  200891. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  200892. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  200893. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  200894. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  200895. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  200896. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  200897. return true;
  200898. }
  200899. juce_UseDebuggingNewOperator
  200900. private:
  200901. const String directoryWithWildCard;
  200902. HANDLE handle;
  200903. Pimpl (const Pimpl&);
  200904. Pimpl& operator= (const Pimpl&);
  200905. };
  200906. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  200907. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  200908. {
  200909. }
  200910. DirectoryIterator::NativeIterator::~NativeIterator()
  200911. {
  200912. }
  200913. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  200914. bool* const isDir, bool* const isHidden, int64* const fileSize,
  200915. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  200916. {
  200917. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  200918. }
  200919. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  200920. {
  200921. HINSTANCE hInstance = 0;
  200922. JUCE_TRY
  200923. {
  200924. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  200925. }
  200926. JUCE_CATCH_ALL
  200927. return hInstance > (HINSTANCE) 32;
  200928. }
  200929. void File::revealToUser() const
  200930. {
  200931. if (isDirectory())
  200932. startAsProcess();
  200933. else if (getParentDirectory().exists())
  200934. getParentDirectory().startAsProcess();
  200935. }
  200936. class NamedPipeInternal
  200937. {
  200938. public:
  200939. NamedPipeInternal (const String& file, const bool isPipe_)
  200940. : pipeH (0),
  200941. cancelEvent (0),
  200942. connected (false),
  200943. isPipe (isPipe_)
  200944. {
  200945. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  200946. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  200947. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  200948. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  200949. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  200950. }
  200951. ~NamedPipeInternal()
  200952. {
  200953. disconnectPipe();
  200954. if (pipeH != 0)
  200955. CloseHandle (pipeH);
  200956. CloseHandle (cancelEvent);
  200957. }
  200958. bool connect (const int timeOutMs)
  200959. {
  200960. if (! isPipe)
  200961. return true;
  200962. if (! connected)
  200963. {
  200964. OVERLAPPED over;
  200965. zerostruct (over);
  200966. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200967. if (ConnectNamedPipe (pipeH, &over))
  200968. {
  200969. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  200970. }
  200971. else
  200972. {
  200973. const int err = GetLastError();
  200974. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  200975. {
  200976. HANDLE handles[] = { over.hEvent, cancelEvent };
  200977. if (WaitForMultipleObjects (2, handles, FALSE,
  200978. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  200979. connected = true;
  200980. }
  200981. else if (err == ERROR_PIPE_CONNECTED)
  200982. {
  200983. connected = true;
  200984. }
  200985. }
  200986. CloseHandle (over.hEvent);
  200987. }
  200988. return connected;
  200989. }
  200990. void disconnectPipe()
  200991. {
  200992. if (connected)
  200993. {
  200994. DisconnectNamedPipe (pipeH);
  200995. connected = false;
  200996. }
  200997. }
  200998. HANDLE pipeH;
  200999. HANDLE cancelEvent;
  201000. bool connected, isPipe;
  201001. };
  201002. void NamedPipe::close()
  201003. {
  201004. cancelPendingReads();
  201005. const ScopedLock sl (lock);
  201006. delete static_cast<NamedPipeInternal*> (internal);
  201007. internal = 0;
  201008. }
  201009. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  201010. {
  201011. close();
  201012. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  201013. if (intern->pipeH != INVALID_HANDLE_VALUE)
  201014. {
  201015. internal = intern.release();
  201016. return true;
  201017. }
  201018. return false;
  201019. }
  201020. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  201021. {
  201022. const ScopedLock sl (lock);
  201023. int bytesRead = -1;
  201024. bool waitAgain = true;
  201025. while (waitAgain && internal != 0)
  201026. {
  201027. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201028. waitAgain = false;
  201029. if (! intern->connect (timeOutMilliseconds))
  201030. break;
  201031. if (maxBytesToRead <= 0)
  201032. return 0;
  201033. OVERLAPPED over;
  201034. zerostruct (over);
  201035. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201036. unsigned long numRead;
  201037. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  201038. {
  201039. bytesRead = (int) numRead;
  201040. }
  201041. else if (GetLastError() == ERROR_IO_PENDING)
  201042. {
  201043. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201044. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201045. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201046. : INFINITE);
  201047. if (waitResult != WAIT_OBJECT_0)
  201048. {
  201049. // if the operation timed out, let's cancel it...
  201050. CancelIo (intern->pipeH);
  201051. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  201052. }
  201053. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  201054. {
  201055. bytesRead = (int) numRead;
  201056. }
  201057. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201058. {
  201059. intern->disconnectPipe();
  201060. waitAgain = true;
  201061. }
  201062. }
  201063. else
  201064. {
  201065. waitAgain = internal != 0;
  201066. Sleep (5);
  201067. }
  201068. CloseHandle (over.hEvent);
  201069. }
  201070. return bytesRead;
  201071. }
  201072. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  201073. {
  201074. int bytesWritten = -1;
  201075. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201076. if (intern != 0 && intern->connect (timeOutMilliseconds))
  201077. {
  201078. if (numBytesToWrite <= 0)
  201079. return 0;
  201080. OVERLAPPED over;
  201081. zerostruct (over);
  201082. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201083. unsigned long numWritten;
  201084. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  201085. {
  201086. bytesWritten = (int) numWritten;
  201087. }
  201088. else if (GetLastError() == ERROR_IO_PENDING)
  201089. {
  201090. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201091. DWORD waitResult;
  201092. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201093. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201094. : INFINITE);
  201095. if (waitResult != WAIT_OBJECT_0)
  201096. {
  201097. CancelIo (intern->pipeH);
  201098. WaitForSingleObject (over.hEvent, INFINITE);
  201099. }
  201100. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  201101. {
  201102. bytesWritten = (int) numWritten;
  201103. }
  201104. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201105. {
  201106. intern->disconnectPipe();
  201107. }
  201108. }
  201109. CloseHandle (over.hEvent);
  201110. }
  201111. return bytesWritten;
  201112. }
  201113. void NamedPipe::cancelPendingReads()
  201114. {
  201115. if (internal != 0)
  201116. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  201117. }
  201118. #endif
  201119. /*** End of inlined file: juce_win32_Files.cpp ***/
  201120. /*** Start of inlined file: juce_win32_Network.cpp ***/
  201121. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201122. // compiled on its own).
  201123. #if JUCE_INCLUDED_FILE
  201124. #ifndef INTERNET_FLAG_NEED_FILE
  201125. #define INTERNET_FLAG_NEED_FILE 0x00000010
  201126. #endif
  201127. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  201128. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  201129. #endif
  201130. struct ConnectionAndRequestStruct
  201131. {
  201132. HINTERNET connection, request;
  201133. };
  201134. static HINTERNET sessionHandle = 0;
  201135. #ifndef WORKAROUND_TIMEOUT_BUG
  201136. //#define WORKAROUND_TIMEOUT_BUG 1
  201137. #endif
  201138. #if WORKAROUND_TIMEOUT_BUG
  201139. // Required because of a Microsoft bug in setting a timeout
  201140. class InternetConnectThread : public Thread
  201141. {
  201142. public:
  201143. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  201144. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  201145. {
  201146. startThread();
  201147. }
  201148. ~InternetConnectThread()
  201149. {
  201150. stopThread (60000);
  201151. }
  201152. void run()
  201153. {
  201154. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  201155. uc.nPort, _T(""), _T(""),
  201156. isFtp ? INTERNET_SERVICE_FTP
  201157. : INTERNET_SERVICE_HTTP,
  201158. 0, 0);
  201159. notify();
  201160. }
  201161. juce_UseDebuggingNewOperator
  201162. private:
  201163. URL_COMPONENTS& uc;
  201164. HINTERNET& connection;
  201165. const bool isFtp;
  201166. InternetConnectThread (const InternetConnectThread&);
  201167. InternetConnectThread& operator= (const InternetConnectThread&);
  201168. };
  201169. #endif
  201170. void* juce_openInternetFile (const String& url,
  201171. const String& headers,
  201172. const MemoryBlock& postData,
  201173. const bool isPost,
  201174. URL::OpenStreamProgressCallback* callback,
  201175. void* callbackContext,
  201176. int timeOutMs)
  201177. {
  201178. if (sessionHandle == 0)
  201179. sessionHandle = InternetOpen (_T("juce"),
  201180. INTERNET_OPEN_TYPE_PRECONFIG,
  201181. 0, 0, 0);
  201182. if (sessionHandle != 0)
  201183. {
  201184. // break up the url..
  201185. TCHAR file[1024], server[1024];
  201186. URL_COMPONENTS uc;
  201187. zerostruct (uc);
  201188. uc.dwStructSize = sizeof (uc);
  201189. uc.dwUrlPathLength = sizeof (file);
  201190. uc.dwHostNameLength = sizeof (server);
  201191. uc.lpszUrlPath = file;
  201192. uc.lpszHostName = server;
  201193. if (InternetCrackUrl (url, 0, 0, &uc))
  201194. {
  201195. int disable = 1;
  201196. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  201197. if (timeOutMs == 0)
  201198. timeOutMs = 30000;
  201199. else if (timeOutMs < 0)
  201200. timeOutMs = -1;
  201201. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  201202. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  201203. #if WORKAROUND_TIMEOUT_BUG
  201204. HINTERNET connection = 0;
  201205. {
  201206. InternetConnectThread connectThread (uc, connection, isFtp);
  201207. connectThread.wait (timeOutMs);
  201208. if (connection == 0)
  201209. {
  201210. InternetCloseHandle (sessionHandle);
  201211. sessionHandle = 0;
  201212. }
  201213. }
  201214. #else
  201215. HINTERNET connection = InternetConnect (sessionHandle,
  201216. uc.lpszHostName,
  201217. uc.nPort,
  201218. _T(""), _T(""),
  201219. isFtp ? INTERNET_SERVICE_FTP
  201220. : INTERNET_SERVICE_HTTP,
  201221. 0, 0);
  201222. #endif
  201223. if (connection != 0)
  201224. {
  201225. if (isFtp)
  201226. {
  201227. HINTERNET request = FtpOpenFile (connection,
  201228. uc.lpszUrlPath,
  201229. GENERIC_READ,
  201230. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  201231. 0);
  201232. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  201233. result->connection = connection;
  201234. result->request = request;
  201235. return result;
  201236. }
  201237. else
  201238. {
  201239. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  201240. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  201241. if (url.startsWithIgnoreCase ("https:"))
  201242. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  201243. // IE7 seems to automatically work out when it's https)
  201244. HINTERNET request = HttpOpenRequest (connection,
  201245. isPost ? _T("POST")
  201246. : _T("GET"),
  201247. uc.lpszUrlPath,
  201248. 0, 0, mimeTypes, flags, 0);
  201249. if (request != 0)
  201250. {
  201251. INTERNET_BUFFERS buffers;
  201252. zerostruct (buffers);
  201253. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  201254. buffers.lpcszHeader = (LPCTSTR) headers;
  201255. buffers.dwHeadersLength = headers.length();
  201256. buffers.dwBufferTotal = (DWORD) postData.getSize();
  201257. ConnectionAndRequestStruct* result = 0;
  201258. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  201259. {
  201260. int bytesSent = 0;
  201261. for (;;)
  201262. {
  201263. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  201264. DWORD bytesDone = 0;
  201265. if (bytesToDo > 0
  201266. && ! InternetWriteFile (request,
  201267. static_cast <const char*> (postData.getData()) + bytesSent,
  201268. bytesToDo, &bytesDone))
  201269. {
  201270. break;
  201271. }
  201272. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  201273. {
  201274. result = new ConnectionAndRequestStruct();
  201275. result->connection = connection;
  201276. result->request = request;
  201277. HttpEndRequest (request, 0, 0, 0);
  201278. return result;
  201279. }
  201280. bytesSent += bytesDone;
  201281. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  201282. break;
  201283. }
  201284. }
  201285. InternetCloseHandle (request);
  201286. }
  201287. InternetCloseHandle (connection);
  201288. }
  201289. }
  201290. }
  201291. }
  201292. return 0;
  201293. }
  201294. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  201295. {
  201296. DWORD bytesRead = 0;
  201297. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201298. if (crs != 0)
  201299. InternetReadFile (crs->request,
  201300. buffer, bytesToRead,
  201301. &bytesRead);
  201302. return bytesRead;
  201303. }
  201304. int juce_seekInInternetFile (void* handle, int newPosition)
  201305. {
  201306. if (handle != 0)
  201307. {
  201308. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201309. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  201310. }
  201311. return -1;
  201312. }
  201313. int64 juce_getInternetFileContentLength (void* handle)
  201314. {
  201315. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201316. if (crs != 0)
  201317. {
  201318. DWORD index = 0, result = 0, size = sizeof (result);
  201319. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  201320. &result, &size, &index))
  201321. {
  201322. return (int64) result;
  201323. }
  201324. }
  201325. return -1;
  201326. }
  201327. void juce_closeInternetFile (void* handle)
  201328. {
  201329. if (handle != 0)
  201330. {
  201331. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  201332. InternetCloseHandle (crs->request);
  201333. InternetCloseHandle (crs->connection);
  201334. }
  201335. }
  201336. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  201337. {
  201338. int numFound = 0;
  201339. DynamicLibraryLoader dll ("iphlpapi.dll");
  201340. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  201341. if (getAdaptersInfo != 0)
  201342. {
  201343. ULONG len = sizeof (IP_ADAPTER_INFO);
  201344. MemoryBlock mb;
  201345. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201346. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  201347. {
  201348. mb.setSize (len);
  201349. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201350. }
  201351. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  201352. {
  201353. PIP_ADAPTER_INFO adapter = adapterInfo;
  201354. while (adapter != 0)
  201355. {
  201356. int64 mac = 0;
  201357. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  201358. mac = (mac << 8) | adapter->Address[i];
  201359. if (littleEndian)
  201360. mac = (int64) ByteOrder::swap ((uint64) mac);
  201361. if (numFound < maxNum && mac != 0)
  201362. addresses [numFound++] = mac;
  201363. adapter = adapter->Next;
  201364. }
  201365. }
  201366. }
  201367. return numFound;
  201368. }
  201369. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  201370. {
  201371. int numFound = 0;
  201372. DynamicLibraryLoader dll ("netapi32.dll");
  201373. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  201374. if (NetbiosCall != 0)
  201375. {
  201376. NCB ncb;
  201377. zerostruct (ncb);
  201378. struct ASTAT
  201379. {
  201380. ADAPTER_STATUS adapt;
  201381. NAME_BUFFER NameBuff [30];
  201382. };
  201383. ASTAT astat;
  201384. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  201385. LANA_ENUM enums;
  201386. zerostruct (enums);
  201387. ncb.ncb_command = NCBENUM;
  201388. ncb.ncb_buffer = (unsigned char*) &enums;
  201389. ncb.ncb_length = sizeof (LANA_ENUM);
  201390. NetbiosCall (&ncb);
  201391. for (int i = 0; i < enums.length; ++i)
  201392. {
  201393. zerostruct (ncb);
  201394. ncb.ncb_command = NCBRESET;
  201395. ncb.ncb_lana_num = enums.lana[i];
  201396. if (NetbiosCall (&ncb) == 0)
  201397. {
  201398. zerostruct (ncb);
  201399. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  201400. ncb.ncb_command = NCBASTAT;
  201401. ncb.ncb_lana_num = enums.lana[i];
  201402. ncb.ncb_buffer = (unsigned char*) &astat;
  201403. ncb.ncb_length = sizeof (ASTAT);
  201404. if (NetbiosCall (&ncb) == 0)
  201405. {
  201406. if (astat.adapt.adapter_type == 0xfe)
  201407. {
  201408. uint64 mac = 0;
  201409. for (int i = 6; --i >= 0;)
  201410. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  201411. if (numFound < maxNum && mac != 0)
  201412. addresses [numFound++] = mac;
  201413. }
  201414. }
  201415. }
  201416. }
  201417. }
  201418. return numFound;
  201419. }
  201420. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  201421. {
  201422. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  201423. if (numFound == 0)
  201424. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  201425. return numFound;
  201426. }
  201427. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  201428. const String& emailSubject,
  201429. const String& bodyText,
  201430. const StringArray& filesToAttach)
  201431. {
  201432. HMODULE h = LoadLibraryA ("MAPI32.dll");
  201433. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  201434. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  201435. bool ok = false;
  201436. if (mapiSendMail != 0)
  201437. {
  201438. MapiMessage message;
  201439. zerostruct (message);
  201440. message.lpszSubject = (LPSTR) emailSubject.toCString();
  201441. message.lpszNoteText = (LPSTR) bodyText.toCString();
  201442. MapiRecipDesc recip;
  201443. zerostruct (recip);
  201444. recip.ulRecipClass = MAPI_TO;
  201445. String targetEmailAddress_ (targetEmailAddress);
  201446. if (targetEmailAddress_.isEmpty())
  201447. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  201448. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  201449. message.nRecipCount = 1;
  201450. message.lpRecips = &recip;
  201451. HeapBlock <MapiFileDesc> files;
  201452. files.calloc (filesToAttach.size());
  201453. message.nFileCount = filesToAttach.size();
  201454. message.lpFiles = files;
  201455. for (int i = 0; i < filesToAttach.size(); ++i)
  201456. {
  201457. files[i].nPosition = (ULONG) -1;
  201458. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  201459. }
  201460. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  201461. }
  201462. FreeLibrary (h);
  201463. return ok;
  201464. }
  201465. #endif
  201466. /*** End of inlined file: juce_win32_Network.cpp ***/
  201467. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  201468. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201469. // compiled on its own).
  201470. #if JUCE_INCLUDED_FILE
  201471. static HKEY findKeyForPath (String name,
  201472. const bool createForWriting,
  201473. String& valueName)
  201474. {
  201475. HKEY rootKey = 0;
  201476. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  201477. rootKey = HKEY_CURRENT_USER;
  201478. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  201479. rootKey = HKEY_LOCAL_MACHINE;
  201480. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  201481. rootKey = HKEY_CLASSES_ROOT;
  201482. if (rootKey != 0)
  201483. {
  201484. name = name.substring (name.indexOfChar ('\\') + 1);
  201485. const int lastSlash = name.lastIndexOfChar ('\\');
  201486. valueName = name.substring (lastSlash + 1);
  201487. name = name.substring (0, lastSlash);
  201488. HKEY key;
  201489. DWORD result;
  201490. if (createForWriting)
  201491. {
  201492. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  201493. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  201494. return key;
  201495. }
  201496. else
  201497. {
  201498. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  201499. return key;
  201500. }
  201501. }
  201502. return 0;
  201503. }
  201504. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  201505. const String& defaultValue)
  201506. {
  201507. String valueName, result (defaultValue);
  201508. HKEY k = findKeyForPath (regValuePath, false, valueName);
  201509. if (k != 0)
  201510. {
  201511. WCHAR buffer [2048];
  201512. unsigned long bufferSize = sizeof (buffer);
  201513. DWORD type = REG_SZ;
  201514. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  201515. {
  201516. if (type == REG_SZ)
  201517. result = buffer;
  201518. else if (type == REG_DWORD)
  201519. result = String ((int) *(DWORD*) buffer);
  201520. }
  201521. RegCloseKey (k);
  201522. }
  201523. return result;
  201524. }
  201525. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  201526. const String& value)
  201527. {
  201528. String valueName;
  201529. HKEY k = findKeyForPath (regValuePath, true, valueName);
  201530. if (k != 0)
  201531. {
  201532. RegSetValueEx (k, valueName, 0, REG_SZ,
  201533. (const BYTE*) (const WCHAR*) value,
  201534. sizeof (WCHAR) * (value.length() + 1));
  201535. RegCloseKey (k);
  201536. }
  201537. }
  201538. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  201539. {
  201540. bool exists = false;
  201541. String valueName;
  201542. HKEY k = findKeyForPath (regValuePath, false, valueName);
  201543. if (k != 0)
  201544. {
  201545. unsigned char buffer [2048];
  201546. unsigned long bufferSize = sizeof (buffer);
  201547. DWORD type = 0;
  201548. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  201549. exists = true;
  201550. RegCloseKey (k);
  201551. }
  201552. return exists;
  201553. }
  201554. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  201555. {
  201556. String valueName;
  201557. HKEY k = findKeyForPath (regValuePath, true, valueName);
  201558. if (k != 0)
  201559. {
  201560. RegDeleteValue (k, valueName);
  201561. RegCloseKey (k);
  201562. }
  201563. }
  201564. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  201565. {
  201566. String valueName;
  201567. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  201568. if (k != 0)
  201569. {
  201570. RegDeleteKey (k, valueName);
  201571. RegCloseKey (k);
  201572. }
  201573. }
  201574. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  201575. const String& symbolicDescription,
  201576. const String& fullDescription,
  201577. const File& targetExecutable,
  201578. int iconResourceNumber)
  201579. {
  201580. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  201581. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  201582. if (iconResourceNumber != 0)
  201583. setRegistryValue (key + "\\DefaultIcon\\",
  201584. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  201585. setRegistryValue (key + "\\", fullDescription);
  201586. setRegistryValue (key + "\\shell\\open\\command\\",
  201587. targetExecutable.getFullPathName() + " %1");
  201588. }
  201589. bool juce_IsRunningInWine()
  201590. {
  201591. HKEY key;
  201592. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  201593. {
  201594. RegCloseKey (key);
  201595. return true;
  201596. }
  201597. return false;
  201598. }
  201599. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  201600. {
  201601. String s (::GetCommandLineW());
  201602. StringArray tokens;
  201603. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  201604. return tokens.joinIntoString (" ", 1);
  201605. }
  201606. static void* currentModuleHandle = 0;
  201607. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  201608. {
  201609. if (currentModuleHandle == 0)
  201610. currentModuleHandle = GetModuleHandle (0);
  201611. return currentModuleHandle;
  201612. }
  201613. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  201614. {
  201615. currentModuleHandle = newHandle;
  201616. }
  201617. void PlatformUtilities::fpuReset()
  201618. {
  201619. #if JUCE_MSVC
  201620. _clearfp();
  201621. #endif
  201622. }
  201623. void PlatformUtilities::beep()
  201624. {
  201625. MessageBeep (MB_OK);
  201626. }
  201627. #endif
  201628. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  201629. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  201630. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  201631. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201632. // compiled on its own).
  201633. #if JUCE_INCLUDED_FILE
  201634. static const unsigned int specialId = WM_APP + 0x4400;
  201635. static const unsigned int broadcastId = WM_APP + 0x4403;
  201636. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  201637. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  201638. HWND juce_messageWindowHandle = 0;
  201639. extern long improbableWindowNumber; // defined in windowing.cpp
  201640. #ifndef WM_APPCOMMAND
  201641. #define WM_APPCOMMAND 0x0319
  201642. #endif
  201643. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  201644. const UINT message,
  201645. const WPARAM wParam,
  201646. const LPARAM lParam) throw()
  201647. {
  201648. JUCE_TRY
  201649. {
  201650. if (h == juce_messageWindowHandle)
  201651. {
  201652. if (message == specialCallbackId)
  201653. {
  201654. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  201655. return (LRESULT) (*func) ((void*) lParam);
  201656. }
  201657. else if (message == specialId)
  201658. {
  201659. // these are trapped early in the dispatch call, but must also be checked
  201660. // here in case there are windows modal dialog boxes doing their own
  201661. // dispatch loop and not calling our version
  201662. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  201663. return 0;
  201664. }
  201665. else if (message == broadcastId)
  201666. {
  201667. const ScopedPointer <String> messageString ((String*) lParam);
  201668. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  201669. return 0;
  201670. }
  201671. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  201672. {
  201673. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  201674. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  201675. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  201676. return 0;
  201677. }
  201678. }
  201679. }
  201680. JUCE_CATCH_EXCEPTION
  201681. return DefWindowProc (h, message, wParam, lParam);
  201682. }
  201683. static bool isEventBlockedByModalComps (MSG& m)
  201684. {
  201685. if (Component::getNumCurrentlyModalComponents() == 0
  201686. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  201687. return false;
  201688. switch (m.message)
  201689. {
  201690. case WM_MOUSEMOVE:
  201691. case WM_NCMOUSEMOVE:
  201692. case 0x020A: /* WM_MOUSEWHEEL */
  201693. case 0x020E: /* WM_MOUSEHWHEEL */
  201694. case WM_KEYUP:
  201695. case WM_SYSKEYUP:
  201696. case WM_CHAR:
  201697. case WM_APPCOMMAND:
  201698. case WM_LBUTTONUP:
  201699. case WM_MBUTTONUP:
  201700. case WM_RBUTTONUP:
  201701. case WM_MOUSEACTIVATE:
  201702. case WM_NCMOUSEHOVER:
  201703. case WM_MOUSEHOVER:
  201704. return true;
  201705. case WM_NCLBUTTONDOWN:
  201706. case WM_NCLBUTTONDBLCLK:
  201707. case WM_NCRBUTTONDOWN:
  201708. case WM_NCRBUTTONDBLCLK:
  201709. case WM_NCMBUTTONDOWN:
  201710. case WM_NCMBUTTONDBLCLK:
  201711. case WM_LBUTTONDOWN:
  201712. case WM_LBUTTONDBLCLK:
  201713. case WM_MBUTTONDOWN:
  201714. case WM_MBUTTONDBLCLK:
  201715. case WM_RBUTTONDOWN:
  201716. case WM_RBUTTONDBLCLK:
  201717. case WM_KEYDOWN:
  201718. case WM_SYSKEYDOWN:
  201719. {
  201720. Component* const modal = Component::getCurrentlyModalComponent (0);
  201721. if (modal != 0)
  201722. modal->inputAttemptWhenModal();
  201723. return true;
  201724. }
  201725. default:
  201726. break;
  201727. }
  201728. return false;
  201729. }
  201730. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  201731. {
  201732. MSG m;
  201733. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  201734. return false;
  201735. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  201736. {
  201737. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  201738. {
  201739. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  201740. }
  201741. else if (m.message == WM_QUIT)
  201742. {
  201743. if (JUCEApplication::getInstance())
  201744. JUCEApplication::getInstance()->systemRequestedQuit();
  201745. }
  201746. else if (! isEventBlockedByModalComps (m))
  201747. {
  201748. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  201749. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  201750. {
  201751. // if it's someone else's window being clicked on, and the focus is
  201752. // currently on a juce window, pass the kb focus over..
  201753. HWND currentFocus = GetFocus();
  201754. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  201755. SetFocus (m.hwnd);
  201756. }
  201757. TranslateMessage (&m);
  201758. DispatchMessage (&m);
  201759. }
  201760. }
  201761. return true;
  201762. }
  201763. bool juce_postMessageToSystemQueue (void* message)
  201764. {
  201765. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  201766. }
  201767. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  201768. void* userData)
  201769. {
  201770. if (MessageManager::getInstance()->isThisTheMessageThread())
  201771. {
  201772. return (*callback) (userData);
  201773. }
  201774. else
  201775. {
  201776. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  201777. // deadlock because the message manager is blocked from running, and can't
  201778. // call your function..
  201779. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  201780. return (void*) SendMessage (juce_messageWindowHandle,
  201781. specialCallbackId,
  201782. (WPARAM) callback,
  201783. (LPARAM) userData);
  201784. }
  201785. }
  201786. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  201787. {
  201788. if (hwnd != juce_messageWindowHandle)
  201789. reinterpret_cast <VoidArray*> (lParam)->add ((void*) hwnd);
  201790. return TRUE;
  201791. }
  201792. void MessageManager::broadcastMessage (const String& value) throw()
  201793. {
  201794. VoidArray windows;
  201795. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  201796. const String localCopy (value);
  201797. COPYDATASTRUCT data;
  201798. data.dwData = broadcastId;
  201799. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  201800. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  201801. for (int i = windows.size(); --i >= 0;)
  201802. {
  201803. HWND hwnd = (HWND) windows.getUnchecked(i);
  201804. TCHAR windowName [64]; // no need to read longer strings than this
  201805. GetWindowText (hwnd, windowName, 64);
  201806. windowName [63] = 0;
  201807. if (String (windowName) == messageWindowName)
  201808. {
  201809. DWORD_PTR result;
  201810. SendMessageTimeout (hwnd, WM_COPYDATA,
  201811. (WPARAM) juce_messageWindowHandle,
  201812. (LPARAM) &data,
  201813. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  201814. 8000,
  201815. &result);
  201816. }
  201817. }
  201818. }
  201819. static const String getMessageWindowClassName()
  201820. {
  201821. // this name has to be different for each app/dll instance because otherwise
  201822. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201823. // window class).
  201824. static int number = 0;
  201825. if (number == 0)
  201826. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  201827. return "JUCEcs_" + String (number);
  201828. }
  201829. void MessageManager::doPlatformSpecificInitialisation()
  201830. {
  201831. OleInitialize (0);
  201832. const String className (getMessageWindowClassName());
  201833. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201834. WNDCLASSEX wc;
  201835. zerostruct (wc);
  201836. wc.cbSize = sizeof (wc);
  201837. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  201838. wc.cbWndExtra = 4;
  201839. wc.hInstance = hmod;
  201840. wc.lpszClassName = className;
  201841. RegisterClassEx (&wc);
  201842. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  201843. messageWindowName,
  201844. 0, 0, 0, 0, 0, 0, 0,
  201845. hmod, 0);
  201846. }
  201847. void MessageManager::doPlatformSpecificShutdown()
  201848. {
  201849. DestroyWindow (juce_messageWindowHandle);
  201850. UnregisterClass (getMessageWindowClassName(), 0);
  201851. OleUninitialize();
  201852. }
  201853. #endif
  201854. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  201855. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  201856. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201857. // compiled on its own).
  201858. #if JUCE_INCLUDED_FILE
  201859. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  201860. // these are in the windows SDK, but need to be repeated here for GCC..
  201861. #ifndef GET_APPCOMMAND_LPARAM
  201862. #define FAPPCOMMAND_MASK 0xF000
  201863. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  201864. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  201865. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  201866. #define APPCOMMAND_MEDIA_STOP 13
  201867. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  201868. #define WM_APPCOMMAND 0x0319
  201869. #endif
  201870. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  201871. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  201872. extern bool juce_IsRunningInWine();
  201873. #ifndef ULW_ALPHA
  201874. #define ULW_ALPHA 0x00000002
  201875. #endif
  201876. #ifndef AC_SRC_ALPHA
  201877. #define AC_SRC_ALPHA 0x01
  201878. #endif
  201879. static HPALETTE palette = 0;
  201880. static bool createPaletteIfNeeded = true;
  201881. static bool shouldDeactivateTitleBar = true;
  201882. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  201883. #define WM_TRAYNOTIFY WM_USER + 100
  201884. using ::abs;
  201885. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  201886. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  201887. bool Desktop::canUseSemiTransparentWindows() throw()
  201888. {
  201889. if (updateLayeredWindow == 0)
  201890. {
  201891. if (! juce_IsRunningInWine())
  201892. {
  201893. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  201894. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  201895. }
  201896. }
  201897. return updateLayeredWindow != 0;
  201898. }
  201899. const int extendedKeyModifier = 0x10000;
  201900. const int KeyPress::spaceKey = VK_SPACE;
  201901. const int KeyPress::returnKey = VK_RETURN;
  201902. const int KeyPress::escapeKey = VK_ESCAPE;
  201903. const int KeyPress::backspaceKey = VK_BACK;
  201904. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  201905. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  201906. const int KeyPress::tabKey = VK_TAB;
  201907. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  201908. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  201909. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  201910. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  201911. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  201912. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  201913. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  201914. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  201915. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  201916. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  201917. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  201918. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  201919. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  201920. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  201921. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  201922. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  201923. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  201924. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  201925. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  201926. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  201927. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  201928. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  201929. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  201930. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  201931. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  201932. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  201933. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  201934. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  201935. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  201936. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  201937. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  201938. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  201939. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  201940. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  201941. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  201942. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  201943. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  201944. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  201945. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  201946. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  201947. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  201948. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  201949. const int KeyPress::playKey = 0x30000;
  201950. const int KeyPress::stopKey = 0x30001;
  201951. const int KeyPress::fastForwardKey = 0x30002;
  201952. const int KeyPress::rewindKey = 0x30003;
  201953. class WindowsBitmapImage : public Image
  201954. {
  201955. public:
  201956. HBITMAP hBitmap;
  201957. BITMAPV4HEADER bitmapInfo;
  201958. HDC hdc;
  201959. unsigned char* bitmapData;
  201960. WindowsBitmapImage (const PixelFormat format_,
  201961. const int w, const int h, const bool clearImage)
  201962. : Image (format_, w, h)
  201963. {
  201964. jassert (format_ == RGB || format_ == ARGB);
  201965. pixelStride = (format_ == RGB) ? 3 : 4;
  201966. zerostruct (bitmapInfo);
  201967. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  201968. bitmapInfo.bV4Width = w;
  201969. bitmapInfo.bV4Height = h;
  201970. bitmapInfo.bV4Planes = 1;
  201971. bitmapInfo.bV4CSType = 1;
  201972. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  201973. if (format_ == ARGB)
  201974. {
  201975. bitmapInfo.bV4AlphaMask = 0xff000000;
  201976. bitmapInfo.bV4RedMask = 0xff0000;
  201977. bitmapInfo.bV4GreenMask = 0xff00;
  201978. bitmapInfo.bV4BlueMask = 0xff;
  201979. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  201980. }
  201981. else
  201982. {
  201983. bitmapInfo.bV4V4Compression = BI_RGB;
  201984. }
  201985. lineStride = -((w * pixelStride + 3) & ~3);
  201986. HDC dc = GetDC (0);
  201987. hdc = CreateCompatibleDC (dc);
  201988. ReleaseDC (0, dc);
  201989. SetMapMode (hdc, MM_TEXT);
  201990. hBitmap = CreateDIBSection (hdc,
  201991. (BITMAPINFO*) &(bitmapInfo),
  201992. DIB_RGB_COLORS,
  201993. (void**) &bitmapData,
  201994. 0, 0);
  201995. SelectObject (hdc, hBitmap);
  201996. if (format_ == ARGB && clearImage)
  201997. zeromem (bitmapData, abs (h * lineStride));
  201998. imageData = bitmapData - (lineStride * (h - 1));
  201999. }
  202000. ~WindowsBitmapImage()
  202001. {
  202002. DeleteDC (hdc);
  202003. DeleteObject (hBitmap);
  202004. }
  202005. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  202006. const int x, const int y,
  202007. const RectangleList& maskedRegion) throw()
  202008. {
  202009. static HDRAWDIB hdd = 0;
  202010. static bool needToCreateDrawDib = true;
  202011. if (needToCreateDrawDib)
  202012. {
  202013. needToCreateDrawDib = false;
  202014. HDC dc = GetDC (0);
  202015. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202016. ReleaseDC (0, dc);
  202017. // only open if we're not palettised
  202018. if (n > 8)
  202019. hdd = DrawDibOpen();
  202020. }
  202021. if (createPaletteIfNeeded)
  202022. {
  202023. HDC dc = GetDC (0);
  202024. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202025. ReleaseDC (0, dc);
  202026. if (n <= 8)
  202027. palette = CreateHalftonePalette (dc);
  202028. createPaletteIfNeeded = false;
  202029. }
  202030. if (palette != 0)
  202031. {
  202032. SelectPalette (dc, palette, FALSE);
  202033. RealizePalette (dc);
  202034. SetStretchBltMode (dc, HALFTONE);
  202035. }
  202036. SetMapMode (dc, MM_TEXT);
  202037. if (transparent)
  202038. {
  202039. POINT p, pos;
  202040. SIZE size;
  202041. RECT windowBounds;
  202042. GetWindowRect (hwnd, &windowBounds);
  202043. p.x = -x;
  202044. p.y = -y;
  202045. pos.x = windowBounds.left;
  202046. pos.y = windowBounds.top;
  202047. size.cx = windowBounds.right - windowBounds.left;
  202048. size.cy = windowBounds.bottom - windowBounds.top;
  202049. BLENDFUNCTION bf;
  202050. bf.AlphaFormat = AC_SRC_ALPHA;
  202051. bf.BlendFlags = 0;
  202052. bf.BlendOp = AC_SRC_OVER;
  202053. bf.SourceConstantAlpha = 0xff;
  202054. if (! maskedRegion.isEmpty())
  202055. {
  202056. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202057. {
  202058. const Rectangle<int>& r = *i.getRectangle();
  202059. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202060. }
  202061. }
  202062. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  202063. }
  202064. else
  202065. {
  202066. int savedDC = 0;
  202067. if (! maskedRegion.isEmpty())
  202068. {
  202069. savedDC = SaveDC (dc);
  202070. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202071. {
  202072. const Rectangle<int>& r = *i.getRectangle();
  202073. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202074. }
  202075. }
  202076. const int w = getWidth();
  202077. const int h = getHeight();
  202078. if (hdd == 0)
  202079. {
  202080. StretchDIBits (dc,
  202081. x, y, w, h,
  202082. 0, 0, w, h,
  202083. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  202084. DIB_RGB_COLORS, SRCCOPY);
  202085. }
  202086. else
  202087. {
  202088. DrawDibDraw (hdd, dc, x, y, -1, -1,
  202089. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  202090. 0, 0, w, h, 0);
  202091. }
  202092. if (! maskedRegion.isEmpty())
  202093. RestoreDC (dc, savedDC);
  202094. }
  202095. }
  202096. juce_UseDebuggingNewOperator
  202097. private:
  202098. WindowsBitmapImage (const WindowsBitmapImage&);
  202099. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  202100. };
  202101. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  202102. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  202103. {
  202104. SHORT k = (SHORT) keyCode;
  202105. if ((keyCode & extendedKeyModifier) == 0
  202106. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  202107. k += (SHORT) 'A' - (SHORT) 'a';
  202108. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  202109. (SHORT) '+', VK_OEM_PLUS,
  202110. (SHORT) '-', VK_OEM_MINUS,
  202111. (SHORT) '.', VK_OEM_PERIOD,
  202112. (SHORT) ';', VK_OEM_1,
  202113. (SHORT) ':', VK_OEM_1,
  202114. (SHORT) '/', VK_OEM_2,
  202115. (SHORT) '?', VK_OEM_2,
  202116. (SHORT) '[', VK_OEM_4,
  202117. (SHORT) ']', VK_OEM_6 };
  202118. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  202119. if (k == translatedValues [i])
  202120. k = translatedValues [i + 1];
  202121. return (GetKeyState (k) & 0x8000) != 0;
  202122. }
  202123. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  202124. {
  202125. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  202126. return callback (userData);
  202127. else
  202128. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  202129. }
  202130. class Win32ComponentPeer : public ComponentPeer
  202131. {
  202132. public:
  202133. Win32ComponentPeer (Component* const component,
  202134. const int windowStyleFlags)
  202135. : ComponentPeer (component, windowStyleFlags),
  202136. dontRepaint (false),
  202137. fullScreen (false),
  202138. isDragging (false),
  202139. isMouseOver (false),
  202140. hasCreatedCaret (false),
  202141. currentWindowIcon (0),
  202142. taskBarIcon (0),
  202143. dropTarget (0)
  202144. {
  202145. callFunctionIfNotLocked (&createWindowCallback, this);
  202146. setTitle (component->getName());
  202147. if ((windowStyleFlags & windowHasDropShadow) != 0
  202148. && Desktop::canUseSemiTransparentWindows())
  202149. {
  202150. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  202151. if (shadower != 0)
  202152. shadower->setOwner (component);
  202153. }
  202154. else
  202155. {
  202156. shadower = 0;
  202157. }
  202158. }
  202159. ~Win32ComponentPeer()
  202160. {
  202161. setTaskBarIcon (0);
  202162. deleteAndZero (shadower);
  202163. // do this before the next bit to avoid messages arriving for this window
  202164. // before it's destroyed
  202165. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  202166. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  202167. if (currentWindowIcon != 0)
  202168. DestroyIcon (currentWindowIcon);
  202169. if (dropTarget != 0)
  202170. {
  202171. dropTarget->Release();
  202172. dropTarget = 0;
  202173. }
  202174. }
  202175. void* getNativeHandle() const
  202176. {
  202177. return hwnd;
  202178. }
  202179. void setVisible (bool shouldBeVisible)
  202180. {
  202181. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  202182. if (shouldBeVisible)
  202183. InvalidateRect (hwnd, 0, 0);
  202184. else
  202185. lastPaintTime = 0;
  202186. }
  202187. void setTitle (const String& title)
  202188. {
  202189. SetWindowText (hwnd, title);
  202190. }
  202191. void setPosition (int x, int y)
  202192. {
  202193. offsetWithinParent (x, y);
  202194. SetWindowPos (hwnd, 0,
  202195. x - windowBorder.getLeft(),
  202196. y - windowBorder.getTop(),
  202197. 0, 0,
  202198. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202199. }
  202200. void repaintNowIfTransparent()
  202201. {
  202202. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  202203. handlePaintMessage();
  202204. }
  202205. void updateBorderSize()
  202206. {
  202207. WINDOWINFO info;
  202208. info.cbSize = sizeof (info);
  202209. if (GetWindowInfo (hwnd, &info))
  202210. {
  202211. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  202212. info.rcClient.left - info.rcWindow.left,
  202213. info.rcWindow.bottom - info.rcClient.bottom,
  202214. info.rcWindow.right - info.rcClient.right);
  202215. }
  202216. }
  202217. void setSize (int w, int h)
  202218. {
  202219. SetWindowPos (hwnd, 0, 0, 0,
  202220. w + windowBorder.getLeftAndRight(),
  202221. h + windowBorder.getTopAndBottom(),
  202222. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202223. updateBorderSize();
  202224. repaintNowIfTransparent();
  202225. }
  202226. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  202227. {
  202228. fullScreen = isNowFullScreen;
  202229. offsetWithinParent (x, y);
  202230. SetWindowPos (hwnd, 0,
  202231. x - windowBorder.getLeft(),
  202232. y - windowBorder.getTop(),
  202233. w + windowBorder.getLeftAndRight(),
  202234. h + windowBorder.getTopAndBottom(),
  202235. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202236. updateBorderSize();
  202237. repaintNowIfTransparent();
  202238. }
  202239. const Rectangle<int> getBounds() const
  202240. {
  202241. RECT r;
  202242. GetWindowRect (hwnd, &r);
  202243. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  202244. HWND parentH = GetParent (hwnd);
  202245. if (parentH != 0)
  202246. {
  202247. GetWindowRect (parentH, &r);
  202248. bounds.translate (-r.left, -r.top);
  202249. }
  202250. return windowBorder.subtractedFrom (bounds);
  202251. }
  202252. const Point<int> getScreenPosition() const
  202253. {
  202254. RECT r;
  202255. GetWindowRect (hwnd, &r);
  202256. return Point<int> (r.left + windowBorder.getLeft(),
  202257. r.top + windowBorder.getTop());
  202258. }
  202259. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  202260. {
  202261. return relativePosition + getScreenPosition();
  202262. }
  202263. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  202264. {
  202265. return screenPosition - getScreenPosition();
  202266. }
  202267. void setMinimised (bool shouldBeMinimised)
  202268. {
  202269. if (shouldBeMinimised != isMinimised())
  202270. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  202271. }
  202272. bool isMinimised() const
  202273. {
  202274. WINDOWPLACEMENT wp;
  202275. wp.length = sizeof (WINDOWPLACEMENT);
  202276. GetWindowPlacement (hwnd, &wp);
  202277. return wp.showCmd == SW_SHOWMINIMIZED;
  202278. }
  202279. void setFullScreen (bool shouldBeFullScreen)
  202280. {
  202281. setMinimised (false);
  202282. if (fullScreen != shouldBeFullScreen)
  202283. {
  202284. fullScreen = shouldBeFullScreen;
  202285. const Component::SafePointer<Component> deletionChecker (component);
  202286. if (! fullScreen)
  202287. {
  202288. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  202289. if (hasTitleBar())
  202290. ShowWindow (hwnd, SW_SHOWNORMAL);
  202291. if (! boundsCopy.isEmpty())
  202292. {
  202293. setBounds (boundsCopy.getX(),
  202294. boundsCopy.getY(),
  202295. boundsCopy.getWidth(),
  202296. boundsCopy.getHeight(),
  202297. false);
  202298. }
  202299. }
  202300. else
  202301. {
  202302. if (hasTitleBar())
  202303. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  202304. else
  202305. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  202306. }
  202307. if (deletionChecker != 0)
  202308. handleMovedOrResized();
  202309. }
  202310. }
  202311. bool isFullScreen() const
  202312. {
  202313. if (! hasTitleBar())
  202314. return fullScreen;
  202315. WINDOWPLACEMENT wp;
  202316. wp.length = sizeof (wp);
  202317. GetWindowPlacement (hwnd, &wp);
  202318. return wp.showCmd == SW_SHOWMAXIMIZED;
  202319. }
  202320. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  202321. {
  202322. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  202323. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  202324. return false;
  202325. RECT r;
  202326. GetWindowRect (hwnd, &r);
  202327. POINT p;
  202328. p.x = position.getX() + r.left + windowBorder.getLeft();
  202329. p.y = position.getY() + r.top + windowBorder.getTop();
  202330. HWND w = WindowFromPoint (p);
  202331. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  202332. }
  202333. const BorderSize getFrameSize() const
  202334. {
  202335. return windowBorder;
  202336. }
  202337. bool setAlwaysOnTop (bool alwaysOnTop)
  202338. {
  202339. const bool oldDeactivate = shouldDeactivateTitleBar;
  202340. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202341. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  202342. 0, 0, 0, 0,
  202343. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202344. shouldDeactivateTitleBar = oldDeactivate;
  202345. if (shadower != 0)
  202346. shadower->componentBroughtToFront (*component);
  202347. return true;
  202348. }
  202349. void toFront (bool makeActive)
  202350. {
  202351. setMinimised (false);
  202352. const bool oldDeactivate = shouldDeactivateTitleBar;
  202353. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202354. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  202355. shouldDeactivateTitleBar = oldDeactivate;
  202356. if (! makeActive)
  202357. {
  202358. // in this case a broughttofront call won't have occured, so do it now..
  202359. handleBroughtToFront();
  202360. }
  202361. }
  202362. void toBehind (ComponentPeer* other)
  202363. {
  202364. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  202365. jassert (otherPeer != 0); // wrong type of window?
  202366. if (otherPeer != 0)
  202367. {
  202368. setMinimised (false);
  202369. // must be careful not to try to put a topmost window behind a normal one, or win32
  202370. // promotes the normal one to be topmost!
  202371. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  202372. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  202373. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202374. else if (otherPeer->getComponent()->isAlwaysOnTop())
  202375. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  202376. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202377. }
  202378. }
  202379. bool isFocused() const
  202380. {
  202381. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  202382. }
  202383. void grabFocus()
  202384. {
  202385. const bool oldDeactivate = shouldDeactivateTitleBar;
  202386. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202387. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  202388. shouldDeactivateTitleBar = oldDeactivate;
  202389. }
  202390. void textInputRequired (const Point<int>&)
  202391. {
  202392. if (! hasCreatedCaret)
  202393. {
  202394. hasCreatedCaret = true;
  202395. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  202396. }
  202397. ShowCaret (hwnd);
  202398. SetCaretPos (0, 0);
  202399. }
  202400. void repaint (int x, int y, int w, int h)
  202401. {
  202402. const RECT r = { x, y, x + w, y + h };
  202403. InvalidateRect (hwnd, &r, FALSE);
  202404. }
  202405. void performAnyPendingRepaintsNow()
  202406. {
  202407. MSG m;
  202408. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  202409. DispatchMessage (&m);
  202410. }
  202411. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  202412. {
  202413. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  202414. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  202415. return 0;
  202416. }
  202417. void setTaskBarIcon (const Image* const image)
  202418. {
  202419. if (image != 0)
  202420. {
  202421. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  202422. if (taskBarIcon == 0)
  202423. {
  202424. taskBarIcon = new NOTIFYICONDATA();
  202425. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  202426. taskBarIcon->hWnd = (HWND) hwnd;
  202427. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  202428. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  202429. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  202430. taskBarIcon->hIcon = hicon;
  202431. taskBarIcon->szTip[0] = 0;
  202432. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  202433. }
  202434. else
  202435. {
  202436. HICON oldIcon = taskBarIcon->hIcon;
  202437. taskBarIcon->hIcon = hicon;
  202438. taskBarIcon->uFlags = NIF_ICON;
  202439. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  202440. DestroyIcon (oldIcon);
  202441. }
  202442. DestroyIcon (hicon);
  202443. }
  202444. else if (taskBarIcon != 0)
  202445. {
  202446. taskBarIcon->uFlags = 0;
  202447. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  202448. DestroyIcon (taskBarIcon->hIcon);
  202449. deleteAndZero (taskBarIcon);
  202450. }
  202451. }
  202452. void setTaskBarIconToolTip (const String& toolTip) const
  202453. {
  202454. if (taskBarIcon != 0)
  202455. {
  202456. taskBarIcon->uFlags = NIF_TIP;
  202457. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  202458. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  202459. }
  202460. }
  202461. bool isInside (HWND h) const
  202462. {
  202463. return GetAncestor (hwnd, GA_ROOT) == h;
  202464. }
  202465. static void updateKeyModifiers() throw()
  202466. {
  202467. int keyMods = 0;
  202468. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  202469. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  202470. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  202471. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  202472. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  202473. }
  202474. static void updateModifiersFromWParam (const WPARAM wParam)
  202475. {
  202476. int mouseMods = 0;
  202477. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  202478. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  202479. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  202480. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  202481. updateKeyModifiers();
  202482. }
  202483. static int64 getMouseEventTime()
  202484. {
  202485. static int64 eventTimeOffset = 0;
  202486. static DWORD lastMessageTime = 0;
  202487. const DWORD thisMessageTime = GetMessageTime();
  202488. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  202489. {
  202490. lastMessageTime = thisMessageTime;
  202491. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  202492. }
  202493. return eventTimeOffset + thisMessageTime;
  202494. }
  202495. juce_UseDebuggingNewOperator
  202496. bool dontRepaint;
  202497. static ModifierKeys currentModifiers;
  202498. static ModifierKeys modifiersAtLastCallback;
  202499. private:
  202500. HWND hwnd;
  202501. DropShadower* shadower;
  202502. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  202503. BorderSize windowBorder;
  202504. HICON currentWindowIcon;
  202505. NOTIFYICONDATA* taskBarIcon;
  202506. IDropTarget* dropTarget;
  202507. class TemporaryImage : public Timer
  202508. {
  202509. public:
  202510. TemporaryImage() {}
  202511. ~TemporaryImage() {}
  202512. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  202513. {
  202514. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  202515. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  202516. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  202517. startTimer (3000);
  202518. return image;
  202519. }
  202520. void timerCallback()
  202521. {
  202522. stopTimer();
  202523. image = 0;
  202524. }
  202525. private:
  202526. ScopedPointer <WindowsBitmapImage> image;
  202527. TemporaryImage (const TemporaryImage&);
  202528. TemporaryImage& operator= (const TemporaryImage&);
  202529. };
  202530. TemporaryImage offscreenImageGenerator;
  202531. class WindowClassHolder : public DeletedAtShutdown
  202532. {
  202533. public:
  202534. WindowClassHolder()
  202535. : windowClassName ("JUCE_")
  202536. {
  202537. // this name has to be different for each app/dll instance because otherwise
  202538. // poor old Win32 can get a bit confused (even despite it not being a process-global
  202539. // window class).
  202540. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  202541. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  202542. TCHAR moduleFile [1024];
  202543. moduleFile[0] = 0;
  202544. GetModuleFileName (moduleHandle, moduleFile, 1024);
  202545. WORD iconNum = 0;
  202546. WNDCLASSEX wcex;
  202547. wcex.cbSize = sizeof (wcex);
  202548. wcex.style = CS_OWNDC;
  202549. wcex.lpfnWndProc = (WNDPROC) windowProc;
  202550. wcex.lpszClassName = windowClassName;
  202551. wcex.cbClsExtra = 0;
  202552. wcex.cbWndExtra = 32;
  202553. wcex.hInstance = moduleHandle;
  202554. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  202555. iconNum = 1;
  202556. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  202557. wcex.hCursor = 0;
  202558. wcex.hbrBackground = 0;
  202559. wcex.lpszMenuName = 0;
  202560. RegisterClassEx (&wcex);
  202561. }
  202562. ~WindowClassHolder()
  202563. {
  202564. if (ComponentPeer::getNumPeers() == 0)
  202565. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  202566. clearSingletonInstance();
  202567. }
  202568. String windowClassName;
  202569. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  202570. };
  202571. static void* createWindowCallback (void* userData)
  202572. {
  202573. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  202574. return 0;
  202575. }
  202576. void createWindow()
  202577. {
  202578. DWORD exstyle = WS_EX_ACCEPTFILES;
  202579. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  202580. if (hasTitleBar())
  202581. {
  202582. type |= WS_OVERLAPPED;
  202583. exstyle |= WS_EX_APPWINDOW;
  202584. if ((styleFlags & windowHasCloseButton) != 0)
  202585. {
  202586. type |= WS_SYSMENU;
  202587. }
  202588. else
  202589. {
  202590. // annoyingly, windows won't let you have a min/max button without a close button
  202591. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  202592. }
  202593. if ((styleFlags & windowIsResizable) != 0)
  202594. type |= WS_THICKFRAME;
  202595. }
  202596. else
  202597. {
  202598. type |= WS_POPUP | WS_SYSMENU;
  202599. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  202600. exstyle |= WS_EX_TOOLWINDOW;
  202601. else
  202602. exstyle |= WS_EX_APPWINDOW;
  202603. }
  202604. if ((styleFlags & windowHasMinimiseButton) != 0)
  202605. type |= WS_MINIMIZEBOX;
  202606. if ((styleFlags & windowHasMaximiseButton) != 0)
  202607. type |= WS_MAXIMIZEBOX;
  202608. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  202609. exstyle |= WS_EX_TRANSPARENT;
  202610. if ((styleFlags & windowIsSemiTransparent) != 0
  202611. && Desktop::canUseSemiTransparentWindows())
  202612. exstyle |= WS_EX_LAYERED;
  202613. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  202614. if (hwnd != 0)
  202615. {
  202616. SetWindowLongPtr (hwnd, 0, 0);
  202617. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  202618. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  202619. if (dropTarget == 0)
  202620. dropTarget = new JuceDropTarget (this);
  202621. RegisterDragDrop (hwnd, dropTarget);
  202622. updateBorderSize();
  202623. // Calling this function here is (for some reason) necessary to make Windows
  202624. // correctly enable the menu items that we specify in the wm_initmenu message.
  202625. GetSystemMenu (hwnd, false);
  202626. }
  202627. else
  202628. {
  202629. jassertfalse
  202630. }
  202631. }
  202632. static void* destroyWindowCallback (void* handle)
  202633. {
  202634. RevokeDragDrop ((HWND) handle);
  202635. DestroyWindow ((HWND) handle);
  202636. return 0;
  202637. }
  202638. static void* toFrontCallback1 (void* h)
  202639. {
  202640. SetForegroundWindow ((HWND) h);
  202641. return 0;
  202642. }
  202643. static void* toFrontCallback2 (void* h)
  202644. {
  202645. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202646. return 0;
  202647. }
  202648. static void* setFocusCallback (void* h)
  202649. {
  202650. SetFocus ((HWND) h);
  202651. return 0;
  202652. }
  202653. static void* getFocusCallback (void*)
  202654. {
  202655. return GetFocus();
  202656. }
  202657. void offsetWithinParent (int& x, int& y) const
  202658. {
  202659. if (isTransparent())
  202660. {
  202661. HWND parentHwnd = GetParent (hwnd);
  202662. if (parentHwnd != 0)
  202663. {
  202664. RECT parentRect;
  202665. GetWindowRect (parentHwnd, &parentRect);
  202666. x += parentRect.left;
  202667. y += parentRect.top;
  202668. }
  202669. }
  202670. }
  202671. bool isTransparent() const
  202672. {
  202673. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  202674. }
  202675. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  202676. void setIcon (const Image& newIcon)
  202677. {
  202678. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  202679. if (hicon != 0)
  202680. {
  202681. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  202682. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  202683. if (currentWindowIcon != 0)
  202684. DestroyIcon (currentWindowIcon);
  202685. currentWindowIcon = hicon;
  202686. }
  202687. }
  202688. void handlePaintMessage()
  202689. {
  202690. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  202691. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  202692. PAINTSTRUCT paintStruct;
  202693. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  202694. // message and become re-entrant, but that's OK
  202695. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  202696. // corrupt the image it's using to paint into, so do a check here.
  202697. static bool reentrant = false;
  202698. if (reentrant)
  202699. {
  202700. DeleteObject (rgn);
  202701. EndPaint (hwnd, &paintStruct);
  202702. return;
  202703. }
  202704. reentrant = true;
  202705. // this is the rectangle to update..
  202706. int x = paintStruct.rcPaint.left;
  202707. int y = paintStruct.rcPaint.top;
  202708. int w = paintStruct.rcPaint.right - x;
  202709. int h = paintStruct.rcPaint.bottom - y;
  202710. const bool transparent = isTransparent();
  202711. if (transparent)
  202712. {
  202713. // it's not possible to have a transparent window with a title bar at the moment!
  202714. jassert (! hasTitleBar());
  202715. RECT r;
  202716. GetWindowRect (hwnd, &r);
  202717. x = y = 0;
  202718. w = r.right - r.left;
  202719. h = r.bottom - r.top;
  202720. }
  202721. if (w > 0 && h > 0)
  202722. {
  202723. clearMaskedRegion();
  202724. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  202725. RectangleList contextClip;
  202726. bool needToPaintAll = true;
  202727. if (regionType == COMPLEXREGION && ! transparent)
  202728. {
  202729. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  202730. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  202731. DeleteObject (clipRgn);
  202732. char rgnData [8192];
  202733. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  202734. if (res > 0 && res <= sizeof (rgnData))
  202735. {
  202736. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  202737. if (hdr->iType == RDH_RECTANGLES
  202738. && hdr->rcBound.right - hdr->rcBound.left >= w
  202739. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  202740. {
  202741. needToPaintAll = false;
  202742. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  202743. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  202744. while (--num >= 0)
  202745. {
  202746. // (need to move this one pixel to the left because of a win32 bug)
  202747. const int cx = jmax (x, (int) rects->left - 1);
  202748. const int cy = rects->top;
  202749. const int cw = rects->right - cx;
  202750. const int ch = rects->bottom - rects->top;
  202751. if (cx + cw - x <= w && cy + ch - y <= h)
  202752. {
  202753. contextClip.addWithoutMerging (Rectangle<int> (cx - x, cy - y, cw, ch));
  202754. }
  202755. else
  202756. {
  202757. needToPaintAll = true;
  202758. break;
  202759. }
  202760. ++rects;
  202761. }
  202762. }
  202763. }
  202764. }
  202765. if (needToPaintAll)
  202766. {
  202767. contextClip.clear();
  202768. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  202769. }
  202770. if (transparent)
  202771. {
  202772. RectangleList::Iterator i (contextClip);
  202773. while (i.next())
  202774. {
  202775. const Rectangle<int>& r = *i.getRectangle();
  202776. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  202777. }
  202778. }
  202779. // if the component's not opaque, this won't draw properly unless the platform can support this
  202780. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  202781. updateCurrentModifiers();
  202782. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  202783. context.clipToRectangleList (contextClip);
  202784. context.setOrigin (-x, -y);
  202785. handlePaint (context);
  202786. if (! dontRepaint)
  202787. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  202788. }
  202789. DeleteObject (rgn);
  202790. EndPaint (hwnd, &paintStruct);
  202791. reentrant = false;
  202792. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  202793. _fpreset(); // because some graphics cards can unmask FP exceptions
  202794. #endif
  202795. lastPaintTime = Time::getMillisecondCounter();
  202796. }
  202797. void doMouseEvent (const Point<int>& position)
  202798. {
  202799. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  202800. }
  202801. void doMouseMove (const Point<int>& position)
  202802. {
  202803. if (! isMouseOver)
  202804. {
  202805. isMouseOver = true;
  202806. updateKeyModifiers();
  202807. TRACKMOUSEEVENT tme;
  202808. tme.cbSize = sizeof (tme);
  202809. tme.dwFlags = TME_LEAVE;
  202810. tme.hwndTrack = hwnd;
  202811. tme.dwHoverTime = 0;
  202812. if (! TrackMouseEvent (&tme))
  202813. jassertfalse;
  202814. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  202815. }
  202816. else if (! isDragging)
  202817. {
  202818. if (! contains (position, false))
  202819. return;
  202820. }
  202821. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  202822. static uint32 lastMouseTime = 0;
  202823. const uint32 now = Time::getMillisecondCounter();
  202824. const int maxMouseMovesPerSecond = 60;
  202825. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  202826. {
  202827. lastMouseTime = now;
  202828. doMouseEvent (position);
  202829. }
  202830. }
  202831. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  202832. {
  202833. if (GetCapture() != hwnd)
  202834. SetCapture (hwnd);
  202835. doMouseMove (position);
  202836. updateModifiersFromWParam (wParam);
  202837. isDragging = true;
  202838. doMouseEvent (position);
  202839. }
  202840. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  202841. {
  202842. updateModifiersFromWParam (wParam);
  202843. isDragging = false;
  202844. // release the mouse capture if the user has released all buttons
  202845. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  202846. ReleaseCapture();
  202847. doMouseEvent (position);
  202848. }
  202849. void doCaptureChanged()
  202850. {
  202851. if (isDragging)
  202852. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  202853. }
  202854. void doMouseExit()
  202855. {
  202856. isMouseOver = false;
  202857. doMouseEvent (getCurrentMousePos());
  202858. }
  202859. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  202860. {
  202861. updateKeyModifiers();
  202862. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  202863. handleMouseWheel (0, position, getMouseEventTime(),
  202864. isVertical ? 0.0f : amount,
  202865. isVertical ? amount : 0.0f);
  202866. }
  202867. void sendModifierKeyChangeIfNeeded()
  202868. {
  202869. if (modifiersAtLastCallback != currentModifiers)
  202870. {
  202871. modifiersAtLastCallback = currentModifiers;
  202872. handleModifierKeysChange();
  202873. }
  202874. }
  202875. bool doKeyUp (const WPARAM key)
  202876. {
  202877. updateKeyModifiers();
  202878. switch (key)
  202879. {
  202880. case VK_SHIFT:
  202881. case VK_CONTROL:
  202882. case VK_MENU:
  202883. case VK_CAPITAL:
  202884. case VK_LWIN:
  202885. case VK_RWIN:
  202886. case VK_APPS:
  202887. case VK_NUMLOCK:
  202888. case VK_SCROLL:
  202889. case VK_LSHIFT:
  202890. case VK_RSHIFT:
  202891. case VK_LCONTROL:
  202892. case VK_LMENU:
  202893. case VK_RCONTROL:
  202894. case VK_RMENU:
  202895. sendModifierKeyChangeIfNeeded();
  202896. }
  202897. return handleKeyUpOrDown (false)
  202898. || Component::getCurrentlyModalComponent() != 0;
  202899. }
  202900. bool doKeyDown (const WPARAM key)
  202901. {
  202902. updateKeyModifiers();
  202903. bool used = false;
  202904. switch (key)
  202905. {
  202906. case VK_SHIFT:
  202907. case VK_LSHIFT:
  202908. case VK_RSHIFT:
  202909. case VK_CONTROL:
  202910. case VK_LCONTROL:
  202911. case VK_RCONTROL:
  202912. case VK_MENU:
  202913. case VK_LMENU:
  202914. case VK_RMENU:
  202915. case VK_LWIN:
  202916. case VK_RWIN:
  202917. case VK_CAPITAL:
  202918. case VK_NUMLOCK:
  202919. case VK_SCROLL:
  202920. case VK_APPS:
  202921. sendModifierKeyChangeIfNeeded();
  202922. break;
  202923. case VK_LEFT:
  202924. case VK_RIGHT:
  202925. case VK_UP:
  202926. case VK_DOWN:
  202927. case VK_PRIOR:
  202928. case VK_NEXT:
  202929. case VK_HOME:
  202930. case VK_END:
  202931. case VK_DELETE:
  202932. case VK_INSERT:
  202933. case VK_F1:
  202934. case VK_F2:
  202935. case VK_F3:
  202936. case VK_F4:
  202937. case VK_F5:
  202938. case VK_F6:
  202939. case VK_F7:
  202940. case VK_F8:
  202941. case VK_F9:
  202942. case VK_F10:
  202943. case VK_F11:
  202944. case VK_F12:
  202945. case VK_F13:
  202946. case VK_F14:
  202947. case VK_F15:
  202948. case VK_F16:
  202949. used = handleKeyUpOrDown (true);
  202950. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  202951. break;
  202952. case VK_ADD:
  202953. case VK_SUBTRACT:
  202954. case VK_MULTIPLY:
  202955. case VK_DIVIDE:
  202956. case VK_SEPARATOR:
  202957. case VK_DECIMAL:
  202958. used = handleKeyUpOrDown (true);
  202959. break;
  202960. default:
  202961. used = handleKeyUpOrDown (true);
  202962. {
  202963. MSG msg;
  202964. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  202965. {
  202966. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  202967. // manually generate the key-press event that matches this key-down.
  202968. const UINT keyChar = MapVirtualKey (key, 2);
  202969. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  202970. }
  202971. }
  202972. break;
  202973. }
  202974. if (Component::getCurrentlyModalComponent() != 0)
  202975. used = true;
  202976. return used;
  202977. }
  202978. bool doKeyChar (int key, const LPARAM flags)
  202979. {
  202980. updateKeyModifiers();
  202981. juce_wchar textChar = (juce_wchar) key;
  202982. const int virtualScanCode = (flags >> 16) & 0xff;
  202983. if (key >= '0' && key <= '9')
  202984. {
  202985. switch (virtualScanCode) // check for a numeric keypad scan-code
  202986. {
  202987. case 0x52:
  202988. case 0x4f:
  202989. case 0x50:
  202990. case 0x51:
  202991. case 0x4b:
  202992. case 0x4c:
  202993. case 0x4d:
  202994. case 0x47:
  202995. case 0x48:
  202996. case 0x49:
  202997. key = (key - '0') + KeyPress::numberPad0;
  202998. break;
  202999. default:
  203000. break;
  203001. }
  203002. }
  203003. else
  203004. {
  203005. // convert the scan code to an unmodified character code..
  203006. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  203007. UINT keyChar = MapVirtualKey (virtualKey, 2);
  203008. keyChar = LOWORD (keyChar);
  203009. if (keyChar != 0)
  203010. key = (int) keyChar;
  203011. // avoid sending junk text characters for some control-key combinations
  203012. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  203013. textChar = 0;
  203014. }
  203015. return handleKeyPress (key, textChar);
  203016. }
  203017. bool doAppCommand (const LPARAM lParam)
  203018. {
  203019. int key = 0;
  203020. switch (GET_APPCOMMAND_LPARAM (lParam))
  203021. {
  203022. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  203023. key = KeyPress::playKey;
  203024. break;
  203025. case APPCOMMAND_MEDIA_STOP:
  203026. key = KeyPress::stopKey;
  203027. break;
  203028. case APPCOMMAND_MEDIA_NEXTTRACK:
  203029. key = KeyPress::fastForwardKey;
  203030. break;
  203031. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  203032. key = KeyPress::rewindKey;
  203033. break;
  203034. }
  203035. if (key != 0)
  203036. {
  203037. updateKeyModifiers();
  203038. if (hwnd == GetActiveWindow())
  203039. {
  203040. handleKeyPress (key, 0);
  203041. return true;
  203042. }
  203043. }
  203044. return false;
  203045. }
  203046. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  203047. {
  203048. public:
  203049. JuceDropTarget (Win32ComponentPeer* const owner_)
  203050. : owner (owner_)
  203051. {
  203052. }
  203053. ~JuceDropTarget() {}
  203054. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203055. {
  203056. updateFileList (pDataObject);
  203057. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203058. *pdwEffect = DROPEFFECT_COPY;
  203059. return S_OK;
  203060. }
  203061. HRESULT __stdcall DragLeave()
  203062. {
  203063. owner->handleFileDragExit (files);
  203064. return S_OK;
  203065. }
  203066. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203067. {
  203068. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203069. *pdwEffect = DROPEFFECT_COPY;
  203070. return S_OK;
  203071. }
  203072. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203073. {
  203074. updateFileList (pDataObject);
  203075. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203076. *pdwEffect = DROPEFFECT_COPY;
  203077. return S_OK;
  203078. }
  203079. private:
  203080. Win32ComponentPeer* const owner;
  203081. StringArray files;
  203082. void updateFileList (IDataObject* const pDataObject)
  203083. {
  203084. files.clear();
  203085. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203086. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203087. if (pDataObject->GetData (&format, &medium) == S_OK)
  203088. {
  203089. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  203090. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  203091. unsigned int i = 0;
  203092. if (pDropFiles->fWide)
  203093. {
  203094. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  203095. for (;;)
  203096. {
  203097. unsigned int len = 0;
  203098. while (i + len < totalLen && fname [i + len] != 0)
  203099. ++len;
  203100. if (len == 0)
  203101. break;
  203102. files.add (String (fname + i, len));
  203103. i += len + 1;
  203104. }
  203105. }
  203106. else
  203107. {
  203108. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  203109. for (;;)
  203110. {
  203111. unsigned int len = 0;
  203112. while (i + len < totalLen && fname [i + len] != 0)
  203113. ++len;
  203114. if (len == 0)
  203115. break;
  203116. files.add (String (fname + i, len));
  203117. i += len + 1;
  203118. }
  203119. }
  203120. GlobalUnlock (medium.hGlobal);
  203121. }
  203122. }
  203123. JuceDropTarget (const JuceDropTarget&);
  203124. JuceDropTarget& operator= (const JuceDropTarget&);
  203125. };
  203126. void doSettingChange()
  203127. {
  203128. Desktop::getInstance().refreshMonitorSizes();
  203129. if (fullScreen && ! isMinimised())
  203130. {
  203131. const Rectangle<int> r (component->getParentMonitorArea());
  203132. SetWindowPos (hwnd, 0,
  203133. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  203134. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  203135. }
  203136. }
  203137. public:
  203138. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203139. {
  203140. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  203141. if (peer != 0)
  203142. return peer->peerWindowProc (h, message, wParam, lParam);
  203143. return DefWindowProcW (h, message, wParam, lParam);
  203144. }
  203145. private:
  203146. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  203147. {
  203148. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  203149. }
  203150. const Point<int> getCurrentMousePos() throw()
  203151. {
  203152. RECT wr;
  203153. GetWindowRect (hwnd, &wr);
  203154. const DWORD mp = GetMessagePos();
  203155. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  203156. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  203157. }
  203158. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203159. {
  203160. if (isValidPeer (this))
  203161. {
  203162. switch (message)
  203163. {
  203164. case WM_NCHITTEST:
  203165. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  203166. return HTTRANSPARENT;
  203167. if (hasTitleBar())
  203168. break;
  203169. return HTCLIENT;
  203170. case WM_PAINT:
  203171. handlePaintMessage();
  203172. return 0;
  203173. case WM_NCPAINT:
  203174. if (wParam != 1)
  203175. handlePaintMessage();
  203176. if (hasTitleBar())
  203177. break;
  203178. return 0;
  203179. case WM_ERASEBKGND:
  203180. case WM_NCCALCSIZE:
  203181. if (hasTitleBar())
  203182. break;
  203183. return 1;
  203184. case WM_MOUSEMOVE:
  203185. doMouseMove (getPointFromLParam (lParam));
  203186. return 0;
  203187. case WM_MOUSELEAVE:
  203188. doMouseExit();
  203189. return 0;
  203190. case WM_LBUTTONDOWN:
  203191. case WM_MBUTTONDOWN:
  203192. case WM_RBUTTONDOWN:
  203193. doMouseDown (getPointFromLParam (lParam), wParam);
  203194. return 0;
  203195. case WM_LBUTTONUP:
  203196. case WM_MBUTTONUP:
  203197. case WM_RBUTTONUP:
  203198. doMouseUp (getPointFromLParam (lParam), wParam);
  203199. return 0;
  203200. case WM_CAPTURECHANGED:
  203201. doCaptureChanged();
  203202. return 0;
  203203. case WM_NCMOUSEMOVE:
  203204. if (hasTitleBar())
  203205. break;
  203206. return 0;
  203207. case 0x020A: /* WM_MOUSEWHEEL */
  203208. doMouseWheel (getCurrentMousePos(), wParam, true);
  203209. return 0;
  203210. case 0x020E: /* WM_MOUSEHWHEEL */
  203211. doMouseWheel (getCurrentMousePos(), wParam, false);
  203212. return 0;
  203213. case WM_WINDOWPOSCHANGING:
  203214. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  203215. {
  203216. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  203217. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  203218. {
  203219. if (constrainer != 0)
  203220. {
  203221. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  203222. component->getY() - windowBorder.getTop(),
  203223. component->getWidth() + windowBorder.getLeftAndRight(),
  203224. component->getHeight() + windowBorder.getTopAndBottom());
  203225. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  203226. constrainer->checkBounds (pos, current,
  203227. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  203228. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  203229. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  203230. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  203231. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  203232. wp->x = pos.getX();
  203233. wp->y = pos.getY();
  203234. wp->cx = pos.getWidth();
  203235. wp->cy = pos.getHeight();
  203236. }
  203237. }
  203238. }
  203239. return 0;
  203240. case WM_WINDOWPOSCHANGED:
  203241. handleMovedOrResized();
  203242. if (dontRepaint)
  203243. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  203244. return 0;
  203245. case WM_KEYDOWN:
  203246. case WM_SYSKEYDOWN:
  203247. if (doKeyDown (wParam))
  203248. return 0;
  203249. break;
  203250. case WM_KEYUP:
  203251. case WM_SYSKEYUP:
  203252. if (doKeyUp (wParam))
  203253. return 0;
  203254. break;
  203255. case WM_CHAR:
  203256. if (doKeyChar ((int) wParam, lParam))
  203257. return 0;
  203258. break;
  203259. case WM_APPCOMMAND:
  203260. if (doAppCommand (lParam))
  203261. return TRUE;
  203262. break;
  203263. case WM_SETFOCUS:
  203264. updateKeyModifiers();
  203265. handleFocusGain();
  203266. break;
  203267. case WM_KILLFOCUS:
  203268. if (hasCreatedCaret)
  203269. {
  203270. hasCreatedCaret = false;
  203271. DestroyCaret();
  203272. }
  203273. handleFocusLoss();
  203274. break;
  203275. case WM_ACTIVATEAPP:
  203276. // Windows does weird things to process priority when you swap apps,
  203277. // so this forces an update when the app is brought to the front
  203278. if (wParam != FALSE)
  203279. juce_repeatLastProcessPriority();
  203280. else
  203281. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  203282. juce_CheckCurrentlyFocusedTopLevelWindow();
  203283. modifiersAtLastCallback = -1;
  203284. return 0;
  203285. case WM_ACTIVATE:
  203286. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  203287. {
  203288. modifiersAtLastCallback = -1;
  203289. updateKeyModifiers();
  203290. if (isMinimised())
  203291. {
  203292. component->repaint();
  203293. handleMovedOrResized();
  203294. if (! ComponentPeer::isValidPeer (this))
  203295. return 0;
  203296. }
  203297. if (LOWORD (wParam) == WA_CLICKACTIVE
  203298. && component->isCurrentlyBlockedByAnotherModalComponent())
  203299. {
  203300. const Point<int> mousePos (component->getMouseXYRelative());
  203301. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  203302. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  203303. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  203304. return 0;
  203305. }
  203306. handleBroughtToFront();
  203307. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203308. Component::getCurrentlyModalComponent()->toFront (true);
  203309. return 0;
  203310. }
  203311. break;
  203312. case WM_NCACTIVATE:
  203313. // while a temporary window is being shown, prevent Windows from deactivating the
  203314. // title bars of our main windows.
  203315. if (wParam == 0 && ! shouldDeactivateTitleBar)
  203316. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  203317. break;
  203318. case WM_MOUSEACTIVATE:
  203319. if (! component->getMouseClickGrabsKeyboardFocus())
  203320. return MA_NOACTIVATE;
  203321. break;
  203322. case WM_SHOWWINDOW:
  203323. if (wParam != 0)
  203324. handleBroughtToFront();
  203325. break;
  203326. case WM_CLOSE:
  203327. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  203328. handleUserClosingWindow();
  203329. return 0;
  203330. case WM_QUERYENDSESSION:
  203331. if (JUCEApplication::getInstance() != 0)
  203332. {
  203333. JUCEApplication::getInstance()->systemRequestedQuit();
  203334. return MessageManager::getInstance()->hasStopMessageBeenSent();
  203335. }
  203336. return TRUE;
  203337. case WM_TRAYNOTIFY:
  203338. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203339. {
  203340. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  203341. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203342. {
  203343. Component* const current = Component::getCurrentlyModalComponent();
  203344. if (current != 0)
  203345. current->inputAttemptWhenModal();
  203346. }
  203347. }
  203348. else
  203349. {
  203350. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  203351. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  203352. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  203353. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  203354. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  203355. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203356. eventMods = eventMods.withoutMouseButtons();
  203357. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  203358. Point<int>(), eventMods, component, getMouseEventTime(),
  203359. Point<int>(), getMouseEventTime(), 1, false);
  203360. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  203361. {
  203362. SetFocus (hwnd);
  203363. SetForegroundWindow (hwnd);
  203364. component->mouseDown (e);
  203365. }
  203366. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203367. {
  203368. component->mouseUp (e);
  203369. }
  203370. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203371. {
  203372. component->mouseDoubleClick (e);
  203373. }
  203374. else if (lParam == WM_MOUSEMOVE)
  203375. {
  203376. component->mouseMove (e);
  203377. }
  203378. }
  203379. break;
  203380. case WM_SYNCPAINT:
  203381. return 0;
  203382. case WM_PALETTECHANGED:
  203383. InvalidateRect (h, 0, 0);
  203384. break;
  203385. case WM_DISPLAYCHANGE:
  203386. InvalidateRect (h, 0, 0);
  203387. createPaletteIfNeeded = true;
  203388. // intentional fall-through...
  203389. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  203390. doSettingChange();
  203391. break;
  203392. case WM_INITMENU:
  203393. if (! hasTitleBar())
  203394. {
  203395. if (isFullScreen())
  203396. {
  203397. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  203398. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  203399. }
  203400. else if (! isMinimised())
  203401. {
  203402. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  203403. }
  203404. }
  203405. break;
  203406. case WM_SYSCOMMAND:
  203407. switch (wParam & 0xfff0)
  203408. {
  203409. case SC_CLOSE:
  203410. if (sendInputAttemptWhenModalMessage())
  203411. return 0;
  203412. if (hasTitleBar())
  203413. {
  203414. PostMessage (h, WM_CLOSE, 0, 0);
  203415. return 0;
  203416. }
  203417. break;
  203418. case SC_KEYMENU:
  203419. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  203420. // obscure situations that can arise if a modal loop is started from an alt-key
  203421. // keypress).
  203422. if (hasTitleBar() && h == GetCapture())
  203423. ReleaseCapture();
  203424. break;
  203425. case SC_MAXIMIZE:
  203426. if (sendInputAttemptWhenModalMessage())
  203427. return 0;
  203428. setFullScreen (true);
  203429. return 0;
  203430. case SC_MINIMIZE:
  203431. if (sendInputAttemptWhenModalMessage())
  203432. return 0;
  203433. if (! hasTitleBar())
  203434. {
  203435. setMinimised (true);
  203436. return 0;
  203437. }
  203438. break;
  203439. case SC_RESTORE:
  203440. if (sendInputAttemptWhenModalMessage())
  203441. return 0;
  203442. if (hasTitleBar())
  203443. {
  203444. if (isFullScreen())
  203445. {
  203446. setFullScreen (false);
  203447. return 0;
  203448. }
  203449. }
  203450. else
  203451. {
  203452. if (isMinimised())
  203453. setMinimised (false);
  203454. else if (isFullScreen())
  203455. setFullScreen (false);
  203456. return 0;
  203457. }
  203458. break;
  203459. }
  203460. break;
  203461. case WM_NCLBUTTONDOWN:
  203462. case WM_NCRBUTTONDOWN:
  203463. case WM_NCMBUTTONDOWN:
  203464. sendInputAttemptWhenModalMessage();
  203465. break;
  203466. //case WM_IME_STARTCOMPOSITION;
  203467. // return 0;
  203468. case WM_GETDLGCODE:
  203469. return DLGC_WANTALLKEYS;
  203470. default:
  203471. break;
  203472. }
  203473. }
  203474. return DefWindowProcW (h, message, wParam, lParam);
  203475. }
  203476. bool sendInputAttemptWhenModalMessage()
  203477. {
  203478. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203479. {
  203480. Component* const current = Component::getCurrentlyModalComponent();
  203481. if (current != 0)
  203482. current->inputAttemptWhenModal();
  203483. return true;
  203484. }
  203485. return false;
  203486. }
  203487. Win32ComponentPeer (const Win32ComponentPeer&);
  203488. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  203489. };
  203490. ModifierKeys Win32ComponentPeer::currentModifiers;
  203491. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  203492. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  203493. {
  203494. return new Win32ComponentPeer (this, styleFlags);
  203495. }
  203496. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  203497. void ModifierKeys::updateCurrentModifiers() throw()
  203498. {
  203499. currentModifiers = Win32ComponentPeer::currentModifiers;
  203500. }
  203501. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  203502. {
  203503. Win32ComponentPeer::updateKeyModifiers();
  203504. int keyMods = 0;
  203505. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  203506. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  203507. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  203508. Win32ComponentPeer::currentModifiers
  203509. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  203510. return Win32ComponentPeer::currentModifiers;
  203511. }
  203512. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  203513. {
  203514. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  203515. if (wp != 0)
  203516. wp->setTaskBarIcon (&newImage);
  203517. }
  203518. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  203519. {
  203520. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  203521. if (wp != 0)
  203522. wp->setTaskBarIconToolTip (tooltip);
  203523. }
  203524. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  203525. {
  203526. DWORD val = GetWindowLong (h, styleType);
  203527. if (bitIsSet)
  203528. val |= feature;
  203529. else
  203530. val &= ~feature;
  203531. SetWindowLongPtr (h, styleType, val);
  203532. SetWindowPos (h, 0, 0, 0, 0, 0,
  203533. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  203534. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  203535. }
  203536. bool Process::isForegroundProcess()
  203537. {
  203538. HWND fg = GetForegroundWindow();
  203539. if (fg == 0)
  203540. return true;
  203541. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  203542. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  203543. // have to see if any of our windows are children of the foreground window
  203544. fg = GetAncestor (fg, GA_ROOT);
  203545. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  203546. {
  203547. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  203548. if (wp != 0 && wp->isInside (fg))
  203549. return true;
  203550. }
  203551. return false;
  203552. }
  203553. bool AlertWindow::showNativeDialogBox (const String& title,
  203554. const String& bodyText,
  203555. bool isOkCancel)
  203556. {
  203557. return MessageBox (0, bodyText, title,
  203558. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  203559. : MB_OK)) == IDOK;
  203560. }
  203561. void Desktop::createMouseInputSources()
  203562. {
  203563. mouseSources.add (new MouseInputSource (0, true));
  203564. }
  203565. const Point<int> Desktop::getMousePosition()
  203566. {
  203567. POINT mousePos;
  203568. GetCursorPos (&mousePos);
  203569. return Point<int> (mousePos.x, mousePos.y);
  203570. }
  203571. void Desktop::setMousePosition (const Point<int>& newPosition)
  203572. {
  203573. SetCursorPos (newPosition.getX(), newPosition.getY());
  203574. }
  203575. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  203576. {
  203577. return new Image (format, imageWidth, imageHeight, clearImage);
  203578. }
  203579. class ScreenSaverDefeater : public Timer,
  203580. public DeletedAtShutdown
  203581. {
  203582. public:
  203583. ScreenSaverDefeater() throw()
  203584. {
  203585. startTimer (10000);
  203586. timerCallback();
  203587. }
  203588. ~ScreenSaverDefeater() {}
  203589. void timerCallback()
  203590. {
  203591. if (Process::isForegroundProcess())
  203592. {
  203593. // simulate a shift key getting pressed..
  203594. INPUT input[2];
  203595. input[0].type = INPUT_KEYBOARD;
  203596. input[0].ki.wVk = VK_SHIFT;
  203597. input[0].ki.dwFlags = 0;
  203598. input[0].ki.dwExtraInfo = 0;
  203599. input[1].type = INPUT_KEYBOARD;
  203600. input[1].ki.wVk = VK_SHIFT;
  203601. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  203602. input[1].ki.dwExtraInfo = 0;
  203603. SendInput (2, input, sizeof (INPUT));
  203604. }
  203605. }
  203606. };
  203607. static ScreenSaverDefeater* screenSaverDefeater = 0;
  203608. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  203609. {
  203610. if (isEnabled)
  203611. {
  203612. deleteAndZero (screenSaverDefeater);
  203613. }
  203614. else if (screenSaverDefeater == 0)
  203615. {
  203616. screenSaverDefeater = new ScreenSaverDefeater();
  203617. }
  203618. }
  203619. bool Desktop::isScreenSaverEnabled() throw()
  203620. {
  203621. return screenSaverDefeater == 0;
  203622. }
  203623. /* (The code below is the "correct" way to disable the screen saver, but it
  203624. completely fails on winXP when the saver is password-protected...)
  203625. static bool juce_screenSaverEnabled = true;
  203626. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  203627. {
  203628. juce_screenSaverEnabled = isEnabled;
  203629. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  203630. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  203631. }
  203632. bool Desktop::isScreenSaverEnabled() throw()
  203633. {
  203634. return juce_screenSaverEnabled;
  203635. }
  203636. */
  203637. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  203638. {
  203639. if (enableOrDisable)
  203640. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  203641. }
  203642. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  203643. {
  203644. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  203645. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  203646. return TRUE;
  203647. }
  203648. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  203649. {
  203650. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  203651. // make sure the first in the list is the main monitor
  203652. for (int i = 1; i < monitorCoords.size(); ++i)
  203653. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  203654. monitorCoords.swap (i, 0);
  203655. if (monitorCoords.size() == 0)
  203656. {
  203657. RECT r;
  203658. GetWindowRect (GetDesktopWindow(), &r);
  203659. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  203660. }
  203661. if (clipToWorkArea)
  203662. {
  203663. // clip the main monitor to the active non-taskbar area
  203664. RECT r;
  203665. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  203666. Rectangle<int>& screen = monitorCoords.getReference (0);
  203667. screen.setPosition (jmax (screen.getX(), (int) r.left),
  203668. jmax (screen.getY(), (int) r.top));
  203669. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  203670. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  203671. }
  203672. }
  203673. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  203674. {
  203675. Image* im = 0;
  203676. if (bitmap != 0)
  203677. {
  203678. BITMAP bm;
  203679. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  203680. && bm.bmWidth > 0 && bm.bmHeight > 0)
  203681. {
  203682. HDC tempDC = GetDC (0);
  203683. HDC dc = CreateCompatibleDC (tempDC);
  203684. ReleaseDC (0, tempDC);
  203685. SelectObject (dc, bitmap);
  203686. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  203687. for (int y = bm.bmHeight; --y >= 0;)
  203688. {
  203689. for (int x = bm.bmWidth; --x >= 0;)
  203690. {
  203691. COLORREF col = GetPixel (dc, x, y);
  203692. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  203693. (uint8) GetGValue (col),
  203694. (uint8) GetBValue (col)));
  203695. }
  203696. }
  203697. DeleteDC (dc);
  203698. }
  203699. }
  203700. return im;
  203701. }
  203702. static Image* createImageFromHICON (HICON icon) throw()
  203703. {
  203704. ICONINFO info;
  203705. if (GetIconInfo (icon, &info))
  203706. {
  203707. ScopedPointer<Image> mask (createImageFromHBITMAP (info.hbmMask));
  203708. if (mask == 0)
  203709. return 0;
  203710. ScopedPointer<Image> image (createImageFromHBITMAP (info.hbmColor));
  203711. if (image == 0)
  203712. return mask.release();
  203713. for (int y = image->getHeight(); --y >= 0;)
  203714. {
  203715. for (int x = image->getWidth(); --x >= 0;)
  203716. {
  203717. const float brightness = mask->getPixelAt (x, y).getBrightness();
  203718. if (brightness > 0.0f)
  203719. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  203720. }
  203721. }
  203722. return image.release();
  203723. }
  203724. return 0;
  203725. }
  203726. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  203727. {
  203728. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  203729. {
  203730. Graphics g (bitmap);
  203731. g.drawImageAt (&image, 0, 0);
  203732. }
  203733. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  203734. ICONINFO info;
  203735. info.fIcon = isIcon;
  203736. info.xHotspot = hotspotX;
  203737. info.yHotspot = hotspotY;
  203738. info.hbmMask = mask;
  203739. info.hbmColor = bitmap.hBitmap;
  203740. HICON hi = CreateIconIndirect (&info);
  203741. DeleteObject (mask);
  203742. return hi;
  203743. }
  203744. Image* juce_createIconForFile (const File& file)
  203745. {
  203746. Image* image = 0;
  203747. WCHAR filename [1024];
  203748. file.getFullPathName().copyToUnicode (filename, 1023);
  203749. WORD iconNum = 0;
  203750. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  203751. filename, &iconNum);
  203752. if (icon != 0)
  203753. {
  203754. image = createImageFromHICON (icon);
  203755. DestroyIcon (icon);
  203756. }
  203757. return image;
  203758. }
  203759. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  203760. {
  203761. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  203762. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  203763. const Image* im = &image;
  203764. ScopedPointer<Image> newIm;
  203765. if (image.getWidth() > maxW || image.getHeight() > maxH)
  203766. {
  203767. im = newIm = image.createCopy (maxW, maxH);
  203768. hotspotX = (hotspotX * maxW) / image.getWidth();
  203769. hotspotY = (hotspotY * maxH) / image.getHeight();
  203770. }
  203771. return createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  203772. }
  203773. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  203774. {
  203775. if (cursorHandle != 0 && ! isStandard)
  203776. DestroyCursor ((HCURSOR) cursorHandle);
  203777. }
  203778. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  203779. {
  203780. LPCTSTR cursorName = IDC_ARROW;
  203781. switch (type)
  203782. {
  203783. case NormalCursor: break;
  203784. case NoCursor: return 0;
  203785. case WaitCursor: cursorName = IDC_WAIT; break;
  203786. case IBeamCursor: cursorName = IDC_IBEAM; break;
  203787. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  203788. case CrosshairCursor: cursorName = IDC_CROSS; break;
  203789. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  203790. case LeftRightResizeCursor:
  203791. case LeftEdgeResizeCursor:
  203792. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  203793. case UpDownResizeCursor:
  203794. case TopEdgeResizeCursor:
  203795. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  203796. case TopLeftCornerResizeCursor:
  203797. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  203798. case TopRightCornerResizeCursor:
  203799. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  203800. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  203801. case DraggingHandCursor:
  203802. {
  203803. static void* dragHandCursor = 0;
  203804. if (dragHandCursor == 0)
  203805. {
  203806. static const unsigned char dragHandData[] =
  203807. { 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,
  203808. 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,
  203809. 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 };
  203810. const ScopedPointer <Image> image (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)));
  203811. dragHandCursor = createMouseCursorFromImage (*image, 8, 7);
  203812. }
  203813. return dragHandCursor;
  203814. }
  203815. default:
  203816. jassertfalse; break;
  203817. }
  203818. HCURSOR cursorH = LoadCursor (0, cursorName);
  203819. if (cursorH == 0)
  203820. cursorH = LoadCursor (0, IDC_ARROW);
  203821. return cursorH;
  203822. }
  203823. void MouseCursor::showInWindow (ComponentPeer*) const
  203824. {
  203825. SetCursor ((HCURSOR) getHandle());
  203826. }
  203827. void MouseCursor::showInAllWindows() const
  203828. {
  203829. showInWindow (0);
  203830. }
  203831. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  203832. {
  203833. public:
  203834. JuceDropSource() {}
  203835. ~JuceDropSource() {}
  203836. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  203837. {
  203838. if (escapePressed)
  203839. return DRAGDROP_S_CANCEL;
  203840. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  203841. return DRAGDROP_S_DROP;
  203842. return S_OK;
  203843. }
  203844. HRESULT __stdcall GiveFeedback (DWORD)
  203845. {
  203846. return DRAGDROP_S_USEDEFAULTCURSORS;
  203847. }
  203848. };
  203849. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  203850. {
  203851. public:
  203852. JuceEnumFormatEtc (const FORMATETC* const format_)
  203853. : format (format_),
  203854. index (0)
  203855. {
  203856. }
  203857. ~JuceEnumFormatEtc() {}
  203858. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  203859. {
  203860. if (result == 0)
  203861. return E_POINTER;
  203862. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  203863. newOne->index = index;
  203864. *result = newOne;
  203865. return S_OK;
  203866. }
  203867. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  203868. {
  203869. if (pceltFetched != 0)
  203870. *pceltFetched = 0;
  203871. else if (celt != 1)
  203872. return S_FALSE;
  203873. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  203874. {
  203875. copyFormatEtc (lpFormatEtc [0], *format);
  203876. ++index;
  203877. if (pceltFetched != 0)
  203878. *pceltFetched = 1;
  203879. return S_OK;
  203880. }
  203881. return S_FALSE;
  203882. }
  203883. HRESULT __stdcall Skip (ULONG celt)
  203884. {
  203885. if (index + (int) celt >= 1)
  203886. return S_FALSE;
  203887. index += celt;
  203888. return S_OK;
  203889. }
  203890. HRESULT __stdcall Reset()
  203891. {
  203892. index = 0;
  203893. return S_OK;
  203894. }
  203895. private:
  203896. const FORMATETC* const format;
  203897. int index;
  203898. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  203899. {
  203900. dest = source;
  203901. if (source.ptd != 0)
  203902. {
  203903. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  203904. *(dest.ptd) = *(source.ptd);
  203905. }
  203906. }
  203907. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  203908. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  203909. };
  203910. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  203911. {
  203912. JuceDropSource* const dropSource;
  203913. const FORMATETC* const format;
  203914. const STGMEDIUM* const medium;
  203915. JuceDataObject (const JuceDataObject&);
  203916. JuceDataObject& operator= (const JuceDataObject&);
  203917. public:
  203918. JuceDataObject (JuceDropSource* const dropSource_,
  203919. const FORMATETC* const format_,
  203920. const STGMEDIUM* const medium_)
  203921. : dropSource (dropSource_),
  203922. format (format_),
  203923. medium (medium_)
  203924. {
  203925. }
  203926. virtual ~JuceDataObject()
  203927. {
  203928. jassert (refCount == 0);
  203929. }
  203930. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  203931. {
  203932. if ((pFormatEtc->tymed & format->tymed) != 0
  203933. && pFormatEtc->cfFormat == format->cfFormat
  203934. && pFormatEtc->dwAspect == format->dwAspect)
  203935. {
  203936. pMedium->tymed = format->tymed;
  203937. pMedium->pUnkForRelease = 0;
  203938. if (format->tymed == TYMED_HGLOBAL)
  203939. {
  203940. const SIZE_T len = GlobalSize (medium->hGlobal);
  203941. void* const src = GlobalLock (medium->hGlobal);
  203942. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  203943. memcpy (dst, src, len);
  203944. GlobalUnlock (medium->hGlobal);
  203945. pMedium->hGlobal = dst;
  203946. return S_OK;
  203947. }
  203948. }
  203949. return DV_E_FORMATETC;
  203950. }
  203951. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  203952. {
  203953. if (f == 0)
  203954. return E_INVALIDARG;
  203955. if (f->tymed == format->tymed
  203956. && f->cfFormat == format->cfFormat
  203957. && f->dwAspect == format->dwAspect)
  203958. return S_OK;
  203959. return DV_E_FORMATETC;
  203960. }
  203961. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  203962. {
  203963. pFormatEtcOut->ptd = 0;
  203964. return E_NOTIMPL;
  203965. }
  203966. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  203967. {
  203968. if (result == 0)
  203969. return E_POINTER;
  203970. if (direction == DATADIR_GET)
  203971. {
  203972. *result = new JuceEnumFormatEtc (format);
  203973. return S_OK;
  203974. }
  203975. *result = 0;
  203976. return E_NOTIMPL;
  203977. }
  203978. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  203979. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  203980. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  203981. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  203982. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  203983. };
  203984. static HDROP createHDrop (const StringArray& fileNames) throw()
  203985. {
  203986. int totalChars = 0;
  203987. for (int i = fileNames.size(); --i >= 0;)
  203988. totalChars += fileNames[i].length() + 1;
  203989. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  203990. sizeof (DROPFILES)
  203991. + sizeof (WCHAR) * (totalChars + 2));
  203992. if (hDrop != 0)
  203993. {
  203994. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  203995. pDropFiles->pFiles = sizeof (DROPFILES);
  203996. pDropFiles->fWide = true;
  203997. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  203998. for (int i = 0; i < fileNames.size(); ++i)
  203999. {
  204000. fileNames[i].copyToUnicode (fname, 2048);
  204001. fname += fileNames[i].length() + 1;
  204002. }
  204003. *fname = 0;
  204004. GlobalUnlock (hDrop);
  204005. }
  204006. return hDrop;
  204007. }
  204008. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  204009. {
  204010. JuceDropSource* const source = new JuceDropSource();
  204011. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  204012. DWORD effect;
  204013. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  204014. data->Release();
  204015. source->Release();
  204016. return res == DRAGDROP_S_DROP;
  204017. }
  204018. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  204019. {
  204020. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204021. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204022. medium.hGlobal = createHDrop (files);
  204023. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  204024. : DROPEFFECT_COPY);
  204025. }
  204026. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  204027. {
  204028. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204029. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204030. const int numChars = text.length();
  204031. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  204032. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  204033. text.copyToUnicode (data, numChars + 1);
  204034. format.cfFormat = CF_UNICODETEXT;
  204035. GlobalUnlock (medium.hGlobal);
  204036. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  204037. }
  204038. #endif
  204039. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  204040. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  204041. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204042. // compiled on its own).
  204043. #if JUCE_INCLUDED_FILE
  204044. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204045. NEWTEXTMETRICEXW*,
  204046. int type,
  204047. LPARAM lParam)
  204048. {
  204049. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204050. {
  204051. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204052. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  204053. }
  204054. return 1;
  204055. }
  204056. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204057. NEWTEXTMETRICEXW*,
  204058. int type,
  204059. LPARAM lParam)
  204060. {
  204061. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204062. {
  204063. LOGFONTW lf;
  204064. zerostruct (lf);
  204065. lf.lfWeight = FW_DONTCARE;
  204066. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204067. lf.lfQuality = DEFAULT_QUALITY;
  204068. lf.lfCharSet = DEFAULT_CHARSET;
  204069. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204070. lf.lfPitchAndFamily = FF_DONTCARE;
  204071. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204072. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  204073. HDC dc = CreateCompatibleDC (0);
  204074. EnumFontFamiliesEx (dc, &lf,
  204075. (FONTENUMPROCW) &wfontEnum2,
  204076. lParam, 0);
  204077. DeleteDC (dc);
  204078. }
  204079. return 1;
  204080. }
  204081. const StringArray Font::findAllTypefaceNames()
  204082. {
  204083. StringArray results;
  204084. HDC dc = CreateCompatibleDC (0);
  204085. {
  204086. LOGFONTW lf;
  204087. zerostruct (lf);
  204088. lf.lfWeight = FW_DONTCARE;
  204089. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204090. lf.lfQuality = DEFAULT_QUALITY;
  204091. lf.lfCharSet = DEFAULT_CHARSET;
  204092. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204093. lf.lfPitchAndFamily = FF_DONTCARE;
  204094. lf.lfFaceName[0] = 0;
  204095. EnumFontFamiliesEx (dc, &lf,
  204096. (FONTENUMPROCW) &wfontEnum1,
  204097. (LPARAM) &results, 0);
  204098. }
  204099. DeleteDC (dc);
  204100. results.sort (true);
  204101. return results;
  204102. }
  204103. extern bool juce_IsRunningInWine();
  204104. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  204105. {
  204106. if (juce_IsRunningInWine())
  204107. {
  204108. // If we're running in Wine, then use fonts that might be available on Linux..
  204109. defaultSans = "Bitstream Vera Sans";
  204110. defaultSerif = "Bitstream Vera Serif";
  204111. defaultFixed = "Bitstream Vera Sans Mono";
  204112. }
  204113. else
  204114. {
  204115. defaultSans = "Verdana";
  204116. defaultSerif = "Times";
  204117. defaultFixed = "Lucida Console";
  204118. }
  204119. }
  204120. class FontDCHolder : private DeletedAtShutdown
  204121. {
  204122. public:
  204123. FontDCHolder()
  204124. : dc (0), numKPs (0), size (0),
  204125. bold (false), italic (false)
  204126. {
  204127. }
  204128. ~FontDCHolder()
  204129. {
  204130. if (dc != 0)
  204131. {
  204132. DeleteDC (dc);
  204133. DeleteObject (fontH);
  204134. }
  204135. clearSingletonInstance();
  204136. }
  204137. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204138. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  204139. {
  204140. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204141. {
  204142. fontName = fontName_;
  204143. bold = bold_;
  204144. italic = italic_;
  204145. size = size_;
  204146. if (dc != 0)
  204147. {
  204148. DeleteDC (dc);
  204149. DeleteObject (fontH);
  204150. kps.free();
  204151. }
  204152. fontH = 0;
  204153. dc = CreateCompatibleDC (0);
  204154. SetMapperFlags (dc, 0);
  204155. SetMapMode (dc, MM_TEXT);
  204156. LOGFONTW lfw;
  204157. zerostruct (lfw);
  204158. lfw.lfCharSet = DEFAULT_CHARSET;
  204159. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204160. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204161. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204162. lfw.lfQuality = PROOF_QUALITY;
  204163. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204164. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204165. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  204166. lfw.lfHeight = size > 0 ? size : -256;
  204167. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204168. if (standardSizedFont != 0)
  204169. {
  204170. if (SelectObject (dc, standardSizedFont) != 0)
  204171. {
  204172. fontH = standardSizedFont;
  204173. if (size == 0)
  204174. {
  204175. OUTLINETEXTMETRIC otm;
  204176. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204177. {
  204178. lfw.lfHeight = -(int) otm.otmEMSquare;
  204179. fontH = CreateFontIndirect (&lfw);
  204180. SelectObject (dc, fontH);
  204181. DeleteObject (standardSizedFont);
  204182. }
  204183. }
  204184. }
  204185. else
  204186. {
  204187. jassertfalse
  204188. }
  204189. }
  204190. else
  204191. {
  204192. jassertfalse
  204193. }
  204194. }
  204195. return dc;
  204196. }
  204197. KERNINGPAIR* getKerningPairs (int& numKPs_)
  204198. {
  204199. if (kps == 0)
  204200. {
  204201. numKPs = GetKerningPairs (dc, 0, 0);
  204202. kps.calloc (numKPs);
  204203. GetKerningPairs (dc, numKPs, kps);
  204204. }
  204205. numKPs_ = numKPs;
  204206. return kps;
  204207. }
  204208. private:
  204209. HFONT fontH;
  204210. HDC dc;
  204211. String fontName;
  204212. HeapBlock <KERNINGPAIR> kps;
  204213. int numKPs, size;
  204214. bool bold, italic;
  204215. FontDCHolder (const FontDCHolder&);
  204216. FontDCHolder& operator= (const FontDCHolder&);
  204217. };
  204218. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204219. class WindowsTypeface : public CustomTypeface
  204220. {
  204221. public:
  204222. WindowsTypeface (const Font& font)
  204223. {
  204224. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  204225. font.isBold(), font.isItalic(), 0);
  204226. TEXTMETRIC tm;
  204227. tm.tmAscent = tm.tmHeight = 1;
  204228. tm.tmDefaultChar = 0;
  204229. GetTextMetrics (dc, &tm);
  204230. setCharacteristics (font.getTypefaceName(),
  204231. tm.tmAscent / (float) tm.tmHeight,
  204232. font.isBold(), font.isItalic(),
  204233. tm.tmDefaultChar);
  204234. }
  204235. bool loadGlyphIfPossible (juce_wchar character)
  204236. {
  204237. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  204238. GLYPHMETRICS gm;
  204239. {
  204240. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204241. WORD index = 0;
  204242. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204243. && index == 0xffff)
  204244. {
  204245. return false;
  204246. }
  204247. }
  204248. Path glyphPath;
  204249. TEXTMETRIC tm;
  204250. if (! GetTextMetrics (dc, &tm))
  204251. {
  204252. addGlyph (character, glyphPath, 0);
  204253. return true;
  204254. }
  204255. const float height = (float) tm.tmHeight;
  204256. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204257. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204258. &gm, 0, 0, &identityMatrix);
  204259. if (bufSize > 0)
  204260. {
  204261. HeapBlock<char> data (bufSize);
  204262. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204263. bufSize, data, &identityMatrix);
  204264. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  204265. const float scaleX = 1.0f / height;
  204266. const float scaleY = -1.0f / height;
  204267. while ((char*) pheader < data + bufSize)
  204268. {
  204269. float x = scaleX * pheader->pfxStart.x.value;
  204270. float y = scaleY * pheader->pfxStart.y.value;
  204271. glyphPath.startNewSubPath (x, y);
  204272. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204273. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204274. while ((const char*) curve < curveEnd)
  204275. {
  204276. if (curve->wType == TT_PRIM_LINE)
  204277. {
  204278. for (int i = 0; i < curve->cpfx; ++i)
  204279. {
  204280. x = scaleX * curve->apfx[i].x.value;
  204281. y = scaleY * curve->apfx[i].y.value;
  204282. glyphPath.lineTo (x, y);
  204283. }
  204284. }
  204285. else if (curve->wType == TT_PRIM_QSPLINE)
  204286. {
  204287. for (int i = 0; i < curve->cpfx - 1; ++i)
  204288. {
  204289. const float x2 = scaleX * curve->apfx[i].x.value;
  204290. const float y2 = scaleY * curve->apfx[i].y.value;
  204291. float x3, y3;
  204292. if (i < curve->cpfx - 2)
  204293. {
  204294. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  204295. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  204296. }
  204297. else
  204298. {
  204299. x3 = scaleX * curve->apfx[i + 1].x.value;
  204300. y3 = scaleY * curve->apfx[i + 1].y.value;
  204301. }
  204302. glyphPath.quadraticTo (x2, y2, x3, y3);
  204303. x = x3;
  204304. y = y3;
  204305. }
  204306. }
  204307. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204308. }
  204309. pheader = (const TTPOLYGONHEADER*) curve;
  204310. glyphPath.closeSubPath();
  204311. }
  204312. }
  204313. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  204314. int numKPs;
  204315. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204316. for (int i = 0; i < numKPs; ++i)
  204317. {
  204318. if (kps[i].wFirst == character)
  204319. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  204320. kps[i].iKernAmount / height);
  204321. }
  204322. return true;
  204323. }
  204324. };
  204325. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  204326. {
  204327. return new WindowsTypeface (font);
  204328. }
  204329. #endif
  204330. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  204331. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  204332. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204333. // compiled on its own).
  204334. #if JUCE_INCLUDED_FILE
  204335. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  204336. namespace FileChooserHelpers
  204337. {
  204338. static const void* defaultDirPath = 0;
  204339. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  204340. static Component* currentExtraFileWin = 0;
  204341. static bool areThereAnyAlwaysOnTopWindows()
  204342. {
  204343. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  204344. {
  204345. Component* c = Desktop::getInstance().getComponent (i);
  204346. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  204347. return true;
  204348. }
  204349. return false;
  204350. }
  204351. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  204352. {
  204353. if (msg == BFFM_INITIALIZED)
  204354. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  204355. else if (msg == BFFM_VALIDATEFAILEDW)
  204356. returnedString = (LPCWSTR) lParam;
  204357. else if (msg == BFFM_VALIDATEFAILEDA)
  204358. returnedString = (const char*) lParam;
  204359. return 0;
  204360. }
  204361. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  204362. {
  204363. if (currentExtraFileWin != 0)
  204364. {
  204365. if (uiMsg == WM_INITDIALOG)
  204366. {
  204367. HWND dialogH = GetParent (hdlg);
  204368. jassert (dialogH != 0);
  204369. if (dialogH == 0)
  204370. dialogH = hdlg;
  204371. RECT r, cr;
  204372. GetWindowRect (dialogH, &r);
  204373. GetClientRect (dialogH, &cr);
  204374. SetWindowPos (dialogH, 0,
  204375. r.left, r.top,
  204376. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  204377. jmax (150, (int) (r.bottom - r.top)),
  204378. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  204379. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  204380. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  204381. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  204382. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  204383. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  204384. }
  204385. else if (uiMsg == WM_NOTIFY)
  204386. {
  204387. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  204388. if (ofn->hdr.code == CDN_SELCHANGE)
  204389. {
  204390. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  204391. if (comp != 0)
  204392. {
  204393. TCHAR path [MAX_PATH * 2];
  204394. path[0] = 0;
  204395. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  204396. const String fn ((const WCHAR*) path);
  204397. comp->selectedFileChanged (File (fn));
  204398. }
  204399. }
  204400. }
  204401. }
  204402. return 0;
  204403. }
  204404. class FPComponentHolder : public Component
  204405. {
  204406. public:
  204407. FPComponentHolder()
  204408. {
  204409. setVisible (true);
  204410. setOpaque (true);
  204411. }
  204412. ~FPComponentHolder()
  204413. {
  204414. }
  204415. void paint (Graphics& g)
  204416. {
  204417. g.fillAll (Colours::lightgrey);
  204418. }
  204419. private:
  204420. FPComponentHolder (const FPComponentHolder&);
  204421. FPComponentHolder& operator= (const FPComponentHolder&);
  204422. };
  204423. }
  204424. void FileChooser::showPlatformDialog (Array<File>& results,
  204425. const String& title,
  204426. const File& currentFileOrDirectory,
  204427. const String& filter,
  204428. bool selectsDirectory,
  204429. bool /*selectsFiles*/,
  204430. bool isSaveDialogue,
  204431. bool warnAboutOverwritingExistingFiles,
  204432. bool selectMultipleFiles,
  204433. FilePreviewComponent* extraInfoComponent)
  204434. {
  204435. using namespace FileChooserHelpers;
  204436. const int numCharsAvailable = 32768;
  204437. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  204438. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  204439. int fnameIdx = 0;
  204440. JUCE_TRY
  204441. {
  204442. // use a modal window as the parent for this dialog box
  204443. // to block input from other app windows
  204444. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  204445. Component w (String::empty);
  204446. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  204447. mainMon.getY() + mainMon.getHeight() / 4,
  204448. 0, 0);
  204449. w.setOpaque (true);
  204450. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  204451. w.addToDesktop (0);
  204452. if (extraInfoComponent == 0)
  204453. w.enterModalState();
  204454. String initialDir;
  204455. if (currentFileOrDirectory.isDirectory())
  204456. {
  204457. initialDir = currentFileOrDirectory.getFullPathName();
  204458. }
  204459. else
  204460. {
  204461. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  204462. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  204463. }
  204464. if (currentExtraFileWin->isValidComponent())
  204465. {
  204466. jassertfalse
  204467. return;
  204468. }
  204469. if (selectsDirectory)
  204470. {
  204471. LPITEMIDLIST list = 0;
  204472. filenameSpace.fillWith (0);
  204473. {
  204474. BROWSEINFO bi;
  204475. zerostruct (bi);
  204476. bi.hwndOwner = (HWND) w.getWindowHandle();
  204477. bi.pszDisplayName = fname;
  204478. bi.lpszTitle = title;
  204479. bi.lpfn = browseCallbackProc;
  204480. #ifdef BIF_USENEWUI
  204481. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204482. #else
  204483. bi.ulFlags = 0x50;
  204484. #endif
  204485. defaultDirPath = (const WCHAR*) initialDir;
  204486. list = SHBrowseForFolder (&bi);
  204487. if (! SHGetPathFromIDListW (list, fname))
  204488. {
  204489. fname[0] = 0;
  204490. returnedString = String::empty;
  204491. }
  204492. }
  204493. LPMALLOC al;
  204494. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204495. al->Free (list);
  204496. defaultDirPath = 0;
  204497. if (returnedString.isNotEmpty())
  204498. {
  204499. const String stringFName (fname);
  204500. results.add (File (stringFName).getSiblingFile (returnedString));
  204501. returnedString = String::empty;
  204502. return;
  204503. }
  204504. }
  204505. else
  204506. {
  204507. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  204508. if (warnAboutOverwritingExistingFiles)
  204509. flags |= OFN_OVERWRITEPROMPT;
  204510. if (selectMultipleFiles)
  204511. flags |= OFN_ALLOWMULTISELECT;
  204512. if (extraInfoComponent != 0)
  204513. {
  204514. flags |= OFN_ENABLEHOOK;
  204515. currentExtraFileWin = new FPComponentHolder();
  204516. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204517. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204518. extraInfoComponent->getHeight());
  204519. currentExtraFileWin->addToDesktop (0);
  204520. currentExtraFileWin->enterModalState();
  204521. }
  204522. {
  204523. WCHAR filters [1024];
  204524. zeromem (filters, sizeof (filters));
  204525. filter.copyToUnicode (filters, 1024);
  204526. filter.copyToUnicode (filters + filter.length() + 1,
  204527. 1022 - filter.length());
  204528. OPENFILENAMEW of;
  204529. zerostruct (of);
  204530. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204531. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204532. #else
  204533. of.lStructSize = sizeof (of);
  204534. #endif
  204535. of.hwndOwner = (HWND) w.getWindowHandle();
  204536. of.lpstrFilter = filters;
  204537. of.nFilterIndex = 1;
  204538. of.lpstrFile = fname;
  204539. of.nMaxFile = numCharsAvailable;
  204540. of.lpstrInitialDir = initialDir;
  204541. of.lpstrTitle = title;
  204542. of.Flags = flags;
  204543. if (extraInfoComponent != 0)
  204544. of.lpfnHook = &openCallback;
  204545. if (isSaveDialogue)
  204546. {
  204547. if (! GetSaveFileName (&of))
  204548. fname[0] = 0;
  204549. else
  204550. fnameIdx = of.nFileOffset;
  204551. }
  204552. else
  204553. {
  204554. if (! GetOpenFileName (&of))
  204555. fname[0] = 0;
  204556. else
  204557. fnameIdx = of.nFileOffset;
  204558. }
  204559. }
  204560. }
  204561. }
  204562. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204563. catch (...)
  204564. {
  204565. fname[0] = 0;
  204566. }
  204567. #endif
  204568. deleteAndZero (currentExtraFileWin);
  204569. const WCHAR* const files = fname;
  204570. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204571. {
  204572. const WCHAR* filename = files + fnameIdx;
  204573. while (*filename != 0)
  204574. {
  204575. const String filepath (String (files) + "\\" + String (filename));
  204576. results.add (File (filepath));
  204577. filename += CharacterFunctions::length (filename) + 1;
  204578. }
  204579. }
  204580. else if (files[0] != 0)
  204581. {
  204582. results.add (File (files));
  204583. }
  204584. }
  204585. #endif
  204586. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  204587. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  204588. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204589. // compiled on its own).
  204590. #if JUCE_INCLUDED_FILE
  204591. void SystemClipboard::copyTextToClipboard (const String& text)
  204592. {
  204593. if (OpenClipboard (0) != 0)
  204594. {
  204595. if (EmptyClipboard() != 0)
  204596. {
  204597. const int len = text.length();
  204598. if (len > 0)
  204599. {
  204600. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  204601. (len + 1) * sizeof (wchar_t));
  204602. if (bufH != 0)
  204603. {
  204604. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  204605. text.copyToUnicode (data, len);
  204606. GlobalUnlock (bufH);
  204607. SetClipboardData (CF_UNICODETEXT, bufH);
  204608. }
  204609. }
  204610. }
  204611. CloseClipboard();
  204612. }
  204613. }
  204614. const String SystemClipboard::getTextFromClipboard()
  204615. {
  204616. String result;
  204617. if (OpenClipboard (0) != 0)
  204618. {
  204619. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  204620. if (bufH != 0)
  204621. {
  204622. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  204623. if (data != 0)
  204624. {
  204625. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  204626. GlobalUnlock (bufH);
  204627. }
  204628. }
  204629. CloseClipboard();
  204630. }
  204631. return result;
  204632. }
  204633. #endif
  204634. /*** End of inlined file: juce_win32_Misc.cpp ***/
  204635. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  204636. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204637. // compiled on its own).
  204638. #if JUCE_INCLUDED_FILE
  204639. namespace ActiveXHelpers
  204640. {
  204641. class JuceIStorage : public ComBaseClassHelper <IStorage>
  204642. {
  204643. public:
  204644. JuceIStorage() {}
  204645. ~JuceIStorage() {}
  204646. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204647. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204648. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  204649. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  204650. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  204651. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  204652. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  204653. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  204654. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  204655. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  204656. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  204657. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  204658. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  204659. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  204660. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  204661. juce_UseDebuggingNewOperator
  204662. };
  204663. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  204664. {
  204665. HWND window;
  204666. public:
  204667. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  204668. ~JuceOleInPlaceFrame() {}
  204669. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204670. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204671. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  204672. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204673. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204674. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  204675. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  204676. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  204677. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  204678. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  204679. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  204680. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  204681. juce_UseDebuggingNewOperator
  204682. };
  204683. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  204684. {
  204685. HWND window;
  204686. JuceOleInPlaceFrame* frame;
  204687. public:
  204688. JuceIOleInPlaceSite (HWND window_)
  204689. : window (window_),
  204690. frame (new JuceOleInPlaceFrame (window))
  204691. {}
  204692. ~JuceIOleInPlaceSite()
  204693. {
  204694. frame->Release();
  204695. }
  204696. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204697. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204698. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  204699. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  204700. HRESULT __stdcall OnUIActivate() { return S_OK; }
  204701. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  204702. {
  204703. *lplpFrame = frame;
  204704. *lplpDoc = 0;
  204705. lpFrameInfo->fMDIApp = FALSE;
  204706. lpFrameInfo->hwndFrame = window;
  204707. lpFrameInfo->haccel = 0;
  204708. lpFrameInfo->cAccelEntries = 0;
  204709. return S_OK;
  204710. }
  204711. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  204712. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  204713. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  204714. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  204715. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  204716. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  204717. juce_UseDebuggingNewOperator
  204718. };
  204719. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  204720. {
  204721. JuceIOleInPlaceSite* inplaceSite;
  204722. public:
  204723. JuceIOleClientSite (HWND window)
  204724. : inplaceSite (new JuceIOleInPlaceSite (window))
  204725. {}
  204726. ~JuceIOleClientSite()
  204727. {
  204728. inplaceSite->Release();
  204729. }
  204730. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  204731. {
  204732. if (type == IID_IOleInPlaceSite)
  204733. {
  204734. inplaceSite->AddRef();
  204735. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  204736. return S_OK;
  204737. }
  204738. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  204739. }
  204740. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  204741. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  204742. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  204743. HRESULT __stdcall ShowObject() { return S_OK; }
  204744. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  204745. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  204746. juce_UseDebuggingNewOperator
  204747. };
  204748. static VoidArray activeXComps;
  204749. static HWND getHWND (const ActiveXControlComponent* const component)
  204750. {
  204751. HWND hwnd = 0;
  204752. const IID iid = IID_IOleWindow;
  204753. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  204754. if (window != 0)
  204755. {
  204756. window->GetWindow (&hwnd);
  204757. window->Release();
  204758. }
  204759. return hwnd;
  204760. }
  204761. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  204762. {
  204763. RECT activeXRect, peerRect;
  204764. GetWindowRect (hwnd, &activeXRect);
  204765. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  204766. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  204767. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  204768. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  204769. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  204770. switch (message)
  204771. {
  204772. case WM_MOUSEMOVE:
  204773. case WM_LBUTTONDOWN:
  204774. case WM_MBUTTONDOWN:
  204775. case WM_RBUTTONDOWN:
  204776. case WM_LBUTTONUP:
  204777. case WM_MBUTTONUP:
  204778. case WM_RBUTTONUP:
  204779. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  204780. break;
  204781. default:
  204782. break;
  204783. }
  204784. }
  204785. }
  204786. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  204787. {
  204788. ActiveXControlComponent* const owner;
  204789. bool wasShowing;
  204790. public:
  204791. HWND controlHWND;
  204792. IStorage* storage;
  204793. IOleClientSite* clientSite;
  204794. IOleObject* control;
  204795. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  204796. : ComponentMovementWatcher (owner_),
  204797. owner (owner_),
  204798. wasShowing (owner_ != 0 && owner_->isShowing()),
  204799. controlHWND (0),
  204800. storage (new ActiveXHelpers::JuceIStorage()),
  204801. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  204802. control (0)
  204803. {
  204804. }
  204805. ~Pimpl()
  204806. {
  204807. if (control != 0)
  204808. {
  204809. control->Close (OLECLOSE_NOSAVE);
  204810. control->Release();
  204811. }
  204812. clientSite->Release();
  204813. storage->Release();
  204814. }
  204815. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  204816. {
  204817. Component* const topComp = owner->getTopLevelComponent();
  204818. if (topComp->getPeer() != 0)
  204819. {
  204820. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  204821. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  204822. }
  204823. }
  204824. void componentPeerChanged()
  204825. {
  204826. const bool isShowingNow = owner->isShowing();
  204827. if (wasShowing != isShowingNow)
  204828. {
  204829. wasShowing = isShowingNow;
  204830. owner->setControlVisible (isShowingNow);
  204831. }
  204832. componentMovedOrResized (true, true);
  204833. }
  204834. void componentVisibilityChanged (Component&)
  204835. {
  204836. componentPeerChanged();
  204837. }
  204838. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  204839. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  204840. {
  204841. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  204842. {
  204843. const ActiveXControlComponent* const ax
  204844. = static_cast <const ActiveXControlComponent*> (ActiveXHelpers::activeXComps.getUnchecked(i));
  204845. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  204846. {
  204847. switch (message)
  204848. {
  204849. case WM_MOUSEMOVE:
  204850. case WM_LBUTTONDOWN:
  204851. case WM_MBUTTONDOWN:
  204852. case WM_RBUTTONDOWN:
  204853. case WM_LBUTTONUP:
  204854. case WM_MBUTTONUP:
  204855. case WM_RBUTTONUP:
  204856. case WM_LBUTTONDBLCLK:
  204857. case WM_MBUTTONDBLCLK:
  204858. case WM_RBUTTONDBLCLK:
  204859. if (ax->isShowing())
  204860. {
  204861. ComponentPeer* const peer = ax->getPeer();
  204862. if (peer != 0)
  204863. {
  204864. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  204865. if (! ax->areMouseEventsAllowed())
  204866. return 0;
  204867. }
  204868. }
  204869. break;
  204870. default:
  204871. break;
  204872. }
  204873. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  204874. }
  204875. }
  204876. return DefWindowProc (hwnd, message, wParam, lParam);
  204877. }
  204878. };
  204879. ActiveXControlComponent::ActiveXControlComponent()
  204880. : originalWndProc (0),
  204881. mouseEventsAllowed (true)
  204882. {
  204883. ActiveXHelpers::activeXComps.add (this);
  204884. }
  204885. ActiveXControlComponent::~ActiveXControlComponent()
  204886. {
  204887. deleteControl();
  204888. ActiveXHelpers::activeXComps.removeValue (this);
  204889. }
  204890. void ActiveXControlComponent::paint (Graphics& g)
  204891. {
  204892. if (control == 0)
  204893. g.fillAll (Colours::lightgrey);
  204894. }
  204895. bool ActiveXControlComponent::createControl (const void* controlIID)
  204896. {
  204897. deleteControl();
  204898. ComponentPeer* const peer = getPeer();
  204899. // the component must have already been added to a real window when you call this!
  204900. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  204901. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  204902. {
  204903. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  204904. HWND hwnd = (HWND) peer->getNativeHandle();
  204905. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  204906. HRESULT hr;
  204907. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  204908. newControl->clientSite, newControl->storage,
  204909. (void**) &(newControl->control))) == S_OK)
  204910. {
  204911. newControl->control->SetHostNames (L"Juce", 0);
  204912. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  204913. {
  204914. RECT rect;
  204915. rect.left = pos.getX();
  204916. rect.top = pos.getY();
  204917. rect.right = pos.getX() + getWidth();
  204918. rect.bottom = pos.getY() + getHeight();
  204919. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  204920. {
  204921. control = newControl;
  204922. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  204923. control->controlHWND = ActiveXHelpers::getHWND (this);
  204924. if (control->controlHWND != 0)
  204925. {
  204926. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  204927. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  204928. }
  204929. return true;
  204930. }
  204931. }
  204932. }
  204933. }
  204934. return false;
  204935. }
  204936. void ActiveXControlComponent::deleteControl()
  204937. {
  204938. control = 0;
  204939. originalWndProc = 0;
  204940. }
  204941. void* ActiveXControlComponent::queryInterface (const void* iid) const
  204942. {
  204943. void* result = 0;
  204944. if (control != 0 && control->control != 0
  204945. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  204946. return result;
  204947. return 0;
  204948. }
  204949. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  204950. {
  204951. if (control->controlHWND != 0)
  204952. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  204953. }
  204954. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  204955. {
  204956. if (control->controlHWND != 0)
  204957. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204958. }
  204959. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  204960. {
  204961. mouseEventsAllowed = eventsCanReachControl;
  204962. }
  204963. #endif
  204964. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  204965. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  204966. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204967. // compiled on its own).
  204968. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  204969. using namespace QTOLibrary;
  204970. using namespace QTOControlLib;
  204971. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  204972. static bool isQTAvailable = false;
  204973. class QuickTimeMovieComponent::Pimpl
  204974. {
  204975. public:
  204976. Pimpl() : dataHandle (0)
  204977. {
  204978. }
  204979. ~Pimpl()
  204980. {
  204981. clearHandle();
  204982. }
  204983. void clearHandle()
  204984. {
  204985. if (dataHandle != 0)
  204986. {
  204987. DisposeHandle (dataHandle);
  204988. dataHandle = 0;
  204989. }
  204990. }
  204991. IQTControlPtr qtControl;
  204992. IQTMoviePtr qtMovie;
  204993. Handle dataHandle;
  204994. };
  204995. QuickTimeMovieComponent::QuickTimeMovieComponent()
  204996. : movieLoaded (false),
  204997. controllerVisible (true)
  204998. {
  204999. pimpl = new Pimpl();
  205000. setMouseEventsAllowed (false);
  205001. }
  205002. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  205003. {
  205004. closeMovie();
  205005. pimpl->qtControl = 0;
  205006. deleteControl();
  205007. pimpl = 0;
  205008. }
  205009. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  205010. {
  205011. if (! isQTAvailable)
  205012. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  205013. return isQTAvailable;
  205014. }
  205015. void QuickTimeMovieComponent::createControlIfNeeded()
  205016. {
  205017. if (isShowing() && ! isControlCreated())
  205018. {
  205019. const IID qtIID = __uuidof (QTControl);
  205020. if (createControl (&qtIID))
  205021. {
  205022. const IID qtInterfaceIID = __uuidof (IQTControl);
  205023. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  205024. if (pimpl->qtControl != 0)
  205025. {
  205026. pimpl->qtControl->Release(); // it has one ref too many at this point
  205027. pimpl->qtControl->QuickTimeInitialize();
  205028. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  205029. if (movieFile != File::nonexistent)
  205030. loadMovie (movieFile, controllerVisible);
  205031. }
  205032. }
  205033. }
  205034. }
  205035. bool QuickTimeMovieComponent::isControlCreated() const
  205036. {
  205037. return isControlOpen();
  205038. }
  205039. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  205040. const bool isControllerVisible)
  205041. {
  205042. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  205043. movieFile = File::nonexistent;
  205044. movieLoaded = false;
  205045. pimpl->qtMovie = 0;
  205046. controllerVisible = isControllerVisible;
  205047. createControlIfNeeded();
  205048. if (isControlCreated())
  205049. {
  205050. if (pimpl->qtControl != 0)
  205051. {
  205052. pimpl->qtControl->Put_MovieHandle (0);
  205053. pimpl->clearHandle();
  205054. Movie movie;
  205055. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  205056. {
  205057. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  205058. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  205059. if (pimpl->qtMovie != 0)
  205060. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  205061. : qtMovieControllerTypeNone);
  205062. }
  205063. if (movie == 0)
  205064. pimpl->clearHandle();
  205065. }
  205066. movieLoaded = (pimpl->qtMovie != 0);
  205067. }
  205068. else
  205069. {
  205070. // You're trying to open a movie when the control hasn't yet been created, probably because
  205071. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  205072. jassertfalse
  205073. }
  205074. return movieLoaded;
  205075. }
  205076. void QuickTimeMovieComponent::closeMovie()
  205077. {
  205078. stop();
  205079. movieFile = File::nonexistent;
  205080. movieLoaded = false;
  205081. pimpl->qtMovie = 0;
  205082. if (pimpl->qtControl != 0)
  205083. pimpl->qtControl->Put_MovieHandle (0);
  205084. pimpl->clearHandle();
  205085. }
  205086. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  205087. {
  205088. return movieFile;
  205089. }
  205090. bool QuickTimeMovieComponent::isMovieOpen() const
  205091. {
  205092. return movieLoaded;
  205093. }
  205094. double QuickTimeMovieComponent::getMovieDuration() const
  205095. {
  205096. if (pimpl->qtMovie != 0)
  205097. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  205098. return 0.0;
  205099. }
  205100. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  205101. {
  205102. if (pimpl->qtMovie != 0)
  205103. {
  205104. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  205105. width = r.right - r.left;
  205106. height = r.bottom - r.top;
  205107. }
  205108. else
  205109. {
  205110. width = height = 0;
  205111. }
  205112. }
  205113. void QuickTimeMovieComponent::play()
  205114. {
  205115. if (pimpl->qtMovie != 0)
  205116. pimpl->qtMovie->Play();
  205117. }
  205118. void QuickTimeMovieComponent::stop()
  205119. {
  205120. if (pimpl->qtMovie != 0)
  205121. pimpl->qtMovie->Stop();
  205122. }
  205123. bool QuickTimeMovieComponent::isPlaying() const
  205124. {
  205125. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  205126. }
  205127. void QuickTimeMovieComponent::setPosition (const double seconds)
  205128. {
  205129. if (pimpl->qtMovie != 0)
  205130. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  205131. }
  205132. double QuickTimeMovieComponent::getPosition() const
  205133. {
  205134. if (pimpl->qtMovie != 0)
  205135. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  205136. return 0.0;
  205137. }
  205138. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  205139. {
  205140. if (pimpl->qtMovie != 0)
  205141. pimpl->qtMovie->PutRate (newSpeed);
  205142. }
  205143. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  205144. {
  205145. if (pimpl->qtMovie != 0)
  205146. {
  205147. pimpl->qtMovie->PutAudioVolume (newVolume);
  205148. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  205149. }
  205150. }
  205151. float QuickTimeMovieComponent::getMovieVolume() const
  205152. {
  205153. if (pimpl->qtMovie != 0)
  205154. return pimpl->qtMovie->GetAudioVolume();
  205155. return 0.0f;
  205156. }
  205157. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  205158. {
  205159. if (pimpl->qtMovie != 0)
  205160. pimpl->qtMovie->PutLoop (shouldLoop);
  205161. }
  205162. bool QuickTimeMovieComponent::isLooping() const
  205163. {
  205164. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  205165. }
  205166. bool QuickTimeMovieComponent::isControllerVisible() const
  205167. {
  205168. return controllerVisible;
  205169. }
  205170. void QuickTimeMovieComponent::parentHierarchyChanged()
  205171. {
  205172. createControlIfNeeded();
  205173. QTCompBaseClass::parentHierarchyChanged();
  205174. }
  205175. void QuickTimeMovieComponent::visibilityChanged()
  205176. {
  205177. createControlIfNeeded();
  205178. QTCompBaseClass::visibilityChanged();
  205179. }
  205180. void QuickTimeMovieComponent::paint (Graphics& g)
  205181. {
  205182. if (! isControlCreated())
  205183. g.fillAll (Colours::black);
  205184. }
  205185. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  205186. {
  205187. Handle dataRef = 0;
  205188. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  205189. if (err == noErr)
  205190. {
  205191. Str255 suffix;
  205192. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  205193. StringPtr name = suffix;
  205194. err = PtrAndHand (name, dataRef, name[0] + 1);
  205195. if (err == noErr)
  205196. {
  205197. long atoms[3];
  205198. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  205199. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  205200. atoms[2] = EndianU32_NtoB (MovieFileType);
  205201. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  205202. if (err == noErr)
  205203. return dataRef;
  205204. }
  205205. DisposeHandle (dataRef);
  205206. }
  205207. return 0;
  205208. }
  205209. static CFStringRef juceStringToCFString (const String& s)
  205210. {
  205211. const int len = s.length();
  205212. const juce_wchar* const t = s;
  205213. HeapBlock <UniChar> temp (len + 2);
  205214. for (int i = 0; i <= len; ++i)
  205215. temp[i] = t[i];
  205216. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  205217. }
  205218. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  205219. {
  205220. Boolean trueBool = true;
  205221. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205222. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  205223. props[prop].propValueSize = sizeof (trueBool);
  205224. props[prop].propValueAddress = &trueBool;
  205225. ++prop;
  205226. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205227. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  205228. props[prop].propValueSize = sizeof (trueBool);
  205229. props[prop].propValueAddress = &trueBool;
  205230. ++prop;
  205231. Boolean isActive = true;
  205232. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  205233. props[prop].propID = kQTNewMoviePropertyID_Active;
  205234. props[prop].propValueSize = sizeof (isActive);
  205235. props[prop].propValueAddress = &isActive;
  205236. ++prop;
  205237. MacSetPort (0);
  205238. jassert (prop <= 5);
  205239. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  205240. return err == noErr;
  205241. }
  205242. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  205243. {
  205244. if (input == 0)
  205245. return false;
  205246. dataHandle = 0;
  205247. bool ok = false;
  205248. QTNewMoviePropertyElement props[5];
  205249. zeromem (props, sizeof (props));
  205250. int prop = 0;
  205251. DataReferenceRecord dr;
  205252. props[prop].propClass = kQTPropertyClass_DataLocation;
  205253. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  205254. props[prop].propValueSize = sizeof (dr);
  205255. props[prop].propValueAddress = &dr;
  205256. ++prop;
  205257. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  205258. if (fin != 0)
  205259. {
  205260. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  205261. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  205262. &dr.dataRef, &dr.dataRefType);
  205263. ok = openMovie (props, prop, movie);
  205264. DisposeHandle (dr.dataRef);
  205265. CFRelease (filePath);
  205266. }
  205267. else
  205268. {
  205269. // sanity-check because this currently needs to load the whole stream into memory..
  205270. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  205271. dataHandle = NewHandle ((Size) input->getTotalLength());
  205272. HLock (dataHandle);
  205273. // read the entire stream into memory - this is a pain, but can't get it to work
  205274. // properly using a custom callback to supply the data.
  205275. input->read (*dataHandle, (int) input->getTotalLength());
  205276. HUnlock (dataHandle);
  205277. // different types to get QT to try. (We should really be a bit smarter here by
  205278. // working out in advance which one the stream contains, rather than just trying
  205279. // each one)
  205280. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  205281. "\04.avi", "\04.m4a" };
  205282. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  205283. {
  205284. /* // this fails for some bizarre reason - it can be bodged to work with
  205285. // movies, but can't seem to do it for other file types..
  205286. QTNewMovieUserProcRecord procInfo;
  205287. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  205288. procInfo.getMovieUserProcRefcon = this;
  205289. procInfo.defaultDataRef.dataRef = dataRef;
  205290. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  205291. props[prop].propClass = kQTPropertyClass_DataLocation;
  205292. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  205293. props[prop].propValueSize = sizeof (procInfo);
  205294. props[prop].propValueAddress = (void*) &procInfo;
  205295. ++prop; */
  205296. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  205297. dr.dataRefType = HandleDataHandlerSubType;
  205298. ok = openMovie (props, prop, movie);
  205299. DisposeHandle (dr.dataRef);
  205300. }
  205301. }
  205302. return ok;
  205303. }
  205304. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  205305. const bool isControllerVisible)
  205306. {
  205307. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  205308. movieFile = movieFile_;
  205309. return ok;
  205310. }
  205311. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  205312. const bool isControllerVisible)
  205313. {
  205314. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  205315. }
  205316. void QuickTimeMovieComponent::goToStart()
  205317. {
  205318. setPosition (0.0);
  205319. }
  205320. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  205321. const RectanglePlacement& placement)
  205322. {
  205323. int normalWidth, normalHeight;
  205324. getMovieNormalSize (normalWidth, normalHeight);
  205325. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  205326. {
  205327. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  205328. placement.applyTo (x, y, w, h,
  205329. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  205330. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  205331. if (w > 0 && h > 0)
  205332. {
  205333. setBounds (roundToInt (x), roundToInt (y),
  205334. roundToInt (w), roundToInt (h));
  205335. }
  205336. }
  205337. else
  205338. {
  205339. setBounds (spaceToFitWithin);
  205340. }
  205341. }
  205342. #endif
  205343. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  205344. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  205345. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205346. // compiled on its own).
  205347. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  205348. class WebBrowserComponentInternal : public ActiveXControlComponent
  205349. {
  205350. public:
  205351. WebBrowserComponentInternal()
  205352. : browser (0),
  205353. connectionPoint (0),
  205354. adviseCookie (0)
  205355. {
  205356. }
  205357. ~WebBrowserComponentInternal()
  205358. {
  205359. if (connectionPoint != 0)
  205360. connectionPoint->Unadvise (adviseCookie);
  205361. if (browser != 0)
  205362. browser->Release();
  205363. }
  205364. void createBrowser()
  205365. {
  205366. createControl (&CLSID_WebBrowser);
  205367. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  205368. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  205369. if (connectionPointContainer != 0)
  205370. {
  205371. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  205372. &connectionPoint);
  205373. if (connectionPoint != 0)
  205374. {
  205375. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205376. jassert (owner != 0);
  205377. EventHandler* handler = new EventHandler (owner);
  205378. connectionPoint->Advise (handler, &adviseCookie);
  205379. handler->Release();
  205380. }
  205381. }
  205382. }
  205383. void goToURL (const String& url,
  205384. const StringArray* headers,
  205385. const MemoryBlock* postData)
  205386. {
  205387. if (browser != 0)
  205388. {
  205389. LPSAFEARRAY sa = 0;
  205390. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  205391. VariantInit (&flags);
  205392. VariantInit (&frame);
  205393. VariantInit (&postDataVar);
  205394. VariantInit (&headersVar);
  205395. if (headers != 0)
  205396. {
  205397. V_VT (&headersVar) = VT_BSTR;
  205398. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  205399. }
  205400. if (postData != 0 && postData->getSize() > 0)
  205401. {
  205402. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205403. if (sa != 0)
  205404. {
  205405. void* data = 0;
  205406. SafeArrayAccessData (sa, &data);
  205407. jassert (data != 0);
  205408. if (data != 0)
  205409. {
  205410. postData->copyTo (data, 0, postData->getSize());
  205411. SafeArrayUnaccessData (sa);
  205412. VARIANT postDataVar2;
  205413. VariantInit (&postDataVar2);
  205414. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205415. V_ARRAY (&postDataVar2) = sa;
  205416. postDataVar = postDataVar2;
  205417. }
  205418. }
  205419. }
  205420. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205421. &flags, &frame,
  205422. &postDataVar, &headersVar);
  205423. if (sa != 0)
  205424. SafeArrayDestroy (sa);
  205425. VariantClear (&flags);
  205426. VariantClear (&frame);
  205427. VariantClear (&postDataVar);
  205428. VariantClear (&headersVar);
  205429. }
  205430. }
  205431. IWebBrowser2* browser;
  205432. juce_UseDebuggingNewOperator
  205433. private:
  205434. IConnectionPoint* connectionPoint;
  205435. DWORD adviseCookie;
  205436. class EventHandler : public ComBaseClassHelper <IDispatch>,
  205437. public ComponentMovementWatcher
  205438. {
  205439. public:
  205440. EventHandler (WebBrowserComponent* owner_)
  205441. : ComponentMovementWatcher (owner_),
  205442. owner (owner_)
  205443. {
  205444. }
  205445. ~EventHandler()
  205446. {
  205447. }
  205448. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205449. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205450. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205451. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205452. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205453. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205454. UINT __RPC_FAR* /*puArgErr*/)
  205455. {
  205456. switch (dispIdMember)
  205457. {
  205458. case DISPID_BEFORENAVIGATE2:
  205459. {
  205460. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205461. String url;
  205462. if ((vurl->vt & VT_BYREF) != 0)
  205463. url = *vurl->pbstrVal;
  205464. else
  205465. url = vurl->bstrVal;
  205466. *pDispParams->rgvarg->pboolVal
  205467. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205468. : VARIANT_TRUE;
  205469. return S_OK;
  205470. }
  205471. default:
  205472. break;
  205473. }
  205474. return E_NOTIMPL;
  205475. }
  205476. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  205477. void componentPeerChanged() {}
  205478. void componentVisibilityChanged (Component&)
  205479. {
  205480. owner->visibilityChanged();
  205481. }
  205482. juce_UseDebuggingNewOperator
  205483. private:
  205484. WebBrowserComponent* const owner;
  205485. EventHandler (const EventHandler&);
  205486. EventHandler& operator= (const EventHandler&);
  205487. };
  205488. };
  205489. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  205490. : browser (0),
  205491. blankPageShown (false),
  205492. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  205493. {
  205494. setOpaque (true);
  205495. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205496. }
  205497. WebBrowserComponent::~WebBrowserComponent()
  205498. {
  205499. delete browser;
  205500. }
  205501. void WebBrowserComponent::goToURL (const String& url,
  205502. const StringArray* headers,
  205503. const MemoryBlock* postData)
  205504. {
  205505. lastURL = url;
  205506. lastHeaders.clear();
  205507. if (headers != 0)
  205508. lastHeaders = *headers;
  205509. lastPostData.setSize (0);
  205510. if (postData != 0)
  205511. lastPostData = *postData;
  205512. blankPageShown = false;
  205513. browser->goToURL (url, headers, postData);
  205514. }
  205515. void WebBrowserComponent::stop()
  205516. {
  205517. if (browser->browser != 0)
  205518. browser->browser->Stop();
  205519. }
  205520. void WebBrowserComponent::goBack()
  205521. {
  205522. lastURL = String::empty;
  205523. blankPageShown = false;
  205524. if (browser->browser != 0)
  205525. browser->browser->GoBack();
  205526. }
  205527. void WebBrowserComponent::goForward()
  205528. {
  205529. lastURL = String::empty;
  205530. if (browser->browser != 0)
  205531. browser->browser->GoForward();
  205532. }
  205533. void WebBrowserComponent::refresh()
  205534. {
  205535. if (browser->browser != 0)
  205536. browser->browser->Refresh();
  205537. }
  205538. void WebBrowserComponent::paint (Graphics& g)
  205539. {
  205540. if (browser->browser == 0)
  205541. g.fillAll (Colours::white);
  205542. }
  205543. void WebBrowserComponent::checkWindowAssociation()
  205544. {
  205545. if (isShowing())
  205546. {
  205547. if (browser->browser == 0 && getPeer() != 0)
  205548. {
  205549. browser->createBrowser();
  205550. reloadLastURL();
  205551. }
  205552. else
  205553. {
  205554. if (blankPageShown)
  205555. goBack();
  205556. }
  205557. }
  205558. else
  205559. {
  205560. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  205561. {
  205562. // when the component becomes invisible, some stuff like flash
  205563. // carries on playing audio, so we need to force it onto a blank
  205564. // page to avoid this..
  205565. blankPageShown = true;
  205566. browser->goToURL ("about:blank", 0, 0);
  205567. }
  205568. }
  205569. }
  205570. void WebBrowserComponent::reloadLastURL()
  205571. {
  205572. if (lastURL.isNotEmpty())
  205573. {
  205574. goToURL (lastURL, &lastHeaders, &lastPostData);
  205575. lastURL = String::empty;
  205576. }
  205577. }
  205578. void WebBrowserComponent::parentHierarchyChanged()
  205579. {
  205580. checkWindowAssociation();
  205581. }
  205582. void WebBrowserComponent::resized()
  205583. {
  205584. browser->setSize (getWidth(), getHeight());
  205585. }
  205586. void WebBrowserComponent::visibilityChanged()
  205587. {
  205588. checkWindowAssociation();
  205589. }
  205590. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205591. {
  205592. return true;
  205593. }
  205594. #endif
  205595. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  205596. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  205597. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205598. // compiled on its own).
  205599. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  205600. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  205601. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  205602. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  205603. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  205604. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  205605. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  205606. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  205607. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  205608. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  205609. #define WGL_ACCELERATION_ARB 0x2003
  205610. #define WGL_SWAP_METHOD_ARB 0x2007
  205611. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  205612. #define WGL_PIXEL_TYPE_ARB 0x2013
  205613. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  205614. #define WGL_COLOR_BITS_ARB 0x2014
  205615. #define WGL_RED_BITS_ARB 0x2015
  205616. #define WGL_GREEN_BITS_ARB 0x2017
  205617. #define WGL_BLUE_BITS_ARB 0x2019
  205618. #define WGL_ALPHA_BITS_ARB 0x201B
  205619. #define WGL_DEPTH_BITS_ARB 0x2022
  205620. #define WGL_STENCIL_BITS_ARB 0x2023
  205621. #define WGL_FULL_ACCELERATION_ARB 0x2027
  205622. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  205623. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  205624. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  205625. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  205626. #define WGL_STEREO_ARB 0x2012
  205627. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  205628. #define WGL_SAMPLES_ARB 0x2042
  205629. #define WGL_TYPE_RGBA_ARB 0x202B
  205630. static void getWglExtensions (HDC dc, StringArray& result) throw()
  205631. {
  205632. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  205633. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  205634. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  205635. else
  205636. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  205637. }
  205638. class WindowedGLContext : public OpenGLContext
  205639. {
  205640. public:
  205641. WindowedGLContext (Component* const component_,
  205642. HGLRC contextToShareWith,
  205643. const OpenGLPixelFormat& pixelFormat)
  205644. : renderContext (0),
  205645. nativeWindow (0),
  205646. dc (0),
  205647. component (component_)
  205648. {
  205649. jassert (component != 0);
  205650. createNativeWindow();
  205651. // Use a default pixel format that should be supported everywhere
  205652. PIXELFORMATDESCRIPTOR pfd;
  205653. zerostruct (pfd);
  205654. pfd.nSize = sizeof (pfd);
  205655. pfd.nVersion = 1;
  205656. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  205657. pfd.iPixelType = PFD_TYPE_RGBA;
  205658. pfd.cColorBits = 24;
  205659. pfd.cDepthBits = 16;
  205660. const int format = ChoosePixelFormat (dc, &pfd);
  205661. if (format != 0)
  205662. SetPixelFormat (dc, format, &pfd);
  205663. renderContext = wglCreateContext (dc);
  205664. makeActive();
  205665. setPixelFormat (pixelFormat);
  205666. if (contextToShareWith != 0 && renderContext != 0)
  205667. wglShareLists (contextToShareWith, renderContext);
  205668. }
  205669. ~WindowedGLContext()
  205670. {
  205671. makeInactive();
  205672. wglDeleteContext (renderContext);
  205673. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205674. delete nativeWindow;
  205675. }
  205676. bool makeActive() const throw()
  205677. {
  205678. jassert (renderContext != 0);
  205679. return wglMakeCurrent (dc, renderContext) != 0;
  205680. }
  205681. bool makeInactive() const throw()
  205682. {
  205683. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  205684. }
  205685. bool isActive() const throw()
  205686. {
  205687. return wglGetCurrentContext() == renderContext;
  205688. }
  205689. const OpenGLPixelFormat getPixelFormat() const
  205690. {
  205691. OpenGLPixelFormat pf;
  205692. makeActive();
  205693. StringArray availableExtensions;
  205694. getWglExtensions (dc, availableExtensions);
  205695. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  205696. return pf;
  205697. }
  205698. void* getRawContext() const throw()
  205699. {
  205700. return renderContext;
  205701. }
  205702. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  205703. {
  205704. makeActive();
  205705. PIXELFORMATDESCRIPTOR pfd;
  205706. zerostruct (pfd);
  205707. pfd.nSize = sizeof (pfd);
  205708. pfd.nVersion = 1;
  205709. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  205710. pfd.iPixelType = PFD_TYPE_RGBA;
  205711. pfd.iLayerType = PFD_MAIN_PLANE;
  205712. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  205713. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  205714. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  205715. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  205716. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  205717. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  205718. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  205719. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  205720. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  205721. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  205722. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  205723. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  205724. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  205725. int format = 0;
  205726. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  205727. StringArray availableExtensions;
  205728. getWglExtensions (dc, availableExtensions);
  205729. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205730. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  205731. {
  205732. int attributes[64];
  205733. int n = 0;
  205734. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  205735. attributes[n++] = GL_TRUE;
  205736. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  205737. attributes[n++] = GL_TRUE;
  205738. attributes[n++] = WGL_ACCELERATION_ARB;
  205739. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  205740. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  205741. attributes[n++] = GL_TRUE;
  205742. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  205743. attributes[n++] = WGL_TYPE_RGBA_ARB;
  205744. attributes[n++] = WGL_COLOR_BITS_ARB;
  205745. attributes[n++] = pfd.cColorBits;
  205746. attributes[n++] = WGL_RED_BITS_ARB;
  205747. attributes[n++] = pixelFormat.redBits;
  205748. attributes[n++] = WGL_GREEN_BITS_ARB;
  205749. attributes[n++] = pixelFormat.greenBits;
  205750. attributes[n++] = WGL_BLUE_BITS_ARB;
  205751. attributes[n++] = pixelFormat.blueBits;
  205752. attributes[n++] = WGL_ALPHA_BITS_ARB;
  205753. attributes[n++] = pixelFormat.alphaBits;
  205754. attributes[n++] = WGL_DEPTH_BITS_ARB;
  205755. attributes[n++] = pixelFormat.depthBufferBits;
  205756. if (pixelFormat.stencilBufferBits > 0)
  205757. {
  205758. attributes[n++] = WGL_STENCIL_BITS_ARB;
  205759. attributes[n++] = pixelFormat.stencilBufferBits;
  205760. }
  205761. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  205762. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  205763. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  205764. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  205765. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  205766. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  205767. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205768. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  205769. if (availableExtensions.contains ("WGL_ARB_multisample")
  205770. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  205771. {
  205772. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  205773. attributes[n++] = 1;
  205774. attributes[n++] = WGL_SAMPLES_ARB;
  205775. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  205776. }
  205777. attributes[n++] = 0;
  205778. UINT formatsCount;
  205779. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  205780. (void) ok;
  205781. jassert (ok);
  205782. }
  205783. else
  205784. {
  205785. format = ChoosePixelFormat (dc, &pfd);
  205786. }
  205787. if (format != 0)
  205788. {
  205789. makeInactive();
  205790. // win32 can't change the pixel format of a window, so need to delete the
  205791. // old one and create a new one..
  205792. jassert (nativeWindow != 0);
  205793. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205794. delete nativeWindow;
  205795. createNativeWindow();
  205796. if (SetPixelFormat (dc, format, &pfd))
  205797. {
  205798. wglDeleteContext (renderContext);
  205799. renderContext = wglCreateContext (dc);
  205800. jassert (renderContext != 0);
  205801. return renderContext != 0;
  205802. }
  205803. }
  205804. return false;
  205805. }
  205806. void updateWindowPosition (int x, int y, int w, int h, int)
  205807. {
  205808. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  205809. x, y, w, h,
  205810. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205811. }
  205812. void repaint()
  205813. {
  205814. const Rectangle<int> bounds (nativeWindow->getBounds());
  205815. nativeWindow->repaint (0, 0, bounds.getWidth(), bounds.getHeight());
  205816. }
  205817. void swapBuffers()
  205818. {
  205819. SwapBuffers (dc);
  205820. }
  205821. bool setSwapInterval (int numFramesPerSwap)
  205822. {
  205823. makeActive();
  205824. StringArray availableExtensions;
  205825. getWglExtensions (dc, availableExtensions);
  205826. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  205827. return availableExtensions.contains ("WGL_EXT_swap_control")
  205828. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  205829. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  205830. }
  205831. int getSwapInterval() const
  205832. {
  205833. makeActive();
  205834. StringArray availableExtensions;
  205835. getWglExtensions (dc, availableExtensions);
  205836. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  205837. if (availableExtensions.contains ("WGL_EXT_swap_control")
  205838. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  205839. return wglGetSwapIntervalEXT();
  205840. return 0;
  205841. }
  205842. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  205843. {
  205844. jassert (isActive());
  205845. StringArray availableExtensions;
  205846. getWglExtensions (dc, availableExtensions);
  205847. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205848. int numTypes = 0;
  205849. if (availableExtensions.contains("WGL_ARB_pixel_format")
  205850. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205851. {
  205852. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  205853. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  205854. jassertfalse
  205855. }
  205856. else
  205857. {
  205858. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  205859. }
  205860. OpenGLPixelFormat pf;
  205861. for (int i = 0; i < numTypes; ++i)
  205862. {
  205863. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  205864. {
  205865. bool alreadyListed = false;
  205866. for (int j = results.size(); --j >= 0;)
  205867. if (pf == *results.getUnchecked(j))
  205868. alreadyListed = true;
  205869. if (! alreadyListed)
  205870. results.add (new OpenGLPixelFormat (pf));
  205871. }
  205872. }
  205873. }
  205874. void* getNativeWindowHandle() const
  205875. {
  205876. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  205877. }
  205878. juce_UseDebuggingNewOperator
  205879. HGLRC renderContext;
  205880. private:
  205881. Win32ComponentPeer* nativeWindow;
  205882. Component* const component;
  205883. HDC dc;
  205884. void createNativeWindow()
  205885. {
  205886. nativeWindow = new Win32ComponentPeer (component, 0);
  205887. nativeWindow->dontRepaint = true;
  205888. nativeWindow->setVisible (true);
  205889. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  205890. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  205891. if (peer != 0)
  205892. {
  205893. SetParent (hwnd, (HWND) peer->getNativeHandle());
  205894. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  205895. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  205896. }
  205897. dc = GetDC (hwnd);
  205898. }
  205899. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  205900. OpenGLPixelFormat& result,
  205901. const StringArray& availableExtensions) const throw()
  205902. {
  205903. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205904. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205905. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205906. {
  205907. int attributes[32];
  205908. int numAttributes = 0;
  205909. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  205910. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  205911. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  205912. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  205913. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  205914. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  205915. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  205916. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  205917. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  205918. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  205919. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  205920. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  205921. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  205922. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  205923. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205924. if (availableExtensions.contains ("WGL_ARB_multisample"))
  205925. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  205926. int values[32];
  205927. zeromem (values, sizeof (values));
  205928. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  205929. {
  205930. int n = 0;
  205931. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  205932. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  205933. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  205934. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  205935. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  205936. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  205937. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  205938. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  205939. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  205940. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  205941. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  205942. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  205943. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  205944. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  205945. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  205946. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  205947. return isValidFormat;
  205948. }
  205949. else
  205950. {
  205951. jassertfalse
  205952. }
  205953. }
  205954. else
  205955. {
  205956. PIXELFORMATDESCRIPTOR pfd;
  205957. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  205958. {
  205959. result.redBits = pfd.cRedBits;
  205960. result.greenBits = pfd.cGreenBits;
  205961. result.blueBits = pfd.cBlueBits;
  205962. result.alphaBits = pfd.cAlphaBits;
  205963. result.depthBufferBits = pfd.cDepthBits;
  205964. result.stencilBufferBits = pfd.cStencilBits;
  205965. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  205966. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  205967. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  205968. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  205969. result.fullSceneAntiAliasingNumSamples = 0;
  205970. return true;
  205971. }
  205972. else
  205973. {
  205974. jassertfalse
  205975. }
  205976. }
  205977. return false;
  205978. }
  205979. WindowedGLContext (const WindowedGLContext&);
  205980. WindowedGLContext& operator= (const WindowedGLContext&);
  205981. };
  205982. OpenGLContext* OpenGLComponent::createContext()
  205983. {
  205984. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  205985. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  205986. preferredPixelFormat));
  205987. return (c->renderContext != 0) ? c.release() : 0;
  205988. }
  205989. void* OpenGLComponent::getNativeWindowHandle() const
  205990. {
  205991. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  205992. }
  205993. void juce_glViewport (const int w, const int h)
  205994. {
  205995. glViewport (0, 0, w, h);
  205996. }
  205997. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  205998. OwnedArray <OpenGLPixelFormat>& results)
  205999. {
  206000. Component tempComp;
  206001. {
  206002. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  206003. wc.makeActive();
  206004. wc.findAlternativeOpenGLPixelFormats (results);
  206005. }
  206006. }
  206007. #endif
  206008. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  206009. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  206010. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206011. // compiled on its own).
  206012. #if JUCE_INCLUDED_FILE
  206013. #if JUCE_USE_CDREADER
  206014. namespace CDReaderHelpers
  206015. {
  206016. //***************************************************************************
  206017. // %%% TARGET STATUS VALUES %%%
  206018. //***************************************************************************
  206019. #define STATUS_GOOD 0x00 // Status Good
  206020. #define STATUS_CHKCOND 0x02 // Check Condition
  206021. #define STATUS_CONDMET 0x04 // Condition Met
  206022. #define STATUS_BUSY 0x08 // Busy
  206023. #define STATUS_INTERM 0x10 // Intermediate
  206024. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  206025. #define STATUS_RESCONF 0x18 // Reservation conflict
  206026. #define STATUS_COMTERM 0x22 // Command Terminated
  206027. #define STATUS_QFULL 0x28 // Queue full
  206028. //***************************************************************************
  206029. // %%% SCSI MISCELLANEOUS EQUATES %%%
  206030. //***************************************************************************
  206031. #define MAXLUN 7 // Maximum Logical Unit Id
  206032. #define MAXTARG 7 // Maximum Target Id
  206033. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  206034. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  206035. //***************************************************************************
  206036. // %%% Commands for all Device Types %%%
  206037. //***************************************************************************
  206038. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  206039. #define SCSI_COMPARE 0x39 // Compare (O)
  206040. #define SCSI_COPY 0x18 // Copy (O)
  206041. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  206042. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  206043. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  206044. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  206045. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  206046. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  206047. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  206048. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  206049. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  206050. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  206051. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  206052. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  206053. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  206054. //***************************************************************************
  206055. // %%% Commands Unique to Direct Access Devices %%%
  206056. //***************************************************************************
  206057. #define SCSI_COMPARE 0x39 // Compare (O)
  206058. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  206059. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  206060. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  206061. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  206062. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  206063. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  206064. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  206065. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  206066. #define SCSI_READ_LONG 0x3E // Read Long (O)
  206067. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  206068. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  206069. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  206070. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  206071. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  206072. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  206073. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  206074. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  206075. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  206076. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  206077. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  206078. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  206079. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  206080. #define SCSI_VERIFY 0x2F // Verify (O)
  206081. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  206082. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  206083. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  206084. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  206085. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  206086. //***************************************************************************
  206087. // %%% Commands Unique to Sequential Access Devices %%%
  206088. //***************************************************************************
  206089. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  206090. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  206091. #define SCSI_LOCATE 0x2B // Locate (O)
  206092. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  206093. #define SCSI_READ_POS 0x34 // Read Position (O)
  206094. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  206095. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  206096. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  206097. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  206098. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  206099. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  206100. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  206101. //***************************************************************************
  206102. // %%% Commands Unique to Printer Devices %%%
  206103. //***************************************************************************
  206104. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  206105. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  206106. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  206107. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  206108. //***************************************************************************
  206109. // %%% Commands Unique to Processor Devices %%%
  206110. //***************************************************************************
  206111. #define SCSI_RECEIVE 0x08 // Receive (O)
  206112. #define SCSI_SEND 0x0A // Send (O)
  206113. //***************************************************************************
  206114. // %%% Commands Unique to Write-Once Devices %%%
  206115. //***************************************************************************
  206116. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  206117. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  206118. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  206119. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  206120. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  206121. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  206122. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  206123. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  206124. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  206125. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  206126. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  206127. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  206128. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  206129. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  206130. //***************************************************************************
  206131. // %%% Commands Unique to CD-ROM Devices %%%
  206132. //***************************************************************************
  206133. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  206134. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  206135. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  206136. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  206137. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  206138. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  206139. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  206140. #define SCSI_READHEADER 0x44 // Read Header (O)
  206141. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  206142. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  206143. //***************************************************************************
  206144. // %%% Commands Unique to Scanner Devices %%%
  206145. //***************************************************************************
  206146. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  206147. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  206148. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  206149. #define SCSI_SCAN 0x1B // Scan (O)
  206150. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  206151. //***************************************************************************
  206152. // %%% Commands Unique to Optical Memory Devices %%%
  206153. //***************************************************************************
  206154. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  206155. //***************************************************************************
  206156. // %%% Commands Unique to Medium Changer Devices %%%
  206157. //***************************************************************************
  206158. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  206159. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  206160. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  206161. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  206162. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  206163. //***************************************************************************
  206164. // %%% Commands Unique to Communication Devices %%%
  206165. //***************************************************************************
  206166. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  206167. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  206168. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  206169. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  206170. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  206171. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  206172. //***************************************************************************
  206173. // %%% Request Sense Data Format %%%
  206174. //***************************************************************************
  206175. typedef struct {
  206176. BYTE ErrorCode; // Error Code (70H or 71H)
  206177. BYTE SegmentNum; // Number of current segment descriptor
  206178. BYTE SenseKey; // Sense Key(See bit definitions too)
  206179. BYTE InfoByte0; // Information MSB
  206180. BYTE InfoByte1; // Information MID
  206181. BYTE InfoByte2; // Information MID
  206182. BYTE InfoByte3; // Information LSB
  206183. BYTE AddSenLen; // Additional Sense Length
  206184. BYTE ComSpecInf0; // Command Specific Information MSB
  206185. BYTE ComSpecInf1; // Command Specific Information MID
  206186. BYTE ComSpecInf2; // Command Specific Information MID
  206187. BYTE ComSpecInf3; // Command Specific Information LSB
  206188. BYTE AddSenseCode; // Additional Sense Code
  206189. BYTE AddSenQual; // Additional Sense Code Qualifier
  206190. BYTE FieldRepUCode; // Field Replaceable Unit Code
  206191. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  206192. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  206193. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  206194. BYTE AddSenseBytes; // Additional Sense Bytes
  206195. } SENSE_DATA_FMT;
  206196. //***************************************************************************
  206197. // %%% REQUEST SENSE ERROR CODE %%%
  206198. //***************************************************************************
  206199. #define SERROR_CURRENT 0x70 // Current Errors
  206200. #define SERROR_DEFERED 0x71 // Deferred Errors
  206201. //***************************************************************************
  206202. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  206203. //***************************************************************************
  206204. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  206205. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  206206. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  206207. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  206208. //***************************************************************************
  206209. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  206210. //***************************************************************************
  206211. #define KEY_NOSENSE 0x00 // No Sense
  206212. #define KEY_RECERROR 0x01 // Recovered Error
  206213. #define KEY_NOTREADY 0x02 // Not Ready
  206214. #define KEY_MEDIUMERR 0x03 // Medium Error
  206215. #define KEY_HARDERROR 0x04 // Hardware Error
  206216. #define KEY_ILLGLREQ 0x05 // Illegal Request
  206217. #define KEY_UNITATT 0x06 // Unit Attention
  206218. #define KEY_DATAPROT 0x07 // Data Protect
  206219. #define KEY_BLANKCHK 0x08 // Blank Check
  206220. #define KEY_VENDSPEC 0x09 // Vendor Specific
  206221. #define KEY_COPYABORT 0x0A // Copy Abort
  206222. #define KEY_EQUAL 0x0C // Equal (Search)
  206223. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  206224. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  206225. #define KEY_RESERVED 0x0F // Reserved
  206226. //***************************************************************************
  206227. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  206228. //***************************************************************************
  206229. #define DTYPE_DASD 0x00 // Disk Device
  206230. #define DTYPE_SEQD 0x01 // Tape Device
  206231. #define DTYPE_PRNT 0x02 // Printer
  206232. #define DTYPE_PROC 0x03 // Processor
  206233. #define DTYPE_WORM 0x04 // Write-once read-multiple
  206234. #define DTYPE_CROM 0x05 // CD-ROM device
  206235. #define DTYPE_SCAN 0x06 // Scanner device
  206236. #define DTYPE_OPTI 0x07 // Optical memory device
  206237. #define DTYPE_JUKE 0x08 // Medium Changer device
  206238. #define DTYPE_COMM 0x09 // Communications device
  206239. #define DTYPE_RESL 0x0A // Reserved (low)
  206240. #define DTYPE_RESH 0x1E // Reserved (high)
  206241. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  206242. //***************************************************************************
  206243. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  206244. //***************************************************************************
  206245. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  206246. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  206247. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  206248. #define ANSI_RESLO 0x3 // Reserved (low)
  206249. #define ANSI_RESHI 0x7 // Reserved (high)
  206250. typedef struct
  206251. {
  206252. USHORT Length;
  206253. UCHAR ScsiStatus;
  206254. UCHAR PathId;
  206255. UCHAR TargetId;
  206256. UCHAR Lun;
  206257. UCHAR CdbLength;
  206258. UCHAR SenseInfoLength;
  206259. UCHAR DataIn;
  206260. ULONG DataTransferLength;
  206261. ULONG TimeOutValue;
  206262. ULONG DataBufferOffset;
  206263. ULONG SenseInfoOffset;
  206264. UCHAR Cdb[16];
  206265. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  206266. typedef struct
  206267. {
  206268. USHORT Length;
  206269. UCHAR ScsiStatus;
  206270. UCHAR PathId;
  206271. UCHAR TargetId;
  206272. UCHAR Lun;
  206273. UCHAR CdbLength;
  206274. UCHAR SenseInfoLength;
  206275. UCHAR DataIn;
  206276. ULONG DataTransferLength;
  206277. ULONG TimeOutValue;
  206278. PVOID DataBuffer;
  206279. ULONG SenseInfoOffset;
  206280. UCHAR Cdb[16];
  206281. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  206282. typedef struct
  206283. {
  206284. SCSI_PASS_THROUGH_DIRECT spt;
  206285. ULONG Filler;
  206286. UCHAR ucSenseBuf[32];
  206287. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  206288. typedef struct
  206289. {
  206290. ULONG Length;
  206291. UCHAR PortNumber;
  206292. UCHAR PathId;
  206293. UCHAR TargetId;
  206294. UCHAR Lun;
  206295. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  206296. #define METHOD_BUFFERED 0
  206297. #define METHOD_IN_DIRECT 1
  206298. #define METHOD_OUT_DIRECT 2
  206299. #define METHOD_NEITHER 3
  206300. #define FILE_ANY_ACCESS 0
  206301. #ifndef FILE_READ_ACCESS
  206302. #define FILE_READ_ACCESS (0x0001)
  206303. #endif
  206304. #ifndef FILE_WRITE_ACCESS
  206305. #define FILE_WRITE_ACCESS (0x0002)
  206306. #endif
  206307. #define IOCTL_SCSI_BASE 0x00000004
  206308. #define SCSI_IOCTL_DATA_OUT 0
  206309. #define SCSI_IOCTL_DATA_IN 1
  206310. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  206311. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  206312. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  206313. )
  206314. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206315. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  206316. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206317. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  206318. #define SENSE_LEN 14
  206319. #define SRB_DIR_SCSI 0x00
  206320. #define SRB_POSTING 0x01
  206321. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  206322. #define SRB_DIR_IN 0x08
  206323. #define SRB_DIR_OUT 0x10
  206324. #define SRB_EVENT_NOTIFY 0x40
  206325. #define RESIDUAL_COUNT_SUPPORTED 0x02
  206326. #define MAX_SRB_TIMEOUT 1080001u
  206327. #define DEFAULT_SRB_TIMEOUT 1080001u
  206328. #define SC_HA_INQUIRY 0x00
  206329. #define SC_GET_DEV_TYPE 0x01
  206330. #define SC_EXEC_SCSI_CMD 0x02
  206331. #define SC_ABORT_SRB 0x03
  206332. #define SC_RESET_DEV 0x04
  206333. #define SC_SET_HA_PARMS 0x05
  206334. #define SC_GET_DISK_INFO 0x06
  206335. #define SC_RESCAN_SCSI_BUS 0x07
  206336. #define SC_GETSET_TIMEOUTS 0x08
  206337. #define SS_PENDING 0x00
  206338. #define SS_COMP 0x01
  206339. #define SS_ABORTED 0x02
  206340. #define SS_ABORT_FAIL 0x03
  206341. #define SS_ERR 0x04
  206342. #define SS_INVALID_CMD 0x80
  206343. #define SS_INVALID_HA 0x81
  206344. #define SS_NO_DEVICE 0x82
  206345. #define SS_INVALID_SRB 0xE0
  206346. #define SS_OLD_MANAGER 0xE1
  206347. #define SS_BUFFER_ALIGN 0xE1
  206348. #define SS_ILLEGAL_MODE 0xE2
  206349. #define SS_NO_ASPI 0xE3
  206350. #define SS_FAILED_INIT 0xE4
  206351. #define SS_ASPI_IS_BUSY 0xE5
  206352. #define SS_BUFFER_TO_BIG 0xE6
  206353. #define SS_BUFFER_TOO_BIG 0xE6
  206354. #define SS_MISMATCHED_COMPONENTS 0xE7
  206355. #define SS_NO_ADAPTERS 0xE8
  206356. #define SS_INSUFFICIENT_RESOURCES 0xE9
  206357. #define SS_ASPI_IS_SHUTDOWN 0xEA
  206358. #define SS_BAD_INSTALL 0xEB
  206359. #define HASTAT_OK 0x00
  206360. #define HASTAT_SEL_TO 0x11
  206361. #define HASTAT_DO_DU 0x12
  206362. #define HASTAT_BUS_FREE 0x13
  206363. #define HASTAT_PHASE_ERR 0x14
  206364. #define HASTAT_TIMEOUT 0x09
  206365. #define HASTAT_COMMAND_TIMEOUT 0x0B
  206366. #define HASTAT_MESSAGE_REJECT 0x0D
  206367. #define HASTAT_BUS_RESET 0x0E
  206368. #define HASTAT_PARITY_ERROR 0x0F
  206369. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  206370. #define PACKED
  206371. #pragma pack(1)
  206372. typedef struct
  206373. {
  206374. BYTE SRB_Cmd;
  206375. BYTE SRB_Status;
  206376. BYTE SRB_HaID;
  206377. BYTE SRB_Flags;
  206378. DWORD SRB_Hdr_Rsvd;
  206379. BYTE HA_Count;
  206380. BYTE HA_SCSI_ID;
  206381. BYTE HA_ManagerId[16];
  206382. BYTE HA_Identifier[16];
  206383. BYTE HA_Unique[16];
  206384. WORD HA_Rsvd1;
  206385. BYTE pad[20];
  206386. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  206387. typedef struct
  206388. {
  206389. BYTE SRB_Cmd;
  206390. BYTE SRB_Status;
  206391. BYTE SRB_HaID;
  206392. BYTE SRB_Flags;
  206393. DWORD SRB_Hdr_Rsvd;
  206394. BYTE SRB_Target;
  206395. BYTE SRB_Lun;
  206396. BYTE SRB_DeviceType;
  206397. BYTE SRB_Rsvd1;
  206398. BYTE pad[68];
  206399. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  206400. typedef struct
  206401. {
  206402. BYTE SRB_Cmd;
  206403. BYTE SRB_Status;
  206404. BYTE SRB_HaID;
  206405. BYTE SRB_Flags;
  206406. DWORD SRB_Hdr_Rsvd;
  206407. BYTE SRB_Target;
  206408. BYTE SRB_Lun;
  206409. WORD SRB_Rsvd1;
  206410. DWORD SRB_BufLen;
  206411. BYTE FAR *SRB_BufPointer;
  206412. BYTE SRB_SenseLen;
  206413. BYTE SRB_CDBLen;
  206414. BYTE SRB_HaStat;
  206415. BYTE SRB_TargStat;
  206416. VOID FAR *SRB_PostProc;
  206417. BYTE SRB_Rsvd2[20];
  206418. BYTE CDBByte[16];
  206419. BYTE SenseArea[SENSE_LEN+2];
  206420. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  206421. typedef struct
  206422. {
  206423. BYTE SRB_Cmd;
  206424. BYTE SRB_Status;
  206425. BYTE SRB_HaId;
  206426. BYTE SRB_Flags;
  206427. DWORD SRB_Hdr_Rsvd;
  206428. } PACKED SRB, *PSRB, FAR *LPSRB;
  206429. #pragma pack()
  206430. struct CDDeviceInfo
  206431. {
  206432. char vendor[9];
  206433. char productId[17];
  206434. char rev[5];
  206435. char vendorSpec[21];
  206436. BYTE ha;
  206437. BYTE tgt;
  206438. BYTE lun;
  206439. char scsiDriveLetter; // will be 0 if not using scsi
  206440. };
  206441. class CDReadBuffer
  206442. {
  206443. public:
  206444. int startFrame;
  206445. int numFrames;
  206446. int dataStartOffset;
  206447. int dataLength;
  206448. int bufferSize;
  206449. HeapBlock<BYTE> buffer;
  206450. int index;
  206451. bool wantsIndex;
  206452. CDReadBuffer (const int numberOfFrames)
  206453. : startFrame (0),
  206454. numFrames (0),
  206455. dataStartOffset (0),
  206456. dataLength (0),
  206457. bufferSize (2352 * numberOfFrames),
  206458. buffer (bufferSize),
  206459. index (0),
  206460. wantsIndex (false)
  206461. {
  206462. }
  206463. bool isZero() const throw()
  206464. {
  206465. BYTE* p = buffer + dataStartOffset;
  206466. for (int i = dataLength; --i >= 0;)
  206467. if (*p++ != 0)
  206468. return false;
  206469. return true;
  206470. }
  206471. };
  206472. class CDDeviceHandle;
  206473. class CDController
  206474. {
  206475. public:
  206476. CDController();
  206477. virtual ~CDController();
  206478. virtual bool read (CDReadBuffer* t) = 0;
  206479. virtual void shutDown();
  206480. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  206481. int getLastIndex();
  206482. public:
  206483. bool initialised;
  206484. CDDeviceHandle* deviceInfo;
  206485. int framesToCheck, framesOverlap;
  206486. void prepare (SRB_ExecSCSICmd& s);
  206487. void perform (SRB_ExecSCSICmd& s);
  206488. void setPaused (bool paused);
  206489. };
  206490. #pragma pack(1)
  206491. struct TOCTRACK
  206492. {
  206493. BYTE rsvd;
  206494. BYTE ADR;
  206495. BYTE trackNumber;
  206496. BYTE rsvd2;
  206497. BYTE addr[4];
  206498. };
  206499. struct TOC
  206500. {
  206501. WORD tocLen;
  206502. BYTE firstTrack;
  206503. BYTE lastTrack;
  206504. TOCTRACK tracks[100];
  206505. };
  206506. #pragma pack()
  206507. enum
  206508. {
  206509. READTYPE_ANY = 0,
  206510. READTYPE_ATAPI1 = 1,
  206511. READTYPE_ATAPI2 = 2,
  206512. READTYPE_READ6 = 3,
  206513. READTYPE_READ10 = 4,
  206514. READTYPE_READ_D8 = 5,
  206515. READTYPE_READ_D4 = 6,
  206516. READTYPE_READ_D4_1 = 7,
  206517. READTYPE_READ10_2 = 8
  206518. };
  206519. class CDDeviceHandle
  206520. {
  206521. public:
  206522. CDDeviceHandle (const CDDeviceInfo* const device)
  206523. : scsiHandle (0),
  206524. readType (READTYPE_ANY),
  206525. controller (0)
  206526. {
  206527. memcpy (&info, device, sizeof (info));
  206528. }
  206529. ~CDDeviceHandle()
  206530. {
  206531. if (controller != 0)
  206532. {
  206533. controller->shutDown();
  206534. controller = 0;
  206535. }
  206536. if (scsiHandle != 0)
  206537. CloseHandle (scsiHandle);
  206538. }
  206539. bool readTOC (TOC* lpToc, bool useMSF);
  206540. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  206541. void openDrawer (bool shouldBeOpen);
  206542. CDDeviceInfo info;
  206543. HANDLE scsiHandle;
  206544. BYTE readType;
  206545. private:
  206546. ScopedPointer<CDController> controller;
  206547. bool testController (const int readType,
  206548. CDController* const newController,
  206549. CDReadBuffer* const bufferToUse);
  206550. };
  206551. DWORD (*fGetASPI32SupportInfo)(void);
  206552. DWORD (*fSendASPI32Command)(LPSRB);
  206553. static HINSTANCE winAspiLib = 0;
  206554. static bool usingScsi = false;
  206555. static bool initialised = false;
  206556. static bool InitialiseCDRipper()
  206557. {
  206558. if (! initialised)
  206559. {
  206560. initialised = true;
  206561. OSVERSIONINFO info;
  206562. info.dwOSVersionInfoSize = sizeof (info);
  206563. GetVersionEx (&info);
  206564. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  206565. if (! usingScsi)
  206566. {
  206567. fGetASPI32SupportInfo = 0;
  206568. fSendASPI32Command = 0;
  206569. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  206570. if (winAspiLib != 0)
  206571. {
  206572. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  206573. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  206574. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  206575. return false;
  206576. }
  206577. else
  206578. {
  206579. usingScsi = true;
  206580. }
  206581. }
  206582. }
  206583. return true;
  206584. }
  206585. static void DeinitialiseCDRipper()
  206586. {
  206587. if (winAspiLib != 0)
  206588. {
  206589. fGetASPI32SupportInfo = 0;
  206590. fSendASPI32Command = 0;
  206591. FreeLibrary (winAspiLib);
  206592. winAspiLib = 0;
  206593. }
  206594. initialised = false;
  206595. }
  206596. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  206597. {
  206598. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  206599. OSVERSIONINFO info;
  206600. info.dwOSVersionInfoSize = sizeof (info);
  206601. GetVersionEx (&info);
  206602. DWORD flags = GENERIC_READ;
  206603. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  206604. flags = GENERIC_READ | GENERIC_WRITE;
  206605. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206606. if (h == INVALID_HANDLE_VALUE)
  206607. {
  206608. flags ^= GENERIC_WRITE;
  206609. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206610. }
  206611. return h;
  206612. }
  206613. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  206614. const char driveLetter,
  206615. HANDLE& deviceHandle,
  206616. const bool retryOnFailure = true)
  206617. {
  206618. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  206619. zerostruct (s);
  206620. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  206621. s.spt.CdbLength = srb->SRB_CDBLen;
  206622. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  206623. ? SCSI_IOCTL_DATA_IN
  206624. : ((srb->SRB_Flags & SRB_DIR_OUT)
  206625. ? SCSI_IOCTL_DATA_OUT
  206626. : SCSI_IOCTL_DATA_UNSPECIFIED));
  206627. s.spt.DataTransferLength = srb->SRB_BufLen;
  206628. s.spt.TimeOutValue = 5;
  206629. s.spt.DataBuffer = srb->SRB_BufPointer;
  206630. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206631. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  206632. srb->SRB_Status = SS_ERR;
  206633. srb->SRB_TargStat = 0x0004;
  206634. DWORD bytesReturned = 0;
  206635. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206636. &s, sizeof (s),
  206637. &s, sizeof (s),
  206638. &bytesReturned, 0) != 0)
  206639. {
  206640. srb->SRB_Status = SS_COMP;
  206641. }
  206642. else if (retryOnFailure)
  206643. {
  206644. const DWORD error = GetLastError();
  206645. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  206646. {
  206647. if (error != ERROR_INVALID_HANDLE)
  206648. CloseHandle (deviceHandle);
  206649. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  206650. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  206651. }
  206652. }
  206653. return srb->SRB_Status;
  206654. }
  206655. // Controller types..
  206656. class ControllerType1 : public CDController
  206657. {
  206658. public:
  206659. ControllerType1() {}
  206660. ~ControllerType1() {}
  206661. bool read (CDReadBuffer* rb)
  206662. {
  206663. if (rb->numFrames * 2352 > rb->bufferSize)
  206664. return false;
  206665. SRB_ExecSCSICmd s;
  206666. prepare (s);
  206667. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206668. s.SRB_BufLen = rb->bufferSize;
  206669. s.SRB_BufPointer = rb->buffer;
  206670. s.SRB_CDBLen = 12;
  206671. s.CDBByte[0] = 0xBE;
  206672. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206673. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206674. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206675. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206676. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  206677. perform (s);
  206678. if (s.SRB_Status != SS_COMP)
  206679. return false;
  206680. rb->dataLength = rb->numFrames * 2352;
  206681. rb->dataStartOffset = 0;
  206682. return true;
  206683. }
  206684. };
  206685. class ControllerType2 : public CDController
  206686. {
  206687. public:
  206688. ControllerType2() {}
  206689. ~ControllerType2() {}
  206690. void shutDown()
  206691. {
  206692. if (initialised)
  206693. {
  206694. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  206695. SRB_ExecSCSICmd s;
  206696. prepare (s);
  206697. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  206698. s.SRB_BufLen = 0x0C;
  206699. s.SRB_BufPointer = bufPointer;
  206700. s.SRB_CDBLen = 6;
  206701. s.CDBByte[0] = 0x15;
  206702. s.CDBByte[4] = 0x0C;
  206703. perform (s);
  206704. }
  206705. }
  206706. bool init()
  206707. {
  206708. SRB_ExecSCSICmd s;
  206709. s.SRB_Status = SS_ERR;
  206710. if (deviceInfo->readType == READTYPE_READ10_2)
  206711. {
  206712. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  206713. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  206714. for (int i = 0; i < 2; ++i)
  206715. {
  206716. prepare (s);
  206717. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206718. s.SRB_BufLen = 0x14;
  206719. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  206720. s.SRB_CDBLen = 6;
  206721. s.CDBByte[0] = 0x15;
  206722. s.CDBByte[1] = 0x10;
  206723. s.CDBByte[4] = 0x14;
  206724. perform (s);
  206725. if (s.SRB_Status != SS_COMP)
  206726. return false;
  206727. }
  206728. }
  206729. else
  206730. {
  206731. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  206732. prepare (s);
  206733. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206734. s.SRB_BufLen = 0x0C;
  206735. s.SRB_BufPointer = bufPointer;
  206736. s.SRB_CDBLen = 6;
  206737. s.CDBByte[0] = 0x15;
  206738. s.CDBByte[4] = 0x0C;
  206739. perform (s);
  206740. }
  206741. return s.SRB_Status == SS_COMP;
  206742. }
  206743. bool read (CDReadBuffer* rb)
  206744. {
  206745. if (rb->numFrames * 2352 > rb->bufferSize)
  206746. return false;
  206747. if (!initialised)
  206748. {
  206749. initialised = init();
  206750. if (!initialised)
  206751. return false;
  206752. }
  206753. SRB_ExecSCSICmd s;
  206754. prepare (s);
  206755. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206756. s.SRB_BufLen = rb->bufferSize;
  206757. s.SRB_BufPointer = rb->buffer;
  206758. s.SRB_CDBLen = 10;
  206759. s.CDBByte[0] = 0x28;
  206760. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206761. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206762. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206763. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206764. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206765. perform (s);
  206766. if (s.SRB_Status != SS_COMP)
  206767. return false;
  206768. rb->dataLength = rb->numFrames * 2352;
  206769. rb->dataStartOffset = 0;
  206770. return true;
  206771. }
  206772. };
  206773. class ControllerType3 : public CDController
  206774. {
  206775. public:
  206776. ControllerType3() {}
  206777. ~ControllerType3() {}
  206778. bool read (CDReadBuffer* rb)
  206779. {
  206780. if (rb->numFrames * 2352 > rb->bufferSize)
  206781. return false;
  206782. if (!initialised)
  206783. {
  206784. setPaused (false);
  206785. initialised = true;
  206786. }
  206787. SRB_ExecSCSICmd s;
  206788. prepare (s);
  206789. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206790. s.SRB_BufLen = rb->numFrames * 2352;
  206791. s.SRB_BufPointer = rb->buffer;
  206792. s.SRB_CDBLen = 12;
  206793. s.CDBByte[0] = 0xD8;
  206794. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206795. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206796. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206797. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  206798. perform (s);
  206799. if (s.SRB_Status != SS_COMP)
  206800. return false;
  206801. rb->dataLength = rb->numFrames * 2352;
  206802. rb->dataStartOffset = 0;
  206803. return true;
  206804. }
  206805. };
  206806. class ControllerType4 : public CDController
  206807. {
  206808. public:
  206809. ControllerType4() {}
  206810. ~ControllerType4() {}
  206811. bool selectD4Mode()
  206812. {
  206813. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  206814. SRB_ExecSCSICmd s;
  206815. prepare (s);
  206816. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206817. s.SRB_CDBLen = 6;
  206818. s.SRB_BufLen = 12;
  206819. s.SRB_BufPointer = bufPointer;
  206820. s.CDBByte[0] = 0x15;
  206821. s.CDBByte[1] = 0x10;
  206822. s.CDBByte[4] = 0x08;
  206823. perform (s);
  206824. return s.SRB_Status == SS_COMP;
  206825. }
  206826. bool read (CDReadBuffer* rb)
  206827. {
  206828. if (rb->numFrames * 2352 > rb->bufferSize)
  206829. return false;
  206830. if (!initialised)
  206831. {
  206832. setPaused (true);
  206833. if (deviceInfo->readType == READTYPE_READ_D4_1)
  206834. selectD4Mode();
  206835. initialised = true;
  206836. }
  206837. SRB_ExecSCSICmd s;
  206838. prepare (s);
  206839. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206840. s.SRB_BufLen = rb->bufferSize;
  206841. s.SRB_BufPointer = rb->buffer;
  206842. s.SRB_CDBLen = 10;
  206843. s.CDBByte[0] = 0xD4;
  206844. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206845. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206846. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206847. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206848. perform (s);
  206849. if (s.SRB_Status != SS_COMP)
  206850. return false;
  206851. rb->dataLength = rb->numFrames * 2352;
  206852. rb->dataStartOffset = 0;
  206853. return true;
  206854. }
  206855. };
  206856. CDController::CDController() : initialised (false)
  206857. {
  206858. }
  206859. CDController::~CDController()
  206860. {
  206861. }
  206862. void CDController::prepare (SRB_ExecSCSICmd& s)
  206863. {
  206864. zerostruct (s);
  206865. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206866. s.SRB_HaID = deviceInfo->info.ha;
  206867. s.SRB_Target = deviceInfo->info.tgt;
  206868. s.SRB_Lun = deviceInfo->info.lun;
  206869. s.SRB_SenseLen = SENSE_LEN;
  206870. }
  206871. void CDController::perform (SRB_ExecSCSICmd& s)
  206872. {
  206873. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206874. s.SRB_PostProc = event;
  206875. ResetEvent (event);
  206876. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  206877. deviceInfo->info.scsiDriveLetter,
  206878. deviceInfo->scsiHandle)
  206879. : fSendASPI32Command ((LPSRB)&s);
  206880. if (status == SS_PENDING)
  206881. WaitForSingleObject (event, 4000);
  206882. CloseHandle (event);
  206883. }
  206884. void CDController::setPaused (bool paused)
  206885. {
  206886. SRB_ExecSCSICmd s;
  206887. prepare (s);
  206888. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206889. s.SRB_CDBLen = 10;
  206890. s.CDBByte[0] = 0x4B;
  206891. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  206892. perform (s);
  206893. }
  206894. void CDController::shutDown()
  206895. {
  206896. }
  206897. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  206898. {
  206899. if (overlapBuffer != 0)
  206900. {
  206901. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  206902. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  206903. if (doJitter
  206904. && overlapBuffer->startFrame > 0
  206905. && overlapBuffer->numFrames > 0
  206906. && overlapBuffer->dataLength > 0)
  206907. {
  206908. const int numFrames = rb->numFrames;
  206909. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  206910. {
  206911. rb->startFrame -= framesOverlap;
  206912. if (framesToCheck < framesOverlap
  206913. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  206914. rb->numFrames += framesOverlap;
  206915. }
  206916. else
  206917. {
  206918. overlapBuffer->dataLength = 0;
  206919. overlapBuffer->startFrame = 0;
  206920. overlapBuffer->numFrames = 0;
  206921. }
  206922. }
  206923. if (! read (rb))
  206924. return false;
  206925. if (doJitter)
  206926. {
  206927. const int checkLen = framesToCheck * 2352;
  206928. const int maxToCheck = rb->dataLength - checkLen;
  206929. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  206930. return true;
  206931. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  206932. bool found = false;
  206933. for (int i = 0; i < maxToCheck; ++i)
  206934. {
  206935. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  206936. {
  206937. i += checkLen;
  206938. rb->dataStartOffset = i;
  206939. rb->dataLength -= i;
  206940. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  206941. found = true;
  206942. break;
  206943. }
  206944. }
  206945. rb->numFrames = rb->dataLength / 2352;
  206946. rb->dataLength = 2352 * rb->numFrames;
  206947. if (!found)
  206948. return false;
  206949. }
  206950. if (canDoJitter)
  206951. {
  206952. memcpy (overlapBuffer->buffer,
  206953. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  206954. 2352 * framesToCheck);
  206955. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  206956. overlapBuffer->numFrames = framesToCheck;
  206957. overlapBuffer->dataLength = 2352 * framesToCheck;
  206958. overlapBuffer->dataStartOffset = 0;
  206959. }
  206960. else
  206961. {
  206962. overlapBuffer->startFrame = 0;
  206963. overlapBuffer->numFrames = 0;
  206964. overlapBuffer->dataLength = 0;
  206965. }
  206966. return true;
  206967. }
  206968. else
  206969. {
  206970. return read (rb);
  206971. }
  206972. }
  206973. int CDController::getLastIndex()
  206974. {
  206975. char qdata[100];
  206976. SRB_ExecSCSICmd s;
  206977. prepare (s);
  206978. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206979. s.SRB_BufLen = sizeof (qdata);
  206980. s.SRB_BufPointer = (BYTE*)qdata;
  206981. s.SRB_CDBLen = 12;
  206982. s.CDBByte[0] = 0x42;
  206983. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206984. s.CDBByte[2] = 64;
  206985. s.CDBByte[3] = 1; // get current position
  206986. s.CDBByte[7] = 0;
  206987. s.CDBByte[8] = (BYTE)sizeof (qdata);
  206988. perform (s);
  206989. if (s.SRB_Status == SS_COMP)
  206990. return qdata[7];
  206991. return 0;
  206992. }
  206993. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  206994. {
  206995. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206996. SRB_ExecSCSICmd s;
  206997. zerostruct (s);
  206998. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206999. s.SRB_HaID = info.ha;
  207000. s.SRB_Target = info.tgt;
  207001. s.SRB_Lun = info.lun;
  207002. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207003. s.SRB_BufLen = 0x324;
  207004. s.SRB_BufPointer = (BYTE*)lpToc;
  207005. s.SRB_SenseLen = 0x0E;
  207006. s.SRB_CDBLen = 0x0A;
  207007. s.SRB_PostProc = event;
  207008. s.CDBByte[0] = 0x43;
  207009. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  207010. s.CDBByte[7] = 0x03;
  207011. s.CDBByte[8] = 0x24;
  207012. ResetEvent (event);
  207013. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207014. : fSendASPI32Command ((LPSRB)&s);
  207015. if (status == SS_PENDING)
  207016. WaitForSingleObject (event, 4000);
  207017. CloseHandle (event);
  207018. return (s.SRB_Status == SS_COMP);
  207019. }
  207020. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  207021. CDReadBuffer* const overlapBuffer)
  207022. {
  207023. if (controller == 0)
  207024. {
  207025. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  207026. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  207027. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  207028. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  207029. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  207030. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  207031. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  207032. }
  207033. buffer->index = 0;
  207034. if ((controller != 0)
  207035. && controller->readAudio (buffer, overlapBuffer))
  207036. {
  207037. if (buffer->wantsIndex)
  207038. buffer->index = controller->getLastIndex();
  207039. return true;
  207040. }
  207041. return false;
  207042. }
  207043. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  207044. {
  207045. if (shouldBeOpen)
  207046. {
  207047. if (controller != 0)
  207048. {
  207049. controller->shutDown();
  207050. controller = 0;
  207051. }
  207052. if (scsiHandle != 0)
  207053. {
  207054. CloseHandle (scsiHandle);
  207055. scsiHandle = 0;
  207056. }
  207057. }
  207058. SRB_ExecSCSICmd s;
  207059. zerostruct (s);
  207060. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207061. s.SRB_HaID = info.ha;
  207062. s.SRB_Target = info.tgt;
  207063. s.SRB_Lun = info.lun;
  207064. s.SRB_SenseLen = SENSE_LEN;
  207065. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207066. s.SRB_BufLen = 0;
  207067. s.SRB_BufPointer = 0;
  207068. s.SRB_CDBLen = 12;
  207069. s.CDBByte[0] = 0x1b;
  207070. s.CDBByte[1] = (BYTE)(info.lun << 5);
  207071. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  207072. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207073. s.SRB_PostProc = event;
  207074. ResetEvent (event);
  207075. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207076. : fSendASPI32Command ((LPSRB)&s);
  207077. if (status == SS_PENDING)
  207078. WaitForSingleObject (event, 4000);
  207079. CloseHandle (event);
  207080. }
  207081. bool CDDeviceHandle::testController (const int type,
  207082. CDController* const newController,
  207083. CDReadBuffer* const rb)
  207084. {
  207085. controller = newController;
  207086. readType = (BYTE)type;
  207087. controller->deviceInfo = this;
  207088. controller->framesToCheck = 1;
  207089. controller->framesOverlap = 3;
  207090. bool passed = false;
  207091. memset (rb->buffer, 0xcd, rb->bufferSize);
  207092. if (controller->read (rb))
  207093. {
  207094. passed = true;
  207095. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  207096. int wrong = 0;
  207097. for (int i = rb->dataLength / 4; --i >= 0;)
  207098. {
  207099. if (*p++ == (int) 0xcdcdcdcd)
  207100. {
  207101. if (++wrong == 4)
  207102. {
  207103. passed = false;
  207104. break;
  207105. }
  207106. }
  207107. else
  207108. {
  207109. wrong = 0;
  207110. }
  207111. }
  207112. }
  207113. if (! passed)
  207114. {
  207115. controller->shutDown();
  207116. controller = 0;
  207117. }
  207118. return passed;
  207119. }
  207120. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  207121. {
  207122. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207123. const int bufSize = 128;
  207124. BYTE buffer[bufSize];
  207125. zeromem (buffer, bufSize);
  207126. SRB_ExecSCSICmd s;
  207127. zerostruct (s);
  207128. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207129. s.SRB_HaID = ha;
  207130. s.SRB_Target = tgt;
  207131. s.SRB_Lun = lun;
  207132. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207133. s.SRB_BufLen = bufSize;
  207134. s.SRB_BufPointer = buffer;
  207135. s.SRB_SenseLen = SENSE_LEN;
  207136. s.SRB_CDBLen = 6;
  207137. s.SRB_PostProc = event;
  207138. s.CDBByte[0] = SCSI_INQUIRY;
  207139. s.CDBByte[4] = 100;
  207140. ResetEvent (event);
  207141. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  207142. WaitForSingleObject (event, 4000);
  207143. CloseHandle (event);
  207144. if (s.SRB_Status == SS_COMP)
  207145. {
  207146. memcpy (dev->vendor, &buffer[8], 8);
  207147. memcpy (dev->productId, &buffer[16], 16);
  207148. memcpy (dev->rev, &buffer[32], 4);
  207149. memcpy (dev->vendorSpec, &buffer[36], 20);
  207150. }
  207151. }
  207152. static int FindCDDevices (CDDeviceInfo* const list,
  207153. int maxItems)
  207154. {
  207155. int count = 0;
  207156. if (usingScsi)
  207157. {
  207158. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  207159. {
  207160. TCHAR drivePath[8];
  207161. drivePath[0] = driveLetter;
  207162. drivePath[1] = ':';
  207163. drivePath[2] = '\\';
  207164. drivePath[3] = 0;
  207165. if (GetDriveType (drivePath) == DRIVE_CDROM)
  207166. {
  207167. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  207168. if (h != INVALID_HANDLE_VALUE)
  207169. {
  207170. BYTE buffer[100], passThroughStruct[1024];
  207171. zeromem (buffer, sizeof (buffer));
  207172. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207173. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  207174. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  207175. p->spt.CdbLength = 6;
  207176. p->spt.SenseInfoLength = 24;
  207177. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  207178. p->spt.DataTransferLength = 100;
  207179. p->spt.TimeOutValue = 2;
  207180. p->spt.DataBuffer = buffer;
  207181. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  207182. p->spt.Cdb[0] = 0x12;
  207183. p->spt.Cdb[4] = 100;
  207184. DWORD bytesReturned = 0;
  207185. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  207186. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207187. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207188. &bytesReturned, 0) != 0)
  207189. {
  207190. zeromem (&list[count], sizeof (CDDeviceInfo));
  207191. list[count].scsiDriveLetter = driveLetter;
  207192. memcpy (list[count].vendor, &buffer[8], 8);
  207193. memcpy (list[count].productId, &buffer[16], 16);
  207194. memcpy (list[count].rev, &buffer[32], 4);
  207195. memcpy (list[count].vendorSpec, &buffer[36], 20);
  207196. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207197. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  207198. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  207199. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  207200. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  207201. &bytesReturned, 0) != 0)
  207202. {
  207203. list[count].ha = scsiAddr->PortNumber;
  207204. list[count].tgt = scsiAddr->TargetId;
  207205. list[count].lun = scsiAddr->Lun;
  207206. ++count;
  207207. }
  207208. }
  207209. CloseHandle (h);
  207210. }
  207211. }
  207212. }
  207213. }
  207214. else
  207215. {
  207216. const DWORD d = fGetASPI32SupportInfo();
  207217. BYTE status = HIBYTE (LOWORD (d));
  207218. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  207219. return 0;
  207220. const int numAdapters = LOBYTE (LOWORD (d));
  207221. for (BYTE ha = 0; ha < numAdapters; ++ha)
  207222. {
  207223. SRB_HAInquiry s;
  207224. zerostruct (s);
  207225. s.SRB_Cmd = SC_HA_INQUIRY;
  207226. s.SRB_HaID = ha;
  207227. fSendASPI32Command ((LPSRB)&s);
  207228. if (s.SRB_Status == SS_COMP)
  207229. {
  207230. maxItems = (int)s.HA_Unique[3];
  207231. if (maxItems == 0)
  207232. maxItems = 8;
  207233. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  207234. {
  207235. for (BYTE lun = 0; lun < 8; ++lun)
  207236. {
  207237. SRB_GDEVBlock sb;
  207238. zerostruct (sb);
  207239. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  207240. sb.SRB_HaID = ha;
  207241. sb.SRB_Target = tgt;
  207242. sb.SRB_Lun = lun;
  207243. fSendASPI32Command ((LPSRB) &sb);
  207244. if (sb.SRB_Status == SS_COMP
  207245. && sb.SRB_DeviceType == DTYPE_CROM)
  207246. {
  207247. zeromem (&list[count], sizeof (CDDeviceInfo));
  207248. list[count].ha = ha;
  207249. list[count].tgt = tgt;
  207250. list[count].lun = lun;
  207251. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  207252. ++count;
  207253. }
  207254. }
  207255. }
  207256. }
  207257. }
  207258. }
  207259. return count;
  207260. }
  207261. static int ripperUsers = 0;
  207262. static bool initialisedOk = false;
  207263. class DeinitialiseTimer : private Timer,
  207264. private DeletedAtShutdown
  207265. {
  207266. DeinitialiseTimer (const DeinitialiseTimer&);
  207267. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  207268. public:
  207269. DeinitialiseTimer()
  207270. {
  207271. startTimer (4000);
  207272. }
  207273. ~DeinitialiseTimer()
  207274. {
  207275. if (--ripperUsers == 0)
  207276. DeinitialiseCDRipper();
  207277. }
  207278. void timerCallback()
  207279. {
  207280. delete this;
  207281. }
  207282. juce_UseDebuggingNewOperator
  207283. };
  207284. static void incUserCount()
  207285. {
  207286. if (ripperUsers++ == 0)
  207287. initialisedOk = InitialiseCDRipper();
  207288. }
  207289. static void decUserCount()
  207290. {
  207291. new DeinitialiseTimer();
  207292. }
  207293. struct CDDeviceWrapper
  207294. {
  207295. ScopedPointer<CDDeviceHandle> cdH;
  207296. ScopedPointer<CDReadBuffer> overlapBuffer;
  207297. bool jitter;
  207298. };
  207299. static int getAddressOf (const TOCTRACK* const t)
  207300. {
  207301. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  207302. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  207303. }
  207304. static int getMSFAddressOf (const TOCTRACK* const t)
  207305. {
  207306. return 60 * t->addr[1] + t->addr[2];
  207307. }
  207308. static const int samplesPerFrame = 44100 / 75;
  207309. static const int bytesPerFrame = samplesPerFrame * 4;
  207310. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  207311. {
  207312. SRB_GDEVBlock s;
  207313. zerostruct (s);
  207314. s.SRB_Cmd = SC_GET_DEV_TYPE;
  207315. s.SRB_HaID = device->ha;
  207316. s.SRB_Target = device->tgt;
  207317. s.SRB_Lun = device->lun;
  207318. if (usingScsi)
  207319. {
  207320. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  207321. if (h != INVALID_HANDLE_VALUE)
  207322. {
  207323. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  207324. cdh->scsiHandle = h;
  207325. return cdh;
  207326. }
  207327. }
  207328. else
  207329. {
  207330. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  207331. && s.SRB_DeviceType == DTYPE_CROM)
  207332. {
  207333. return new CDDeviceHandle (device);
  207334. }
  207335. }
  207336. return 0;
  207337. }
  207338. }
  207339. const StringArray AudioCDReader::getAvailableCDNames()
  207340. {
  207341. using namespace CDReaderHelpers;
  207342. StringArray results;
  207343. incUserCount();
  207344. if (initialisedOk)
  207345. {
  207346. CDDeviceInfo list[8];
  207347. const int num = FindCDDevices (list, 8);
  207348. decUserCount();
  207349. for (int i = 0; i < num; ++i)
  207350. {
  207351. String s;
  207352. if (list[i].scsiDriveLetter > 0)
  207353. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  207354. s << String (list[i].vendor).trim()
  207355. << ' ' << String (list[i].productId).trim()
  207356. << ' ' << String (list[i].rev).trim();
  207357. results.add (s);
  207358. }
  207359. }
  207360. return results;
  207361. }
  207362. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  207363. {
  207364. using namespace CDReaderHelpers;
  207365. incUserCount();
  207366. if (initialisedOk)
  207367. {
  207368. CDDeviceInfo list[8];
  207369. const int num = FindCDDevices (list, 8);
  207370. if (((unsigned int) deviceIndex) < (unsigned int) num)
  207371. {
  207372. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  207373. if (handle != 0)
  207374. {
  207375. CDDeviceWrapper* const d = new CDDeviceWrapper();
  207376. d->cdH = handle;
  207377. d->overlapBuffer = new CDReadBuffer(3);
  207378. return new AudioCDReader (d);
  207379. }
  207380. }
  207381. }
  207382. decUserCount();
  207383. return 0;
  207384. }
  207385. AudioCDReader::AudioCDReader (void* handle_)
  207386. : AudioFormatReader (0, "CD Audio"),
  207387. handle (handle_),
  207388. indexingEnabled (false),
  207389. lastIndex (0),
  207390. firstFrameInBuffer (0),
  207391. samplesInBuffer (0)
  207392. {
  207393. using namespace CDReaderHelpers;
  207394. jassert (handle_ != 0);
  207395. refreshTrackLengths();
  207396. sampleRate = 44100.0;
  207397. bitsPerSample = 16;
  207398. lengthInSamples = getPositionOfTrackStart (numTracks);
  207399. numChannels = 2;
  207400. usesFloatingPointData = false;
  207401. buffer.setSize (4 * bytesPerFrame, true);
  207402. }
  207403. AudioCDReader::~AudioCDReader()
  207404. {
  207405. using namespace CDReaderHelpers;
  207406. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207407. delete device;
  207408. decUserCount();
  207409. }
  207410. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  207411. int64 startSampleInFile, int numSamples)
  207412. {
  207413. using namespace CDReaderHelpers;
  207414. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207415. bool ok = true;
  207416. while (numSamples > 0)
  207417. {
  207418. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  207419. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  207420. if (startSampleInFile >= bufferStartSample
  207421. && startSampleInFile < bufferEndSample)
  207422. {
  207423. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  207424. int* const l = destSamples[0] + startOffsetInDestBuffer;
  207425. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207426. const short* src = (const short*) buffer.getData();
  207427. src += 2 * (startSampleInFile - bufferStartSample);
  207428. for (int i = 0; i < toDo; ++i)
  207429. {
  207430. l[i] = src [i << 1] << 16;
  207431. if (r != 0)
  207432. r[i] = src [(i << 1) + 1] << 16;
  207433. }
  207434. startOffsetInDestBuffer += toDo;
  207435. startSampleInFile += toDo;
  207436. numSamples -= toDo;
  207437. }
  207438. else
  207439. {
  207440. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  207441. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  207442. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  207443. {
  207444. device->overlapBuffer->dataLength = 0;
  207445. device->overlapBuffer->startFrame = 0;
  207446. device->overlapBuffer->numFrames = 0;
  207447. device->jitter = false;
  207448. }
  207449. firstFrameInBuffer = frameNeeded;
  207450. lastIndex = 0;
  207451. CDReadBuffer readBuffer (framesInBuffer + 4);
  207452. readBuffer.wantsIndex = indexingEnabled;
  207453. int i;
  207454. for (i = 5; --i >= 0;)
  207455. {
  207456. readBuffer.startFrame = frameNeeded;
  207457. readBuffer.numFrames = framesInBuffer;
  207458. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  207459. break;
  207460. else
  207461. device->overlapBuffer->dataLength = 0;
  207462. }
  207463. if (i >= 0)
  207464. {
  207465. memcpy ((char*) buffer.getData(),
  207466. readBuffer.buffer + readBuffer.dataStartOffset,
  207467. readBuffer.dataLength);
  207468. samplesInBuffer = readBuffer.dataLength >> 2;
  207469. lastIndex = readBuffer.index;
  207470. }
  207471. else
  207472. {
  207473. int* l = destSamples[0] + startOffsetInDestBuffer;
  207474. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207475. while (--numSamples >= 0)
  207476. {
  207477. *l++ = 0;
  207478. if (r != 0)
  207479. *r++ = 0;
  207480. }
  207481. // sometimes the read fails for just the very last couple of blocks, so
  207482. // we'll ignore and errors in the last half-second of the disk..
  207483. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  207484. break;
  207485. }
  207486. }
  207487. }
  207488. return ok;
  207489. }
  207490. bool AudioCDReader::isCDStillPresent() const
  207491. {
  207492. using namespace CDReaderHelpers;
  207493. TOC toc;
  207494. zerostruct (toc);
  207495. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  207496. }
  207497. int AudioCDReader::getNumTracks() const
  207498. {
  207499. return numTracks;
  207500. }
  207501. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  207502. {
  207503. using namespace CDReaderHelpers;
  207504. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  207505. : 0;
  207506. }
  207507. void AudioCDReader::refreshTrackLengths()
  207508. {
  207509. using namespace CDReaderHelpers;
  207510. zeromem (trackStarts, sizeof (trackStarts));
  207511. zeromem (audioTracks, sizeof (audioTracks));
  207512. TOC toc;
  207513. zerostruct (toc);
  207514. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  207515. {
  207516. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  207517. for (int i = 0; i <= numTracks; ++i)
  207518. {
  207519. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  207520. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  207521. }
  207522. }
  207523. else
  207524. {
  207525. numTracks = 0;
  207526. }
  207527. }
  207528. bool AudioCDReader::isTrackAudio (int trackNum) const
  207529. {
  207530. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  207531. : false;
  207532. }
  207533. void AudioCDReader::enableIndexScanning (bool b)
  207534. {
  207535. indexingEnabled = b;
  207536. }
  207537. int AudioCDReader::getLastIndex() const
  207538. {
  207539. return lastIndex;
  207540. }
  207541. const int framesPerIndexRead = 4;
  207542. int AudioCDReader::getIndexAt (int samplePos)
  207543. {
  207544. using namespace CDReaderHelpers;
  207545. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207546. const int frameNeeded = samplePos / samplesPerFrame;
  207547. device->overlapBuffer->dataLength = 0;
  207548. device->overlapBuffer->startFrame = 0;
  207549. device->overlapBuffer->numFrames = 0;
  207550. device->jitter = false;
  207551. firstFrameInBuffer = 0;
  207552. lastIndex = 0;
  207553. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  207554. readBuffer.wantsIndex = true;
  207555. int i;
  207556. for (i = 5; --i >= 0;)
  207557. {
  207558. readBuffer.startFrame = frameNeeded;
  207559. readBuffer.numFrames = framesPerIndexRead;
  207560. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207561. break;
  207562. }
  207563. if (i >= 0)
  207564. return readBuffer.index;
  207565. return -1;
  207566. }
  207567. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  207568. {
  207569. using namespace CDReaderHelpers;
  207570. Array <int> indexes;
  207571. const int trackStart = getPositionOfTrackStart (trackNumber);
  207572. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  207573. bool needToScan = true;
  207574. if (trackEnd - trackStart > 20 * 44100)
  207575. {
  207576. // check the end of the track for indexes before scanning the whole thing
  207577. needToScan = false;
  207578. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  207579. bool seenAnIndex = false;
  207580. while (pos <= trackEnd - samplesPerFrame)
  207581. {
  207582. const int index = getIndexAt (pos);
  207583. if (index == 0)
  207584. {
  207585. // lead-out, so skip back a bit if we've not found any indexes yet..
  207586. if (seenAnIndex)
  207587. break;
  207588. pos -= 44100 * 5;
  207589. if (pos < trackStart)
  207590. break;
  207591. }
  207592. else
  207593. {
  207594. if (index > 0)
  207595. seenAnIndex = true;
  207596. if (index > 1)
  207597. {
  207598. needToScan = true;
  207599. break;
  207600. }
  207601. pos += samplesPerFrame * framesPerIndexRead;
  207602. }
  207603. }
  207604. }
  207605. if (needToScan)
  207606. {
  207607. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207608. int pos = trackStart;
  207609. int last = -1;
  207610. while (pos < trackEnd - samplesPerFrame * 10)
  207611. {
  207612. const int frameNeeded = pos / samplesPerFrame;
  207613. device->overlapBuffer->dataLength = 0;
  207614. device->overlapBuffer->startFrame = 0;
  207615. device->overlapBuffer->numFrames = 0;
  207616. device->jitter = false;
  207617. firstFrameInBuffer = 0;
  207618. CDReadBuffer readBuffer (4);
  207619. readBuffer.wantsIndex = true;
  207620. int i;
  207621. for (i = 5; --i >= 0;)
  207622. {
  207623. readBuffer.startFrame = frameNeeded;
  207624. readBuffer.numFrames = framesPerIndexRead;
  207625. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207626. break;
  207627. }
  207628. if (i < 0)
  207629. break;
  207630. if (readBuffer.index > last && readBuffer.index > 1)
  207631. {
  207632. last = readBuffer.index;
  207633. indexes.add (pos);
  207634. }
  207635. pos += samplesPerFrame * framesPerIndexRead;
  207636. }
  207637. indexes.removeValue (trackStart);
  207638. }
  207639. return indexes;
  207640. }
  207641. int AudioCDReader::getCDDBId()
  207642. {
  207643. using namespace CDReaderHelpers;
  207644. refreshTrackLengths();
  207645. if (numTracks > 0)
  207646. {
  207647. TOC toc;
  207648. zerostruct (toc);
  207649. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  207650. {
  207651. int n = 0;
  207652. for (int i = numTracks; --i >= 0;)
  207653. {
  207654. int j = getMSFAddressOf (&toc.tracks[i]);
  207655. while (j > 0)
  207656. {
  207657. n += (j % 10);
  207658. j /= 10;
  207659. }
  207660. }
  207661. if (n != 0)
  207662. {
  207663. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  207664. - getMSFAddressOf (&toc.tracks[0]);
  207665. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  207666. }
  207667. }
  207668. }
  207669. return 0;
  207670. }
  207671. void AudioCDReader::ejectDisk()
  207672. {
  207673. using namespace CDReaderHelpers;
  207674. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  207675. }
  207676. #endif
  207677. #if JUCE_USE_CDBURNER
  207678. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  207679. {
  207680. CoInitialize (0);
  207681. IDiscMaster* dm;
  207682. IDiscRecorder* result = 0;
  207683. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  207684. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  207685. IID_IDiscMaster,
  207686. (void**) &dm)))
  207687. {
  207688. if (SUCCEEDED (dm->Open()))
  207689. {
  207690. IEnumDiscRecorders* drEnum = 0;
  207691. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  207692. {
  207693. IDiscRecorder* dr = 0;
  207694. DWORD dummy;
  207695. int index = 0;
  207696. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  207697. {
  207698. if (indexToOpen == index)
  207699. {
  207700. result = dr;
  207701. break;
  207702. }
  207703. else if (list != 0)
  207704. {
  207705. BSTR path;
  207706. if (SUCCEEDED (dr->GetPath (&path)))
  207707. list->add ((const WCHAR*) path);
  207708. }
  207709. ++index;
  207710. dr->Release();
  207711. }
  207712. drEnum->Release();
  207713. }
  207714. if (master == 0)
  207715. dm->Close();
  207716. }
  207717. if (master != 0)
  207718. *master = dm;
  207719. else
  207720. dm->Release();
  207721. }
  207722. return result;
  207723. }
  207724. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  207725. public Timer
  207726. {
  207727. public:
  207728. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  207729. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  207730. listener (0), progress (0), shouldCancel (false)
  207731. {
  207732. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  207733. jassert (SUCCEEDED (hr));
  207734. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  207735. //jassert (SUCCEEDED (hr));
  207736. lastState = getDiskState();
  207737. startTimer (2000);
  207738. }
  207739. ~Pimpl() {}
  207740. void releaseObjects()
  207741. {
  207742. discRecorder->Close();
  207743. if (redbook != 0)
  207744. redbook->Release();
  207745. discRecorder->Release();
  207746. discMaster->Release();
  207747. Release();
  207748. }
  207749. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  207750. {
  207751. if (listener != 0 && ! shouldCancel)
  207752. shouldCancel = listener->audioCDBurnProgress (progress);
  207753. *pbCancel = shouldCancel;
  207754. return S_OK;
  207755. }
  207756. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  207757. {
  207758. progress = nCompleted / (float) nTotal;
  207759. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  207760. return E_NOTIMPL;
  207761. }
  207762. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  207763. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  207764. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  207765. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207766. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207767. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207768. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207769. class ScopedDiscOpener
  207770. {
  207771. public:
  207772. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  207773. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  207774. private:
  207775. Pimpl& pimpl;
  207776. ScopedDiscOpener (const ScopedDiscOpener&);
  207777. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  207778. };
  207779. DiskState getDiskState()
  207780. {
  207781. const ScopedDiscOpener opener (*this);
  207782. long type, flags;
  207783. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  207784. if (FAILED (hr))
  207785. return unknown;
  207786. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  207787. return writableDiskPresent;
  207788. if (type == 0)
  207789. return noDisc;
  207790. else
  207791. return readOnlyDiskPresent;
  207792. }
  207793. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  207794. {
  207795. ComSmartPtr<IPropertyStorage> prop;
  207796. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  207797. return defaultReturn;
  207798. PROPSPEC iPropSpec;
  207799. iPropSpec.ulKind = PRSPEC_LPWSTR;
  207800. iPropSpec.lpwstr = name;
  207801. PROPVARIANT iPropVariant;
  207802. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  207803. ? defaultReturn : (int) iPropVariant.lVal;
  207804. }
  207805. bool setIntProperty (const LPOLESTR name, const int value) const
  207806. {
  207807. ComSmartPtr<IPropertyStorage> prop;
  207808. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  207809. return false;
  207810. PROPSPEC iPropSpec;
  207811. iPropSpec.ulKind = PRSPEC_LPWSTR;
  207812. iPropSpec.lpwstr = name;
  207813. PROPVARIANT iPropVariant;
  207814. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  207815. return false;
  207816. iPropVariant.lVal = (long) value;
  207817. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  207818. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  207819. }
  207820. void timerCallback()
  207821. {
  207822. const DiskState state = getDiskState();
  207823. if (state != lastState)
  207824. {
  207825. lastState = state;
  207826. owner.sendChangeMessage (&owner);
  207827. }
  207828. }
  207829. AudioCDBurner& owner;
  207830. DiskState lastState;
  207831. IDiscMaster* discMaster;
  207832. IDiscRecorder* discRecorder;
  207833. IRedbookDiscMaster* redbook;
  207834. AudioCDBurner::BurnProgressListener* listener;
  207835. float progress;
  207836. bool shouldCancel;
  207837. };
  207838. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  207839. {
  207840. IDiscMaster* discMaster = 0;
  207841. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  207842. if (discRecorder != 0)
  207843. pimpl = new Pimpl (*this, discMaster, discRecorder);
  207844. }
  207845. AudioCDBurner::~AudioCDBurner()
  207846. {
  207847. if (pimpl != 0)
  207848. pimpl.release()->releaseObjects();
  207849. }
  207850. const StringArray AudioCDBurner::findAvailableDevices()
  207851. {
  207852. StringArray devs;
  207853. enumCDBurners (&devs, -1, 0);
  207854. return devs;
  207855. }
  207856. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  207857. {
  207858. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  207859. if (b->pimpl == 0)
  207860. b = 0;
  207861. return b.release();
  207862. }
  207863. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  207864. {
  207865. return pimpl->getDiskState();
  207866. }
  207867. bool AudioCDBurner::isDiskPresent() const
  207868. {
  207869. return getDiskState() == writableDiskPresent;
  207870. }
  207871. bool AudioCDBurner::openTray()
  207872. {
  207873. const Pimpl::ScopedDiscOpener opener (*pimpl);
  207874. return SUCCEEDED (pimpl->discRecorder->Eject());
  207875. }
  207876. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  207877. {
  207878. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  207879. DiskState oldState = getDiskState();
  207880. DiskState newState = oldState;
  207881. while (newState == oldState && Time::currentTimeMillis() < timeout)
  207882. {
  207883. newState = getDiskState();
  207884. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  207885. }
  207886. return newState;
  207887. }
  207888. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  207889. {
  207890. Array<int> results;
  207891. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  207892. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  207893. for (int i = 0; i < numElementsInArray (speeds); ++i)
  207894. if (speeds[i] <= maxSpeed)
  207895. results.add (speeds[i]);
  207896. results.addIfNotAlreadyThere (maxSpeed);
  207897. return results;
  207898. }
  207899. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  207900. {
  207901. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  207902. return false;
  207903. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  207904. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  207905. }
  207906. int AudioCDBurner::getNumAvailableAudioBlocks() const
  207907. {
  207908. long blocksFree = 0;
  207909. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  207910. return blocksFree;
  207911. }
  207912. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  207913. bool performFakeBurnForTesting, int writeSpeed)
  207914. {
  207915. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  207916. pimpl->listener = listener;
  207917. pimpl->progress = 0;
  207918. pimpl->shouldCancel = false;
  207919. UINT_PTR cookie;
  207920. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  207921. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  207922. ejectDiscAfterwards);
  207923. String error;
  207924. if (hr != S_OK)
  207925. {
  207926. const char* e = "Couldn't open or write to the CD device";
  207927. if (hr == IMAPI_E_USERABORT)
  207928. e = "User cancelled the write operation";
  207929. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  207930. e = "No Disk present";
  207931. error = e;
  207932. }
  207933. pimpl->discMaster->ProgressUnadvise (cookie);
  207934. pimpl->listener = 0;
  207935. return error;
  207936. }
  207937. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  207938. {
  207939. if (audioSource == 0)
  207940. return false;
  207941. ScopedPointer<AudioSource> source (audioSource);
  207942. long bytesPerBlock;
  207943. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  207944. const int samplesPerBlock = bytesPerBlock / 4;
  207945. bool ok = true;
  207946. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  207947. HeapBlock <byte> buffer (bytesPerBlock);
  207948. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  207949. int samplesDone = 0;
  207950. source->prepareToPlay (samplesPerBlock, 44100.0);
  207951. while (ok)
  207952. {
  207953. {
  207954. AudioSourceChannelInfo info;
  207955. info.buffer = &sourceBuffer;
  207956. info.numSamples = samplesPerBlock;
  207957. info.startSample = 0;
  207958. sourceBuffer.clear();
  207959. source->getNextAudioBlock (info);
  207960. }
  207961. zeromem (buffer, bytesPerBlock);
  207962. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  207963. buffer, samplesPerBlock, 4);
  207964. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  207965. buffer + 2, samplesPerBlock, 4);
  207966. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  207967. if (FAILED (hr))
  207968. ok = false;
  207969. samplesDone += samplesPerBlock;
  207970. if (samplesDone >= numSamples)
  207971. break;
  207972. }
  207973. hr = pimpl->redbook->CloseAudioTrack();
  207974. return ok && hr == S_OK;
  207975. }
  207976. #endif
  207977. #endif
  207978. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  207979. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  207980. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207981. // compiled on its own).
  207982. #if JUCE_INCLUDED_FILE
  207983. using ::free;
  207984. namespace MidiConstants
  207985. {
  207986. static const int midiBufferSize = 1024 * 10;
  207987. static const int numInHeaders = 32;
  207988. static const int inBufferSize = 256;
  207989. }
  207990. class MidiInThread : public Thread
  207991. {
  207992. public:
  207993. MidiInThread (MidiInput* const input_,
  207994. MidiInputCallback* const callback_)
  207995. : Thread ("Juce Midi"),
  207996. hIn (0),
  207997. input (input_),
  207998. callback (callback_),
  207999. isStarted (false),
  208000. startTime (0),
  208001. pendingLength(0)
  208002. {
  208003. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208004. {
  208005. zeromem (&hdr[i], sizeof (MIDIHDR));
  208006. hdr[i].lpData = inData[i];
  208007. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  208008. }
  208009. };
  208010. ~MidiInThread()
  208011. {
  208012. stop();
  208013. if (hIn != 0)
  208014. {
  208015. int count = 5;
  208016. while (--count >= 0)
  208017. {
  208018. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  208019. break;
  208020. Sleep (20);
  208021. }
  208022. }
  208023. }
  208024. void handle (const uint32 message, const uint32 timeStamp)
  208025. {
  208026. const int byte = message & 0xff;
  208027. if (byte < 0x80)
  208028. return;
  208029. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  208030. const double time = timeStampToTime (timeStamp);
  208031. {
  208032. const ScopedLock sl (lock);
  208033. if (pendingLength < MidiConstants::midiBufferSize - 12)
  208034. {
  208035. char* const p = pending + pendingLength;
  208036. *(double*) p = time;
  208037. *(uint32*) (p + 8) = numBytes;
  208038. *(uint32*) (p + 12) = message;
  208039. pendingLength += 12 + numBytes;
  208040. }
  208041. else
  208042. {
  208043. jassertfalse // midi buffer overflow! You might need to increase the size..
  208044. }
  208045. }
  208046. notify();
  208047. }
  208048. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  208049. {
  208050. const int num = hdr->dwBytesRecorded;
  208051. if (num > 0)
  208052. {
  208053. const double time = timeStampToTime (timeStamp);
  208054. {
  208055. const ScopedLock sl (lock);
  208056. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  208057. {
  208058. char* const p = pending + pendingLength;
  208059. *(double*) p = time;
  208060. *(uint32*) (p + 8) = num;
  208061. memcpy (p + 12, hdr->lpData, num);
  208062. pendingLength += 12 + num;
  208063. }
  208064. else
  208065. {
  208066. jassertfalse // midi buffer overflow! You might need to increase the size..
  208067. }
  208068. }
  208069. notify();
  208070. }
  208071. }
  208072. void writeBlock (const int i)
  208073. {
  208074. hdr[i].dwBytesRecorded = 0;
  208075. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208076. jassert (res == MMSYSERR_NOERROR);
  208077. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  208078. jassert (res == MMSYSERR_NOERROR);
  208079. }
  208080. void run()
  208081. {
  208082. MemoryBlock pendingCopy (64);
  208083. while (! threadShouldExit())
  208084. {
  208085. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  208086. {
  208087. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208088. {
  208089. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208090. (void) res;
  208091. jassert (res == MMSYSERR_NOERROR);
  208092. writeBlock (i);
  208093. }
  208094. }
  208095. int len;
  208096. {
  208097. const ScopedLock sl (lock);
  208098. len = pendingLength;
  208099. if (len > 0)
  208100. {
  208101. pendingCopy.ensureSize (len);
  208102. pendingCopy.copyFrom (pending, 0, len);
  208103. pendingLength = 0;
  208104. }
  208105. }
  208106. //xxx needs to figure out if blocks are broken up or not
  208107. if (len == 0)
  208108. {
  208109. wait (500);
  208110. }
  208111. else
  208112. {
  208113. const char* p = (const char*) pendingCopy.getData();
  208114. while (len > 0)
  208115. {
  208116. const double time = *(const double*) p;
  208117. const int messageLen = *(const int*) (p + 8);
  208118. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  208119. callback->handleIncomingMidiMessage (input, message);
  208120. p += 12 + messageLen;
  208121. len -= 12 + messageLen;
  208122. }
  208123. }
  208124. }
  208125. }
  208126. void start()
  208127. {
  208128. jassert (hIn != 0);
  208129. if (hIn != 0 && ! isStarted)
  208130. {
  208131. stop();
  208132. activeMidiThreads.addIfNotAlreadyThere (this);
  208133. int i;
  208134. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  208135. writeBlock (i);
  208136. startTime = Time::getMillisecondCounter();
  208137. MMRESULT res = midiInStart (hIn);
  208138. jassert (res == MMSYSERR_NOERROR);
  208139. if (res == MMSYSERR_NOERROR)
  208140. {
  208141. isStarted = true;
  208142. pendingLength = 0;
  208143. startThread (6);
  208144. }
  208145. }
  208146. }
  208147. void stop()
  208148. {
  208149. if (isStarted)
  208150. {
  208151. stopThread (5000);
  208152. midiInReset (hIn);
  208153. midiInStop (hIn);
  208154. activeMidiThreads.removeValue (this);
  208155. { const ScopedLock sl (lock); }
  208156. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208157. {
  208158. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208159. {
  208160. int c = 10;
  208161. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  208162. Sleep (20);
  208163. jassert (c >= 0);
  208164. }
  208165. }
  208166. isStarted = false;
  208167. pendingLength = 0;
  208168. }
  208169. }
  208170. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  208171. {
  208172. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  208173. if (thread != 0 && activeMidiThreads.contains (thread))
  208174. {
  208175. if (uMsg == MIM_DATA)
  208176. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  208177. else if (uMsg == MIM_LONGDATA)
  208178. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  208179. }
  208180. }
  208181. juce_UseDebuggingNewOperator
  208182. HMIDIIN hIn;
  208183. private:
  208184. static Array <void*, CriticalSection> activeMidiThreads;
  208185. MidiInput* input;
  208186. MidiInputCallback* callback;
  208187. bool isStarted;
  208188. uint32 startTime;
  208189. CriticalSection lock;
  208190. MIDIHDR hdr [MidiConstants::numInHeaders];
  208191. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  208192. int pendingLength;
  208193. char pending [MidiConstants::midiBufferSize];
  208194. double timeStampToTime (uint32 timeStamp)
  208195. {
  208196. timeStamp += startTime;
  208197. const uint32 now = Time::getMillisecondCounter();
  208198. if (timeStamp > now)
  208199. {
  208200. if (timeStamp > now + 2)
  208201. --startTime;
  208202. timeStamp = now;
  208203. }
  208204. return 0.001 * timeStamp;
  208205. }
  208206. MidiInThread (const MidiInThread&);
  208207. MidiInThread& operator= (const MidiInThread&);
  208208. };
  208209. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  208210. const StringArray MidiInput::getDevices()
  208211. {
  208212. StringArray s;
  208213. const int num = midiInGetNumDevs();
  208214. for (int i = 0; i < num; ++i)
  208215. {
  208216. MIDIINCAPS mc;
  208217. zerostruct (mc);
  208218. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208219. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208220. }
  208221. return s;
  208222. }
  208223. int MidiInput::getDefaultDeviceIndex()
  208224. {
  208225. return 0;
  208226. }
  208227. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  208228. {
  208229. if (callback == 0)
  208230. return 0;
  208231. UINT deviceId = MIDI_MAPPER;
  208232. int n = 0;
  208233. String name;
  208234. const int num = midiInGetNumDevs();
  208235. for (int i = 0; i < num; ++i)
  208236. {
  208237. MIDIINCAPS mc;
  208238. zerostruct (mc);
  208239. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208240. {
  208241. if (index == n)
  208242. {
  208243. deviceId = i;
  208244. name = String (mc.szPname, sizeof (mc.szPname));
  208245. break;
  208246. }
  208247. ++n;
  208248. }
  208249. }
  208250. ScopedPointer <MidiInput> in (new MidiInput (name));
  208251. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  208252. HMIDIIN h;
  208253. HRESULT err = midiInOpen (&h, deviceId,
  208254. (DWORD_PTR) &MidiInThread::midiInCallback,
  208255. (DWORD_PTR) (MidiInThread*) thread,
  208256. CALLBACK_FUNCTION);
  208257. if (err == MMSYSERR_NOERROR)
  208258. {
  208259. thread->hIn = h;
  208260. in->internal = thread.release();
  208261. return in.release();
  208262. }
  208263. return 0;
  208264. }
  208265. MidiInput::MidiInput (const String& name_)
  208266. : name (name_),
  208267. internal (0)
  208268. {
  208269. }
  208270. MidiInput::~MidiInput()
  208271. {
  208272. delete static_cast <MidiInThread*> (internal);
  208273. }
  208274. void MidiInput::start()
  208275. {
  208276. static_cast <MidiInThread*> (internal)->start();
  208277. }
  208278. void MidiInput::stop()
  208279. {
  208280. static_cast <MidiInThread*> (internal)->stop();
  208281. }
  208282. struct MidiOutHandle
  208283. {
  208284. int refCount;
  208285. UINT deviceId;
  208286. HMIDIOUT handle;
  208287. static Array<MidiOutHandle*> activeHandles;
  208288. juce_UseDebuggingNewOperator
  208289. };
  208290. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  208291. const StringArray MidiOutput::getDevices()
  208292. {
  208293. StringArray s;
  208294. const int num = midiOutGetNumDevs();
  208295. for (int i = 0; i < num; ++i)
  208296. {
  208297. MIDIOUTCAPS mc;
  208298. zerostruct (mc);
  208299. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208300. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208301. }
  208302. return s;
  208303. }
  208304. int MidiOutput::getDefaultDeviceIndex()
  208305. {
  208306. const int num = midiOutGetNumDevs();
  208307. int n = 0;
  208308. for (int i = 0; i < num; ++i)
  208309. {
  208310. MIDIOUTCAPS mc;
  208311. zerostruct (mc);
  208312. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208313. {
  208314. if ((mc.wTechnology & MOD_MAPPER) != 0)
  208315. return n;
  208316. ++n;
  208317. }
  208318. }
  208319. return 0;
  208320. }
  208321. MidiOutput* MidiOutput::openDevice (int index)
  208322. {
  208323. UINT deviceId = MIDI_MAPPER;
  208324. const int num = midiOutGetNumDevs();
  208325. int i, n = 0;
  208326. for (i = 0; i < num; ++i)
  208327. {
  208328. MIDIOUTCAPS mc;
  208329. zerostruct (mc);
  208330. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208331. {
  208332. // use the microsoft sw synth as a default - best not to allow deviceId
  208333. // to be MIDI_MAPPER, or else device sharing breaks
  208334. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  208335. deviceId = i;
  208336. if (index == n)
  208337. {
  208338. deviceId = i;
  208339. break;
  208340. }
  208341. ++n;
  208342. }
  208343. }
  208344. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  208345. {
  208346. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  208347. if (han != 0 && han->deviceId == deviceId)
  208348. {
  208349. han->refCount++;
  208350. MidiOutput* const out = new MidiOutput();
  208351. out->internal = han;
  208352. return out;
  208353. }
  208354. }
  208355. for (i = 4; --i >= 0;)
  208356. {
  208357. HMIDIOUT h = 0;
  208358. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  208359. if (res == MMSYSERR_NOERROR)
  208360. {
  208361. MidiOutHandle* const han = new MidiOutHandle();
  208362. han->deviceId = deviceId;
  208363. han->refCount = 1;
  208364. han->handle = h;
  208365. MidiOutHandle::activeHandles.add (han);
  208366. MidiOutput* const out = new MidiOutput();
  208367. out->internal = han;
  208368. return out;
  208369. }
  208370. else if (res == MMSYSERR_ALLOCATED)
  208371. {
  208372. Sleep (100);
  208373. }
  208374. else
  208375. {
  208376. break;
  208377. }
  208378. }
  208379. return 0;
  208380. }
  208381. MidiOutput::~MidiOutput()
  208382. {
  208383. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  208384. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  208385. {
  208386. midiOutClose (h->handle);
  208387. MidiOutHandle::activeHandles.removeValue (h);
  208388. delete h;
  208389. }
  208390. }
  208391. void MidiOutput::reset()
  208392. {
  208393. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  208394. midiOutReset (h->handle);
  208395. }
  208396. bool MidiOutput::getVolume (float& leftVol,
  208397. float& rightVol)
  208398. {
  208399. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  208400. DWORD n;
  208401. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  208402. {
  208403. const unsigned short* const nn = (const unsigned short*) &n;
  208404. rightVol = nn[0] / (float) 0xffff;
  208405. leftVol = nn[1] / (float) 0xffff;
  208406. return true;
  208407. }
  208408. else
  208409. {
  208410. rightVol = leftVol = 1.0f;
  208411. return false;
  208412. }
  208413. }
  208414. void MidiOutput::setVolume (float leftVol,
  208415. float rightVol)
  208416. {
  208417. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  208418. DWORD n;
  208419. unsigned short* const nn = (unsigned short*) &n;
  208420. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  208421. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  208422. midiOutSetVolume (handle->handle, n);
  208423. }
  208424. void MidiOutput::sendMessageNow (const MidiMessage& message)
  208425. {
  208426. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  208427. if (message.getRawDataSize() > 3
  208428. || message.isSysEx())
  208429. {
  208430. MIDIHDR h;
  208431. zerostruct (h);
  208432. h.lpData = (char*) message.getRawData();
  208433. h.dwBufferLength = message.getRawDataSize();
  208434. h.dwBytesRecorded = message.getRawDataSize();
  208435. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  208436. {
  208437. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  208438. if (res == MMSYSERR_NOERROR)
  208439. {
  208440. while ((h.dwFlags & MHDR_DONE) == 0)
  208441. Sleep (1);
  208442. int count = 500; // 1 sec timeout
  208443. while (--count >= 0)
  208444. {
  208445. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  208446. if (res == MIDIERR_STILLPLAYING)
  208447. Sleep (2);
  208448. else
  208449. break;
  208450. }
  208451. }
  208452. }
  208453. }
  208454. else
  208455. {
  208456. midiOutShortMsg (handle->handle,
  208457. *(unsigned int*) message.getRawData());
  208458. }
  208459. }
  208460. #endif
  208461. /*** End of inlined file: juce_win32_Midi.cpp ***/
  208462. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  208463. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208464. // compiled on its own).
  208465. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  208466. #undef WINDOWS
  208467. // #define ASIO_DEBUGGING
  208468. #ifdef ASIO_DEBUGGING
  208469. #define log(a) { Logger::writeToLog (a); DBG (a) }
  208470. #else
  208471. #define log(a) {}
  208472. #endif
  208473. #ifdef ASIO_DEBUGGING
  208474. static void logError (const String& context, long error)
  208475. {
  208476. String err ("unknown error");
  208477. if (error == ASE_NotPresent)
  208478. err = "Not Present";
  208479. else if (error == ASE_HWMalfunction)
  208480. err = "Hardware Malfunction";
  208481. else if (error == ASE_InvalidParameter)
  208482. err = "Invalid Parameter";
  208483. else if (error == ASE_InvalidMode)
  208484. err = "Invalid Mode";
  208485. else if (error == ASE_SPNotAdvancing)
  208486. err = "Sample position not advancing";
  208487. else if (error == ASE_NoClock)
  208488. err = "No Clock";
  208489. else if (error == ASE_NoMemory)
  208490. err = "Out of memory";
  208491. log ("!!error: " + context + " - " + err);
  208492. }
  208493. #else
  208494. #define logError(a, b) {}
  208495. #endif
  208496. class ASIOAudioIODevice;
  208497. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  208498. static const int maxASIOChannels = 160;
  208499. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  208500. private Timer
  208501. {
  208502. public:
  208503. Component ourWindow;
  208504. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  208505. const String& optionalDllForDirectLoading_)
  208506. : AudioIODevice (name_, "ASIO"),
  208507. asioObject (0),
  208508. classId (classId_),
  208509. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  208510. currentBitDepth (16),
  208511. currentSampleRate (0),
  208512. isOpen_ (false),
  208513. isStarted (false),
  208514. postOutput (true),
  208515. insideControlPanelModalLoop (false),
  208516. shouldUsePreferredSize (false)
  208517. {
  208518. name = name_;
  208519. ourWindow.addToDesktop (0);
  208520. windowHandle = ourWindow.getWindowHandle();
  208521. jassert (currentASIODev [slotNumber] == 0);
  208522. currentASIODev [slotNumber] = this;
  208523. openDevice();
  208524. }
  208525. ~ASIOAudioIODevice()
  208526. {
  208527. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  208528. if (currentASIODev[i] == this)
  208529. currentASIODev[i] = 0;
  208530. close();
  208531. log ("ASIO - exiting");
  208532. removeCurrentDriver();
  208533. }
  208534. void updateSampleRates()
  208535. {
  208536. // find a list of sample rates..
  208537. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  208538. sampleRates.clear();
  208539. if (asioObject != 0)
  208540. {
  208541. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  208542. {
  208543. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  208544. if (err == 0)
  208545. {
  208546. sampleRates.add ((int) possibleSampleRates[index]);
  208547. log ("rate: " + String ((int) possibleSampleRates[index]));
  208548. }
  208549. else if (err != ASE_NoClock)
  208550. {
  208551. logError ("CanSampleRate", err);
  208552. }
  208553. }
  208554. if (sampleRates.size() == 0)
  208555. {
  208556. double cr = 0;
  208557. const long err = asioObject->getSampleRate (&cr);
  208558. log ("No sample rates supported - current rate: " + String ((int) cr));
  208559. if (err == 0)
  208560. sampleRates.add ((int) cr);
  208561. }
  208562. }
  208563. }
  208564. const StringArray getOutputChannelNames()
  208565. {
  208566. return outputChannelNames;
  208567. }
  208568. const StringArray getInputChannelNames()
  208569. {
  208570. return inputChannelNames;
  208571. }
  208572. int getNumSampleRates()
  208573. {
  208574. return sampleRates.size();
  208575. }
  208576. double getSampleRate (int index)
  208577. {
  208578. return sampleRates [index];
  208579. }
  208580. int getNumBufferSizesAvailable()
  208581. {
  208582. return bufferSizes.size();
  208583. }
  208584. int getBufferSizeSamples (int index)
  208585. {
  208586. return bufferSizes [index];
  208587. }
  208588. int getDefaultBufferSize()
  208589. {
  208590. return preferredSize;
  208591. }
  208592. const String open (const BigInteger& inputChannels,
  208593. const BigInteger& outputChannels,
  208594. double sr,
  208595. int bufferSizeSamples)
  208596. {
  208597. close();
  208598. currentCallback = 0;
  208599. if (bufferSizeSamples <= 0)
  208600. shouldUsePreferredSize = true;
  208601. if (asioObject == 0 || ! isASIOOpen)
  208602. {
  208603. log ("Warning: device not open");
  208604. const String err (openDevice());
  208605. if (asioObject == 0 || ! isASIOOpen)
  208606. return err;
  208607. }
  208608. isStarted = false;
  208609. bufferIndex = -1;
  208610. long err = 0;
  208611. long newPreferredSize = 0;
  208612. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  208613. minSize = 0;
  208614. maxSize = 0;
  208615. newPreferredSize = 0;
  208616. granularity = 0;
  208617. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  208618. {
  208619. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  208620. shouldUsePreferredSize = true;
  208621. preferredSize = newPreferredSize;
  208622. }
  208623. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  208624. // dynamic changes to the buffer size...
  208625. shouldUsePreferredSize = shouldUsePreferredSize
  208626. || getName().containsIgnoreCase ("Digidesign");
  208627. if (shouldUsePreferredSize)
  208628. {
  208629. log ("Using preferred size for buffer..");
  208630. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208631. {
  208632. bufferSizeSamples = preferredSize;
  208633. }
  208634. else
  208635. {
  208636. bufferSizeSamples = 1024;
  208637. logError ("GetBufferSize1", err);
  208638. }
  208639. shouldUsePreferredSize = false;
  208640. }
  208641. int sampleRate = roundDoubleToInt (sr);
  208642. currentSampleRate = sampleRate;
  208643. currentBlockSizeSamples = bufferSizeSamples;
  208644. currentChansOut.clear();
  208645. currentChansIn.clear();
  208646. zeromem (inBuffers, sizeof (inBuffers));
  208647. zeromem (outBuffers, sizeof (outBuffers));
  208648. updateSampleRates();
  208649. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  208650. sampleRate = sampleRates[0];
  208651. jassert (sampleRate != 0);
  208652. if (sampleRate == 0)
  208653. sampleRate = 44100;
  208654. long numSources = 32;
  208655. ASIOClockSource clocks[32];
  208656. zeromem (clocks, sizeof (clocks));
  208657. asioObject->getClockSources (clocks, &numSources);
  208658. bool isSourceSet = false;
  208659. // careful not to remove this loop because it does more than just logging!
  208660. int i;
  208661. for (i = 0; i < numSources; ++i)
  208662. {
  208663. String s ("clock: ");
  208664. s += clocks[i].name;
  208665. if (clocks[i].isCurrentSource)
  208666. {
  208667. isSourceSet = true;
  208668. s << " (cur)";
  208669. }
  208670. log (s);
  208671. }
  208672. if (numSources > 1 && ! isSourceSet)
  208673. {
  208674. log ("setting clock source");
  208675. asioObject->setClockSource (clocks[0].index);
  208676. Thread::sleep (20);
  208677. }
  208678. else
  208679. {
  208680. if (numSources == 0)
  208681. {
  208682. log ("ASIO - no clock sources!");
  208683. }
  208684. }
  208685. double cr = 0;
  208686. err = asioObject->getSampleRate (&cr);
  208687. if (err == 0)
  208688. {
  208689. currentSampleRate = cr;
  208690. }
  208691. else
  208692. {
  208693. logError ("GetSampleRate", err);
  208694. currentSampleRate = 0;
  208695. }
  208696. error = String::empty;
  208697. needToReset = false;
  208698. isReSync = false;
  208699. err = 0;
  208700. bool buffersCreated = false;
  208701. if (currentSampleRate != sampleRate)
  208702. {
  208703. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  208704. err = asioObject->setSampleRate (sampleRate);
  208705. if (err == ASE_NoClock && numSources > 0)
  208706. {
  208707. log ("trying to set a clock source..");
  208708. Thread::sleep (10);
  208709. err = asioObject->setClockSource (clocks[0].index);
  208710. if (err != 0)
  208711. {
  208712. logError ("SetClock", err);
  208713. }
  208714. Thread::sleep (10);
  208715. err = asioObject->setSampleRate (sampleRate);
  208716. }
  208717. }
  208718. if (err == 0)
  208719. {
  208720. currentSampleRate = sampleRate;
  208721. if (needToReset)
  208722. {
  208723. if (isReSync)
  208724. {
  208725. log ("Resync request");
  208726. }
  208727. log ("! Resetting ASIO after sample rate change");
  208728. removeCurrentDriver();
  208729. loadDriver();
  208730. const String error (initDriver());
  208731. if (error.isNotEmpty())
  208732. {
  208733. log ("ASIOInit: " + error);
  208734. }
  208735. needToReset = false;
  208736. isReSync = false;
  208737. }
  208738. numActiveInputChans = 0;
  208739. numActiveOutputChans = 0;
  208740. ASIOBufferInfo* info = bufferInfos;
  208741. int i;
  208742. for (i = 0; i < totalNumInputChans; ++i)
  208743. {
  208744. if (inputChannels[i])
  208745. {
  208746. currentChansIn.setBit (i);
  208747. info->isInput = 1;
  208748. info->channelNum = i;
  208749. info->buffers[0] = info->buffers[1] = 0;
  208750. ++info;
  208751. ++numActiveInputChans;
  208752. }
  208753. }
  208754. for (i = 0; i < totalNumOutputChans; ++i)
  208755. {
  208756. if (outputChannels[i])
  208757. {
  208758. currentChansOut.setBit (i);
  208759. info->isInput = 0;
  208760. info->channelNum = i;
  208761. info->buffers[0] = info->buffers[1] = 0;
  208762. ++info;
  208763. ++numActiveOutputChans;
  208764. }
  208765. }
  208766. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  208767. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208768. if (currentASIODev[0] == this)
  208769. {
  208770. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208771. callbacks.asioMessage = &asioMessagesCallback0;
  208772. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208773. }
  208774. else if (currentASIODev[1] == this)
  208775. {
  208776. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208777. callbacks.asioMessage = &asioMessagesCallback1;
  208778. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208779. }
  208780. else if (currentASIODev[2] == this)
  208781. {
  208782. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208783. callbacks.asioMessage = &asioMessagesCallback2;
  208784. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208785. }
  208786. else
  208787. {
  208788. jassertfalse
  208789. }
  208790. log ("disposing buffers");
  208791. err = asioObject->disposeBuffers();
  208792. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  208793. err = asioObject->createBuffers (bufferInfos,
  208794. totalBuffers,
  208795. currentBlockSizeSamples,
  208796. &callbacks);
  208797. if (err != 0)
  208798. {
  208799. currentBlockSizeSamples = preferredSize;
  208800. logError ("create buffers 2", err);
  208801. asioObject->disposeBuffers();
  208802. err = asioObject->createBuffers (bufferInfos,
  208803. totalBuffers,
  208804. currentBlockSizeSamples,
  208805. &callbacks);
  208806. }
  208807. if (err == 0)
  208808. {
  208809. buffersCreated = true;
  208810. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  208811. int n = 0;
  208812. Array <int> types;
  208813. currentBitDepth = 16;
  208814. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  208815. {
  208816. if (inputChannels[i])
  208817. {
  208818. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  208819. ASIOChannelInfo channelInfo;
  208820. zerostruct (channelInfo);
  208821. channelInfo.channel = i;
  208822. channelInfo.isInput = 1;
  208823. asioObject->getChannelInfo (&channelInfo);
  208824. types.addIfNotAlreadyThere (channelInfo.type);
  208825. typeToFormatParameters (channelInfo.type,
  208826. inputChannelBitDepths[n],
  208827. inputChannelBytesPerSample[n],
  208828. inputChannelIsFloat[n],
  208829. inputChannelLittleEndian[n]);
  208830. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  208831. ++n;
  208832. }
  208833. }
  208834. jassert (numActiveInputChans == n);
  208835. n = 0;
  208836. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  208837. {
  208838. if (outputChannels[i])
  208839. {
  208840. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  208841. ASIOChannelInfo channelInfo;
  208842. zerostruct (channelInfo);
  208843. channelInfo.channel = i;
  208844. channelInfo.isInput = 0;
  208845. asioObject->getChannelInfo (&channelInfo);
  208846. types.addIfNotAlreadyThere (channelInfo.type);
  208847. typeToFormatParameters (channelInfo.type,
  208848. outputChannelBitDepths[n],
  208849. outputChannelBytesPerSample[n],
  208850. outputChannelIsFloat[n],
  208851. outputChannelLittleEndian[n]);
  208852. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  208853. ++n;
  208854. }
  208855. }
  208856. jassert (numActiveOutputChans == n);
  208857. for (i = types.size(); --i >= 0;)
  208858. {
  208859. log ("channel format: " + String (types[i]));
  208860. }
  208861. jassert (n <= totalBuffers);
  208862. for (i = 0; i < numActiveOutputChans; ++i)
  208863. {
  208864. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  208865. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  208866. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  208867. {
  208868. log ("!! Null buffers");
  208869. }
  208870. else
  208871. {
  208872. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  208873. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  208874. }
  208875. }
  208876. inputLatency = outputLatency = 0;
  208877. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208878. {
  208879. log ("ASIO - no latencies");
  208880. }
  208881. else
  208882. {
  208883. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  208884. }
  208885. isOpen_ = true;
  208886. log ("starting ASIO");
  208887. calledback = false;
  208888. err = asioObject->start();
  208889. if (err != 0)
  208890. {
  208891. isOpen_ = false;
  208892. log ("ASIO - stop on failure");
  208893. Thread::sleep (10);
  208894. asioObject->stop();
  208895. error = "Can't start device";
  208896. Thread::sleep (10);
  208897. }
  208898. else
  208899. {
  208900. int count = 300;
  208901. while (--count > 0 && ! calledback)
  208902. Thread::sleep (10);
  208903. isStarted = true;
  208904. if (! calledback)
  208905. {
  208906. error = "Device didn't start correctly";
  208907. log ("ASIO didn't callback - stopping..");
  208908. asioObject->stop();
  208909. }
  208910. }
  208911. }
  208912. else
  208913. {
  208914. error = "Can't create i/o buffers";
  208915. }
  208916. }
  208917. else
  208918. {
  208919. error = "Can't set sample rate: ";
  208920. error << sampleRate;
  208921. }
  208922. if (error.isNotEmpty())
  208923. {
  208924. logError (error, err);
  208925. if (asioObject != 0 && buffersCreated)
  208926. asioObject->disposeBuffers();
  208927. Thread::sleep (20);
  208928. isStarted = false;
  208929. isOpen_ = false;
  208930. close();
  208931. }
  208932. needToReset = false;
  208933. isReSync = false;
  208934. return error;
  208935. }
  208936. void close()
  208937. {
  208938. error = String::empty;
  208939. stopTimer();
  208940. stop();
  208941. if (isASIOOpen && isOpen_)
  208942. {
  208943. const ScopedLock sl (callbackLock);
  208944. isOpen_ = false;
  208945. isStarted = false;
  208946. needToReset = false;
  208947. isReSync = false;
  208948. log ("ASIO - stopping");
  208949. if (asioObject != 0)
  208950. {
  208951. Thread::sleep (20);
  208952. asioObject->stop();
  208953. Thread::sleep (10);
  208954. asioObject->disposeBuffers();
  208955. }
  208956. Thread::sleep (10);
  208957. }
  208958. }
  208959. bool isOpen()
  208960. {
  208961. return isOpen_ || insideControlPanelModalLoop;
  208962. }
  208963. int getCurrentBufferSizeSamples()
  208964. {
  208965. return currentBlockSizeSamples;
  208966. }
  208967. double getCurrentSampleRate()
  208968. {
  208969. return currentSampleRate;
  208970. }
  208971. const BigInteger getActiveOutputChannels() const
  208972. {
  208973. return currentChansOut;
  208974. }
  208975. const BigInteger getActiveInputChannels() const
  208976. {
  208977. return currentChansIn;
  208978. }
  208979. int getCurrentBitDepth()
  208980. {
  208981. return currentBitDepth;
  208982. }
  208983. int getOutputLatencyInSamples()
  208984. {
  208985. return outputLatency + currentBlockSizeSamples / 4;
  208986. }
  208987. int getInputLatencyInSamples()
  208988. {
  208989. return inputLatency + currentBlockSizeSamples / 4;
  208990. }
  208991. void start (AudioIODeviceCallback* callback)
  208992. {
  208993. if (callback != 0)
  208994. {
  208995. callback->audioDeviceAboutToStart (this);
  208996. const ScopedLock sl (callbackLock);
  208997. currentCallback = callback;
  208998. }
  208999. }
  209000. void stop()
  209001. {
  209002. AudioIODeviceCallback* const lastCallback = currentCallback;
  209003. {
  209004. const ScopedLock sl (callbackLock);
  209005. currentCallback = 0;
  209006. }
  209007. if (lastCallback != 0)
  209008. lastCallback->audioDeviceStopped();
  209009. }
  209010. bool isPlaying()
  209011. {
  209012. return isASIOOpen && (currentCallback != 0);
  209013. }
  209014. const String getLastError()
  209015. {
  209016. return error;
  209017. }
  209018. bool hasControlPanel() const
  209019. {
  209020. return true;
  209021. }
  209022. bool showControlPanel()
  209023. {
  209024. log ("ASIO - showing control panel");
  209025. Component modalWindow (String::empty);
  209026. modalWindow.setOpaque (true);
  209027. modalWindow.addToDesktop (0);
  209028. modalWindow.enterModalState();
  209029. bool done = false;
  209030. JUCE_TRY
  209031. {
  209032. // are there are devices that need to be closed before showing their control panel?
  209033. // close();
  209034. insideControlPanelModalLoop = true;
  209035. const uint32 started = Time::getMillisecondCounter();
  209036. if (asioObject != 0)
  209037. {
  209038. asioObject->controlPanel();
  209039. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  209040. log ("spent: " + String (spent));
  209041. if (spent > 300)
  209042. {
  209043. shouldUsePreferredSize = true;
  209044. done = true;
  209045. }
  209046. }
  209047. }
  209048. JUCE_CATCH_ALL
  209049. insideControlPanelModalLoop = false;
  209050. return done;
  209051. }
  209052. void resetRequest() throw()
  209053. {
  209054. needToReset = true;
  209055. }
  209056. void resyncRequest() throw()
  209057. {
  209058. needToReset = true;
  209059. isReSync = true;
  209060. }
  209061. void timerCallback()
  209062. {
  209063. if (! insideControlPanelModalLoop)
  209064. {
  209065. stopTimer();
  209066. // used to cause a reset
  209067. log ("! ASIO restart request!");
  209068. if (isOpen_)
  209069. {
  209070. AudioIODeviceCallback* const oldCallback = currentCallback;
  209071. close();
  209072. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  209073. currentSampleRate, currentBlockSizeSamples);
  209074. if (oldCallback != 0)
  209075. start (oldCallback);
  209076. }
  209077. }
  209078. else
  209079. {
  209080. startTimer (100);
  209081. }
  209082. }
  209083. juce_UseDebuggingNewOperator
  209084. private:
  209085. IASIO* volatile asioObject;
  209086. ASIOCallbacks callbacks;
  209087. void* windowHandle;
  209088. CLSID classId;
  209089. const String optionalDllForDirectLoading;
  209090. String error;
  209091. long totalNumInputChans, totalNumOutputChans;
  209092. StringArray inputChannelNames, outputChannelNames;
  209093. Array<int> sampleRates, bufferSizes;
  209094. long inputLatency, outputLatency;
  209095. long minSize, maxSize, preferredSize, granularity;
  209096. int volatile currentBlockSizeSamples;
  209097. int volatile currentBitDepth;
  209098. double volatile currentSampleRate;
  209099. BigInteger currentChansOut, currentChansIn;
  209100. AudioIODeviceCallback* volatile currentCallback;
  209101. CriticalSection callbackLock;
  209102. ASIOBufferInfo bufferInfos [maxASIOChannels];
  209103. float* inBuffers [maxASIOChannels];
  209104. float* outBuffers [maxASIOChannels];
  209105. int inputChannelBitDepths [maxASIOChannels];
  209106. int outputChannelBitDepths [maxASIOChannels];
  209107. int inputChannelBytesPerSample [maxASIOChannels];
  209108. int outputChannelBytesPerSample [maxASIOChannels];
  209109. bool inputChannelIsFloat [maxASIOChannels];
  209110. bool outputChannelIsFloat [maxASIOChannels];
  209111. bool inputChannelLittleEndian [maxASIOChannels];
  209112. bool outputChannelLittleEndian [maxASIOChannels];
  209113. WaitableEvent event1;
  209114. HeapBlock <float> tempBuffer;
  209115. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  209116. bool isOpen_, isStarted;
  209117. bool volatile isASIOOpen;
  209118. bool volatile calledback;
  209119. bool volatile littleEndian, postOutput, needToReset, isReSync;
  209120. bool volatile insideControlPanelModalLoop;
  209121. bool volatile shouldUsePreferredSize;
  209122. void removeCurrentDriver()
  209123. {
  209124. if (asioObject != 0)
  209125. {
  209126. asioObject->Release();
  209127. asioObject = 0;
  209128. }
  209129. }
  209130. bool loadDriver()
  209131. {
  209132. removeCurrentDriver();
  209133. JUCE_TRY
  209134. {
  209135. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  209136. classId, (void**) &asioObject) == S_OK)
  209137. {
  209138. return true;
  209139. }
  209140. // If a class isn't registered but we have a path for it, we can fallback to
  209141. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  209142. if (optionalDllForDirectLoading.isNotEmpty())
  209143. {
  209144. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  209145. if (h != 0)
  209146. {
  209147. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  209148. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  209149. if (dllGetClassObject != 0)
  209150. {
  209151. IClassFactory* classFactory = 0;
  209152. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  209153. if (classFactory != 0)
  209154. {
  209155. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  209156. classFactory->Release();
  209157. }
  209158. return asioObject != 0;
  209159. }
  209160. }
  209161. }
  209162. }
  209163. JUCE_CATCH_ALL
  209164. asioObject = 0;
  209165. return false;
  209166. }
  209167. const String initDriver()
  209168. {
  209169. if (asioObject != 0)
  209170. {
  209171. char buffer [256];
  209172. zeromem (buffer, sizeof (buffer));
  209173. if (! asioObject->init (windowHandle))
  209174. {
  209175. asioObject->getErrorMessage (buffer);
  209176. return String (buffer, sizeof (buffer) - 1);
  209177. }
  209178. // just in case any daft drivers expect this to be called..
  209179. asioObject->getDriverName (buffer);
  209180. return String::empty;
  209181. }
  209182. return "No Driver";
  209183. }
  209184. const String openDevice()
  209185. {
  209186. // use this in case the driver starts opening dialog boxes..
  209187. Component modalWindow (String::empty);
  209188. modalWindow.setOpaque (true);
  209189. modalWindow.addToDesktop (0);
  209190. modalWindow.enterModalState();
  209191. // open the device and get its info..
  209192. log ("opening ASIO device: " + getName());
  209193. needToReset = false;
  209194. isReSync = false;
  209195. outputChannelNames.clear();
  209196. inputChannelNames.clear();
  209197. bufferSizes.clear();
  209198. sampleRates.clear();
  209199. isASIOOpen = false;
  209200. isOpen_ = false;
  209201. totalNumInputChans = 0;
  209202. totalNumOutputChans = 0;
  209203. numActiveInputChans = 0;
  209204. numActiveOutputChans = 0;
  209205. currentCallback = 0;
  209206. error = String::empty;
  209207. if (getName().isEmpty())
  209208. return error;
  209209. long err = 0;
  209210. if (loadDriver())
  209211. {
  209212. if ((error = initDriver()).isEmpty())
  209213. {
  209214. numActiveInputChans = 0;
  209215. numActiveOutputChans = 0;
  209216. totalNumInputChans = 0;
  209217. totalNumOutputChans = 0;
  209218. if (asioObject != 0
  209219. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  209220. {
  209221. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  209222. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  209223. {
  209224. // find a list of buffer sizes..
  209225. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  209226. if (granularity >= 0)
  209227. {
  209228. granularity = jmax (1, (int) granularity);
  209229. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  209230. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  209231. }
  209232. else if (granularity < 0)
  209233. {
  209234. for (int i = 0; i < 18; ++i)
  209235. {
  209236. const int s = (1 << i);
  209237. if (s >= minSize && s <= maxSize)
  209238. bufferSizes.add (s);
  209239. }
  209240. }
  209241. if (! bufferSizes.contains (preferredSize))
  209242. bufferSizes.insert (0, preferredSize);
  209243. double currentRate = 0;
  209244. asioObject->getSampleRate (&currentRate);
  209245. if (currentRate <= 0.0 || currentRate > 192001.0)
  209246. {
  209247. log ("setting sample rate");
  209248. err = asioObject->setSampleRate (44100.0);
  209249. if (err != 0)
  209250. {
  209251. logError ("setting sample rate", err);
  209252. }
  209253. asioObject->getSampleRate (&currentRate);
  209254. }
  209255. currentSampleRate = currentRate;
  209256. postOutput = (asioObject->outputReady() == 0);
  209257. if (postOutput)
  209258. {
  209259. log ("ASIO outputReady = ok");
  209260. }
  209261. updateSampleRates();
  209262. // ..because cubase does it at this point
  209263. inputLatency = outputLatency = 0;
  209264. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  209265. {
  209266. log ("ASIO - no latencies");
  209267. }
  209268. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  209269. // create some dummy buffers now.. because cubase does..
  209270. numActiveInputChans = 0;
  209271. numActiveOutputChans = 0;
  209272. ASIOBufferInfo* info = bufferInfos;
  209273. int i, numChans = 0;
  209274. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  209275. {
  209276. info->isInput = 1;
  209277. info->channelNum = i;
  209278. info->buffers[0] = info->buffers[1] = 0;
  209279. ++info;
  209280. ++numChans;
  209281. }
  209282. const int outputBufferIndex = numChans;
  209283. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  209284. {
  209285. info->isInput = 0;
  209286. info->channelNum = i;
  209287. info->buffers[0] = info->buffers[1] = 0;
  209288. ++info;
  209289. ++numChans;
  209290. }
  209291. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  209292. if (currentASIODev[0] == this)
  209293. {
  209294. callbacks.bufferSwitch = &bufferSwitchCallback0;
  209295. callbacks.asioMessage = &asioMessagesCallback0;
  209296. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  209297. }
  209298. else if (currentASIODev[1] == this)
  209299. {
  209300. callbacks.bufferSwitch = &bufferSwitchCallback1;
  209301. callbacks.asioMessage = &asioMessagesCallback1;
  209302. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  209303. }
  209304. else if (currentASIODev[2] == this)
  209305. {
  209306. callbacks.bufferSwitch = &bufferSwitchCallback2;
  209307. callbacks.asioMessage = &asioMessagesCallback2;
  209308. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  209309. }
  209310. else
  209311. {
  209312. jassertfalse
  209313. }
  209314. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  209315. if (preferredSize > 0)
  209316. {
  209317. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  209318. if (err != 0)
  209319. {
  209320. logError ("dummy buffers", err);
  209321. }
  209322. }
  209323. long newInps = 0, newOuts = 0;
  209324. asioObject->getChannels (&newInps, &newOuts);
  209325. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  209326. {
  209327. totalNumInputChans = newInps;
  209328. totalNumOutputChans = newOuts;
  209329. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  209330. }
  209331. updateSampleRates();
  209332. ASIOChannelInfo channelInfo;
  209333. channelInfo.type = 0;
  209334. for (i = 0; i < totalNumInputChans; ++i)
  209335. {
  209336. zerostruct (channelInfo);
  209337. channelInfo.channel = i;
  209338. channelInfo.isInput = 1;
  209339. asioObject->getChannelInfo (&channelInfo);
  209340. inputChannelNames.add (String (channelInfo.name));
  209341. }
  209342. for (i = 0; i < totalNumOutputChans; ++i)
  209343. {
  209344. zerostruct (channelInfo);
  209345. channelInfo.channel = i;
  209346. channelInfo.isInput = 0;
  209347. asioObject->getChannelInfo (&channelInfo);
  209348. outputChannelNames.add (String (channelInfo.name));
  209349. typeToFormatParameters (channelInfo.type,
  209350. outputChannelBitDepths[i],
  209351. outputChannelBytesPerSample[i],
  209352. outputChannelIsFloat[i],
  209353. outputChannelLittleEndian[i]);
  209354. if (i < 2)
  209355. {
  209356. // clear the channels that are used with the dummy stuff
  209357. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  209358. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  209359. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  209360. }
  209361. }
  209362. outputChannelNames.trim();
  209363. inputChannelNames.trim();
  209364. outputChannelNames.appendNumbersToDuplicates (false, true);
  209365. inputChannelNames.appendNumbersToDuplicates (false, true);
  209366. // start and stop because cubase does it..
  209367. asioObject->getLatencies (&inputLatency, &outputLatency);
  209368. if ((err = asioObject->start()) != 0)
  209369. {
  209370. // ignore an error here, as it might start later after setting other stuff up
  209371. logError ("ASIO start", err);
  209372. }
  209373. Thread::sleep (100);
  209374. asioObject->stop();
  209375. }
  209376. else
  209377. {
  209378. error = "Can't detect buffer sizes";
  209379. }
  209380. }
  209381. else
  209382. {
  209383. error = "Can't detect asio channels";
  209384. }
  209385. }
  209386. }
  209387. else
  209388. {
  209389. error = "No such device";
  209390. }
  209391. if (error.isNotEmpty())
  209392. {
  209393. logError (error, err);
  209394. if (asioObject != 0)
  209395. asioObject->disposeBuffers();
  209396. removeCurrentDriver();
  209397. isASIOOpen = false;
  209398. }
  209399. else
  209400. {
  209401. isASIOOpen = true;
  209402. log ("ASIO device open");
  209403. }
  209404. isOpen_ = false;
  209405. needToReset = false;
  209406. isReSync = false;
  209407. return error;
  209408. }
  209409. void callback (const long index)
  209410. {
  209411. if (isStarted)
  209412. {
  209413. bufferIndex = index;
  209414. processBuffer();
  209415. }
  209416. else
  209417. {
  209418. if (postOutput && (asioObject != 0))
  209419. asioObject->outputReady();
  209420. }
  209421. calledback = true;
  209422. }
  209423. void processBuffer()
  209424. {
  209425. const ASIOBufferInfo* const infos = bufferInfos;
  209426. const int bi = bufferIndex;
  209427. const ScopedLock sl (callbackLock);
  209428. if (needToReset)
  209429. {
  209430. needToReset = false;
  209431. if (isReSync)
  209432. {
  209433. log ("! ASIO resync");
  209434. isReSync = false;
  209435. }
  209436. else
  209437. {
  209438. startTimer (20);
  209439. }
  209440. }
  209441. if (bi >= 0)
  209442. {
  209443. const int samps = currentBlockSizeSamples;
  209444. if (currentCallback != 0)
  209445. {
  209446. int i;
  209447. for (i = 0; i < numActiveInputChans; ++i)
  209448. {
  209449. float* const dst = inBuffers[i];
  209450. jassert (dst != 0);
  209451. const char* const src = (const char*) (infos[i].buffers[bi]);
  209452. if (inputChannelIsFloat[i])
  209453. {
  209454. memcpy (dst, src, samps * sizeof (float));
  209455. }
  209456. else
  209457. {
  209458. jassert (dst == tempBuffer + (samps * i));
  209459. switch (inputChannelBitDepths[i])
  209460. {
  209461. case 16:
  209462. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  209463. samps, inputChannelLittleEndian[i]);
  209464. break;
  209465. case 24:
  209466. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  209467. samps, inputChannelLittleEndian[i]);
  209468. break;
  209469. case 32:
  209470. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  209471. samps, inputChannelLittleEndian[i]);
  209472. break;
  209473. case 64:
  209474. jassertfalse
  209475. break;
  209476. }
  209477. }
  209478. }
  209479. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  209480. numActiveInputChans,
  209481. outBuffers,
  209482. numActiveOutputChans,
  209483. samps);
  209484. for (i = 0; i < numActiveOutputChans; ++i)
  209485. {
  209486. float* const src = outBuffers[i];
  209487. jassert (src != 0);
  209488. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  209489. if (outputChannelIsFloat[i])
  209490. {
  209491. memcpy (dst, src, samps * sizeof (float));
  209492. }
  209493. else
  209494. {
  209495. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  209496. switch (outputChannelBitDepths[i])
  209497. {
  209498. case 16:
  209499. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  209500. samps, outputChannelLittleEndian[i]);
  209501. break;
  209502. case 24:
  209503. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  209504. samps, outputChannelLittleEndian[i]);
  209505. break;
  209506. case 32:
  209507. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  209508. samps, outputChannelLittleEndian[i]);
  209509. break;
  209510. case 64:
  209511. jassertfalse
  209512. break;
  209513. }
  209514. }
  209515. }
  209516. }
  209517. else
  209518. {
  209519. for (int i = 0; i < numActiveOutputChans; ++i)
  209520. {
  209521. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  209522. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  209523. }
  209524. }
  209525. }
  209526. if (postOutput)
  209527. asioObject->outputReady();
  209528. }
  209529. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  209530. {
  209531. if (currentASIODev[0] != 0)
  209532. currentASIODev[0]->callback (index);
  209533. return 0;
  209534. }
  209535. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  209536. {
  209537. if (currentASIODev[1] != 0)
  209538. currentASIODev[1]->callback (index);
  209539. return 0;
  209540. }
  209541. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  209542. {
  209543. if (currentASIODev[2] != 0)
  209544. currentASIODev[2]->callback (index);
  209545. return 0;
  209546. }
  209547. static void bufferSwitchCallback0 (long index, long)
  209548. {
  209549. if (currentASIODev[0] != 0)
  209550. currentASIODev[0]->callback (index);
  209551. }
  209552. static void bufferSwitchCallback1 (long index, long)
  209553. {
  209554. if (currentASIODev[1] != 0)
  209555. currentASIODev[1]->callback (index);
  209556. }
  209557. static void bufferSwitchCallback2 (long index, long)
  209558. {
  209559. if (currentASIODev[2] != 0)
  209560. currentASIODev[2]->callback (index);
  209561. }
  209562. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  209563. {
  209564. return asioMessagesCallback (selector, value, 0);
  209565. }
  209566. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  209567. {
  209568. return asioMessagesCallback (selector, value, 1);
  209569. }
  209570. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  209571. {
  209572. return asioMessagesCallback (selector, value, 2);
  209573. }
  209574. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  209575. {
  209576. switch (selector)
  209577. {
  209578. case kAsioSelectorSupported:
  209579. if (value == kAsioResetRequest
  209580. || value == kAsioEngineVersion
  209581. || value == kAsioResyncRequest
  209582. || value == kAsioLatenciesChanged
  209583. || value == kAsioSupportsInputMonitor)
  209584. return 1;
  209585. break;
  209586. case kAsioBufferSizeChange:
  209587. break;
  209588. case kAsioResetRequest:
  209589. if (currentASIODev[deviceIndex] != 0)
  209590. currentASIODev[deviceIndex]->resetRequest();
  209591. return 1;
  209592. case kAsioResyncRequest:
  209593. if (currentASIODev[deviceIndex] != 0)
  209594. currentASIODev[deviceIndex]->resyncRequest();
  209595. return 1;
  209596. case kAsioLatenciesChanged:
  209597. return 1;
  209598. case kAsioEngineVersion:
  209599. return 2;
  209600. case kAsioSupportsTimeInfo:
  209601. case kAsioSupportsTimeCode:
  209602. return 0;
  209603. }
  209604. return 0;
  209605. }
  209606. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  209607. {
  209608. }
  209609. static void convertInt16ToFloat (const char* src,
  209610. float* dest,
  209611. const int srcStrideBytes,
  209612. int numSamples,
  209613. const bool littleEndian) throw()
  209614. {
  209615. const double g = 1.0 / 32768.0;
  209616. if (littleEndian)
  209617. {
  209618. while (--numSamples >= 0)
  209619. {
  209620. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  209621. src += srcStrideBytes;
  209622. }
  209623. }
  209624. else
  209625. {
  209626. while (--numSamples >= 0)
  209627. {
  209628. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  209629. src += srcStrideBytes;
  209630. }
  209631. }
  209632. }
  209633. static void convertFloatToInt16 (const float* src,
  209634. char* dest,
  209635. const int dstStrideBytes,
  209636. int numSamples,
  209637. const bool littleEndian) throw()
  209638. {
  209639. const double maxVal = (double) 0x7fff;
  209640. if (littleEndian)
  209641. {
  209642. while (--numSamples >= 0)
  209643. {
  209644. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209645. dest += dstStrideBytes;
  209646. }
  209647. }
  209648. else
  209649. {
  209650. while (--numSamples >= 0)
  209651. {
  209652. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209653. dest += dstStrideBytes;
  209654. }
  209655. }
  209656. }
  209657. static void convertInt24ToFloat (const char* src,
  209658. float* dest,
  209659. const int srcStrideBytes,
  209660. int numSamples,
  209661. const bool littleEndian) throw()
  209662. {
  209663. const double g = 1.0 / 0x7fffff;
  209664. if (littleEndian)
  209665. {
  209666. while (--numSamples >= 0)
  209667. {
  209668. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  209669. src += srcStrideBytes;
  209670. }
  209671. }
  209672. else
  209673. {
  209674. while (--numSamples >= 0)
  209675. {
  209676. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  209677. src += srcStrideBytes;
  209678. }
  209679. }
  209680. }
  209681. static void convertFloatToInt24 (const float* src,
  209682. char* dest,
  209683. const int dstStrideBytes,
  209684. int numSamples,
  209685. const bool littleEndian) throw()
  209686. {
  209687. const double maxVal = (double) 0x7fffff;
  209688. if (littleEndian)
  209689. {
  209690. while (--numSamples >= 0)
  209691. {
  209692. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209693. dest += dstStrideBytes;
  209694. }
  209695. }
  209696. else
  209697. {
  209698. while (--numSamples >= 0)
  209699. {
  209700. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209701. dest += dstStrideBytes;
  209702. }
  209703. }
  209704. }
  209705. static void convertInt32ToFloat (const char* src,
  209706. float* dest,
  209707. const int srcStrideBytes,
  209708. int numSamples,
  209709. const bool littleEndian) throw()
  209710. {
  209711. const double g = 1.0 / 0x7fffffff;
  209712. if (littleEndian)
  209713. {
  209714. while (--numSamples >= 0)
  209715. {
  209716. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  209717. src += srcStrideBytes;
  209718. }
  209719. }
  209720. else
  209721. {
  209722. while (--numSamples >= 0)
  209723. {
  209724. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  209725. src += srcStrideBytes;
  209726. }
  209727. }
  209728. }
  209729. static void convertFloatToInt32 (const float* src,
  209730. char* dest,
  209731. const int dstStrideBytes,
  209732. int numSamples,
  209733. const bool littleEndian) throw()
  209734. {
  209735. const double maxVal = (double) 0x7fffffff;
  209736. if (littleEndian)
  209737. {
  209738. while (--numSamples >= 0)
  209739. {
  209740. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209741. dest += dstStrideBytes;
  209742. }
  209743. }
  209744. else
  209745. {
  209746. while (--numSamples >= 0)
  209747. {
  209748. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209749. dest += dstStrideBytes;
  209750. }
  209751. }
  209752. }
  209753. static void typeToFormatParameters (const long type,
  209754. int& bitDepth,
  209755. int& byteStride,
  209756. bool& formatIsFloat,
  209757. bool& littleEndian) throw()
  209758. {
  209759. bitDepth = 0;
  209760. littleEndian = false;
  209761. formatIsFloat = false;
  209762. switch (type)
  209763. {
  209764. case ASIOSTInt16MSB:
  209765. case ASIOSTInt16LSB:
  209766. case ASIOSTInt32MSB16:
  209767. case ASIOSTInt32LSB16:
  209768. bitDepth = 16; break;
  209769. case ASIOSTFloat32MSB:
  209770. case ASIOSTFloat32LSB:
  209771. formatIsFloat = true;
  209772. bitDepth = 32; break;
  209773. case ASIOSTInt32MSB:
  209774. case ASIOSTInt32LSB:
  209775. bitDepth = 32; break;
  209776. case ASIOSTInt24MSB:
  209777. case ASIOSTInt24LSB:
  209778. case ASIOSTInt32MSB24:
  209779. case ASIOSTInt32LSB24:
  209780. case ASIOSTInt32MSB18:
  209781. case ASIOSTInt32MSB20:
  209782. case ASIOSTInt32LSB18:
  209783. case ASIOSTInt32LSB20:
  209784. bitDepth = 24; break;
  209785. case ASIOSTFloat64MSB:
  209786. case ASIOSTFloat64LSB:
  209787. default:
  209788. bitDepth = 64;
  209789. break;
  209790. }
  209791. switch (type)
  209792. {
  209793. case ASIOSTInt16MSB:
  209794. case ASIOSTInt32MSB16:
  209795. case ASIOSTFloat32MSB:
  209796. case ASIOSTFloat64MSB:
  209797. case ASIOSTInt32MSB:
  209798. case ASIOSTInt32MSB18:
  209799. case ASIOSTInt32MSB20:
  209800. case ASIOSTInt32MSB24:
  209801. case ASIOSTInt24MSB:
  209802. littleEndian = false; break;
  209803. case ASIOSTInt16LSB:
  209804. case ASIOSTInt32LSB16:
  209805. case ASIOSTFloat32LSB:
  209806. case ASIOSTFloat64LSB:
  209807. case ASIOSTInt32LSB:
  209808. case ASIOSTInt32LSB18:
  209809. case ASIOSTInt32LSB20:
  209810. case ASIOSTInt32LSB24:
  209811. case ASIOSTInt24LSB:
  209812. littleEndian = true; break;
  209813. default:
  209814. break;
  209815. }
  209816. switch (type)
  209817. {
  209818. case ASIOSTInt16LSB:
  209819. case ASIOSTInt16MSB:
  209820. byteStride = 2; break;
  209821. case ASIOSTInt24LSB:
  209822. case ASIOSTInt24MSB:
  209823. byteStride = 3; break;
  209824. case ASIOSTInt32MSB16:
  209825. case ASIOSTInt32LSB16:
  209826. case ASIOSTInt32MSB:
  209827. case ASIOSTInt32MSB18:
  209828. case ASIOSTInt32MSB20:
  209829. case ASIOSTInt32MSB24:
  209830. case ASIOSTInt32LSB:
  209831. case ASIOSTInt32LSB18:
  209832. case ASIOSTInt32LSB20:
  209833. case ASIOSTInt32LSB24:
  209834. case ASIOSTFloat32LSB:
  209835. case ASIOSTFloat32MSB:
  209836. byteStride = 4; break;
  209837. case ASIOSTFloat64MSB:
  209838. case ASIOSTFloat64LSB:
  209839. byteStride = 8; break;
  209840. default:
  209841. break;
  209842. }
  209843. }
  209844. };
  209845. class ASIOAudioIODeviceType : public AudioIODeviceType
  209846. {
  209847. public:
  209848. ASIOAudioIODeviceType()
  209849. : AudioIODeviceType ("ASIO"),
  209850. hasScanned (false)
  209851. {
  209852. CoInitialize (0);
  209853. }
  209854. ~ASIOAudioIODeviceType()
  209855. {
  209856. }
  209857. void scanForDevices()
  209858. {
  209859. hasScanned = true;
  209860. deviceNames.clear();
  209861. classIds.clear();
  209862. HKEY hk = 0;
  209863. int index = 0;
  209864. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  209865. {
  209866. for (;;)
  209867. {
  209868. char name [256];
  209869. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  209870. {
  209871. addDriverInfo (name, hk);
  209872. }
  209873. else
  209874. {
  209875. break;
  209876. }
  209877. }
  209878. RegCloseKey (hk);
  209879. }
  209880. }
  209881. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  209882. {
  209883. jassert (hasScanned); // need to call scanForDevices() before doing this
  209884. return deviceNames;
  209885. }
  209886. int getDefaultDeviceIndex (bool) const
  209887. {
  209888. jassert (hasScanned); // need to call scanForDevices() before doing this
  209889. for (int i = deviceNames.size(); --i >= 0;)
  209890. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  209891. return i; // asio4all is a safe choice for a default..
  209892. #if JUCE_DEBUG
  209893. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  209894. return 1; // (the digi m-box driver crashes the app when you run
  209895. // it in the debugger, which can be a bit annoying)
  209896. #endif
  209897. return 0;
  209898. }
  209899. static int findFreeSlot()
  209900. {
  209901. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209902. if (currentASIODev[i] == 0)
  209903. return i;
  209904. jassertfalse; // unfortunately you can only have a finite number
  209905. // of ASIO devices open at the same time..
  209906. return -1;
  209907. }
  209908. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  209909. {
  209910. jassert (hasScanned); // need to call scanForDevices() before doing this
  209911. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  209912. }
  209913. bool hasSeparateInputsAndOutputs() const { return false; }
  209914. AudioIODevice* createDevice (const String& outputDeviceName,
  209915. const String& inputDeviceName)
  209916. {
  209917. // ASIO can't open two different devices for input and output - they must be the same one.
  209918. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  209919. jassert (hasScanned); // need to call scanForDevices() before doing this
  209920. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  209921. : inputDeviceName);
  209922. if (index >= 0)
  209923. {
  209924. const int freeSlot = findFreeSlot();
  209925. if (freeSlot >= 0)
  209926. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  209927. }
  209928. return 0;
  209929. }
  209930. juce_UseDebuggingNewOperator
  209931. private:
  209932. StringArray deviceNames;
  209933. OwnedArray <CLSID> classIds;
  209934. bool hasScanned;
  209935. static bool checkClassIsOk (const String& classId)
  209936. {
  209937. HKEY hk = 0;
  209938. bool ok = false;
  209939. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  209940. {
  209941. int index = 0;
  209942. for (;;)
  209943. {
  209944. WCHAR buf [512];
  209945. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  209946. {
  209947. if (classId.equalsIgnoreCase (buf))
  209948. {
  209949. HKEY subKey, pathKey;
  209950. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209951. {
  209952. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  209953. {
  209954. WCHAR pathName [1024];
  209955. DWORD dtype = REG_SZ;
  209956. DWORD dsize = sizeof (pathName);
  209957. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  209958. ok = File (pathName).exists();
  209959. RegCloseKey (pathKey);
  209960. }
  209961. RegCloseKey (subKey);
  209962. }
  209963. break;
  209964. }
  209965. }
  209966. else
  209967. {
  209968. break;
  209969. }
  209970. }
  209971. RegCloseKey (hk);
  209972. }
  209973. return ok;
  209974. }
  209975. void addDriverInfo (const String& keyName, HKEY hk)
  209976. {
  209977. HKEY subKey;
  209978. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209979. {
  209980. WCHAR buf [256];
  209981. zerostruct (buf);
  209982. DWORD dtype = REG_SZ;
  209983. DWORD dsize = sizeof (buf);
  209984. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209985. {
  209986. if (dsize > 0 && checkClassIsOk (buf))
  209987. {
  209988. CLSID classId;
  209989. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  209990. {
  209991. dtype = REG_SZ;
  209992. dsize = sizeof (buf);
  209993. String deviceName;
  209994. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209995. deviceName = buf;
  209996. else
  209997. deviceName = keyName;
  209998. log ("found " + deviceName);
  209999. deviceNames.add (deviceName);
  210000. classIds.add (new CLSID (classId));
  210001. }
  210002. }
  210003. RegCloseKey (subKey);
  210004. }
  210005. }
  210006. }
  210007. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  210008. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  210009. };
  210010. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  210011. {
  210012. return new ASIOAudioIODeviceType();
  210013. }
  210014. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  210015. void* guid,
  210016. const String& optionalDllForDirectLoading)
  210017. {
  210018. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  210019. if (freeSlot < 0)
  210020. return 0;
  210021. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  210022. }
  210023. #undef log
  210024. #endif
  210025. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  210026. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  210027. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210028. // compiled on its own).
  210029. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  210030. END_JUCE_NAMESPACE
  210031. extern "C"
  210032. {
  210033. // Declare just the minimum number of interfaces for the DSound objects that we need..
  210034. typedef struct typeDSBUFFERDESC
  210035. {
  210036. DWORD dwSize;
  210037. DWORD dwFlags;
  210038. DWORD dwBufferBytes;
  210039. DWORD dwReserved;
  210040. LPWAVEFORMATEX lpwfxFormat;
  210041. GUID guid3DAlgorithm;
  210042. } DSBUFFERDESC;
  210043. struct IDirectSoundBuffer;
  210044. #undef INTERFACE
  210045. #define INTERFACE IDirectSound
  210046. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  210047. {
  210048. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210049. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210050. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210051. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  210052. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210053. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  210054. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  210055. STDMETHOD(Compact) (THIS) PURE;
  210056. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  210057. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  210058. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210059. };
  210060. #undef INTERFACE
  210061. #define INTERFACE IDirectSoundBuffer
  210062. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  210063. {
  210064. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210065. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210066. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210067. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210068. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210069. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210070. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  210071. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  210072. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  210073. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210074. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  210075. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210076. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  210077. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  210078. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  210079. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  210080. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  210081. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  210082. STDMETHOD(Stop) (THIS) PURE;
  210083. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210084. STDMETHOD(Restore) (THIS) PURE;
  210085. };
  210086. typedef struct typeDSCBUFFERDESC
  210087. {
  210088. DWORD dwSize;
  210089. DWORD dwFlags;
  210090. DWORD dwBufferBytes;
  210091. DWORD dwReserved;
  210092. LPWAVEFORMATEX lpwfxFormat;
  210093. } DSCBUFFERDESC;
  210094. struct IDirectSoundCaptureBuffer;
  210095. #undef INTERFACE
  210096. #define INTERFACE IDirectSoundCapture
  210097. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  210098. {
  210099. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210100. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210101. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210102. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  210103. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210104. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210105. };
  210106. #undef INTERFACE
  210107. #define INTERFACE IDirectSoundCaptureBuffer
  210108. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  210109. {
  210110. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210111. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210112. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210113. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210114. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210115. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210116. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210117. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  210118. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210119. STDMETHOD(Start) (THIS_ DWORD) PURE;
  210120. STDMETHOD(Stop) (THIS) PURE;
  210121. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210122. };
  210123. };
  210124. BEGIN_JUCE_NAMESPACE
  210125. static const String getDSErrorMessage (HRESULT hr)
  210126. {
  210127. const char* result = 0;
  210128. switch (hr)
  210129. {
  210130. case MAKE_HRESULT(1, 0x878, 10):
  210131. result = "Device already allocated";
  210132. break;
  210133. case MAKE_HRESULT(1, 0x878, 30):
  210134. result = "Control unavailable";
  210135. break;
  210136. case E_INVALIDARG:
  210137. result = "Invalid parameter";
  210138. break;
  210139. case MAKE_HRESULT(1, 0x878, 50):
  210140. result = "Invalid call";
  210141. break;
  210142. case E_FAIL:
  210143. result = "Generic error";
  210144. break;
  210145. case MAKE_HRESULT(1, 0x878, 70):
  210146. result = "Priority level error";
  210147. break;
  210148. case E_OUTOFMEMORY:
  210149. result = "Out of memory";
  210150. break;
  210151. case MAKE_HRESULT(1, 0x878, 100):
  210152. result = "Bad format";
  210153. break;
  210154. case E_NOTIMPL:
  210155. result = "Unsupported function";
  210156. break;
  210157. case MAKE_HRESULT(1, 0x878, 120):
  210158. result = "No driver";
  210159. break;
  210160. case MAKE_HRESULT(1, 0x878, 130):
  210161. result = "Already initialised";
  210162. break;
  210163. case CLASS_E_NOAGGREGATION:
  210164. result = "No aggregation";
  210165. break;
  210166. case MAKE_HRESULT(1, 0x878, 150):
  210167. result = "Buffer lost";
  210168. break;
  210169. case MAKE_HRESULT(1, 0x878, 160):
  210170. result = "Another app has priority";
  210171. break;
  210172. case MAKE_HRESULT(1, 0x878, 170):
  210173. result = "Uninitialised";
  210174. break;
  210175. case E_NOINTERFACE:
  210176. result = "No interface";
  210177. break;
  210178. case S_OK:
  210179. result = "No error";
  210180. break;
  210181. default:
  210182. return "Unknown error: " + String ((int) hr);
  210183. }
  210184. return result;
  210185. }
  210186. #define DS_DEBUGGING 1
  210187. #ifdef DS_DEBUGGING
  210188. #define CATCH JUCE_CATCH_EXCEPTION
  210189. #undef log
  210190. #define log(a) Logger::writeToLog(a);
  210191. #undef logError
  210192. #define logError(a) logDSError(a, __LINE__);
  210193. static void logDSError (HRESULT hr, int lineNum)
  210194. {
  210195. if (hr != S_OK)
  210196. {
  210197. String error ("DS error at line ");
  210198. error << lineNum << " - " << getDSErrorMessage (hr);
  210199. log (error);
  210200. }
  210201. }
  210202. #else
  210203. #define CATCH JUCE_CATCH_ALL
  210204. #define log(a)
  210205. #define logError(a)
  210206. #endif
  210207. #define DSOUND_FUNCTION(functionName, params) \
  210208. typedef HRESULT (WINAPI *type##functionName) params; \
  210209. static type##functionName ds##functionName = 0;
  210210. #define DSOUND_FUNCTION_LOAD(functionName) \
  210211. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  210212. jassert (ds##functionName != 0);
  210213. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  210214. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  210215. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  210216. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  210217. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210218. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210219. static void initialiseDSoundFunctions()
  210220. {
  210221. if (dsDirectSoundCreate == 0)
  210222. {
  210223. HMODULE h = LoadLibraryA ("dsound.dll");
  210224. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  210225. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  210226. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  210227. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  210228. }
  210229. }
  210230. class DSoundInternalOutChannel
  210231. {
  210232. String name;
  210233. LPGUID guid;
  210234. int sampleRate, bufferSizeSamples;
  210235. float* leftBuffer;
  210236. float* rightBuffer;
  210237. IDirectSound* pDirectSound;
  210238. IDirectSoundBuffer* pOutputBuffer;
  210239. DWORD writeOffset;
  210240. int totalBytesPerBuffer;
  210241. int bytesPerBuffer;
  210242. unsigned int lastPlayCursor;
  210243. public:
  210244. int bitDepth;
  210245. bool doneFlag;
  210246. DSoundInternalOutChannel (const String& name_,
  210247. LPGUID guid_,
  210248. int rate,
  210249. int bufferSize,
  210250. float* left,
  210251. float* right)
  210252. : name (name_),
  210253. guid (guid_),
  210254. sampleRate (rate),
  210255. bufferSizeSamples (bufferSize),
  210256. leftBuffer (left),
  210257. rightBuffer (right),
  210258. pDirectSound (0),
  210259. pOutputBuffer (0),
  210260. bitDepth (16)
  210261. {
  210262. }
  210263. ~DSoundInternalOutChannel()
  210264. {
  210265. close();
  210266. }
  210267. void close()
  210268. {
  210269. HRESULT hr;
  210270. if (pOutputBuffer != 0)
  210271. {
  210272. JUCE_TRY
  210273. {
  210274. log ("closing dsound out: " + name);
  210275. hr = pOutputBuffer->Stop();
  210276. logError (hr);
  210277. }
  210278. CATCH
  210279. JUCE_TRY
  210280. {
  210281. hr = pOutputBuffer->Release();
  210282. logError (hr);
  210283. }
  210284. CATCH
  210285. pOutputBuffer = 0;
  210286. }
  210287. if (pDirectSound != 0)
  210288. {
  210289. JUCE_TRY
  210290. {
  210291. hr = pDirectSound->Release();
  210292. logError (hr);
  210293. }
  210294. CATCH
  210295. pDirectSound = 0;
  210296. }
  210297. }
  210298. const String open()
  210299. {
  210300. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  210301. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  210302. pDirectSound = 0;
  210303. pOutputBuffer = 0;
  210304. writeOffset = 0;
  210305. String error;
  210306. HRESULT hr = E_NOINTERFACE;
  210307. if (dsDirectSoundCreate != 0)
  210308. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  210309. if (hr == S_OK)
  210310. {
  210311. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210312. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210313. const int numChannels = 2;
  210314. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  210315. logError (hr);
  210316. if (hr == S_OK)
  210317. {
  210318. IDirectSoundBuffer* pPrimaryBuffer;
  210319. DSBUFFERDESC primaryDesc;
  210320. zerostruct (primaryDesc);
  210321. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210322. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  210323. primaryDesc.dwBufferBytes = 0;
  210324. primaryDesc.lpwfxFormat = 0;
  210325. log ("opening dsound out step 2");
  210326. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  210327. logError (hr);
  210328. if (hr == S_OK)
  210329. {
  210330. WAVEFORMATEX wfFormat;
  210331. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210332. wfFormat.nChannels = (unsigned short) numChannels;
  210333. wfFormat.nSamplesPerSec = sampleRate;
  210334. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  210335. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  210336. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210337. wfFormat.cbSize = 0;
  210338. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  210339. logError (hr);
  210340. if (hr == S_OK)
  210341. {
  210342. DSBUFFERDESC secondaryDesc;
  210343. zerostruct (secondaryDesc);
  210344. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210345. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  210346. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  210347. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  210348. secondaryDesc.lpwfxFormat = &wfFormat;
  210349. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  210350. logError (hr);
  210351. if (hr == S_OK)
  210352. {
  210353. log ("opening dsound out step 3");
  210354. DWORD dwDataLen;
  210355. unsigned char* pDSBuffData;
  210356. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  210357. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  210358. logError (hr);
  210359. if (hr == S_OK)
  210360. {
  210361. zeromem (pDSBuffData, dwDataLen);
  210362. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  210363. if (hr == S_OK)
  210364. {
  210365. hr = pOutputBuffer->SetCurrentPosition (0);
  210366. if (hr == S_OK)
  210367. {
  210368. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  210369. if (hr == S_OK)
  210370. return String::empty;
  210371. }
  210372. }
  210373. }
  210374. }
  210375. }
  210376. }
  210377. }
  210378. }
  210379. error = getDSErrorMessage (hr);
  210380. close();
  210381. return error;
  210382. }
  210383. void synchronisePosition()
  210384. {
  210385. if (pOutputBuffer != 0)
  210386. {
  210387. DWORD playCursor;
  210388. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  210389. }
  210390. }
  210391. bool service()
  210392. {
  210393. if (pOutputBuffer == 0)
  210394. return true;
  210395. DWORD playCursor, writeCursor;
  210396. for (;;)
  210397. {
  210398. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  210399. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210400. {
  210401. pOutputBuffer->Restore();
  210402. continue;
  210403. }
  210404. if (hr == S_OK)
  210405. break;
  210406. logError (hr);
  210407. jassertfalse
  210408. return true;
  210409. }
  210410. int playWriteGap = writeCursor - playCursor;
  210411. if (playWriteGap < 0)
  210412. playWriteGap += totalBytesPerBuffer;
  210413. int bytesEmpty = playCursor - writeOffset;
  210414. if (bytesEmpty < 0)
  210415. bytesEmpty += totalBytesPerBuffer;
  210416. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  210417. {
  210418. writeOffset = writeCursor;
  210419. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  210420. }
  210421. if (bytesEmpty >= bytesPerBuffer)
  210422. {
  210423. LPBYTE lpbuf1 = 0;
  210424. LPBYTE lpbuf2 = 0;
  210425. DWORD dwSize1 = 0;
  210426. DWORD dwSize2 = 0;
  210427. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  210428. bytesPerBuffer,
  210429. (void**) &lpbuf1, &dwSize1,
  210430. (void**) &lpbuf2, &dwSize2, 0);
  210431. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210432. {
  210433. pOutputBuffer->Restore();
  210434. hr = pOutputBuffer->Lock (writeOffset,
  210435. bytesPerBuffer,
  210436. (void**) &lpbuf1, &dwSize1,
  210437. (void**) &lpbuf2, &dwSize2, 0);
  210438. }
  210439. if (hr == S_OK)
  210440. {
  210441. if (bitDepth == 16)
  210442. {
  210443. const float gainL = 32767.0f;
  210444. const float gainR = 32767.0f;
  210445. int* dest = (int*)lpbuf1;
  210446. const float* left = leftBuffer;
  210447. const float* right = rightBuffer;
  210448. int samples1 = dwSize1 >> 2;
  210449. int samples2 = dwSize2 >> 2;
  210450. if (left == 0)
  210451. {
  210452. while (--samples1 >= 0)
  210453. {
  210454. int r = roundToInt (gainR * *right++);
  210455. if (r < -32768)
  210456. r = -32768;
  210457. else if (r > 32767)
  210458. r = 32767;
  210459. *dest++ = (r << 16);
  210460. }
  210461. dest = (int*)lpbuf2;
  210462. while (--samples2 >= 0)
  210463. {
  210464. int r = roundToInt (gainR * *right++);
  210465. if (r < -32768)
  210466. r = -32768;
  210467. else if (r > 32767)
  210468. r = 32767;
  210469. *dest++ = (r << 16);
  210470. }
  210471. }
  210472. else if (right == 0)
  210473. {
  210474. while (--samples1 >= 0)
  210475. {
  210476. int l = roundToInt (gainL * *left++);
  210477. if (l < -32768)
  210478. l = -32768;
  210479. else if (l > 32767)
  210480. l = 32767;
  210481. l &= 0xffff;
  210482. *dest++ = l;
  210483. }
  210484. dest = (int*)lpbuf2;
  210485. while (--samples2 >= 0)
  210486. {
  210487. int l = roundToInt (gainL * *left++);
  210488. if (l < -32768)
  210489. l = -32768;
  210490. else if (l > 32767)
  210491. l = 32767;
  210492. l &= 0xffff;
  210493. *dest++ = l;
  210494. }
  210495. }
  210496. else
  210497. {
  210498. while (--samples1 >= 0)
  210499. {
  210500. int l = roundToInt (gainL * *left++);
  210501. if (l < -32768)
  210502. l = -32768;
  210503. else if (l > 32767)
  210504. l = 32767;
  210505. l &= 0xffff;
  210506. int r = roundToInt (gainR * *right++);
  210507. if (r < -32768)
  210508. r = -32768;
  210509. else if (r > 32767)
  210510. r = 32767;
  210511. *dest++ = (r << 16) | l;
  210512. }
  210513. dest = (int*)lpbuf2;
  210514. while (--samples2 >= 0)
  210515. {
  210516. int l = roundToInt (gainL * *left++);
  210517. if (l < -32768)
  210518. l = -32768;
  210519. else if (l > 32767)
  210520. l = 32767;
  210521. l &= 0xffff;
  210522. int r = roundToInt (gainR * *right++);
  210523. if (r < -32768)
  210524. r = -32768;
  210525. else if (r > 32767)
  210526. r = 32767;
  210527. *dest++ = (r << 16) | l;
  210528. }
  210529. }
  210530. }
  210531. else
  210532. {
  210533. jassertfalse
  210534. }
  210535. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  210536. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  210537. }
  210538. else
  210539. {
  210540. jassertfalse
  210541. logError (hr);
  210542. }
  210543. bytesEmpty -= bytesPerBuffer;
  210544. return true;
  210545. }
  210546. else
  210547. {
  210548. return false;
  210549. }
  210550. }
  210551. };
  210552. struct DSoundInternalInChannel
  210553. {
  210554. String name;
  210555. LPGUID guid;
  210556. int sampleRate, bufferSizeSamples;
  210557. float* leftBuffer;
  210558. float* rightBuffer;
  210559. IDirectSound* pDirectSound;
  210560. IDirectSoundCapture* pDirectSoundCapture;
  210561. IDirectSoundCaptureBuffer* pInputBuffer;
  210562. public:
  210563. unsigned int readOffset;
  210564. int bytesPerBuffer, totalBytesPerBuffer;
  210565. int bitDepth;
  210566. bool doneFlag;
  210567. DSoundInternalInChannel (const String& name_,
  210568. LPGUID guid_,
  210569. int rate,
  210570. int bufferSize,
  210571. float* left,
  210572. float* right)
  210573. : name (name_),
  210574. guid (guid_),
  210575. sampleRate (rate),
  210576. bufferSizeSamples (bufferSize),
  210577. leftBuffer (left),
  210578. rightBuffer (right),
  210579. pDirectSound (0),
  210580. pDirectSoundCapture (0),
  210581. pInputBuffer (0),
  210582. bitDepth (16)
  210583. {
  210584. }
  210585. ~DSoundInternalInChannel()
  210586. {
  210587. close();
  210588. }
  210589. void close()
  210590. {
  210591. HRESULT hr;
  210592. if (pInputBuffer != 0)
  210593. {
  210594. JUCE_TRY
  210595. {
  210596. log ("closing dsound in: " + name);
  210597. hr = pInputBuffer->Stop();
  210598. logError (hr);
  210599. }
  210600. CATCH
  210601. JUCE_TRY
  210602. {
  210603. hr = pInputBuffer->Release();
  210604. logError (hr);
  210605. }
  210606. CATCH
  210607. pInputBuffer = 0;
  210608. }
  210609. if (pDirectSoundCapture != 0)
  210610. {
  210611. JUCE_TRY
  210612. {
  210613. hr = pDirectSoundCapture->Release();
  210614. logError (hr);
  210615. }
  210616. CATCH
  210617. pDirectSoundCapture = 0;
  210618. }
  210619. if (pDirectSound != 0)
  210620. {
  210621. JUCE_TRY
  210622. {
  210623. hr = pDirectSound->Release();
  210624. logError (hr);
  210625. }
  210626. CATCH
  210627. pDirectSound = 0;
  210628. }
  210629. }
  210630. const String open()
  210631. {
  210632. log ("opening dsound in device: " + name
  210633. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  210634. pDirectSound = 0;
  210635. pDirectSoundCapture = 0;
  210636. pInputBuffer = 0;
  210637. readOffset = 0;
  210638. totalBytesPerBuffer = 0;
  210639. String error;
  210640. HRESULT hr = E_NOINTERFACE;
  210641. if (dsDirectSoundCaptureCreate != 0)
  210642. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  210643. logError (hr);
  210644. if (hr == S_OK)
  210645. {
  210646. const int numChannels = 2;
  210647. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210648. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210649. WAVEFORMATEX wfFormat;
  210650. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210651. wfFormat.nChannels = (unsigned short)numChannels;
  210652. wfFormat.nSamplesPerSec = sampleRate;
  210653. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  210654. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  210655. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210656. wfFormat.cbSize = 0;
  210657. DSCBUFFERDESC captureDesc;
  210658. zerostruct (captureDesc);
  210659. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  210660. captureDesc.dwFlags = 0;
  210661. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  210662. captureDesc.lpwfxFormat = &wfFormat;
  210663. log ("opening dsound in step 2");
  210664. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  210665. logError (hr);
  210666. if (hr == S_OK)
  210667. {
  210668. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  210669. logError (hr);
  210670. if (hr == S_OK)
  210671. return String::empty;
  210672. }
  210673. }
  210674. error = getDSErrorMessage (hr);
  210675. close();
  210676. return error;
  210677. }
  210678. void synchronisePosition()
  210679. {
  210680. if (pInputBuffer != 0)
  210681. {
  210682. DWORD capturePos;
  210683. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  210684. }
  210685. }
  210686. bool service()
  210687. {
  210688. if (pInputBuffer == 0)
  210689. return true;
  210690. DWORD capturePos, readPos;
  210691. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  210692. logError (hr);
  210693. if (hr != S_OK)
  210694. return true;
  210695. int bytesFilled = readPos - readOffset;
  210696. if (bytesFilled < 0)
  210697. bytesFilled += totalBytesPerBuffer;
  210698. if (bytesFilled >= bytesPerBuffer)
  210699. {
  210700. LPBYTE lpbuf1 = 0;
  210701. LPBYTE lpbuf2 = 0;
  210702. DWORD dwsize1 = 0;
  210703. DWORD dwsize2 = 0;
  210704. HRESULT hr = pInputBuffer->Lock (readOffset,
  210705. bytesPerBuffer,
  210706. (void**) &lpbuf1, &dwsize1,
  210707. (void**) &lpbuf2, &dwsize2, 0);
  210708. if (hr == S_OK)
  210709. {
  210710. if (bitDepth == 16)
  210711. {
  210712. const float g = 1.0f / 32768.0f;
  210713. float* destL = leftBuffer;
  210714. float* destR = rightBuffer;
  210715. int samples1 = dwsize1 >> 2;
  210716. int samples2 = dwsize2 >> 2;
  210717. const short* src = (const short*)lpbuf1;
  210718. if (destL == 0)
  210719. {
  210720. while (--samples1 >= 0)
  210721. {
  210722. ++src;
  210723. *destR++ = *src++ * g;
  210724. }
  210725. src = (const short*)lpbuf2;
  210726. while (--samples2 >= 0)
  210727. {
  210728. ++src;
  210729. *destR++ = *src++ * g;
  210730. }
  210731. }
  210732. else if (destR == 0)
  210733. {
  210734. while (--samples1 >= 0)
  210735. {
  210736. *destL++ = *src++ * g;
  210737. ++src;
  210738. }
  210739. src = (const short*)lpbuf2;
  210740. while (--samples2 >= 0)
  210741. {
  210742. *destL++ = *src++ * g;
  210743. ++src;
  210744. }
  210745. }
  210746. else
  210747. {
  210748. while (--samples1 >= 0)
  210749. {
  210750. *destL++ = *src++ * g;
  210751. *destR++ = *src++ * g;
  210752. }
  210753. src = (const short*)lpbuf2;
  210754. while (--samples2 >= 0)
  210755. {
  210756. *destL++ = *src++ * g;
  210757. *destR++ = *src++ * g;
  210758. }
  210759. }
  210760. }
  210761. else
  210762. {
  210763. jassertfalse
  210764. }
  210765. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  210766. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  210767. }
  210768. else
  210769. {
  210770. logError (hr);
  210771. jassertfalse
  210772. }
  210773. bytesFilled -= bytesPerBuffer;
  210774. return true;
  210775. }
  210776. else
  210777. {
  210778. return false;
  210779. }
  210780. }
  210781. };
  210782. class DSoundAudioIODevice : public AudioIODevice,
  210783. public Thread
  210784. {
  210785. public:
  210786. DSoundAudioIODevice (const String& deviceName,
  210787. const int outputDeviceIndex_,
  210788. const int inputDeviceIndex_)
  210789. : AudioIODevice (deviceName, "DirectSound"),
  210790. Thread ("Juce DSound"),
  210791. isOpen_ (false),
  210792. isStarted (false),
  210793. outputDeviceIndex (outputDeviceIndex_),
  210794. inputDeviceIndex (inputDeviceIndex_),
  210795. totalSamplesOut (0),
  210796. sampleRate (0.0),
  210797. inputBuffers (1, 1),
  210798. outputBuffers (1, 1),
  210799. callback (0),
  210800. bufferSizeSamples (0)
  210801. {
  210802. if (outputDeviceIndex_ >= 0)
  210803. {
  210804. outChannels.add (TRANS("Left"));
  210805. outChannels.add (TRANS("Right"));
  210806. }
  210807. if (inputDeviceIndex_ >= 0)
  210808. {
  210809. inChannels.add (TRANS("Left"));
  210810. inChannels.add (TRANS("Right"));
  210811. }
  210812. }
  210813. ~DSoundAudioIODevice()
  210814. {
  210815. close();
  210816. }
  210817. const StringArray getOutputChannelNames()
  210818. {
  210819. return outChannels;
  210820. }
  210821. const StringArray getInputChannelNames()
  210822. {
  210823. return inChannels;
  210824. }
  210825. int getNumSampleRates()
  210826. {
  210827. return 4;
  210828. }
  210829. double getSampleRate (int index)
  210830. {
  210831. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210832. return samps [jlimit (0, 3, index)];
  210833. }
  210834. int getNumBufferSizesAvailable()
  210835. {
  210836. return 50;
  210837. }
  210838. int getBufferSizeSamples (int index)
  210839. {
  210840. int n = 64;
  210841. for (int i = 0; i < index; ++i)
  210842. n += (n < 512) ? 32
  210843. : ((n < 1024) ? 64
  210844. : ((n < 2048) ? 128 : 256));
  210845. return n;
  210846. }
  210847. int getDefaultBufferSize()
  210848. {
  210849. return 2560;
  210850. }
  210851. const String open (const BigInteger& inputChannels,
  210852. const BigInteger& outputChannels,
  210853. double sampleRate,
  210854. int bufferSizeSamples)
  210855. {
  210856. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  210857. isOpen_ = lastError.isEmpty();
  210858. return lastError;
  210859. }
  210860. void close()
  210861. {
  210862. stop();
  210863. if (isOpen_)
  210864. {
  210865. closeDevice();
  210866. isOpen_ = false;
  210867. }
  210868. }
  210869. bool isOpen()
  210870. {
  210871. return isOpen_ && isThreadRunning();
  210872. }
  210873. int getCurrentBufferSizeSamples()
  210874. {
  210875. return bufferSizeSamples;
  210876. }
  210877. double getCurrentSampleRate()
  210878. {
  210879. return sampleRate;
  210880. }
  210881. int getCurrentBitDepth()
  210882. {
  210883. int i, bits = 256;
  210884. for (i = inChans.size(); --i >= 0;)
  210885. bits = jmin (bits, inChans[i]->bitDepth);
  210886. for (i = outChans.size(); --i >= 0;)
  210887. bits = jmin (bits, outChans[i]->bitDepth);
  210888. if (bits > 32)
  210889. bits = 16;
  210890. return bits;
  210891. }
  210892. const BigInteger getActiveOutputChannels() const
  210893. {
  210894. return enabledOutputs;
  210895. }
  210896. const BigInteger getActiveInputChannels() const
  210897. {
  210898. return enabledInputs;
  210899. }
  210900. int getOutputLatencyInSamples()
  210901. {
  210902. return (int) (getCurrentBufferSizeSamples() * 1.5);
  210903. }
  210904. int getInputLatencyInSamples()
  210905. {
  210906. return getOutputLatencyInSamples();
  210907. }
  210908. void start (AudioIODeviceCallback* call)
  210909. {
  210910. if (isOpen_ && call != 0 && ! isStarted)
  210911. {
  210912. if (! isThreadRunning())
  210913. {
  210914. // something gone wrong and the thread's stopped..
  210915. isOpen_ = false;
  210916. return;
  210917. }
  210918. call->audioDeviceAboutToStart (this);
  210919. const ScopedLock sl (startStopLock);
  210920. callback = call;
  210921. isStarted = true;
  210922. }
  210923. }
  210924. void stop()
  210925. {
  210926. if (isStarted)
  210927. {
  210928. AudioIODeviceCallback* const callbackLocal = callback;
  210929. {
  210930. const ScopedLock sl (startStopLock);
  210931. isStarted = false;
  210932. }
  210933. if (callbackLocal != 0)
  210934. callbackLocal->audioDeviceStopped();
  210935. }
  210936. }
  210937. bool isPlaying()
  210938. {
  210939. return isStarted && isOpen_ && isThreadRunning();
  210940. }
  210941. const String getLastError()
  210942. {
  210943. return lastError;
  210944. }
  210945. juce_UseDebuggingNewOperator
  210946. StringArray inChannels, outChannels;
  210947. int outputDeviceIndex, inputDeviceIndex;
  210948. private:
  210949. bool isOpen_;
  210950. bool isStarted;
  210951. String lastError;
  210952. OwnedArray <DSoundInternalInChannel> inChans;
  210953. OwnedArray <DSoundInternalOutChannel> outChans;
  210954. WaitableEvent startEvent;
  210955. int bufferSizeSamples;
  210956. int volatile totalSamplesOut;
  210957. int64 volatile lastBlockTime;
  210958. double sampleRate;
  210959. BigInteger enabledInputs, enabledOutputs;
  210960. AudioSampleBuffer inputBuffers, outputBuffers;
  210961. AudioIODeviceCallback* callback;
  210962. CriticalSection startStopLock;
  210963. DSoundAudioIODevice (const DSoundAudioIODevice&);
  210964. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  210965. const String openDevice (const BigInteger& inputChannels,
  210966. const BigInteger& outputChannels,
  210967. double sampleRate_,
  210968. int bufferSizeSamples_);
  210969. void closeDevice()
  210970. {
  210971. isStarted = false;
  210972. stopThread (5000);
  210973. inChans.clear();
  210974. outChans.clear();
  210975. inputBuffers.setSize (1, 1);
  210976. outputBuffers.setSize (1, 1);
  210977. }
  210978. void resync()
  210979. {
  210980. if (! threadShouldExit())
  210981. {
  210982. sleep (5);
  210983. int i;
  210984. for (i = 0; i < outChans.size(); ++i)
  210985. outChans.getUnchecked(i)->synchronisePosition();
  210986. for (i = 0; i < inChans.size(); ++i)
  210987. inChans.getUnchecked(i)->synchronisePosition();
  210988. }
  210989. }
  210990. public:
  210991. void run()
  210992. {
  210993. while (! threadShouldExit())
  210994. {
  210995. if (wait (100))
  210996. break;
  210997. }
  210998. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  210999. const int maxTimeMS = jmax (5, 3 * latencyMs);
  211000. while (! threadShouldExit())
  211001. {
  211002. int numToDo = 0;
  211003. uint32 startTime = Time::getMillisecondCounter();
  211004. int i;
  211005. for (i = inChans.size(); --i >= 0;)
  211006. {
  211007. inChans.getUnchecked(i)->doneFlag = false;
  211008. ++numToDo;
  211009. }
  211010. for (i = outChans.size(); --i >= 0;)
  211011. {
  211012. outChans.getUnchecked(i)->doneFlag = false;
  211013. ++numToDo;
  211014. }
  211015. if (numToDo > 0)
  211016. {
  211017. const int maxCount = 3;
  211018. int count = maxCount;
  211019. for (;;)
  211020. {
  211021. for (i = inChans.size(); --i >= 0;)
  211022. {
  211023. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  211024. if ((! in->doneFlag) && in->service())
  211025. {
  211026. in->doneFlag = true;
  211027. --numToDo;
  211028. }
  211029. }
  211030. for (i = outChans.size(); --i >= 0;)
  211031. {
  211032. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  211033. if ((! out->doneFlag) && out->service())
  211034. {
  211035. out->doneFlag = true;
  211036. --numToDo;
  211037. }
  211038. }
  211039. if (numToDo <= 0)
  211040. break;
  211041. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  211042. {
  211043. resync();
  211044. break;
  211045. }
  211046. if (--count <= 0)
  211047. {
  211048. Sleep (1);
  211049. count = maxCount;
  211050. }
  211051. if (threadShouldExit())
  211052. return;
  211053. }
  211054. }
  211055. else
  211056. {
  211057. sleep (1);
  211058. }
  211059. const ScopedLock sl (startStopLock);
  211060. if (isStarted)
  211061. {
  211062. JUCE_TRY
  211063. {
  211064. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  211065. inputBuffers.getNumChannels(),
  211066. outputBuffers.getArrayOfChannels(),
  211067. outputBuffers.getNumChannels(),
  211068. bufferSizeSamples);
  211069. }
  211070. JUCE_CATCH_EXCEPTION
  211071. totalSamplesOut += bufferSizeSamples;
  211072. }
  211073. else
  211074. {
  211075. outputBuffers.clear();
  211076. totalSamplesOut = 0;
  211077. sleep (1);
  211078. }
  211079. }
  211080. }
  211081. };
  211082. class DSoundAudioIODeviceType : public AudioIODeviceType
  211083. {
  211084. public:
  211085. DSoundAudioIODeviceType()
  211086. : AudioIODeviceType ("DirectSound"),
  211087. hasScanned (false)
  211088. {
  211089. initialiseDSoundFunctions();
  211090. }
  211091. ~DSoundAudioIODeviceType()
  211092. {
  211093. }
  211094. void scanForDevices()
  211095. {
  211096. hasScanned = true;
  211097. outputDeviceNames.clear();
  211098. outputGuids.clear();
  211099. inputDeviceNames.clear();
  211100. inputGuids.clear();
  211101. if (dsDirectSoundEnumerateW != 0)
  211102. {
  211103. dsDirectSoundEnumerateW (outputEnumProcW, this);
  211104. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  211105. }
  211106. }
  211107. const StringArray getDeviceNames (bool wantInputNames) const
  211108. {
  211109. jassert (hasScanned); // need to call scanForDevices() before doing this
  211110. return wantInputNames ? inputDeviceNames
  211111. : outputDeviceNames;
  211112. }
  211113. int getDefaultDeviceIndex (bool /*forInput*/) const
  211114. {
  211115. jassert (hasScanned); // need to call scanForDevices() before doing this
  211116. return 0;
  211117. }
  211118. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  211119. {
  211120. jassert (hasScanned); // need to call scanForDevices() before doing this
  211121. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  211122. if (d == 0)
  211123. return -1;
  211124. return asInput ? d->inputDeviceIndex
  211125. : d->outputDeviceIndex;
  211126. }
  211127. bool hasSeparateInputsAndOutputs() const { return true; }
  211128. AudioIODevice* createDevice (const String& outputDeviceName,
  211129. const String& inputDeviceName)
  211130. {
  211131. jassert (hasScanned); // need to call scanForDevices() before doing this
  211132. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211133. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211134. if (outputIndex >= 0 || inputIndex >= 0)
  211135. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211136. : inputDeviceName,
  211137. outputIndex, inputIndex);
  211138. return 0;
  211139. }
  211140. juce_UseDebuggingNewOperator
  211141. StringArray outputDeviceNames;
  211142. OwnedArray <GUID> outputGuids;
  211143. StringArray inputDeviceNames;
  211144. OwnedArray <GUID> inputGuids;
  211145. private:
  211146. bool hasScanned;
  211147. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  211148. {
  211149. desc = desc.trim();
  211150. if (desc.isNotEmpty())
  211151. {
  211152. const String origDesc (desc);
  211153. int n = 2;
  211154. while (outputDeviceNames.contains (desc))
  211155. desc = origDesc + " (" + String (n++) + ")";
  211156. outputDeviceNames.add (desc);
  211157. if (lpGUID != 0)
  211158. outputGuids.add (new GUID (*lpGUID));
  211159. else
  211160. outputGuids.add (0);
  211161. }
  211162. return TRUE;
  211163. }
  211164. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211165. {
  211166. return ((DSoundAudioIODeviceType*) object)
  211167. ->outputEnumProc (lpGUID, String (description));
  211168. }
  211169. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211170. {
  211171. return ((DSoundAudioIODeviceType*) object)
  211172. ->outputEnumProc (lpGUID, String (description));
  211173. }
  211174. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  211175. {
  211176. desc = desc.trim();
  211177. if (desc.isNotEmpty())
  211178. {
  211179. const String origDesc (desc);
  211180. int n = 2;
  211181. while (inputDeviceNames.contains (desc))
  211182. desc = origDesc + " (" + String (n++) + ")";
  211183. inputDeviceNames.add (desc);
  211184. if (lpGUID != 0)
  211185. inputGuids.add (new GUID (*lpGUID));
  211186. else
  211187. inputGuids.add (0);
  211188. }
  211189. return TRUE;
  211190. }
  211191. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211192. {
  211193. return ((DSoundAudioIODeviceType*) object)
  211194. ->inputEnumProc (lpGUID, String (description));
  211195. }
  211196. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211197. {
  211198. return ((DSoundAudioIODeviceType*) object)
  211199. ->inputEnumProc (lpGUID, String (description));
  211200. }
  211201. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  211202. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  211203. };
  211204. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  211205. const BigInteger& outputChannels,
  211206. double sampleRate_,
  211207. int bufferSizeSamples_)
  211208. {
  211209. closeDevice();
  211210. totalSamplesOut = 0;
  211211. sampleRate = sampleRate_;
  211212. if (bufferSizeSamples_ <= 0)
  211213. bufferSizeSamples_ = 960; // use as a default size if none is set.
  211214. bufferSizeSamples = bufferSizeSamples_ & ~7;
  211215. DSoundAudioIODeviceType dlh;
  211216. dlh.scanForDevices();
  211217. enabledInputs = inputChannels;
  211218. enabledInputs.setRange (inChannels.size(),
  211219. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  211220. false);
  211221. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  211222. int i, numIns = 0;
  211223. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  211224. {
  211225. float* left = 0;
  211226. if (enabledInputs[i])
  211227. left = inputBuffers.getSampleData (numIns++);
  211228. float* right = 0;
  211229. if (enabledInputs[i + 1])
  211230. right = inputBuffers.getSampleData (numIns++);
  211231. if (left != 0 || right != 0)
  211232. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  211233. dlh.inputGuids [inputDeviceIndex],
  211234. (int) sampleRate, bufferSizeSamples,
  211235. left, right));
  211236. }
  211237. enabledOutputs = outputChannels;
  211238. enabledOutputs.setRange (outChannels.size(),
  211239. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  211240. false);
  211241. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  211242. int numOuts = 0;
  211243. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  211244. {
  211245. float* left = 0;
  211246. if (enabledOutputs[i])
  211247. left = outputBuffers.getSampleData (numOuts++);
  211248. float* right = 0;
  211249. if (enabledOutputs[i + 1])
  211250. right = outputBuffers.getSampleData (numOuts++);
  211251. if (left != 0 || right != 0)
  211252. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  211253. dlh.outputGuids [outputDeviceIndex],
  211254. (int) sampleRate, bufferSizeSamples,
  211255. left, right));
  211256. }
  211257. String error;
  211258. // boost our priority while opening the devices to try to get better sync between them
  211259. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  211260. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  211261. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  211262. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  211263. for (i = 0; i < outChans.size(); ++i)
  211264. {
  211265. error = outChans[i]->open();
  211266. if (error.isNotEmpty())
  211267. {
  211268. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  211269. break;
  211270. }
  211271. }
  211272. if (error.isEmpty())
  211273. {
  211274. for (i = 0; i < inChans.size(); ++i)
  211275. {
  211276. error = inChans[i]->open();
  211277. if (error.isNotEmpty())
  211278. {
  211279. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  211280. break;
  211281. }
  211282. }
  211283. }
  211284. if (error.isEmpty())
  211285. {
  211286. totalSamplesOut = 0;
  211287. for (i = 0; i < outChans.size(); ++i)
  211288. outChans.getUnchecked(i)->synchronisePosition();
  211289. for (i = 0; i < inChans.size(); ++i)
  211290. inChans.getUnchecked(i)->synchronisePosition();
  211291. startThread (9);
  211292. sleep (10);
  211293. notify();
  211294. }
  211295. else
  211296. {
  211297. log (error);
  211298. }
  211299. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  211300. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  211301. return error;
  211302. }
  211303. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  211304. {
  211305. return new DSoundAudioIODeviceType();
  211306. }
  211307. #undef log
  211308. #endif
  211309. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  211310. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  211311. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211312. // compiled on its own).
  211313. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  211314. #if 1
  211315. const String getAudioErrorDesc (HRESULT hr)
  211316. {
  211317. const char* e = 0;
  211318. switch (hr)
  211319. {
  211320. case E_POINTER: e = "E_POINTER"; break;
  211321. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  211322. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  211323. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  211324. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  211325. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  211326. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  211327. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  211328. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  211329. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  211330. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  211331. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  211332. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  211333. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  211334. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  211335. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  211336. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  211337. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  211338. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  211339. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  211340. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  211341. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  211342. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  211343. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  211344. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  211345. default: return String::toHexString ((int) hr);
  211346. }
  211347. return e;
  211348. }
  211349. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  211350. #define OK(a) wasapi_checkResult(a)
  211351. static bool wasapi_checkResult (HRESULT hr)
  211352. {
  211353. logFailure (hr);
  211354. return SUCCEEDED (hr);
  211355. }
  211356. #else
  211357. #define logFailure(hr) {}
  211358. #define OK(a) SUCCEEDED(a)
  211359. #endif
  211360. static const String wasapi_getDeviceID (IMMDevice* const device)
  211361. {
  211362. String s;
  211363. WCHAR* deviceId = 0;
  211364. if (OK (device->GetId (&deviceId)))
  211365. {
  211366. s = String (deviceId);
  211367. CoTaskMemFree (deviceId);
  211368. }
  211369. return s;
  211370. }
  211371. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  211372. {
  211373. EDataFlow flow = eRender;
  211374. ComSmartPtr <IMMEndpoint> endPoint;
  211375. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  211376. (void) OK (endPoint->GetDataFlow (&flow));
  211377. return flow;
  211378. }
  211379. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  211380. {
  211381. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  211382. }
  211383. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  211384. {
  211385. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  211386. : sizeof (WAVEFORMATEX));
  211387. }
  211388. class WASAPIDeviceBase
  211389. {
  211390. public:
  211391. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211392. : device (device_),
  211393. sampleRate (0),
  211394. numChannels (0),
  211395. actualNumChannels (0),
  211396. defaultSampleRate (0),
  211397. minBufferSize (0),
  211398. defaultBufferSize (0),
  211399. latencySamples (0),
  211400. useExclusiveMode (useExclusiveMode_)
  211401. {
  211402. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  211403. ComSmartPtr <IAudioClient> tempClient (createClient());
  211404. if (tempClient == 0)
  211405. return;
  211406. REFERENCE_TIME defaultPeriod, minPeriod;
  211407. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  211408. return;
  211409. WAVEFORMATEX* mixFormat = 0;
  211410. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  211411. return;
  211412. WAVEFORMATEXTENSIBLE format;
  211413. wasapi_copyWavFormat (format, mixFormat);
  211414. CoTaskMemFree (mixFormat);
  211415. actualNumChannels = numChannels = format.Format.nChannels;
  211416. defaultSampleRate = format.Format.nSamplesPerSec;
  211417. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  211418. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  211419. rates.addUsingDefaultSort (defaultSampleRate);
  211420. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  211421. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  211422. {
  211423. if (ratesToTest[i] == defaultSampleRate)
  211424. continue;
  211425. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  211426. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211427. (WAVEFORMATEX*) &format, 0)))
  211428. if (! rates.contains (ratesToTest[i]))
  211429. rates.addUsingDefaultSort (ratesToTest[i]);
  211430. }
  211431. }
  211432. ~WASAPIDeviceBase()
  211433. {
  211434. device = 0;
  211435. CloseHandle (clientEvent);
  211436. }
  211437. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  211438. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  211439. {
  211440. sampleRate = newSampleRate;
  211441. channels = newChannels;
  211442. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  211443. numChannels = channels.getHighestBit() + 1;
  211444. if (numChannels == 0)
  211445. return true;
  211446. client = createClient();
  211447. if (client != 0
  211448. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  211449. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  211450. {
  211451. channelMaps.clear();
  211452. for (int i = 0; i <= channels.getHighestBit(); ++i)
  211453. if (channels[i])
  211454. channelMaps.add (i);
  211455. REFERENCE_TIME latency;
  211456. if (OK (client->GetStreamLatency (&latency)))
  211457. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  211458. (void) OK (client->GetBufferSize (&actualBufferSize));
  211459. return OK (client->SetEventHandle (clientEvent));
  211460. }
  211461. return false;
  211462. }
  211463. void closeClient()
  211464. {
  211465. if (client != 0)
  211466. client->Stop();
  211467. client = 0;
  211468. ResetEvent (clientEvent);
  211469. }
  211470. ComSmartPtr <IMMDevice> device;
  211471. ComSmartPtr <IAudioClient> client;
  211472. double sampleRate, defaultSampleRate;
  211473. int numChannels, actualNumChannels;
  211474. int minBufferSize, defaultBufferSize, latencySamples;
  211475. const bool useExclusiveMode;
  211476. Array <double> rates;
  211477. HANDLE clientEvent;
  211478. BigInteger channels;
  211479. AudioDataConverters::DataFormat dataFormat;
  211480. Array <int> channelMaps;
  211481. UINT32 actualBufferSize;
  211482. int bytesPerSample;
  211483. private:
  211484. const ComSmartPtr <IAudioClient> createClient()
  211485. {
  211486. ComSmartPtr <IAudioClient> client;
  211487. if (device != 0)
  211488. {
  211489. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  211490. logFailure (hr);
  211491. }
  211492. return client;
  211493. }
  211494. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  211495. {
  211496. WAVEFORMATEXTENSIBLE format;
  211497. zerostruct (format);
  211498. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  211499. {
  211500. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  211501. }
  211502. else
  211503. {
  211504. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  211505. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  211506. }
  211507. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  211508. format.Format.nChannels = (WORD) numChannels;
  211509. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  211510. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  211511. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  211512. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  211513. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  211514. switch (numChannels)
  211515. {
  211516. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  211517. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  211518. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211519. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211520. 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;
  211521. default: break;
  211522. }
  211523. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  211524. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211525. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  211526. logFailure (hr);
  211527. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  211528. {
  211529. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  211530. hr = S_OK;
  211531. }
  211532. CoTaskMemFree (nearestFormat);
  211533. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  211534. if (useExclusiveMode)
  211535. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  211536. GUID session;
  211537. if (hr == S_OK
  211538. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211539. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  211540. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  211541. {
  211542. actualNumChannels = format.Format.nChannels;
  211543. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  211544. bytesPerSample = format.Format.wBitsPerSample / 8;
  211545. dataFormat = isFloat ? AudioDataConverters::float32LE
  211546. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  211547. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  211548. : AudioDataConverters::int16LE)));
  211549. return true;
  211550. }
  211551. return false;
  211552. }
  211553. WASAPIDeviceBase (const WASAPIDeviceBase&);
  211554. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  211555. };
  211556. class WASAPIInputDevice : public WASAPIDeviceBase
  211557. {
  211558. public:
  211559. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211560. : WASAPIDeviceBase (device_, useExclusiveMode_),
  211561. reservoir (1, 1)
  211562. {
  211563. }
  211564. ~WASAPIInputDevice()
  211565. {
  211566. close();
  211567. }
  211568. bool open (const double newSampleRate, const BigInteger& newChannels)
  211569. {
  211570. reservoirSize = 0;
  211571. reservoirCapacity = 16384;
  211572. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  211573. return openClient (newSampleRate, newChannels)
  211574. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  211575. }
  211576. void close()
  211577. {
  211578. closeClient();
  211579. captureClient = 0;
  211580. reservoir.setSize (0);
  211581. }
  211582. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  211583. {
  211584. if (numChannels <= 0)
  211585. return;
  211586. int offset = 0;
  211587. while (bufferSize > 0)
  211588. {
  211589. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  211590. {
  211591. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  211592. for (int i = 0; i < numDestBuffers; ++i)
  211593. {
  211594. float* const dest = destBuffers[i] + offset;
  211595. const int srcChan = channelMaps.getUnchecked(i);
  211596. switch (dataFormat)
  211597. {
  211598. case AudioDataConverters::float32LE:
  211599. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211600. break;
  211601. case AudioDataConverters::int32LE:
  211602. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211603. break;
  211604. case AudioDataConverters::int24LE:
  211605. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211606. break;
  211607. case AudioDataConverters::int16LE:
  211608. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211609. break;
  211610. default: jassertfalse; break;
  211611. }
  211612. }
  211613. bufferSize -= samplesToDo;
  211614. offset += samplesToDo;
  211615. reservoirSize -= samplesToDo;
  211616. }
  211617. else
  211618. {
  211619. UINT32 packetLength = 0;
  211620. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  211621. break;
  211622. if (packetLength == 0)
  211623. {
  211624. if (thread.threadShouldExit())
  211625. break;
  211626. Thread::sleep (1);
  211627. continue;
  211628. }
  211629. uint8* inputData = 0;
  211630. UINT32 numSamplesAvailable;
  211631. DWORD flags;
  211632. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  211633. {
  211634. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  211635. for (int i = 0; i < numDestBuffers; ++i)
  211636. {
  211637. float* const dest = destBuffers[i] + offset;
  211638. const int srcChan = channelMaps.getUnchecked(i);
  211639. switch (dataFormat)
  211640. {
  211641. case AudioDataConverters::float32LE:
  211642. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211643. break;
  211644. case AudioDataConverters::int32LE:
  211645. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211646. break;
  211647. case AudioDataConverters::int24LE:
  211648. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211649. break;
  211650. case AudioDataConverters::int16LE:
  211651. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211652. break;
  211653. default: jassertfalse; break;
  211654. }
  211655. }
  211656. bufferSize -= samplesToDo;
  211657. offset += samplesToDo;
  211658. if (samplesToDo < (int) numSamplesAvailable)
  211659. {
  211660. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  211661. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  211662. bytesPerSample * actualNumChannels * reservoirSize);
  211663. }
  211664. captureClient->ReleaseBuffer (numSamplesAvailable);
  211665. }
  211666. }
  211667. }
  211668. }
  211669. ComSmartPtr <IAudioCaptureClient> captureClient;
  211670. MemoryBlock reservoir;
  211671. int reservoirSize, reservoirCapacity;
  211672. private:
  211673. WASAPIInputDevice (const WASAPIInputDevice&);
  211674. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  211675. };
  211676. class WASAPIOutputDevice : public WASAPIDeviceBase
  211677. {
  211678. public:
  211679. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211680. : WASAPIDeviceBase (device_, useExclusiveMode_)
  211681. {
  211682. }
  211683. ~WASAPIOutputDevice()
  211684. {
  211685. close();
  211686. }
  211687. bool open (const double newSampleRate, const BigInteger& newChannels)
  211688. {
  211689. return openClient (newSampleRate, newChannels)
  211690. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  211691. }
  211692. void close()
  211693. {
  211694. closeClient();
  211695. renderClient = 0;
  211696. }
  211697. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  211698. {
  211699. if (numChannels <= 0)
  211700. return;
  211701. int offset = 0;
  211702. while (bufferSize > 0)
  211703. {
  211704. UINT32 padding = 0;
  211705. if (! OK (client->GetCurrentPadding (&padding)))
  211706. return;
  211707. int samplesToDo = useExclusiveMode ? bufferSize
  211708. : jmin ((int) (actualBufferSize - padding), bufferSize);
  211709. if (samplesToDo <= 0)
  211710. {
  211711. if (thread.threadShouldExit())
  211712. break;
  211713. Thread::sleep (0);
  211714. continue;
  211715. }
  211716. uint8* outputData = 0;
  211717. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  211718. {
  211719. for (int i = 0; i < numSrcBuffers; ++i)
  211720. {
  211721. const float* const source = srcBuffers[i] + offset;
  211722. const int destChan = channelMaps.getUnchecked(i);
  211723. switch (dataFormat)
  211724. {
  211725. case AudioDataConverters::float32LE:
  211726. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211727. break;
  211728. case AudioDataConverters::int32LE:
  211729. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211730. break;
  211731. case AudioDataConverters::int24LE:
  211732. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  211733. break;
  211734. case AudioDataConverters::int16LE:
  211735. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  211736. break;
  211737. default: jassertfalse; break;
  211738. }
  211739. }
  211740. renderClient->ReleaseBuffer (samplesToDo, 0);
  211741. offset += samplesToDo;
  211742. bufferSize -= samplesToDo;
  211743. }
  211744. }
  211745. }
  211746. ComSmartPtr <IAudioRenderClient> renderClient;
  211747. private:
  211748. WASAPIOutputDevice (const WASAPIOutputDevice&);
  211749. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  211750. };
  211751. class WASAPIAudioIODevice : public AudioIODevice,
  211752. public Thread
  211753. {
  211754. public:
  211755. WASAPIAudioIODevice (const String& deviceName,
  211756. const String& outputDeviceId_,
  211757. const String& inputDeviceId_,
  211758. const bool useExclusiveMode_)
  211759. : AudioIODevice (deviceName, "Windows Audio"),
  211760. Thread ("Juce WASAPI"),
  211761. isOpen_ (false),
  211762. isStarted (false),
  211763. outputDevice (0),
  211764. outputDeviceId (outputDeviceId_),
  211765. inputDevice (0),
  211766. inputDeviceId (inputDeviceId_),
  211767. useExclusiveMode (useExclusiveMode_),
  211768. currentBufferSizeSamples (0),
  211769. currentSampleRate (0),
  211770. callback (0)
  211771. {
  211772. }
  211773. ~WASAPIAudioIODevice()
  211774. {
  211775. close();
  211776. deleteAndZero (inputDevice);
  211777. deleteAndZero (outputDevice);
  211778. }
  211779. bool initialise()
  211780. {
  211781. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  211782. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  211783. latencyIn = latencyOut = 0;
  211784. Array <double> ratesIn, ratesOut;
  211785. if (createDevices())
  211786. {
  211787. jassert (inputDevice != 0 || outputDevice != 0);
  211788. if (inputDevice != 0 && outputDevice != 0)
  211789. {
  211790. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  211791. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  211792. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  211793. sampleRates = inputDevice->rates;
  211794. sampleRates.removeValuesNotIn (outputDevice->rates);
  211795. }
  211796. else
  211797. {
  211798. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  211799. defaultSampleRate = d->defaultSampleRate;
  211800. minBufferSize = d->minBufferSize;
  211801. defaultBufferSize = d->defaultBufferSize;
  211802. sampleRates = d->rates;
  211803. }
  211804. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  211805. if (minBufferSize != defaultBufferSize)
  211806. bufferSizes.addUsingDefaultSort (minBufferSize);
  211807. int n = 64;
  211808. for (int i = 0; i < 40; ++i)
  211809. {
  211810. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  211811. bufferSizes.addUsingDefaultSort (n);
  211812. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  211813. }
  211814. return true;
  211815. }
  211816. return false;
  211817. }
  211818. const StringArray getOutputChannelNames()
  211819. {
  211820. StringArray outChannels;
  211821. if (outputDevice != 0)
  211822. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  211823. outChannels.add ("Output channel " + String (i));
  211824. return outChannels;
  211825. }
  211826. const StringArray getInputChannelNames()
  211827. {
  211828. StringArray inChannels;
  211829. if (inputDevice != 0)
  211830. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  211831. inChannels.add ("Input channel " + String (i));
  211832. return inChannels;
  211833. }
  211834. int getNumSampleRates() { return sampleRates.size(); }
  211835. double getSampleRate (int index) { return sampleRates [index]; }
  211836. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211837. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211838. int getDefaultBufferSize() { return defaultBufferSize; }
  211839. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  211840. double getCurrentSampleRate() { return currentSampleRate; }
  211841. int getCurrentBitDepth() { return 32; }
  211842. int getOutputLatencyInSamples() { return latencyOut; }
  211843. int getInputLatencyInSamples() { return latencyIn; }
  211844. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  211845. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  211846. const String getLastError() { return lastError; }
  211847. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  211848. double sampleRate, int bufferSizeSamples)
  211849. {
  211850. close();
  211851. lastError = String::empty;
  211852. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  211853. {
  211854. lastError = "The input and output devices don't share a common sample rate!";
  211855. return lastError;
  211856. }
  211857. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  211858. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  211859. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  211860. {
  211861. lastError = "Couldn't open the input device!";
  211862. return lastError;
  211863. }
  211864. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  211865. {
  211866. close();
  211867. lastError = "Couldn't open the output device!";
  211868. return lastError;
  211869. }
  211870. if (inputDevice != 0)
  211871. ResetEvent (inputDevice->clientEvent);
  211872. if (outputDevice != 0)
  211873. ResetEvent (outputDevice->clientEvent);
  211874. startThread (8);
  211875. Thread::sleep (5);
  211876. if (inputDevice != 0 && inputDevice->client != 0)
  211877. {
  211878. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  211879. HRESULT hr = inputDevice->client->Start();
  211880. logFailure (hr); //xxx handle this
  211881. }
  211882. if (outputDevice != 0 && outputDevice->client != 0)
  211883. {
  211884. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  211885. HRESULT hr = outputDevice->client->Start();
  211886. logFailure (hr); //xxx handle this
  211887. }
  211888. isOpen_ = true;
  211889. return lastError;
  211890. }
  211891. void close()
  211892. {
  211893. stop();
  211894. if (inputDevice != 0)
  211895. SetEvent (inputDevice->clientEvent);
  211896. if (outputDevice != 0)
  211897. SetEvent (outputDevice->clientEvent);
  211898. stopThread (5000);
  211899. if (inputDevice != 0)
  211900. inputDevice->close();
  211901. if (outputDevice != 0)
  211902. outputDevice->close();
  211903. isOpen_ = false;
  211904. }
  211905. bool isOpen() { return isOpen_ && isThreadRunning(); }
  211906. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  211907. void start (AudioIODeviceCallback* call)
  211908. {
  211909. if (isOpen_ && call != 0 && ! isStarted)
  211910. {
  211911. if (! isThreadRunning())
  211912. {
  211913. // something's gone wrong and the thread's stopped..
  211914. isOpen_ = false;
  211915. return;
  211916. }
  211917. call->audioDeviceAboutToStart (this);
  211918. const ScopedLock sl (startStopLock);
  211919. callback = call;
  211920. isStarted = true;
  211921. }
  211922. }
  211923. void stop()
  211924. {
  211925. if (isStarted)
  211926. {
  211927. AudioIODeviceCallback* const callbackLocal = callback;
  211928. {
  211929. const ScopedLock sl (startStopLock);
  211930. isStarted = false;
  211931. }
  211932. if (callbackLocal != 0)
  211933. callbackLocal->audioDeviceStopped();
  211934. }
  211935. }
  211936. void setMMThreadPriority()
  211937. {
  211938. DynamicLibraryLoader dll ("avrt.dll");
  211939. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  211940. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  211941. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  211942. {
  211943. DWORD dummy = 0;
  211944. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  211945. if (h != 0)
  211946. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  211947. }
  211948. }
  211949. void run()
  211950. {
  211951. setMMThreadPriority();
  211952. const int bufferSize = currentBufferSizeSamples;
  211953. HANDLE events[2];
  211954. int numEvents = 0;
  211955. if (inputDevice != 0)
  211956. events [numEvents++] = inputDevice->clientEvent;
  211957. if (outputDevice != 0)
  211958. events [numEvents++] = outputDevice->clientEvent;
  211959. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  211960. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  211961. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  211962. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  211963. float** const inputBuffers = ins.getArrayOfChannels();
  211964. float** const outputBuffers = outs.getArrayOfChannels();
  211965. ins.clear();
  211966. while (! threadShouldExit())
  211967. {
  211968. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  211969. : WaitForMultipleObjects (numEvents, events, true, 1000);
  211970. if (result == WAIT_TIMEOUT)
  211971. continue;
  211972. if (threadShouldExit())
  211973. break;
  211974. if (inputDevice != 0)
  211975. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  211976. // Make the callback..
  211977. {
  211978. const ScopedLock sl (startStopLock);
  211979. if (isStarted)
  211980. {
  211981. JUCE_TRY
  211982. {
  211983. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  211984. numInputBuffers,
  211985. outputBuffers,
  211986. numOutputBuffers,
  211987. bufferSize);
  211988. }
  211989. JUCE_CATCH_EXCEPTION
  211990. }
  211991. else
  211992. {
  211993. outs.clear();
  211994. }
  211995. }
  211996. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  211997. continue;
  211998. if (outputDevice != 0)
  211999. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  212000. }
  212001. }
  212002. juce_UseDebuggingNewOperator
  212003. String outputDeviceId, inputDeviceId;
  212004. String lastError;
  212005. private:
  212006. // Device stats...
  212007. WASAPIInputDevice* inputDevice;
  212008. WASAPIOutputDevice* outputDevice;
  212009. const bool useExclusiveMode;
  212010. double defaultSampleRate;
  212011. int minBufferSize, defaultBufferSize;
  212012. int latencyIn, latencyOut;
  212013. Array <double> sampleRates;
  212014. Array <int> bufferSizes;
  212015. // Active state...
  212016. bool isOpen_, isStarted;
  212017. int currentBufferSizeSamples;
  212018. double currentSampleRate;
  212019. AudioIODeviceCallback* callback;
  212020. CriticalSection startStopLock;
  212021. bool createDevices()
  212022. {
  212023. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212024. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212025. return false;
  212026. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212027. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  212028. return false;
  212029. UINT32 numDevices = 0;
  212030. if (! OK (deviceCollection->GetCount (&numDevices)))
  212031. return false;
  212032. for (UINT32 i = 0; i < numDevices; ++i)
  212033. {
  212034. ComSmartPtr <IMMDevice> device;
  212035. if (! OK (deviceCollection->Item (i, &device)))
  212036. continue;
  212037. const String deviceId (wasapi_getDeviceID (device));
  212038. if (deviceId.isEmpty())
  212039. continue;
  212040. const EDataFlow flow = wasapi_getDataFlow (device);
  212041. if (deviceId == inputDeviceId && flow == eCapture)
  212042. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  212043. else if (deviceId == outputDeviceId && flow == eRender)
  212044. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  212045. }
  212046. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  212047. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  212048. }
  212049. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  212050. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  212051. };
  212052. class WASAPIAudioIODeviceType : public AudioIODeviceType
  212053. {
  212054. public:
  212055. WASAPIAudioIODeviceType()
  212056. : AudioIODeviceType ("Windows Audio"),
  212057. hasScanned (false)
  212058. {
  212059. }
  212060. ~WASAPIAudioIODeviceType()
  212061. {
  212062. }
  212063. void scanForDevices()
  212064. {
  212065. hasScanned = true;
  212066. outputDeviceNames.clear();
  212067. inputDeviceNames.clear();
  212068. outputDeviceIds.clear();
  212069. inputDeviceIds.clear();
  212070. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212071. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212072. return;
  212073. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  212074. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  212075. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212076. UINT32 numDevices = 0;
  212077. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  212078. && OK (deviceCollection->GetCount (&numDevices))))
  212079. return;
  212080. for (UINT32 i = 0; i < numDevices; ++i)
  212081. {
  212082. ComSmartPtr <IMMDevice> device;
  212083. if (! OK (deviceCollection->Item (i, &device)))
  212084. continue;
  212085. const String deviceId (wasapi_getDeviceID (device));
  212086. DWORD state = 0;
  212087. if (! OK (device->GetState (&state)))
  212088. continue;
  212089. if (state != DEVICE_STATE_ACTIVE)
  212090. continue;
  212091. String name;
  212092. {
  212093. ComSmartPtr <IPropertyStore> properties;
  212094. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  212095. continue;
  212096. PROPVARIANT value;
  212097. PropVariantInit (&value);
  212098. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  212099. name = value.pwszVal;
  212100. PropVariantClear (&value);
  212101. }
  212102. const EDataFlow flow = wasapi_getDataFlow (device);
  212103. if (flow == eRender)
  212104. {
  212105. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  212106. outputDeviceIds.insert (index, deviceId);
  212107. outputDeviceNames.insert (index, name);
  212108. }
  212109. else if (flow == eCapture)
  212110. {
  212111. const int index = (deviceId == defaultCapture) ? 0 : -1;
  212112. inputDeviceIds.insert (index, deviceId);
  212113. inputDeviceNames.insert (index, name);
  212114. }
  212115. }
  212116. inputDeviceNames.appendNumbersToDuplicates (false, false);
  212117. outputDeviceNames.appendNumbersToDuplicates (false, false);
  212118. }
  212119. const StringArray getDeviceNames (bool wantInputNames) const
  212120. {
  212121. jassert (hasScanned); // need to call scanForDevices() before doing this
  212122. return wantInputNames ? inputDeviceNames
  212123. : outputDeviceNames;
  212124. }
  212125. int getDefaultDeviceIndex (bool /*forInput*/) const
  212126. {
  212127. jassert (hasScanned); // need to call scanForDevices() before doing this
  212128. return 0;
  212129. }
  212130. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  212131. {
  212132. jassert (hasScanned); // need to call scanForDevices() before doing this
  212133. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  212134. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  212135. : outputDeviceIds.indexOf (d->outputDeviceId));
  212136. }
  212137. bool hasSeparateInputsAndOutputs() const { return true; }
  212138. AudioIODevice* createDevice (const String& outputDeviceName,
  212139. const String& inputDeviceName)
  212140. {
  212141. jassert (hasScanned); // need to call scanForDevices() before doing this
  212142. const bool useExclusiveMode = false;
  212143. ScopedPointer<WASAPIAudioIODevice> device;
  212144. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  212145. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  212146. if (outputIndex >= 0 || inputIndex >= 0)
  212147. {
  212148. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  212149. : inputDeviceName,
  212150. outputDeviceIds [outputIndex],
  212151. inputDeviceIds [inputIndex],
  212152. useExclusiveMode);
  212153. if (! device->initialise())
  212154. device = 0;
  212155. }
  212156. return device.release();
  212157. }
  212158. juce_UseDebuggingNewOperator
  212159. StringArray outputDeviceNames, outputDeviceIds;
  212160. StringArray inputDeviceNames, inputDeviceIds;
  212161. private:
  212162. bool hasScanned;
  212163. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  212164. {
  212165. String s;
  212166. IMMDevice* dev = 0;
  212167. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  212168. eMultimedia, &dev)))
  212169. {
  212170. WCHAR* deviceId = 0;
  212171. if (OK (dev->GetId (&deviceId)))
  212172. {
  212173. s = String (deviceId);
  212174. CoTaskMemFree (deviceId);
  212175. }
  212176. dev->Release();
  212177. }
  212178. return s;
  212179. }
  212180. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  212181. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  212182. };
  212183. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  212184. {
  212185. return new WASAPIAudioIODeviceType();
  212186. }
  212187. #undef logFailure
  212188. #undef OK
  212189. #endif
  212190. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  212191. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  212192. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212193. // compiled on its own).
  212194. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  212195. class DShowCameraDeviceInteral : public ChangeBroadcaster
  212196. {
  212197. public:
  212198. DShowCameraDeviceInteral (CameraDevice* const owner_,
  212199. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  212200. const ComSmartPtr <IBaseFilter>& filter_,
  212201. int minWidth, int minHeight,
  212202. int maxWidth, int maxHeight)
  212203. : owner (owner_),
  212204. captureGraphBuilder (captureGraphBuilder_),
  212205. filter (filter_),
  212206. ok (false),
  212207. imageNeedsFlipping (false),
  212208. width (0),
  212209. height (0),
  212210. activeUsers (0),
  212211. recordNextFrameTime (false),
  212212. activeImage (0),
  212213. loadingImage (0)
  212214. {
  212215. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  212216. if (FAILED (hr))
  212217. return;
  212218. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  212219. if (FAILED (hr))
  212220. return;
  212221. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  212222. if (FAILED (hr))
  212223. return;
  212224. {
  212225. ComSmartPtr <IAMStreamConfig> streamConfig;
  212226. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  212227. IID_IAMStreamConfig, (void**) &streamConfig);
  212228. if (streamConfig != 0)
  212229. {
  212230. getVideoSizes (streamConfig);
  212231. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  212232. return;
  212233. }
  212234. }
  212235. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  212236. if (FAILED (hr))
  212237. return;
  212238. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  212239. if (FAILED (hr))
  212240. return;
  212241. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  212242. if (FAILED (hr))
  212243. return;
  212244. if (! connectFilters (filter, smartTee))
  212245. return;
  212246. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  212247. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  212248. if (FAILED (hr))
  212249. return;
  212250. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  212251. if (FAILED (hr))
  212252. return;
  212253. AM_MEDIA_TYPE mt;
  212254. zerostruct (mt);
  212255. mt.majortype = MEDIATYPE_Video;
  212256. mt.subtype = MEDIASUBTYPE_RGB24;
  212257. mt.formattype = FORMAT_VideoInfo;
  212258. sampleGrabber->SetMediaType (&mt);
  212259. callback = new GrabberCallback (*this);
  212260. sampleGrabber->SetCallback (callback, 1);
  212261. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  212262. if (FAILED (hr))
  212263. return;
  212264. ComSmartPtr <IPin> grabberInputPin;
  212265. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  212266. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  212267. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  212268. return;
  212269. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  212270. if (FAILED (hr))
  212271. return;
  212272. zerostruct (mt);
  212273. hr = sampleGrabber->GetConnectedMediaType (&mt);
  212274. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  212275. width = pVih->bmiHeader.biWidth;
  212276. height = pVih->bmiHeader.biHeight;
  212277. ComSmartPtr <IBaseFilter> nullFilter;
  212278. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  212279. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  212280. if (connectFilters (sampleGrabberBase, nullFilter)
  212281. && addGraphToRot())
  212282. {
  212283. activeImage = new Image (Image::RGB, width, height, true);
  212284. loadingImage = new Image (Image::RGB, width, height, true);
  212285. ok = true;
  212286. }
  212287. }
  212288. ~DShowCameraDeviceInteral()
  212289. {
  212290. if (mediaControl != 0)
  212291. mediaControl->Stop();
  212292. removeGraphFromRot();
  212293. for (int i = viewerComps.size(); --i >= 0;)
  212294. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  212295. callback = 0;
  212296. graphBuilder = 0;
  212297. sampleGrabber = 0;
  212298. mediaControl = 0;
  212299. filter = 0;
  212300. captureGraphBuilder = 0;
  212301. smartTee = 0;
  212302. smartTeePreviewOutputPin = 0;
  212303. smartTeeCaptureOutputPin = 0;
  212304. asfWriter = 0;
  212305. delete activeImage;
  212306. delete loadingImage;
  212307. }
  212308. void addUser()
  212309. {
  212310. if (ok && activeUsers++ == 0)
  212311. mediaControl->Run();
  212312. }
  212313. void removeUser()
  212314. {
  212315. if (ok && --activeUsers == 0)
  212316. mediaControl->Stop();
  212317. }
  212318. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  212319. {
  212320. if (recordNextFrameTime)
  212321. {
  212322. const double defaultCameraLatency = 0.1;
  212323. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  212324. recordNextFrameTime = false;
  212325. ComSmartPtr <IPin> pin;
  212326. if (getPin (filter, PINDIR_OUTPUT, &pin))
  212327. {
  212328. ComSmartPtr <IAMPushSource> pushSource;
  212329. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  212330. if (pushSource != 0)
  212331. {
  212332. REFERENCE_TIME latency = 0;
  212333. hr = pushSource->GetLatency (&latency);
  212334. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  212335. }
  212336. }
  212337. }
  212338. {
  212339. const int lineStride = width * 3;
  212340. const ScopedLock sl (imageSwapLock);
  212341. {
  212342. const Image::BitmapData destData (*loadingImage, 0, 0, width, height, true);
  212343. for (int i = 0; i < height; ++i)
  212344. memcpy (destData.getLinePointer ((height - 1) - i),
  212345. buffer + lineStride * i,
  212346. lineStride);
  212347. }
  212348. imageNeedsFlipping = true;
  212349. }
  212350. if (listeners.size() > 0)
  212351. callListeners (*loadingImage);
  212352. sendChangeMessage (this);
  212353. }
  212354. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  212355. {
  212356. if (imageNeedsFlipping)
  212357. {
  212358. const ScopedLock sl (imageSwapLock);
  212359. swapVariables (loadingImage, activeImage);
  212360. imageNeedsFlipping = false;
  212361. }
  212362. RectanglePlacement rp (RectanglePlacement::centred);
  212363. double dx = 0, dy = 0, dw = width, dh = height;
  212364. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  212365. const int rx = roundToInt (dx), ry = roundToInt (dy);
  212366. const int rw = roundToInt (dw), rh = roundToInt (dh);
  212367. g.saveState();
  212368. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  212369. g.fillAll (Colours::black);
  212370. g.restoreState();
  212371. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  212372. }
  212373. bool createFileCaptureFilter (const File& file)
  212374. {
  212375. removeFileCaptureFilter();
  212376. file.deleteFile();
  212377. mediaControl->Stop();
  212378. firstRecordedTime = Time();
  212379. recordNextFrameTime = true;
  212380. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  212381. if (SUCCEEDED (hr))
  212382. {
  212383. ComSmartPtr <IFileSinkFilter> fileSink;
  212384. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  212385. if (SUCCEEDED (hr))
  212386. {
  212387. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  212388. if (SUCCEEDED (hr))
  212389. {
  212390. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  212391. if (SUCCEEDED (hr))
  212392. {
  212393. ComSmartPtr <IConfigAsfWriter> asfConfig;
  212394. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  212395. asfConfig->SetIndexMode (true);
  212396. ComSmartPtr <IWMProfileManager> profileManager;
  212397. hr = WMCreateProfileManager (&profileManager);
  212398. // This gibberish is the DirectShow profile for a video-only wmv file.
  212399. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  212400. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  212401. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  212402. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  212403. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  212404. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  212405. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  212406. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  212407. prof = prof.replace ("$WIDTH", String (width))
  212408. .replace ("$HEIGHT", String (height));
  212409. ComSmartPtr <IWMProfile> currentProfile;
  212410. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  212411. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  212412. if (SUCCEEDED (hr))
  212413. {
  212414. ComSmartPtr <IPin> asfWriterInputPin;
  212415. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  212416. {
  212417. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  212418. if (SUCCEEDED (hr)
  212419. && ok && activeUsers > 0
  212420. && SUCCEEDED (mediaControl->Run()))
  212421. {
  212422. return true;
  212423. }
  212424. }
  212425. }
  212426. }
  212427. }
  212428. }
  212429. }
  212430. removeFileCaptureFilter();
  212431. if (ok && activeUsers > 0)
  212432. mediaControl->Run();
  212433. return false;
  212434. }
  212435. void removeFileCaptureFilter()
  212436. {
  212437. mediaControl->Stop();
  212438. if (asfWriter != 0)
  212439. {
  212440. graphBuilder->RemoveFilter (asfWriter);
  212441. asfWriter = 0;
  212442. }
  212443. if (ok && activeUsers > 0)
  212444. mediaControl->Run();
  212445. }
  212446. void addListener (CameraImageListener* listenerToAdd)
  212447. {
  212448. const ScopedLock sl (listenerLock);
  212449. if (listeners.size() == 0)
  212450. addUser();
  212451. listeners.addIfNotAlreadyThere (listenerToAdd);
  212452. }
  212453. void removeListener (CameraImageListener* listenerToRemove)
  212454. {
  212455. const ScopedLock sl (listenerLock);
  212456. listeners.removeValue (listenerToRemove);
  212457. if (listeners.size() == 0)
  212458. removeUser();
  212459. }
  212460. void callListeners (Image& image)
  212461. {
  212462. const ScopedLock sl (listenerLock);
  212463. for (int i = listeners.size(); --i >= 0;)
  212464. {
  212465. CameraImageListener* l = (CameraImageListener*) listeners[i];
  212466. if (l != 0)
  212467. l->imageReceived (image);
  212468. }
  212469. }
  212470. class DShowCaptureViewerComp : public Component,
  212471. public ChangeListener
  212472. {
  212473. public:
  212474. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  212475. : owner (owner_)
  212476. {
  212477. setOpaque (true);
  212478. owner->addChangeListener (this);
  212479. owner->addUser();
  212480. owner->viewerComps.add (this);
  212481. setSize (owner_->width, owner_->height);
  212482. }
  212483. ~DShowCaptureViewerComp()
  212484. {
  212485. if (owner != 0)
  212486. {
  212487. owner->viewerComps.removeValue (this);
  212488. owner->removeUser();
  212489. owner->removeChangeListener (this);
  212490. }
  212491. }
  212492. void ownerDeleted()
  212493. {
  212494. owner = 0;
  212495. }
  212496. void paint (Graphics& g)
  212497. {
  212498. g.setColour (Colours::black);
  212499. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  212500. if (owner != 0)
  212501. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  212502. else
  212503. g.fillAll (Colours::black);
  212504. }
  212505. void changeListenerCallback (void*)
  212506. {
  212507. repaint();
  212508. }
  212509. private:
  212510. DShowCameraDeviceInteral* owner;
  212511. };
  212512. bool ok;
  212513. int width, height;
  212514. Time firstRecordedTime;
  212515. VoidArray viewerComps;
  212516. private:
  212517. CameraDevice* const owner;
  212518. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212519. ComSmartPtr <IBaseFilter> filter;
  212520. ComSmartPtr <IBaseFilter> smartTee;
  212521. ComSmartPtr <IGraphBuilder> graphBuilder;
  212522. ComSmartPtr <ISampleGrabber> sampleGrabber;
  212523. ComSmartPtr <IMediaControl> mediaControl;
  212524. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  212525. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  212526. ComSmartPtr <IBaseFilter> asfWriter;
  212527. int activeUsers;
  212528. Array <int> widths, heights;
  212529. DWORD graphRegistrationID;
  212530. CriticalSection imageSwapLock;
  212531. bool imageNeedsFlipping;
  212532. Image* loadingImage;
  212533. Image* activeImage;
  212534. bool recordNextFrameTime;
  212535. void getVideoSizes (IAMStreamConfig* const streamConfig)
  212536. {
  212537. widths.clear();
  212538. heights.clear();
  212539. int count = 0, size = 0;
  212540. streamConfig->GetNumberOfCapabilities (&count, &size);
  212541. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212542. {
  212543. for (int i = 0; i < count; ++i)
  212544. {
  212545. VIDEO_STREAM_CONFIG_CAPS scc;
  212546. AM_MEDIA_TYPE* config;
  212547. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212548. if (SUCCEEDED (hr))
  212549. {
  212550. const int w = scc.InputSize.cx;
  212551. const int h = scc.InputSize.cy;
  212552. bool duplicate = false;
  212553. for (int j = widths.size(); --j >= 0;)
  212554. {
  212555. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  212556. {
  212557. duplicate = true;
  212558. break;
  212559. }
  212560. }
  212561. if (! duplicate)
  212562. {
  212563. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  212564. widths.add (w);
  212565. heights.add (h);
  212566. }
  212567. deleteMediaType (config);
  212568. }
  212569. }
  212570. }
  212571. }
  212572. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  212573. const int minWidth, const int minHeight,
  212574. const int maxWidth, const int maxHeight)
  212575. {
  212576. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  212577. streamConfig->GetNumberOfCapabilities (&count, &size);
  212578. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212579. {
  212580. AM_MEDIA_TYPE* config;
  212581. VIDEO_STREAM_CONFIG_CAPS scc;
  212582. for (int i = 0; i < count; ++i)
  212583. {
  212584. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212585. if (SUCCEEDED (hr))
  212586. {
  212587. if (scc.InputSize.cx >= minWidth
  212588. && scc.InputSize.cy >= minHeight
  212589. && scc.InputSize.cx <= maxWidth
  212590. && scc.InputSize.cy <= maxHeight)
  212591. {
  212592. int area = scc.InputSize.cx * scc.InputSize.cy;
  212593. if (area > bestArea)
  212594. {
  212595. bestIndex = i;
  212596. bestArea = area;
  212597. }
  212598. }
  212599. deleteMediaType (config);
  212600. }
  212601. }
  212602. if (bestIndex >= 0)
  212603. {
  212604. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  212605. hr = streamConfig->SetFormat (config);
  212606. deleteMediaType (config);
  212607. return SUCCEEDED (hr);
  212608. }
  212609. }
  212610. return false;
  212611. }
  212612. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  212613. {
  212614. ComSmartPtr <IEnumPins> enumerator;
  212615. ComSmartPtr <IPin> pin;
  212616. filter->EnumPins (&enumerator);
  212617. while (enumerator->Next (1, &pin, 0) == S_OK)
  212618. {
  212619. PIN_DIRECTION dir;
  212620. pin->QueryDirection (&dir);
  212621. if (wantedDirection == dir)
  212622. {
  212623. PIN_INFO info;
  212624. zerostruct (info);
  212625. pin->QueryPinInfo (&info);
  212626. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  212627. {
  212628. pin->AddRef();
  212629. *result = pin;
  212630. return true;
  212631. }
  212632. }
  212633. }
  212634. return false;
  212635. }
  212636. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  212637. {
  212638. ComSmartPtr <IPin> in, out;
  212639. return getPin (first, PINDIR_OUTPUT, &out)
  212640. && getPin (second, PINDIR_INPUT, &in)
  212641. && SUCCEEDED (graphBuilder->Connect (out, in));
  212642. }
  212643. bool addGraphToRot()
  212644. {
  212645. ComSmartPtr <IRunningObjectTable> rot;
  212646. if (FAILED (GetRunningObjectTable (0, &rot)))
  212647. return false;
  212648. ComSmartPtr <IMoniker> moniker;
  212649. WCHAR buffer[128];
  212650. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  212651. if (FAILED (hr))
  212652. return false;
  212653. graphRegistrationID = 0;
  212654. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  212655. }
  212656. void removeGraphFromRot()
  212657. {
  212658. ComSmartPtr <IRunningObjectTable> rot;
  212659. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  212660. rot->Revoke (graphRegistrationID);
  212661. }
  212662. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  212663. {
  212664. if (pmt->cbFormat != 0)
  212665. CoTaskMemFree ((PVOID) pmt->pbFormat);
  212666. if (pmt->pUnk != 0)
  212667. pmt->pUnk->Release();
  212668. CoTaskMemFree (pmt);
  212669. }
  212670. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  212671. {
  212672. public:
  212673. GrabberCallback (DShowCameraDeviceInteral& owner_)
  212674. : owner (owner_)
  212675. {
  212676. }
  212677. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  212678. {
  212679. return E_FAIL;
  212680. }
  212681. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  212682. {
  212683. owner.handleFrame (time, buffer, bufferSize);
  212684. return S_OK;
  212685. }
  212686. private:
  212687. DShowCameraDeviceInteral& owner;
  212688. GrabberCallback (const GrabberCallback&);
  212689. GrabberCallback& operator= (const GrabberCallback&);
  212690. };
  212691. ComSmartPtr <GrabberCallback> callback;
  212692. VoidArray listeners;
  212693. CriticalSection listenerLock;
  212694. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  212695. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  212696. };
  212697. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  212698. : name (name_)
  212699. {
  212700. isRecording = false;
  212701. }
  212702. CameraDevice::~CameraDevice()
  212703. {
  212704. stopRecording();
  212705. delete static_cast <DShowCameraDeviceInteral*> (internal);
  212706. internal = 0;
  212707. }
  212708. Component* CameraDevice::createViewerComponent()
  212709. {
  212710. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  212711. }
  212712. const String CameraDevice::getFileExtension()
  212713. {
  212714. return ".wmv";
  212715. }
  212716. void CameraDevice::startRecordingToFile (const File& file, int quality)
  212717. {
  212718. stopRecording();
  212719. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212720. d->addUser();
  212721. isRecording = d->createFileCaptureFilter (file);
  212722. }
  212723. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  212724. {
  212725. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212726. return d->firstRecordedTime;
  212727. }
  212728. void CameraDevice::stopRecording()
  212729. {
  212730. if (isRecording)
  212731. {
  212732. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212733. d->removeFileCaptureFilter();
  212734. d->removeUser();
  212735. isRecording = false;
  212736. }
  212737. }
  212738. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  212739. {
  212740. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212741. if (listenerToAdd != 0)
  212742. d->addListener (listenerToAdd);
  212743. }
  212744. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  212745. {
  212746. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212747. if (listenerToRemove != 0)
  212748. d->removeListener (listenerToRemove);
  212749. }
  212750. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  212751. const int deviceIndexToOpen,
  212752. String& name)
  212753. {
  212754. int index = 0;
  212755. ComSmartPtr <IBaseFilter> result;
  212756. ComSmartPtr <ICreateDevEnum> pDevEnum;
  212757. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  212758. if (SUCCEEDED (hr))
  212759. {
  212760. ComSmartPtr <IEnumMoniker> enumerator;
  212761. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  212762. if (SUCCEEDED (hr) && enumerator != 0)
  212763. {
  212764. ComSmartPtr <IBaseFilter> captureFilter;
  212765. ComSmartPtr <IMoniker> moniker;
  212766. ULONG fetched;
  212767. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  212768. {
  212769. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  212770. if (SUCCEEDED (hr))
  212771. {
  212772. ComSmartPtr <IPropertyBag> propertyBag;
  212773. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  212774. if (SUCCEEDED (hr))
  212775. {
  212776. VARIANT var;
  212777. var.vt = VT_BSTR;
  212778. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  212779. propertyBag = 0;
  212780. if (SUCCEEDED (hr))
  212781. {
  212782. if (names != 0)
  212783. names->add (var.bstrVal);
  212784. if (index == deviceIndexToOpen)
  212785. {
  212786. name = var.bstrVal;
  212787. result = captureFilter;
  212788. captureFilter = 0;
  212789. break;
  212790. }
  212791. ++index;
  212792. }
  212793. moniker = 0;
  212794. }
  212795. captureFilter = 0;
  212796. }
  212797. }
  212798. }
  212799. }
  212800. return result;
  212801. }
  212802. const StringArray CameraDevice::getAvailableDevices()
  212803. {
  212804. StringArray devs;
  212805. String dummy;
  212806. enumerateCameras (&devs, -1, dummy);
  212807. return devs;
  212808. }
  212809. CameraDevice* CameraDevice::openDevice (int index,
  212810. int minWidth, int minHeight,
  212811. int maxWidth, int maxHeight)
  212812. {
  212813. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212814. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  212815. if (SUCCEEDED (hr))
  212816. {
  212817. String name;
  212818. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  212819. if (filter != 0)
  212820. {
  212821. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  212822. DShowCameraDeviceInteral* const intern
  212823. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  212824. minWidth, minHeight, maxWidth, maxHeight);
  212825. cam->internal = intern;
  212826. if (intern->ok)
  212827. return cam.release();
  212828. }
  212829. }
  212830. return 0;
  212831. }
  212832. #endif
  212833. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  212834. #endif
  212835. // Auto-link the other win32 libs that are needed by library calls..
  212836. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  212837. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  212838. // Auto-links to various win32 libs that are needed by library calls..
  212839. #pragma comment(lib, "kernel32.lib")
  212840. #pragma comment(lib, "user32.lib")
  212841. #pragma comment(lib, "shell32.lib")
  212842. #pragma comment(lib, "gdi32.lib")
  212843. #pragma comment(lib, "vfw32.lib")
  212844. #pragma comment(lib, "comdlg32.lib")
  212845. #pragma comment(lib, "winmm.lib")
  212846. #pragma comment(lib, "wininet.lib")
  212847. #pragma comment(lib, "ole32.lib")
  212848. #pragma comment(lib, "oleaut32.lib")
  212849. #pragma comment(lib, "advapi32.lib")
  212850. #pragma comment(lib, "ws2_32.lib")
  212851. #pragma comment(lib, "comsupp.lib")
  212852. #pragma comment(lib, "version.lib")
  212853. #if JUCE_OPENGL
  212854. #pragma comment(lib, "OpenGL32.Lib")
  212855. #pragma comment(lib, "GlU32.Lib")
  212856. #endif
  212857. #if JUCE_QUICKTIME
  212858. #pragma comment (lib, "QTMLClient.lib")
  212859. #endif
  212860. #if JUCE_USE_CAMERA
  212861. #pragma comment (lib, "Strmiids.lib")
  212862. #pragma comment (lib, "wmvcore.lib")
  212863. #endif
  212864. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  212865. #endif
  212866. END_JUCE_NAMESPACE
  212867. #endif
  212868. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  212869. #endif
  212870. #if JUCE_LINUX
  212871. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  212872. /*
  212873. This file wraps together all the mac-specific code, so that
  212874. we can include all the native headers just once, and compile all our
  212875. platform-specific stuff in one big lump, keeping it out of the way of
  212876. the rest of the codebase.
  212877. */
  212878. #if JUCE_LINUX
  212879. BEGIN_JUCE_NAMESPACE
  212880. #define JUCE_INCLUDED_FILE 1
  212881. // Now include the actual code files..
  212882. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  212883. /*
  212884. This file contains posix routines that are common to both the Linux and Mac builds.
  212885. It gets included directly in the cpp files for these platforms.
  212886. */
  212887. CriticalSection::CriticalSection() throw()
  212888. {
  212889. pthread_mutexattr_t atts;
  212890. pthread_mutexattr_init (&atts);
  212891. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  212892. pthread_mutex_init (&internal, &atts);
  212893. }
  212894. CriticalSection::~CriticalSection() throw()
  212895. {
  212896. pthread_mutex_destroy (&internal);
  212897. }
  212898. void CriticalSection::enter() const throw()
  212899. {
  212900. pthread_mutex_lock (&internal);
  212901. }
  212902. bool CriticalSection::tryEnter() const throw()
  212903. {
  212904. return pthread_mutex_trylock (&internal) == 0;
  212905. }
  212906. void CriticalSection::exit() const throw()
  212907. {
  212908. pthread_mutex_unlock (&internal);
  212909. }
  212910. class WaitableEventImpl
  212911. {
  212912. public:
  212913. WaitableEventImpl (const bool manualReset_)
  212914. : triggered (false),
  212915. manualReset (manualReset_)
  212916. {
  212917. pthread_cond_init (&condition, 0);
  212918. pthread_mutex_init (&mutex, 0);
  212919. }
  212920. ~WaitableEventImpl()
  212921. {
  212922. pthread_cond_destroy (&condition);
  212923. pthread_mutex_destroy (&mutex);
  212924. }
  212925. bool wait (const int timeOutMillisecs) throw()
  212926. {
  212927. pthread_mutex_lock (&mutex);
  212928. if (! triggered)
  212929. {
  212930. if (timeOutMillisecs < 0)
  212931. {
  212932. do
  212933. {
  212934. pthread_cond_wait (&condition, &mutex);
  212935. }
  212936. while (! triggered);
  212937. }
  212938. else
  212939. {
  212940. struct timeval now;
  212941. gettimeofday (&now, 0);
  212942. struct timespec time;
  212943. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  212944. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  212945. if (time.tv_nsec >= 1000000000)
  212946. {
  212947. time.tv_nsec -= 1000000000;
  212948. time.tv_sec++;
  212949. }
  212950. do
  212951. {
  212952. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  212953. {
  212954. pthread_mutex_unlock (&mutex);
  212955. return false;
  212956. }
  212957. }
  212958. while (! triggered);
  212959. }
  212960. }
  212961. if (! manualReset)
  212962. triggered = false;
  212963. pthread_mutex_unlock (&mutex);
  212964. return true;
  212965. }
  212966. void signal() throw()
  212967. {
  212968. pthread_mutex_lock (&mutex);
  212969. triggered = true;
  212970. pthread_cond_broadcast (&condition);
  212971. pthread_mutex_unlock (&mutex);
  212972. }
  212973. void reset() throw()
  212974. {
  212975. pthread_mutex_lock (&mutex);
  212976. triggered = false;
  212977. pthread_mutex_unlock (&mutex);
  212978. }
  212979. private:
  212980. pthread_cond_t condition;
  212981. pthread_mutex_t mutex;
  212982. bool triggered;
  212983. const bool manualReset;
  212984. WaitableEventImpl (const WaitableEventImpl&);
  212985. WaitableEventImpl& operator= (const WaitableEventImpl&);
  212986. };
  212987. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  212988. : internal (new WaitableEventImpl (manualReset))
  212989. {
  212990. }
  212991. WaitableEvent::~WaitableEvent() throw()
  212992. {
  212993. delete static_cast <WaitableEventImpl*> (internal);
  212994. }
  212995. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  212996. {
  212997. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  212998. }
  212999. void WaitableEvent::signal() const throw()
  213000. {
  213001. static_cast <WaitableEventImpl*> (internal)->signal();
  213002. }
  213003. void WaitableEvent::reset() const throw()
  213004. {
  213005. static_cast <WaitableEventImpl*> (internal)->reset();
  213006. }
  213007. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  213008. {
  213009. struct timespec time;
  213010. time.tv_sec = millisecs / 1000;
  213011. time.tv_nsec = (millisecs % 1000) * 1000000;
  213012. nanosleep (&time, 0);
  213013. }
  213014. const juce_wchar File::separator = '/';
  213015. const String File::separatorString ("/");
  213016. const File File::getCurrentWorkingDirectory()
  213017. {
  213018. HeapBlock<char> heapBuffer;
  213019. char localBuffer [1024];
  213020. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  213021. int bufferSize = 4096;
  213022. while (cwd == 0 && errno == ERANGE)
  213023. {
  213024. heapBuffer.malloc (bufferSize);
  213025. cwd = getcwd (heapBuffer, bufferSize - 1);
  213026. bufferSize += 1024;
  213027. }
  213028. return File (String::fromUTF8 (cwd));
  213029. }
  213030. bool File::setAsCurrentWorkingDirectory() const
  213031. {
  213032. return chdir (getFullPathName().toUTF8()) == 0;
  213033. }
  213034. static bool juce_stat (const String& fileName, struct stat& info)
  213035. {
  213036. return fileName.isNotEmpty()
  213037. && (stat (fileName.toUTF8(), &info) == 0);
  213038. }
  213039. bool File::isDirectory() const
  213040. {
  213041. struct stat info;
  213042. return fullPath.isEmpty()
  213043. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  213044. }
  213045. bool File::exists() const
  213046. {
  213047. return fullPath.isNotEmpty()
  213048. && access (fullPath.toUTF8(), F_OK) == 0;
  213049. }
  213050. bool File::existsAsFile() const
  213051. {
  213052. return exists() && ! isDirectory();
  213053. }
  213054. int64 File::getSize() const
  213055. {
  213056. struct stat info;
  213057. return juce_stat (fullPath, info) ? info.st_size : 0;
  213058. }
  213059. bool File::hasWriteAccess() const
  213060. {
  213061. if (exists())
  213062. return access (fullPath.toUTF8(), W_OK) == 0;
  213063. if ((! isDirectory()) && fullPath.containsChar (separator))
  213064. return getParentDirectory().hasWriteAccess();
  213065. return false;
  213066. }
  213067. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  213068. {
  213069. struct stat info;
  213070. const int res = stat (fullPath.toUTF8(), &info);
  213071. if (res != 0)
  213072. return false;
  213073. info.st_mode &= 0777; // Just permissions
  213074. if (shouldBeReadOnly)
  213075. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  213076. else
  213077. // Give everybody write permission?
  213078. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  213079. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  213080. }
  213081. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  213082. {
  213083. modificationTime = 0;
  213084. accessTime = 0;
  213085. creationTime = 0;
  213086. struct stat info;
  213087. const int res = stat (fullPath.toUTF8(), &info);
  213088. if (res == 0)
  213089. {
  213090. modificationTime = (int64) info.st_mtime * 1000;
  213091. accessTime = (int64) info.st_atime * 1000;
  213092. creationTime = (int64) info.st_ctime * 1000;
  213093. }
  213094. }
  213095. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  213096. {
  213097. struct utimbuf times;
  213098. times.actime = (time_t) (accessTime / 1000);
  213099. times.modtime = (time_t) (modificationTime / 1000);
  213100. return utime (fullPath.toUTF8(), &times) == 0;
  213101. }
  213102. bool File::deleteFile() const
  213103. {
  213104. if (! exists())
  213105. return true;
  213106. else if (isDirectory())
  213107. return rmdir (fullPath.toUTF8()) == 0;
  213108. else
  213109. return remove (fullPath.toUTF8()) == 0;
  213110. }
  213111. bool File::moveInternal (const File& dest) const
  213112. {
  213113. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  213114. return true;
  213115. if (hasWriteAccess() && copyInternal (dest))
  213116. {
  213117. if (deleteFile())
  213118. return true;
  213119. dest.deleteFile();
  213120. }
  213121. return false;
  213122. }
  213123. void File::createDirectoryInternal (const String& fileName) const
  213124. {
  213125. mkdir (fileName.toUTF8(), 0777);
  213126. }
  213127. void* juce_fileOpen (const File& file, bool forWriting)
  213128. {
  213129. int flags = O_RDONLY;
  213130. if (forWriting)
  213131. {
  213132. if (file.exists())
  213133. {
  213134. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  213135. if (f != -1)
  213136. lseek (f, 0, SEEK_END);
  213137. return (void*) f;
  213138. }
  213139. else
  213140. {
  213141. flags = O_RDWR + O_CREAT;
  213142. }
  213143. }
  213144. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  213145. }
  213146. void juce_fileClose (void* handle)
  213147. {
  213148. if (handle != 0)
  213149. close ((int) (pointer_sized_int) handle);
  213150. }
  213151. int juce_fileRead (void* handle, void* buffer, int size)
  213152. {
  213153. if (handle != 0)
  213154. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  213155. return 0;
  213156. }
  213157. int juce_fileWrite (void* handle, const void* buffer, int size)
  213158. {
  213159. if (handle != 0)
  213160. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  213161. return 0;
  213162. }
  213163. int64 juce_fileSetPosition (void* handle, int64 pos)
  213164. {
  213165. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  213166. return pos;
  213167. return -1;
  213168. }
  213169. int64 FileOutputStream::getPositionInternal() const
  213170. {
  213171. if (fileHandle != 0)
  213172. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  213173. return -1;
  213174. }
  213175. void FileOutputStream::flushInternal()
  213176. {
  213177. if (fileHandle != 0)
  213178. fsync ((int) (pointer_sized_int) fileHandle);
  213179. }
  213180. const File juce_getExecutableFile()
  213181. {
  213182. Dl_info exeInfo;
  213183. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  213184. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  213185. }
  213186. // if this file doesn't exist, find a parent of it that does..
  213187. static bool juce_doStatFS (File f, struct statfs& result)
  213188. {
  213189. for (int i = 5; --i >= 0;)
  213190. {
  213191. if (f.exists())
  213192. break;
  213193. f = f.getParentDirectory();
  213194. }
  213195. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  213196. }
  213197. int64 File::getBytesFreeOnVolume() const
  213198. {
  213199. struct statfs buf;
  213200. if (juce_doStatFS (*this, buf))
  213201. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  213202. return 0;
  213203. }
  213204. int64 File::getVolumeTotalSize() const
  213205. {
  213206. struct statfs buf;
  213207. if (juce_doStatFS (*this, buf))
  213208. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  213209. return 0;
  213210. }
  213211. const String File::getVolumeLabel() const
  213212. {
  213213. #if JUCE_MAC
  213214. struct VolAttrBuf
  213215. {
  213216. u_int32_t length;
  213217. attrreference_t mountPointRef;
  213218. char mountPointSpace [MAXPATHLEN];
  213219. } attrBuf;
  213220. struct attrlist attrList;
  213221. zerostruct (attrList);
  213222. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  213223. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  213224. File f (*this);
  213225. for (;;)
  213226. {
  213227. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  213228. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  213229. (int) attrBuf.mountPointRef.attr_length);
  213230. const File parent (f.getParentDirectory());
  213231. if (f == parent)
  213232. break;
  213233. f = parent;
  213234. }
  213235. #endif
  213236. return String::empty;
  213237. }
  213238. int File::getVolumeSerialNumber() const
  213239. {
  213240. return 0; // xxx
  213241. }
  213242. void juce_runSystemCommand (const String& command)
  213243. {
  213244. int result = system (command.toUTF8());
  213245. (void) result;
  213246. }
  213247. const String juce_getOutputFromCommand (const String& command)
  213248. {
  213249. // slight bodge here, as we just pipe the output into a temp file and read it...
  213250. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  213251. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  213252. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  213253. String result (tempFile.loadFileAsString());
  213254. tempFile.deleteFile();
  213255. return result;
  213256. }
  213257. class InterProcessLock::Pimpl
  213258. {
  213259. public:
  213260. Pimpl (const String& name, const int timeOutMillisecs)
  213261. : handle (0), refCount (1)
  213262. {
  213263. #if JUCE_MAC
  213264. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  213265. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  213266. #else
  213267. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  213268. #endif
  213269. temp.create();
  213270. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  213271. if (handle != 0)
  213272. {
  213273. struct flock fl;
  213274. zerostruct (fl);
  213275. fl.l_whence = SEEK_SET;
  213276. fl.l_type = F_WRLCK;
  213277. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  213278. for (;;)
  213279. {
  213280. const int result = fcntl (handle, F_SETLK, &fl);
  213281. if (result >= 0)
  213282. return;
  213283. if (errno != EINTR)
  213284. {
  213285. if (timeOutMillisecs == 0
  213286. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  213287. break;
  213288. Thread::sleep (10);
  213289. }
  213290. }
  213291. }
  213292. closeFile();
  213293. }
  213294. ~Pimpl()
  213295. {
  213296. closeFile();
  213297. }
  213298. void closeFile()
  213299. {
  213300. if (handle != 0)
  213301. {
  213302. struct flock fl;
  213303. zerostruct (fl);
  213304. fl.l_whence = SEEK_SET;
  213305. fl.l_type = F_UNLCK;
  213306. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  213307. {}
  213308. close (handle);
  213309. handle = 0;
  213310. }
  213311. }
  213312. int handle, refCount;
  213313. };
  213314. InterProcessLock::InterProcessLock (const String& name_)
  213315. : name (name_)
  213316. {
  213317. }
  213318. InterProcessLock::~InterProcessLock()
  213319. {
  213320. }
  213321. bool InterProcessLock::enter (const int timeOutMillisecs)
  213322. {
  213323. const ScopedLock sl (lock);
  213324. if (pimpl == 0)
  213325. {
  213326. pimpl = new Pimpl (name, timeOutMillisecs);
  213327. if (pimpl->handle == 0)
  213328. pimpl = 0;
  213329. }
  213330. else
  213331. {
  213332. pimpl->refCount++;
  213333. }
  213334. return pimpl != 0;
  213335. }
  213336. void InterProcessLock::exit()
  213337. {
  213338. const ScopedLock sl (lock);
  213339. // Trying to release the lock too many times!
  213340. jassert (pimpl != 0);
  213341. if (pimpl != 0 && --(pimpl->refCount) == 0)
  213342. pimpl = 0;
  213343. }
  213344. /*** End of inlined file: juce_posix_SharedCode.h ***/
  213345. /*** Start of inlined file: juce_linux_Files.cpp ***/
  213346. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213347. // compiled on its own).
  213348. #if JUCE_INCLUDED_FILE
  213349. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  213350. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  213351. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  213352. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  213353. bool File::copyInternal (const File& dest) const
  213354. {
  213355. FileInputStream in (*this);
  213356. if (dest.deleteFile())
  213357. {
  213358. {
  213359. FileOutputStream out (dest);
  213360. if (out.failedToOpen())
  213361. return false;
  213362. if (out.writeFromInputStream (in, -1) == getSize())
  213363. return true;
  213364. }
  213365. dest.deleteFile();
  213366. }
  213367. return false;
  213368. }
  213369. void File::findFileSystemRoots (Array<File>& destArray)
  213370. {
  213371. destArray.add (File ("/"));
  213372. }
  213373. bool File::isOnCDRomDrive() const
  213374. {
  213375. struct statfs buf;
  213376. return statfs (getFullPathName().toUTF8(), &buf) == 0
  213377. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  213378. }
  213379. bool File::isOnHardDisk() const
  213380. {
  213381. struct statfs buf;
  213382. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  213383. {
  213384. switch (buf.f_type)
  213385. {
  213386. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  213387. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  213388. case U_NFS_SUPER_MAGIC: // Network NFS
  213389. case U_SMB_SUPER_MAGIC: // Network Samba
  213390. return false;
  213391. default:
  213392. // Assume anything else is a hard-disk (but note it could
  213393. // be a RAM disk. There isn't a good way of determining
  213394. // this for sure)
  213395. return true;
  213396. }
  213397. }
  213398. // Assume so if this fails for some reason
  213399. return true;
  213400. }
  213401. bool File::isOnRemovableDrive() const
  213402. {
  213403. jassertfalse // xxx not implemented for linux!
  213404. return false;
  213405. }
  213406. bool File::isHidden() const
  213407. {
  213408. return getFileName().startsWithChar ('.');
  213409. }
  213410. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  213411. const File File::getSpecialLocation (const SpecialLocationType type)
  213412. {
  213413. switch (type)
  213414. {
  213415. case userHomeDirectory:
  213416. {
  213417. const char* homeDir = getenv ("HOME");
  213418. if (homeDir == 0)
  213419. {
  213420. struct passwd* const pw = getpwuid (getuid());
  213421. if (pw != 0)
  213422. homeDir = pw->pw_dir;
  213423. }
  213424. return File (String::fromUTF8 (homeDir));
  213425. }
  213426. case userDocumentsDirectory:
  213427. case userMusicDirectory:
  213428. case userMoviesDirectory:
  213429. case userApplicationDataDirectory:
  213430. return File ("~");
  213431. case userDesktopDirectory:
  213432. return File ("~/Desktop");
  213433. case commonApplicationDataDirectory:
  213434. return File ("/var");
  213435. case globalApplicationsDirectory:
  213436. return File ("/usr");
  213437. case tempDirectory:
  213438. {
  213439. File tmp ("/var/tmp");
  213440. if (! tmp.isDirectory())
  213441. {
  213442. tmp = "/tmp";
  213443. if (! tmp.isDirectory())
  213444. tmp = File::getCurrentWorkingDirectory();
  213445. }
  213446. return tmp;
  213447. }
  213448. case invokedExecutableFile:
  213449. if (juce_Argv0 != 0)
  213450. return File (String::fromUTF8 (juce_Argv0));
  213451. // deliberate fall-through...
  213452. case currentExecutableFile:
  213453. case currentApplicationFile:
  213454. return juce_getExecutableFile();
  213455. default:
  213456. jassertfalse // unknown type?
  213457. break;
  213458. }
  213459. return File::nonexistent;
  213460. }
  213461. const String File::getVersion() const
  213462. {
  213463. return String::empty; // xxx not yet implemented
  213464. }
  213465. const File File::getLinkedTarget() const
  213466. {
  213467. char buffer [4096];
  213468. size_t numChars = readlink (getFullPathName().toUTF8(),
  213469. buffer, sizeof (buffer));
  213470. if (numChars > 0 && numChars <= sizeof (buffer))
  213471. return File (String::fromUTF8 (buffer, (int) numChars));
  213472. return *this;
  213473. }
  213474. bool File::moveToTrash() const
  213475. {
  213476. if (! exists())
  213477. return true;
  213478. File trashCan ("~/.Trash");
  213479. if (! trashCan.isDirectory())
  213480. trashCan = "~/.local/share/Trash/files";
  213481. if (! trashCan.isDirectory())
  213482. return false;
  213483. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  213484. getFileExtension()));
  213485. }
  213486. class DirectoryIterator::NativeIterator::Pimpl
  213487. {
  213488. public:
  213489. Pimpl (const File& directory, const String& wildCard_)
  213490. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  213491. wildCard (wildCard_),
  213492. dir (opendir (directory.getFullPathName().toUTF8()))
  213493. {
  213494. if (wildCard == "*.*")
  213495. wildCard = "*";
  213496. wildcardUTF8 = wildCard.toUTF8();
  213497. }
  213498. ~Pimpl()
  213499. {
  213500. if (dir != 0)
  213501. closedir (dir);
  213502. }
  213503. bool next (String& filenameFound,
  213504. bool* const isDir, bool* const isHidden, int64* const fileSize,
  213505. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  213506. {
  213507. if (dir == 0)
  213508. return false;
  213509. for (;;)
  213510. {
  213511. struct dirent* const de = readdir (dir);
  213512. if (de == 0)
  213513. return false;
  213514. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  213515. {
  213516. filenameFound = String::fromUTF8 (de->d_name);
  213517. const String path (parentDir + filenameFound);
  213518. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  213519. {
  213520. struct stat info;
  213521. const bool statOk = juce_stat (path, info);
  213522. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  213523. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  213524. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  213525. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  213526. }
  213527. if (isHidden != 0)
  213528. *isHidden = filenameFound.startsWithChar ('.');
  213529. if (isReadOnly != 0)
  213530. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  213531. return true;
  213532. }
  213533. }
  213534. }
  213535. private:
  213536. String parentDir, wildCard;
  213537. const char* wildcardUTF8;
  213538. DIR* dir;
  213539. Pimpl (const Pimpl&);
  213540. Pimpl& operator= (const Pimpl&);
  213541. };
  213542. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  213543. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  213544. {
  213545. }
  213546. DirectoryIterator::NativeIterator::~NativeIterator()
  213547. {
  213548. }
  213549. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  213550. bool* const isDir, bool* const isHidden, int64* const fileSize,
  213551. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  213552. {
  213553. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  213554. }
  213555. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  213556. {
  213557. String cmdString (fileName.replace (" ", "\\ ",false));
  213558. cmdString << " " << parameters;
  213559. if (URL::isProbablyAWebsiteURL (fileName)
  213560. || cmdString.startsWithIgnoreCase ("file:")
  213561. || URL::isProbablyAnEmailAddress (fileName))
  213562. {
  213563. // create a command that tries to launch a bunch of likely browsers
  213564. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  213565. StringArray cmdLines;
  213566. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  213567. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  213568. cmdString = cmdLines.joinIntoString (" || ");
  213569. }
  213570. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  213571. const int cpid = fork();
  213572. if (cpid == 0)
  213573. {
  213574. setsid();
  213575. // Child process
  213576. execve (argv[0], (char**) argv, environ);
  213577. exit (0);
  213578. }
  213579. return cpid >= 0;
  213580. }
  213581. void File::revealToUser() const
  213582. {
  213583. if (isDirectory())
  213584. startAsProcess();
  213585. else if (getParentDirectory().exists())
  213586. getParentDirectory().startAsProcess();
  213587. }
  213588. #endif
  213589. /*** End of inlined file: juce_linux_Files.cpp ***/
  213590. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  213591. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  213592. // compiled on its own).
  213593. #if JUCE_INCLUDED_FILE
  213594. struct NamedPipeInternal
  213595. {
  213596. String pipeInName, pipeOutName;
  213597. int pipeIn, pipeOut;
  213598. bool volatile createdPipe, blocked, stopReadOperation;
  213599. static void signalHandler (int) {}
  213600. };
  213601. void NamedPipe::cancelPendingReads()
  213602. {
  213603. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  213604. {
  213605. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213606. intern->stopReadOperation = true;
  213607. char buffer [1] = { 0 };
  213608. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  213609. (void) bytesWritten;
  213610. int timeout = 2000;
  213611. while (intern->blocked && --timeout >= 0)
  213612. Thread::sleep (2);
  213613. intern->stopReadOperation = false;
  213614. }
  213615. }
  213616. void NamedPipe::close()
  213617. {
  213618. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213619. if (intern != 0)
  213620. {
  213621. internal = 0;
  213622. if (intern->pipeIn != -1)
  213623. ::close (intern->pipeIn);
  213624. if (intern->pipeOut != -1)
  213625. ::close (intern->pipeOut);
  213626. if (intern->createdPipe)
  213627. {
  213628. unlink (intern->pipeInName.toUTF8());
  213629. unlink (intern->pipeOutName.toUTF8());
  213630. }
  213631. delete intern;
  213632. }
  213633. }
  213634. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  213635. {
  213636. close();
  213637. NamedPipeInternal* const intern = new NamedPipeInternal();
  213638. internal = intern;
  213639. intern->createdPipe = createPipe;
  213640. intern->blocked = false;
  213641. intern->stopReadOperation = false;
  213642. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  213643. siginterrupt (SIGPIPE, 1);
  213644. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  213645. intern->pipeInName = pipePath + "_in";
  213646. intern->pipeOutName = pipePath + "_out";
  213647. intern->pipeIn = -1;
  213648. intern->pipeOut = -1;
  213649. if (createPipe)
  213650. {
  213651. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  213652. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  213653. {
  213654. delete intern;
  213655. internal = 0;
  213656. return false;
  213657. }
  213658. }
  213659. return true;
  213660. }
  213661. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  213662. {
  213663. int bytesRead = -1;
  213664. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213665. if (intern != 0)
  213666. {
  213667. intern->blocked = true;
  213668. if (intern->pipeIn == -1)
  213669. {
  213670. if (intern->createdPipe)
  213671. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  213672. else
  213673. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  213674. if (intern->pipeIn == -1)
  213675. {
  213676. intern->blocked = false;
  213677. return -1;
  213678. }
  213679. }
  213680. bytesRead = 0;
  213681. char* p = (char*) destBuffer;
  213682. while (bytesRead < maxBytesToRead)
  213683. {
  213684. const int bytesThisTime = maxBytesToRead - bytesRead;
  213685. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  213686. if (numRead <= 0 || intern->stopReadOperation)
  213687. {
  213688. bytesRead = -1;
  213689. break;
  213690. }
  213691. bytesRead += numRead;
  213692. p += bytesRead;
  213693. }
  213694. intern->blocked = false;
  213695. }
  213696. return bytesRead;
  213697. }
  213698. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  213699. {
  213700. int bytesWritten = -1;
  213701. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213702. if (intern != 0)
  213703. {
  213704. if (intern->pipeOut == -1)
  213705. {
  213706. if (intern->createdPipe)
  213707. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  213708. else
  213709. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  213710. if (intern->pipeOut == -1)
  213711. {
  213712. return -1;
  213713. }
  213714. }
  213715. const char* p = (const char*) sourceBuffer;
  213716. bytesWritten = 0;
  213717. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  213718. while (bytesWritten < numBytesToWrite
  213719. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  213720. {
  213721. const int bytesThisTime = numBytesToWrite - bytesWritten;
  213722. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  213723. if (numWritten <= 0)
  213724. {
  213725. bytesWritten = -1;
  213726. break;
  213727. }
  213728. bytesWritten += numWritten;
  213729. p += bytesWritten;
  213730. }
  213731. }
  213732. return bytesWritten;
  213733. }
  213734. #endif
  213735. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  213736. /*** Start of inlined file: juce_linux_Network.cpp ***/
  213737. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213738. // compiled on its own).
  213739. #if JUCE_INCLUDED_FILE
  213740. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  213741. {
  213742. int numResults = 0;
  213743. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  213744. if (s != -1)
  213745. {
  213746. char buf [1024];
  213747. struct ifconf ifc;
  213748. ifc.ifc_len = sizeof (buf);
  213749. ifc.ifc_buf = buf;
  213750. ioctl (s, SIOCGIFCONF, &ifc);
  213751. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  213752. {
  213753. struct ifreq ifr;
  213754. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  213755. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  213756. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  213757. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  213758. && numResults < maxNum)
  213759. {
  213760. int64 a = 0;
  213761. for (int j = 6; --j >= 0;)
  213762. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  213763. *addresses++ = a;
  213764. ++numResults;
  213765. }
  213766. }
  213767. close (s);
  213768. }
  213769. return numResults;
  213770. }
  213771. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  213772. const String& emailSubject,
  213773. const String& bodyText,
  213774. const StringArray& filesToAttach)
  213775. {
  213776. jassertfalse // xxx todo
  213777. return false;
  213778. }
  213779. /** A HTTP input stream that uses sockets.
  213780. */
  213781. class JUCE_HTTPSocketStream
  213782. {
  213783. public:
  213784. JUCE_HTTPSocketStream()
  213785. : readPosition (0),
  213786. socketHandle (-1),
  213787. levelsOfRedirection (0),
  213788. timeoutSeconds (15)
  213789. {
  213790. }
  213791. ~JUCE_HTTPSocketStream()
  213792. {
  213793. closeSocket();
  213794. }
  213795. bool open (const String& url,
  213796. const String& headers,
  213797. const MemoryBlock& postData,
  213798. const bool isPost,
  213799. URL::OpenStreamProgressCallback* callback,
  213800. void* callbackContext,
  213801. int timeOutMs)
  213802. {
  213803. closeSocket();
  213804. uint32 timeOutTime = Time::getMillisecondCounter();
  213805. if (timeOutMs == 0)
  213806. timeOutTime += 60000;
  213807. else if (timeOutMs < 0)
  213808. timeOutTime = 0xffffffff;
  213809. else
  213810. timeOutTime += timeOutMs;
  213811. String hostName, hostPath;
  213812. int hostPort;
  213813. if (! decomposeURL (url, hostName, hostPath, hostPort))
  213814. return false;
  213815. const struct hostent* host = 0;
  213816. int port = 0;
  213817. String proxyName, proxyPath;
  213818. int proxyPort = 0;
  213819. String proxyURL (getenv ("http_proxy"));
  213820. if (proxyURL.startsWithIgnoreCase ("http://"))
  213821. {
  213822. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  213823. return false;
  213824. host = gethostbyname (proxyName.toUTF8());
  213825. port = proxyPort;
  213826. }
  213827. else
  213828. {
  213829. host = gethostbyname (hostName.toUTF8());
  213830. port = hostPort;
  213831. }
  213832. if (host == 0)
  213833. return false;
  213834. struct sockaddr_in address;
  213835. zerostruct (address);
  213836. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  213837. address.sin_family = host->h_addrtype;
  213838. address.sin_port = htons (port);
  213839. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  213840. if (socketHandle == -1)
  213841. return false;
  213842. int receiveBufferSize = 16384;
  213843. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  213844. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  213845. #if JUCE_MAC
  213846. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  213847. #endif
  213848. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  213849. {
  213850. closeSocket();
  213851. return false;
  213852. }
  213853. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  213854. proxyName, proxyPort,
  213855. hostPath, url,
  213856. headers, postData,
  213857. isPost));
  213858. size_t totalHeaderSent = 0;
  213859. while (totalHeaderSent < requestHeader.getSize())
  213860. {
  213861. if (Time::getMillisecondCounter() > timeOutTime)
  213862. {
  213863. closeSocket();
  213864. return false;
  213865. }
  213866. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  213867. if (send (socketHandle,
  213868. ((const char*) requestHeader.getData()) + totalHeaderSent,
  213869. numToSend, 0)
  213870. != numToSend)
  213871. {
  213872. closeSocket();
  213873. return false;
  213874. }
  213875. totalHeaderSent += numToSend;
  213876. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  213877. {
  213878. closeSocket();
  213879. return false;
  213880. }
  213881. }
  213882. const String responseHeader (readResponse (timeOutTime));
  213883. if (responseHeader.isNotEmpty())
  213884. {
  213885. //DBG (responseHeader);
  213886. StringArray lines;
  213887. lines.addLines (responseHeader);
  213888. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  213889. .substring (0, 3).getIntValue();
  213890. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  213891. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  213892. String location (findHeaderItem (lines, "Location:"));
  213893. if (statusCode >= 300 && statusCode < 400
  213894. && location.isNotEmpty())
  213895. {
  213896. if (! location.startsWithIgnoreCase ("http://"))
  213897. location = "http://" + location;
  213898. if (levelsOfRedirection++ < 3)
  213899. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  213900. }
  213901. else
  213902. {
  213903. levelsOfRedirection = 0;
  213904. return true;
  213905. }
  213906. }
  213907. closeSocket();
  213908. return false;
  213909. }
  213910. int read (void* buffer, int bytesToRead)
  213911. {
  213912. fd_set readbits;
  213913. FD_ZERO (&readbits);
  213914. FD_SET (socketHandle, &readbits);
  213915. struct timeval tv;
  213916. tv.tv_sec = timeoutSeconds;
  213917. tv.tv_usec = 0;
  213918. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213919. return 0; // (timeout)
  213920. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  213921. readPosition += bytesRead;
  213922. return bytesRead;
  213923. }
  213924. int readPosition;
  213925. juce_UseDebuggingNewOperator
  213926. private:
  213927. int socketHandle, levelsOfRedirection;
  213928. const int timeoutSeconds;
  213929. void closeSocket()
  213930. {
  213931. if (socketHandle >= 0)
  213932. close (socketHandle);
  213933. socketHandle = -1;
  213934. }
  213935. const MemoryBlock createRequestHeader (const String& hostName,
  213936. const int hostPort,
  213937. const String& proxyName,
  213938. const int proxyPort,
  213939. const String& hostPath,
  213940. const String& originalURL,
  213941. const String& headers,
  213942. const MemoryBlock& postData,
  213943. const bool isPost)
  213944. {
  213945. String header (isPost ? "POST " : "GET ");
  213946. if (proxyName.isEmpty())
  213947. {
  213948. header << hostPath << " HTTP/1.0\r\nHost: "
  213949. << hostName << ':' << hostPort;
  213950. }
  213951. else
  213952. {
  213953. header << originalURL << " HTTP/1.0\r\nHost: "
  213954. << proxyName << ':' << proxyPort;
  213955. }
  213956. header << "\r\nUser-Agent: JUCE/"
  213957. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  213958. << "\r\nConnection: Close\r\nContent-Length: "
  213959. << postData.getSize() << "\r\n"
  213960. << headers << "\r\n";
  213961. MemoryBlock mb;
  213962. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  213963. mb.append (postData.getData(), postData.getSize());
  213964. return mb;
  213965. }
  213966. const String readResponse (const uint32 timeOutTime)
  213967. {
  213968. int bytesRead = 0, numConsecutiveLFs = 0;
  213969. MemoryBlock buffer (1024, true);
  213970. while (numConsecutiveLFs < 2 && bytesRead < 32768
  213971. && Time::getMillisecondCounter() <= timeOutTime)
  213972. {
  213973. fd_set readbits;
  213974. FD_ZERO (&readbits);
  213975. FD_SET (socketHandle, &readbits);
  213976. struct timeval tv;
  213977. tv.tv_sec = timeoutSeconds;
  213978. tv.tv_usec = 0;
  213979. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213980. return String::empty; // (timeout)
  213981. buffer.ensureSize (bytesRead + 8, true);
  213982. char* const dest = (char*) buffer.getData() + bytesRead;
  213983. if (recv (socketHandle, dest, 1, 0) == -1)
  213984. return String::empty;
  213985. const char lastByte = *dest;
  213986. ++bytesRead;
  213987. if (lastByte == '\n')
  213988. ++numConsecutiveLFs;
  213989. else if (lastByte != '\r')
  213990. numConsecutiveLFs = 0;
  213991. }
  213992. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  213993. if (header.startsWithIgnoreCase ("HTTP/"))
  213994. return header.trimEnd();
  213995. return String::empty;
  213996. }
  213997. static bool decomposeURL (const String& url,
  213998. String& host, String& path, int& port)
  213999. {
  214000. if (! url.startsWithIgnoreCase ("http://"))
  214001. return false;
  214002. const int nextSlash = url.indexOfChar (7, '/');
  214003. int nextColon = url.indexOfChar (7, ':');
  214004. if (nextColon > nextSlash && nextSlash > 0)
  214005. nextColon = -1;
  214006. if (nextColon >= 0)
  214007. {
  214008. host = url.substring (7, nextColon);
  214009. if (nextSlash >= 0)
  214010. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  214011. else
  214012. port = url.substring (nextColon + 1).getIntValue();
  214013. }
  214014. else
  214015. {
  214016. port = 80;
  214017. if (nextSlash >= 0)
  214018. host = url.substring (7, nextSlash);
  214019. else
  214020. host = url.substring (7);
  214021. }
  214022. if (nextSlash >= 0)
  214023. path = url.substring (nextSlash);
  214024. else
  214025. path = "/";
  214026. return true;
  214027. }
  214028. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  214029. {
  214030. for (int i = 0; i < lines.size(); ++i)
  214031. if (lines[i].startsWithIgnoreCase (itemName))
  214032. return lines[i].substring (itemName.length()).trim();
  214033. return String::empty;
  214034. }
  214035. };
  214036. void* juce_openInternetFile (const String& url,
  214037. const String& headers,
  214038. const MemoryBlock& postData,
  214039. const bool isPost,
  214040. URL::OpenStreamProgressCallback* callback,
  214041. void* callbackContext,
  214042. int timeOutMs)
  214043. {
  214044. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  214045. if (s->open (url, headers, postData, isPost,
  214046. callback, callbackContext, timeOutMs))
  214047. return s;
  214048. delete s;
  214049. return 0;
  214050. }
  214051. void juce_closeInternetFile (void* handle)
  214052. {
  214053. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  214054. }
  214055. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  214056. {
  214057. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214058. if (s != 0)
  214059. return s->read (buffer, bytesToRead);
  214060. return 0;
  214061. }
  214062. int64 juce_getInternetFileContentLength (void* handle)
  214063. {
  214064. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214065. if (s != 0)
  214066. {
  214067. //xxx todo
  214068. jassertfalse
  214069. }
  214070. return -1;
  214071. }
  214072. int juce_seekInInternetFile (void* handle, int newPosition)
  214073. {
  214074. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214075. if (s != 0)
  214076. return s->readPosition;
  214077. return 0;
  214078. }
  214079. #endif
  214080. /*** End of inlined file: juce_linux_Network.cpp ***/
  214081. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  214082. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214083. // compiled on its own).
  214084. #if JUCE_INCLUDED_FILE
  214085. void Logger::outputDebugString (const String& text) throw()
  214086. {
  214087. std::cerr << text << std::endl;
  214088. }
  214089. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  214090. {
  214091. return Linux;
  214092. }
  214093. const String SystemStats::getOperatingSystemName() throw()
  214094. {
  214095. return "Linux";
  214096. }
  214097. bool SystemStats::isOperatingSystem64Bit() throw()
  214098. {
  214099. #if JUCE_64BIT
  214100. return true;
  214101. #else
  214102. //xxx not sure how to find this out?..
  214103. return false;
  214104. #endif
  214105. }
  214106. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  214107. {
  214108. String info;
  214109. char buf [256];
  214110. FILE* f = fopen ("/proc/cpuinfo", "r");
  214111. while (f != 0 && fgets (buf, sizeof(buf), f))
  214112. {
  214113. if (strncmp (buf, key, strlen (key)) == 0)
  214114. {
  214115. char* p = buf;
  214116. while (*p && *p != '\n')
  214117. ++p;
  214118. if (*p != 0)
  214119. *p = 0;
  214120. p = buf;
  214121. while (*p != 0 && *p != ':')
  214122. ++p;
  214123. if (*p != 0 && *(p + 1) != 0)
  214124. info = p + 2;
  214125. if (! lastOne)
  214126. break;
  214127. }
  214128. }
  214129. fclose (f);
  214130. return info;
  214131. }
  214132. bool SystemStats::hasMMX() throw()
  214133. {
  214134. return getCpuInfo ("flags").contains ("mmx");
  214135. }
  214136. bool SystemStats::hasSSE() throw()
  214137. {
  214138. return getCpuInfo ("flags").contains ("sse");
  214139. }
  214140. bool SystemStats::hasSSE2() throw()
  214141. {
  214142. return getCpuInfo ("flags").contains ("sse2");
  214143. }
  214144. bool SystemStats::has3DNow() throw()
  214145. {
  214146. return getCpuInfo ("flags").contains ("3dnow");
  214147. }
  214148. const String SystemStats::getCpuVendor() throw()
  214149. {
  214150. return getCpuInfo ("vendor_id");
  214151. }
  214152. int SystemStats::getCpuSpeedInMegaherz() throw()
  214153. {
  214154. const String speed (getCpuInfo ("cpu MHz"));
  214155. return (int) (speed.getFloatValue() + 0.5f);
  214156. }
  214157. int SystemStats::getMemorySizeInMegabytes() throw()
  214158. {
  214159. struct sysinfo sysi;
  214160. if (sysinfo (&sysi) == 0)
  214161. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  214162. return 0;
  214163. }
  214164. uint32 juce_millisecondsSinceStartup() throw()
  214165. {
  214166. static unsigned int calibrate = 0;
  214167. static bool calibrated = false;
  214168. timeval t;
  214169. unsigned int ret = 0;
  214170. if (! gettimeofday (&t, 0))
  214171. {
  214172. if (! calibrated)
  214173. {
  214174. struct sysinfo sysi;
  214175. if (sysinfo (&sysi) == 0)
  214176. // Safe to assume system was not brought up earlier than 1970!
  214177. calibrate = t.tv_sec - sysi.uptime;
  214178. calibrated = true;
  214179. }
  214180. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  214181. }
  214182. return ret;
  214183. }
  214184. double Time::getMillisecondCounterHiRes() throw()
  214185. {
  214186. return getHighResolutionTicks() * 0.001;
  214187. }
  214188. int64 Time::getHighResolutionTicks() throw()
  214189. {
  214190. timeval t;
  214191. if (gettimeofday (&t, 0))
  214192. return 0;
  214193. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  214194. }
  214195. int64 Time::getHighResolutionTicksPerSecond() throw()
  214196. {
  214197. // Microseconds
  214198. return 1000000;
  214199. }
  214200. bool Time::setSystemTimeToThisTime() const throw()
  214201. {
  214202. timeval t;
  214203. t.tv_sec = millisSinceEpoch % 1000000;
  214204. t.tv_usec = millisSinceEpoch - t.tv_sec;
  214205. return settimeofday (&t, NULL) ? false : true;
  214206. }
  214207. int SystemStats::getPageSize() throw()
  214208. {
  214209. static int systemPageSize = 0;
  214210. if (systemPageSize == 0)
  214211. systemPageSize = sysconf (_SC_PAGESIZE);
  214212. return systemPageSize;
  214213. }
  214214. int SystemStats::getNumCpus() throw()
  214215. {
  214216. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  214217. return lastCpu + 1;
  214218. }
  214219. const String SystemStats::getLogonName()
  214220. {
  214221. const char* user = getenv ("USER");
  214222. if (user == 0)
  214223. {
  214224. struct passwd* const pw = getpwuid (getuid());
  214225. if (pw != 0)
  214226. user = pw->pw_name;
  214227. }
  214228. return String::fromUTF8 (user);
  214229. }
  214230. const String SystemStats::getFullUserName()
  214231. {
  214232. return getLogonName();
  214233. }
  214234. void SystemStats::initialiseStats() throw()
  214235. {
  214236. // Process starts off as root when running suid
  214237. Process::lowerPrivilege();
  214238. String s (SystemStats::getJUCEVersion());
  214239. }
  214240. void PlatformUtilities::fpuReset()
  214241. {
  214242. }
  214243. #endif
  214244. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  214245. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  214246. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214247. // compiled on its own).
  214248. #if JUCE_INCLUDED_FILE
  214249. /*
  214250. Note that a lot of methods that you'd expect to find in this file actually
  214251. live in juce_posix_SharedCode.h!
  214252. */
  214253. void JUCE_API juce_threadEntryPoint (void*);
  214254. void* threadEntryProc (void* value)
  214255. {
  214256. // New threads start off as root when running suid
  214257. Process::lowerPrivilege();
  214258. juce_threadEntryPoint (value);
  214259. return 0;
  214260. }
  214261. void* juce_createThread (void* userData)
  214262. {
  214263. pthread_t handle = 0;
  214264. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  214265. {
  214266. pthread_detach (handle);
  214267. return (void*) handle;
  214268. }
  214269. return 0;
  214270. }
  214271. void juce_killThread (void* handle)
  214272. {
  214273. if (handle != 0)
  214274. pthread_cancel ((pthread_t)handle);
  214275. }
  214276. void juce_setCurrentThreadName (const String& /*name*/)
  214277. {
  214278. }
  214279. Thread::ThreadID Thread::getCurrentThreadId()
  214280. {
  214281. return (ThreadID) pthread_self();
  214282. }
  214283. /*
  214284. * This is all a bit non-ideal... the trouble is that on Linux you
  214285. * need to call setpriority to affect the dynamic priority for
  214286. * non-realtime processes, but this requires the pid, which is not
  214287. * accessible from the pthread_t. We could get it by calling getpid
  214288. * once each thread has started, but then we would need a list of
  214289. * running threads etc etc.
  214290. * Also there is no such thing as IDLE priority on Linux.
  214291. * For the moment, map idle, low and normal process priorities to
  214292. * SCHED_OTHER, with the thread priority ignored for these classes.
  214293. * Map high priority processes to the lower half of the SCHED_RR
  214294. * range, and realtime to the upper half
  214295. */
  214296. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  214297. // priority of the current thread
  214298. bool juce_setThreadPriority (void* handle, int priority)
  214299. {
  214300. struct sched_param param;
  214301. int policy, maxp, minp, pri;
  214302. if (handle == 0)
  214303. handle = (void*) pthread_self();
  214304. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  214305. && policy != SCHED_OTHER)
  214306. {
  214307. minp = sched_get_priority_min(policy);
  214308. maxp = sched_get_priority_max(policy);
  214309. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  214310. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  214311. // Realtime process priority
  214312. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  214313. else
  214314. // High process priority
  214315. param.__sched_priority = minp + pri;
  214316. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  214317. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  214318. }
  214319. return false;
  214320. }
  214321. /* Remove this macro if you're having problems compiling the cpu affinity
  214322. calls (the API for these has changed about quite a bit in various Linux
  214323. versions, and a lot of distros seem to ship with obsolete versions)
  214324. */
  214325. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  214326. #define SUPPORT_AFFINITIES 1
  214327. #endif
  214328. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  214329. {
  214330. #if SUPPORT_AFFINITIES
  214331. cpu_set_t affinity;
  214332. CPU_ZERO (&affinity);
  214333. for (int i = 0; i < 32; ++i)
  214334. if ((affinityMask & (1 << i)) != 0)
  214335. CPU_SET (i, &affinity);
  214336. /*
  214337. N.B. If this line causes a compile error, then you've probably not got the latest
  214338. version of glibc installed.
  214339. If you don't want to update your copy of glibc and don't care about cpu affinities,
  214340. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  214341. */
  214342. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  214343. sched_yield();
  214344. #else
  214345. /* affinities aren't supported because either the appropriate header files weren't found,
  214346. or the SUPPORT_AFFINITIES macro was turned off
  214347. */
  214348. jassertfalse
  214349. #endif
  214350. }
  214351. void Thread::yield()
  214352. {
  214353. sched_yield();
  214354. }
  214355. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  214356. void Process::setPriority (ProcessPriority prior)
  214357. {
  214358. struct sched_param param;
  214359. int policy, maxp, minp;
  214360. const int p = (int) prior;
  214361. if (p <= 1)
  214362. policy = SCHED_OTHER;
  214363. else
  214364. policy = SCHED_RR;
  214365. minp = sched_get_priority_min (policy);
  214366. maxp = sched_get_priority_max (policy);
  214367. if (p < 2)
  214368. param.__sched_priority = 0;
  214369. else if (p == 2 )
  214370. // Set to middle of lower realtime priority range
  214371. param.__sched_priority = minp + (maxp - minp) / 4;
  214372. else
  214373. // Set to middle of higher realtime priority range
  214374. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  214375. pthread_setschedparam (pthread_self(), policy, &param);
  214376. }
  214377. void Process::terminate()
  214378. {
  214379. exit (0);
  214380. }
  214381. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  214382. {
  214383. static char testResult = 0;
  214384. if (testResult == 0)
  214385. {
  214386. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  214387. if (testResult >= 0)
  214388. {
  214389. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  214390. testResult = 1;
  214391. }
  214392. }
  214393. return testResult < 0;
  214394. }
  214395. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  214396. {
  214397. return juce_isRunningUnderDebugger();
  214398. }
  214399. void Process::raisePrivilege()
  214400. {
  214401. // If running suid root, change effective user
  214402. // to root
  214403. if (geteuid() != 0 && getuid() == 0)
  214404. {
  214405. setreuid (geteuid(), getuid());
  214406. setregid (getegid(), getgid());
  214407. }
  214408. }
  214409. void Process::lowerPrivilege()
  214410. {
  214411. // If runing suid root, change effective user
  214412. // back to real user
  214413. if (geteuid() == 0 && getuid() != 0)
  214414. {
  214415. setreuid (geteuid(), getuid());
  214416. setregid (getegid(), getgid());
  214417. }
  214418. }
  214419. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214420. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  214421. {
  214422. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  214423. }
  214424. void PlatformUtilities::freeDynamicLibrary (void* handle)
  214425. {
  214426. dlclose(handle);
  214427. }
  214428. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  214429. {
  214430. return dlsym (libraryHandle, procedureName.toCString());
  214431. }
  214432. #endif
  214433. #endif
  214434. /*** End of inlined file: juce_linux_Threads.cpp ***/
  214435. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214436. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  214437. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214438. // compiled on its own).
  214439. #if JUCE_INCLUDED_FILE
  214440. #if JUCE_DEBUG
  214441. #define JUCE_DEBUG_XERRORS 1
  214442. #endif
  214443. extern Display* display;
  214444. extern Window juce_messageWindowHandle;
  214445. static String localClipboardContent;
  214446. static Atom atom_UTF8_STRING;
  214447. static Atom atom_CLIPBOARD;
  214448. static Atom atom_TARGETS;
  214449. static void initSelectionAtoms()
  214450. {
  214451. static bool isInitialised = false;
  214452. if (! isInitialised)
  214453. {
  214454. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  214455. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  214456. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  214457. }
  214458. }
  214459. // Read the content of a window property as either a locale-dependent string or an utf8 string
  214460. // works only for strings shorter than 1000000 bytes
  214461. static String juce_readWindowProperty (Window window, Atom prop,
  214462. Atom fmt, // XA_STRING or UTF8_STRING
  214463. bool deleteAfterReading)
  214464. {
  214465. String returnData;
  214466. char* clipData;
  214467. Atom actualType;
  214468. int actualFormat;
  214469. unsigned long numItems, bytesLeft;
  214470. if (XGetWindowProperty (display, window, prop,
  214471. 0L /* offset */, 1000000 /* length (max) */, False,
  214472. AnyPropertyType /* format */,
  214473. &actualType, &actualFormat, &numItems, &bytesLeft,
  214474. (unsigned char**) &clipData) == Success)
  214475. {
  214476. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  214477. {
  214478. returnData = String::fromUTF8 (clipData, numItems);
  214479. }
  214480. else if (actualType == XA_STRING && actualFormat == 8)
  214481. {
  214482. returnData = String (clipData, numItems);
  214483. }
  214484. if (clipData != 0)
  214485. XFree (clipData);
  214486. jassert (bytesLeft == 0 || numItems == 1000000);
  214487. }
  214488. if (deleteAfterReading)
  214489. XDeleteProperty (display, window, prop);
  214490. return returnData;
  214491. }
  214492. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  214493. static bool juce_requestSelectionContent (String &selection_content, Atom selection, Atom requested_format)
  214494. {
  214495. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  214496. // The selection owner will be asked to set the JUCE_SEL property on the
  214497. // juce_messageWindowHandle with the selection content
  214498. XConvertSelection (display, selection, requested_format, property_name,
  214499. juce_messageWindowHandle, CurrentTime);
  214500. int timeoutMs = 200; // will wait at most for 200 ms
  214501. do
  214502. {
  214503. XEvent event;
  214504. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  214505. {
  214506. if (event.xselection.property == property_name)
  214507. {
  214508. jassert (event.xselection.requestor == juce_messageWindowHandle);
  214509. selection_content = juce_readWindowProperty (event.xselection.requestor,
  214510. event.xselection.property,
  214511. requested_format, true);
  214512. return true;
  214513. }
  214514. else
  214515. {
  214516. return false; // the format we asked for was denied.. (event.xselection.property == None)
  214517. }
  214518. }
  214519. // not very elegant.. we could do a select() or something like that...
  214520. // however clipboard content requesting is inherently slow on x11, it
  214521. // often takes 50ms or more so...
  214522. Thread::sleep (4);
  214523. timeoutMs -= 4;
  214524. }
  214525. while (timeoutMs > 0);
  214526. DBG("timeout for juce_requestSelectionContent");
  214527. return false;
  214528. }
  214529. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  214530. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  214531. {
  214532. initSelectionAtoms();
  214533. // the selection content is sent to the target window as a window property
  214534. XSelectionEvent reply;
  214535. reply.type = SelectionNotify;
  214536. reply.display = evt.display;
  214537. reply.requestor = evt.requestor;
  214538. reply.selection = evt.selection;
  214539. reply.target = evt.target;
  214540. reply.property = None; // == "fail"
  214541. reply.time = evt.time;
  214542. HeapBlock <char> data;
  214543. int propertyFormat = 0, numDataItems = 0;
  214544. if (evt.selection == XA_PRIMARY || evt.selection == atom_CLIPBOARD)
  214545. {
  214546. if (evt.target == XA_STRING)
  214547. {
  214548. // format data according to system locale
  214549. numDataItems = localClipboardContent.getNumBytesAsCString() + 1;
  214550. data.calloc (numDataItems + 1);
  214551. localClipboardContent.copyToCString (data, numDataItems);
  214552. propertyFormat = 8; // bits/item
  214553. }
  214554. else if (evt.target == atom_UTF8_STRING)
  214555. {
  214556. // translate to utf8
  214557. numDataItems = localClipboardContent.getNumBytesAsUTF8() + 1;
  214558. data.calloc (numDataItems + 1);
  214559. localClipboardContent.copyToUTF8 (data, numDataItems);
  214560. propertyFormat = 8; // bits/item
  214561. }
  214562. else if (evt.target == atom_TARGETS)
  214563. {
  214564. // another application wants to know what we are able to send
  214565. numDataItems = 2;
  214566. propertyFormat = 32; // atoms are 32-bit
  214567. data.calloc (numDataItems * 4);
  214568. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  214569. atoms[0] = atom_UTF8_STRING;
  214570. atoms[1] = XA_STRING;
  214571. }
  214572. }
  214573. else
  214574. {
  214575. DBG ("requested unsupported clipboard");
  214576. }
  214577. if (data != 0)
  214578. {
  214579. const int maxReasonableSelectionSize = 1000000;
  214580. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  214581. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  214582. {
  214583. XChangeProperty (evt.display, evt.requestor,
  214584. evt.property, evt.target,
  214585. propertyFormat /* 8 or 32 */, PropModeReplace,
  214586. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  214587. reply.property = evt.property; // " == success"
  214588. }
  214589. }
  214590. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  214591. }
  214592. void SystemClipboard::copyTextToClipboard (const String& clipText)
  214593. {
  214594. initSelectionAtoms();
  214595. localClipboardContent = clipText;
  214596. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  214597. XSetSelectionOwner (display, atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  214598. }
  214599. const String SystemClipboard::getTextFromClipboard()
  214600. {
  214601. initSelectionAtoms();
  214602. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  214603. level" clipboard that is supposed to be filled by ctrl-C
  214604. etc). When a clipboard manager is running, the content of this
  214605. selection is preserved even when the original selection owner
  214606. exits.
  214607. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  214608. filled by good old x11 apps such as xterm)
  214609. */
  214610. String content;
  214611. Atom selection = XA_PRIMARY;
  214612. Window selectionOwner = None;
  214613. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  214614. {
  214615. selection = atom_CLIPBOARD;
  214616. selectionOwner = XGetSelectionOwner (display, selection);
  214617. }
  214618. if (selectionOwner != None)
  214619. {
  214620. if (selectionOwner == juce_messageWindowHandle)
  214621. {
  214622. content = localClipboardContent;
  214623. }
  214624. else
  214625. {
  214626. // first try: we want an utf8 string
  214627. bool ok = juce_requestSelectionContent (content, selection, atom_UTF8_STRING);
  214628. if (! ok)
  214629. {
  214630. // second chance, ask for a good old locale-dependent string ..
  214631. ok = juce_requestSelectionContent (content, selection, XA_STRING);
  214632. }
  214633. }
  214634. }
  214635. return content;
  214636. }
  214637. #endif
  214638. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  214639. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  214640. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214641. // compiled on its own).
  214642. #if JUCE_INCLUDED_FILE
  214643. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  214644. #define JUCE_DEBUG_XERRORS 1
  214645. #endif
  214646. Display* display = 0; // This is also referenced from WindowDriver.cpp
  214647. Window juce_messageWindowHandle = None;
  214648. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  214649. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  214650. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  214651. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  214652. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  214653. class InternalMessageQueue
  214654. {
  214655. public:
  214656. InternalMessageQueue()
  214657. : bytesInSocket (0)
  214658. {
  214659. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  214660. (void) ret; jassert (ret == 0);
  214661. //setNonBlocking (fd[0]);
  214662. //setNonBlocking (fd[1]);
  214663. }
  214664. ~InternalMessageQueue()
  214665. {
  214666. close (fd[0]);
  214667. close (fd[1]);
  214668. }
  214669. void postMessage (Message* msg)
  214670. {
  214671. const int maxBytesInSocketQueue = 128;
  214672. ScopedLock sl (lock);
  214673. queue.add (msg);
  214674. if (bytesInSocket < maxBytesInSocketQueue)
  214675. {
  214676. ++bytesInSocket;
  214677. ScopedUnlock ul (lock);
  214678. const unsigned char x = 0xff;
  214679. size_t bytesWritten = write (fd[0], &x, 1);
  214680. (void) bytesWritten;
  214681. }
  214682. }
  214683. bool isEmpty() const
  214684. {
  214685. ScopedLock sl (lock);
  214686. return queue.size() == 0;
  214687. }
  214688. Message* popNextMessage()
  214689. {
  214690. ScopedLock sl (lock);
  214691. if (bytesInSocket > 0)
  214692. {
  214693. --bytesInSocket;
  214694. ScopedUnlock ul (lock);
  214695. unsigned char x;
  214696. size_t numBytes = read (fd[1], &x, 1);
  214697. (void) numBytes;
  214698. }
  214699. Message* m = queue[0];
  214700. queue.remove (0, false /* deleteObject */);
  214701. return m;
  214702. }
  214703. int getWaitHandle() const { return fd[1]; }
  214704. private:
  214705. CriticalSection lock;
  214706. OwnedArray <Message> queue;
  214707. int fd[2];
  214708. int bytesInSocket;
  214709. static bool setNonBlocking (int handle)
  214710. {
  214711. int socketFlags = fcntl (handle, F_GETFL, 0);
  214712. if (socketFlags == -1)
  214713. return false;
  214714. socketFlags |= O_NONBLOCK;
  214715. return fcntl (handle, F_SETFL, socketFlags) == 0;
  214716. }
  214717. };
  214718. struct MessageThreadFuncCall
  214719. {
  214720. enum { uniqueID = 0x73774623 };
  214721. MessageCallbackFunction* func;
  214722. void* parameter;
  214723. void* result;
  214724. CriticalSection lock;
  214725. WaitableEvent event;
  214726. };
  214727. static InternalMessageQueue* juce_internalMessageQueue = 0;
  214728. // error handling in X11
  214729. static bool errorOccurred = false;
  214730. static bool keyboardBreakOccurred = false;
  214731. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  214732. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  214733. // Usually happens when client-server connection is broken
  214734. static int ioErrorHandler (Display* display)
  214735. {
  214736. DBG ("ERROR: connection to X server broken.. terminating.");
  214737. errorOccurred = true;
  214738. if (JUCEApplication::getInstance() != 0)
  214739. Process::terminate();
  214740. return 0;
  214741. }
  214742. // A protocol error has occurred
  214743. static int errorHandler (Display* display, XErrorEvent* event)
  214744. {
  214745. #if JUCE_DEBUG_XERRORS
  214746. char errorStr[64] = { 0 };
  214747. char requestStr[64] = { 0 };
  214748. XGetErrorText (display, event->error_code, errorStr, 64);
  214749. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(),
  214750. "Unknown", requestStr, 64);
  214751. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  214752. #endif
  214753. return 0;
  214754. }
  214755. // Breakin from keyboard
  214756. static void signalHandler (int sig)
  214757. {
  214758. if (sig == SIGINT)
  214759. {
  214760. keyboardBreakOccurred = true;
  214761. return;
  214762. }
  214763. static bool reentrant = false;
  214764. if (! reentrant)
  214765. {
  214766. reentrant = true;
  214767. // Illegal instruction
  214768. fflush (stdout);
  214769. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  214770. errorOccurred = true;
  214771. if (JUCEApplication::getInstance() != 0)
  214772. Process::terminate();
  214773. }
  214774. else
  214775. {
  214776. if (JUCEApplication::getInstance() != 0)
  214777. exit(0);
  214778. }
  214779. }
  214780. void MessageManager::doPlatformSpecificInitialisation()
  214781. {
  214782. // Initialise xlib for multiple thread support
  214783. static bool initThreadCalled = false;
  214784. if (! initThreadCalled)
  214785. {
  214786. if (! XInitThreads())
  214787. {
  214788. // This is fatal! Print error and closedown
  214789. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  214790. if (JUCEApplication::getInstance() != 0)
  214791. Process::terminate();
  214792. return;
  214793. }
  214794. initThreadCalled = true;
  214795. }
  214796. // This is called if the client/server connection is broken
  214797. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  214798. // This is called if a protocol error occurs
  214799. oldErrorHandler = XSetErrorHandler (errorHandler);
  214800. // Install signal handler for break-in
  214801. struct sigaction saction;
  214802. sigset_t maskSet;
  214803. sigemptyset (&maskSet);
  214804. saction.sa_handler = signalHandler;
  214805. saction.sa_mask = maskSet;
  214806. saction.sa_flags = 0;
  214807. sigaction (SIGINT, &saction, NULL);
  214808. #ifndef _DEBUG
  214809. // Setup signal handlers for various fatal errors
  214810. sigaction (SIGILL, &saction, NULL);
  214811. sigaction (SIGBUS, &saction, NULL);
  214812. sigaction (SIGFPE, &saction, NULL);
  214813. sigaction (SIGSEGV, &saction, NULL);
  214814. sigaction (SIGSYS, &saction, NULL);
  214815. #endif
  214816. // Create the internal message queue
  214817. juce_internalMessageQueue = new InternalMessageQueue();
  214818. // Try to connect to a display
  214819. String displayName (getenv ("DISPLAY"));
  214820. if (displayName.isEmpty())
  214821. displayName = ":0.0";
  214822. display = XOpenDisplay (displayName.toCString());
  214823. if (display == 0)
  214824. {
  214825. // This is not fatal! we can run headless.
  214826. return;
  214827. }
  214828. // Get defaults for various properties
  214829. int screen = DefaultScreen (display);
  214830. Window root = RootWindow (display, screen);
  214831. Visual* visual = DefaultVisual (display, screen);
  214832. // Create a context to store user data associated with Windows we
  214833. // create in WindowDriver
  214834. windowHandleXContext = XUniqueContext();
  214835. // We're only interested in client messages for this window
  214836. // which are always sent
  214837. XSetWindowAttributes swa;
  214838. swa.event_mask = NoEventMask;
  214839. // Create our message window (this will never be mapped)
  214840. juce_messageWindowHandle = XCreateWindow (display, root,
  214841. 0, 0, 1, 1, 0, 0, InputOnly,
  214842. visual, CWEventMask, &swa);
  214843. }
  214844. void MessageManager::doPlatformSpecificShutdown()
  214845. {
  214846. deleteAndZero (juce_internalMessageQueue);
  214847. if (display != 0 && ! errorOccurred)
  214848. {
  214849. XDestroyWindow (display, juce_messageWindowHandle);
  214850. XCloseDisplay (display);
  214851. // reset pointers
  214852. juce_messageWindowHandle = 0;
  214853. display = 0;
  214854. // Restore original error handlers
  214855. XSetIOErrorHandler (oldIOErrorHandler);
  214856. oldIOErrorHandler = 0;
  214857. XSetErrorHandler (oldErrorHandler);
  214858. oldErrorHandler = 0;
  214859. }
  214860. }
  214861. bool juce_postMessageToSystemQueue (void* message)
  214862. {
  214863. if (errorOccurred)
  214864. return false;
  214865. juce_internalMessageQueue->postMessage ((Message*) message);
  214866. return true;
  214867. }
  214868. void MessageManager::broadcastMessage (const String& value) throw()
  214869. {
  214870. /* TODO */
  214871. }
  214872. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  214873. void* parameter)
  214874. {
  214875. if (errorOccurred)
  214876. return 0;
  214877. if (! isThisTheMessageThread())
  214878. {
  214879. MessageThreadFuncCall messageCallContext;
  214880. messageCallContext.func = func;
  214881. messageCallContext.parameter = parameter;
  214882. juce_internalMessageQueue->postMessage (new Message (MessageThreadFuncCall::uniqueID,
  214883. 0, 0, &messageCallContext));
  214884. // Wait for it to complete before continuing
  214885. messageCallContext.event.wait();
  214886. return messageCallContext.result;
  214887. }
  214888. else
  214889. {
  214890. // Just call the function directly
  214891. return func (parameter);
  214892. }
  214893. }
  214894. // Wait for an event (either XEvent, or an internal Message)
  214895. static bool juce_sleepUntilEvent (const int timeoutMs)
  214896. {
  214897. if (! juce_internalMessageQueue->isEmpty())
  214898. return true;
  214899. if (display != 0)
  214900. {
  214901. ScopedXLock xlock;
  214902. if (XPending (display))
  214903. return true;
  214904. }
  214905. struct timeval tv;
  214906. tv.tv_sec = 0;
  214907. tv.tv_usec = timeoutMs * 1000;
  214908. int fd0 = juce_internalMessageQueue->getWaitHandle();
  214909. int fdmax = fd0;
  214910. fd_set readset;
  214911. FD_ZERO (&readset);
  214912. FD_SET (fd0, &readset);
  214913. if (display != 0)
  214914. {
  214915. ScopedXLock xlock;
  214916. int fd1 = XConnectionNumber (display);
  214917. FD_SET (fd1, &readset);
  214918. fdmax = jmax (fd0, fd1);
  214919. }
  214920. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  214921. return (ret > 0); // ret <= 0 if error or timeout
  214922. }
  214923. // Handle next XEvent (if any)
  214924. static bool juce_dispatchNextXEvent()
  214925. {
  214926. if (display == 0)
  214927. return false;
  214928. XEvent evt;
  214929. {
  214930. ScopedXLock xlock;
  214931. if (! XPending (display))
  214932. return false;
  214933. XNextEvent (display, &evt);
  214934. }
  214935. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  214936. {
  214937. juce_handleSelectionRequest (evt.xselectionrequest);
  214938. }
  214939. else if (evt.xany.window != juce_messageWindowHandle)
  214940. {
  214941. juce_windowMessageReceive (&evt);
  214942. }
  214943. return true;
  214944. }
  214945. // Handle next internal Message (if any)
  214946. static bool juce_dispatchNextInternalMessage()
  214947. {
  214948. ScopedPointer <Message> msg (juce_internalMessageQueue->popNextMessage());
  214949. if (msg == 0)
  214950. return false;
  214951. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  214952. {
  214953. // Handle callback message
  214954. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  214955. call->result = (*(call->func)) (call->parameter);
  214956. call->event.signal();
  214957. }
  214958. else
  214959. {
  214960. // Handle "normal" messages
  214961. MessageManager::getInstance()->deliverMessage (msg.release());
  214962. }
  214963. return true;
  214964. }
  214965. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  214966. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  214967. {
  214968. for (;;)
  214969. {
  214970. if (errorOccurred)
  214971. break;
  214972. if (keyboardBreakOccurred)
  214973. {
  214974. errorOccurred = true;
  214975. if (JUCEApplication::getInstance() != 0)
  214976. Process::terminate();
  214977. break;
  214978. }
  214979. static int totalEventCount = 0;
  214980. ++totalEventCount;
  214981. // The purpose here is to give either priority to XEvents or
  214982. // to internal messages This is necessary to keep a "good"
  214983. // behaviour when the cpu is overloaded
  214984. if (totalEventCount & 1)
  214985. {
  214986. if (juce_dispatchNextXEvent() || juce_dispatchNextInternalMessage())
  214987. return true;
  214988. }
  214989. else
  214990. {
  214991. if (juce_dispatchNextInternalMessage() || juce_dispatchNextXEvent())
  214992. return true;
  214993. }
  214994. if (returnIfNoPendingMessages) // early exit
  214995. break;
  214996. // the timeout is to be on the safe side, but it does not seem to be useful
  214997. juce_sleepUntilEvent (2000);
  214998. }
  214999. return false;
  215000. }
  215001. #endif
  215002. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  215003. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  215004. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215005. // compiled on its own).
  215006. #if JUCE_INCLUDED_FILE
  215007. class FreeTypeFontFace
  215008. {
  215009. public:
  215010. enum FontStyle
  215011. {
  215012. Plain = 0,
  215013. Bold = 1,
  215014. Italic = 2
  215015. };
  215016. struct FontNameIndex
  215017. {
  215018. String fileName;
  215019. int faceIndex;
  215020. };
  215021. FreeTypeFontFace (const String& familyName)
  215022. : hasSerif (false),
  215023. monospaced (false)
  215024. {
  215025. family = familyName;
  215026. }
  215027. void setFileName (const String& name, const int faceIndex, FontStyle style)
  215028. {
  215029. if (names [(int) style].fileName.isEmpty())
  215030. {
  215031. names [(int) style].fileName = name;
  215032. names [(int) style].faceIndex = faceIndex;
  215033. }
  215034. }
  215035. const String& getFamilyName() const throw() { return family; }
  215036. const String& getFileName (const int style, int& faceIndex) const throw()
  215037. {
  215038. faceIndex = names[style].faceIndex;
  215039. return names[style].fileName;
  215040. }
  215041. void setMonospaced (bool mono) throw() { monospaced = mono; }
  215042. bool getMonospaced() const throw() { return monospaced; }
  215043. void setSerif (const bool serif) throw() { hasSerif = serif; }
  215044. bool getSerif() const throw() { return hasSerif; }
  215045. private:
  215046. String family;
  215047. FontNameIndex names[4];
  215048. bool hasSerif, monospaced;
  215049. };
  215050. class FreeTypeInterface : public DeletedAtShutdown
  215051. {
  215052. public:
  215053. FreeTypeInterface()
  215054. : ftLib (0),
  215055. lastFace (0),
  215056. lastBold (false),
  215057. lastItalic (false)
  215058. {
  215059. if (FT_Init_FreeType (&ftLib) != 0)
  215060. {
  215061. ftLib = 0;
  215062. DBG ("Failed to initialize FreeType");
  215063. }
  215064. StringArray fontDirs;
  215065. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  215066. fontDirs.removeEmptyStrings (true);
  215067. if (fontDirs.size() == 0)
  215068. {
  215069. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  215070. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  215071. if (fontsInfo != 0)
  215072. {
  215073. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  215074. {
  215075. fontDirs.add (e->getAllSubText().trim());
  215076. }
  215077. }
  215078. }
  215079. if (fontDirs.size() == 0)
  215080. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  215081. for (int i = 0; i < fontDirs.size(); ++i)
  215082. enumerateFaces (fontDirs[i]);
  215083. }
  215084. ~FreeTypeInterface()
  215085. {
  215086. if (lastFace != 0)
  215087. FT_Done_Face (lastFace);
  215088. if (ftLib != 0)
  215089. FT_Done_FreeType (ftLib);
  215090. clearSingletonInstance();
  215091. }
  215092. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  215093. {
  215094. for (int i = 0; i < faces.size(); i++)
  215095. if (faces[i]->getFamilyName() == familyName)
  215096. return faces[i];
  215097. if (! create)
  215098. return NULL;
  215099. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  215100. faces.add (newFace);
  215101. return newFace;
  215102. }
  215103. // Enumerate all font faces available in a given directory
  215104. void enumerateFaces (const String& path)
  215105. {
  215106. File dirPath (path);
  215107. if (path.isEmpty() || ! dirPath.isDirectory())
  215108. return;
  215109. DirectoryIterator di (dirPath, true);
  215110. while (di.next())
  215111. {
  215112. File possible (di.getFile());
  215113. if (possible.hasFileExtension ("ttf")
  215114. || possible.hasFileExtension ("pfb")
  215115. || possible.hasFileExtension ("pcf"))
  215116. {
  215117. FT_Face face;
  215118. int faceIndex = 0;
  215119. int numFaces = 0;
  215120. do
  215121. {
  215122. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  215123. faceIndex, &face) == 0)
  215124. {
  215125. if (faceIndex == 0)
  215126. numFaces = face->num_faces;
  215127. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  215128. {
  215129. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  215130. int style = (int) FreeTypeFontFace::Plain;
  215131. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  215132. style |= (int) FreeTypeFontFace::Bold;
  215133. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  215134. style |= (int) FreeTypeFontFace::Italic;
  215135. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  215136. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  215137. // Surely there must be a better way to do this?
  215138. const String name (face->family_name);
  215139. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  215140. || name.containsIgnoreCase ("Verdana")
  215141. || name.containsIgnoreCase ("Arial")));
  215142. }
  215143. FT_Done_Face (face);
  215144. }
  215145. ++faceIndex;
  215146. }
  215147. while (faceIndex < numFaces);
  215148. }
  215149. }
  215150. }
  215151. // Create a FreeType face object for a given font
  215152. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  215153. {
  215154. FT_Face face = 0;
  215155. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  215156. {
  215157. face = lastFace;
  215158. }
  215159. else
  215160. {
  215161. if (lastFace != 0)
  215162. {
  215163. FT_Done_Face (lastFace);
  215164. lastFace = 0;
  215165. }
  215166. lastFontName = fontName;
  215167. lastBold = bold;
  215168. lastItalic = italic;
  215169. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  215170. if (ftFace != 0)
  215171. {
  215172. int style = (int) FreeTypeFontFace::Plain;
  215173. if (bold)
  215174. style |= (int) FreeTypeFontFace::Bold;
  215175. if (italic)
  215176. style |= (int) FreeTypeFontFace::Italic;
  215177. int faceIndex;
  215178. String fileName (ftFace->getFileName (style, faceIndex));
  215179. if (fileName.isEmpty())
  215180. {
  215181. style ^= (int) FreeTypeFontFace::Bold;
  215182. fileName = ftFace->getFileName (style, faceIndex);
  215183. if (fileName.isEmpty())
  215184. {
  215185. style ^= (int) FreeTypeFontFace::Bold;
  215186. style ^= (int) FreeTypeFontFace::Italic;
  215187. fileName = ftFace->getFileName (style, faceIndex);
  215188. if (! fileName.length())
  215189. {
  215190. style ^= (int) FreeTypeFontFace::Bold;
  215191. fileName = ftFace->getFileName (style, faceIndex);
  215192. }
  215193. }
  215194. }
  215195. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  215196. {
  215197. face = lastFace;
  215198. // If there isn't a unicode charmap then select the first one.
  215199. if (FT_Select_Charmap (face, ft_encoding_unicode))
  215200. FT_Set_Charmap (face, face->charmaps[0]);
  215201. }
  215202. }
  215203. }
  215204. return face;
  215205. }
  215206. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  215207. {
  215208. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  215209. const float height = (float) (face->ascender - face->descender);
  215210. const float scaleX = 1.0f / height;
  215211. const float scaleY = -1.0f / height;
  215212. Path destShape;
  215213. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  215214. || face->glyph->format != ft_glyph_format_outline)
  215215. {
  215216. return false;
  215217. }
  215218. const FT_Outline* const outline = &face->glyph->outline;
  215219. const short* const contours = outline->contours;
  215220. const char* const tags = outline->tags;
  215221. FT_Vector* const points = outline->points;
  215222. for (int c = 0; c < outline->n_contours; c++)
  215223. {
  215224. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  215225. const int endPoint = contours[c];
  215226. for (int p = startPoint; p <= endPoint; p++)
  215227. {
  215228. const float x = scaleX * points[p].x;
  215229. const float y = scaleY * points[p].y;
  215230. if (p == startPoint)
  215231. {
  215232. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215233. {
  215234. float x2 = scaleX * points [endPoint].x;
  215235. float y2 = scaleY * points [endPoint].y;
  215236. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  215237. {
  215238. x2 = (x + x2) * 0.5f;
  215239. y2 = (y + y2) * 0.5f;
  215240. }
  215241. destShape.startNewSubPath (x2, y2);
  215242. }
  215243. else
  215244. {
  215245. destShape.startNewSubPath (x, y);
  215246. }
  215247. }
  215248. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  215249. {
  215250. if (p != startPoint)
  215251. destShape.lineTo (x, y);
  215252. }
  215253. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215254. {
  215255. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  215256. float x2 = scaleX * points [nextIndex].x;
  215257. float y2 = scaleY * points [nextIndex].y;
  215258. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  215259. {
  215260. x2 = (x + x2) * 0.5f;
  215261. y2 = (y + y2) * 0.5f;
  215262. }
  215263. else
  215264. {
  215265. ++p;
  215266. }
  215267. destShape.quadraticTo (x, y, x2, y2);
  215268. }
  215269. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  215270. {
  215271. if (p >= endPoint)
  215272. return false;
  215273. const int next1 = p + 1;
  215274. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  215275. const float x2 = scaleX * points [next1].x;
  215276. const float y2 = scaleY * points [next1].y;
  215277. const float x3 = scaleX * points [next2].x;
  215278. const float y3 = scaleY * points [next2].y;
  215279. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  215280. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  215281. return false;
  215282. destShape.cubicTo (x, y, x2, y2, x3, y3);
  215283. p += 2;
  215284. }
  215285. }
  215286. destShape.closeSubPath();
  215287. }
  215288. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  215289. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  215290. addKerning (face, dest, character, glyphIndex);
  215291. return true;
  215292. }
  215293. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  215294. {
  215295. const float height = (float) (face->ascender - face->descender);
  215296. uint32 rightGlyphIndex;
  215297. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  215298. while (rightGlyphIndex != 0)
  215299. {
  215300. FT_Vector kerning;
  215301. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  215302. {
  215303. if (kerning.x != 0)
  215304. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  215305. }
  215306. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  215307. }
  215308. }
  215309. // Add a glyph to a font
  215310. bool addGlyphToFont (const uint32 character, const String& fontName,
  215311. bool bold, bool italic, CustomTypeface& dest)
  215312. {
  215313. FT_Face face = createFT_Face (fontName, bold, italic);
  215314. return face != 0 && addGlyph (face, dest, character);
  215315. }
  215316. void getFamilyNames (StringArray& familyNames) const
  215317. {
  215318. for (int i = 0; i < faces.size(); i++)
  215319. familyNames.add (faces[i]->getFamilyName());
  215320. }
  215321. void getMonospacedNames (StringArray& monoSpaced) const
  215322. {
  215323. for (int i = 0; i < faces.size(); i++)
  215324. if (faces[i]->getMonospaced())
  215325. monoSpaced.add (faces[i]->getFamilyName());
  215326. }
  215327. void getSerifNames (StringArray& serif) const
  215328. {
  215329. for (int i = 0; i < faces.size(); i++)
  215330. if (faces[i]->getSerif())
  215331. serif.add (faces[i]->getFamilyName());
  215332. }
  215333. void getSansSerifNames (StringArray& sansSerif) const
  215334. {
  215335. for (int i = 0; i < faces.size(); i++)
  215336. if (! faces[i]->getSerif())
  215337. sansSerif.add (faces[i]->getFamilyName());
  215338. }
  215339. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  215340. private:
  215341. FT_Library ftLib;
  215342. FT_Face lastFace;
  215343. String lastFontName;
  215344. bool lastBold, lastItalic;
  215345. OwnedArray<FreeTypeFontFace> faces;
  215346. };
  215347. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  215348. class FreetypeTypeface : public CustomTypeface
  215349. {
  215350. public:
  215351. FreetypeTypeface (const Font& font)
  215352. {
  215353. FT_Face face = FreeTypeInterface::getInstance()
  215354. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  215355. if (face == 0)
  215356. {
  215357. #if JUCE_DEBUG
  215358. String msg ("Failed to create typeface: ");
  215359. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  215360. DBG (msg);
  215361. #endif
  215362. }
  215363. else
  215364. {
  215365. setCharacteristics (font.getTypefaceName(),
  215366. face->ascender / (float) (face->ascender - face->descender),
  215367. font.isBold(), font.isItalic(),
  215368. L' ');
  215369. }
  215370. }
  215371. bool loadGlyphIfPossible (juce_wchar character)
  215372. {
  215373. return FreeTypeInterface::getInstance()
  215374. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  215375. }
  215376. };
  215377. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  215378. {
  215379. return new FreetypeTypeface (font);
  215380. }
  215381. const StringArray Font::findAllTypefaceNames()
  215382. {
  215383. StringArray s;
  215384. FreeTypeInterface::getInstance()->getFamilyNames (s);
  215385. s.sort (true);
  215386. return s;
  215387. }
  215388. static const String pickBestFont (const StringArray& names,
  215389. const char* const choicesString)
  215390. {
  215391. StringArray choices;
  215392. choices.addTokens (String (choicesString), ",", String::empty);
  215393. choices.trim();
  215394. choices.removeEmptyStrings();
  215395. int i, j;
  215396. for (j = 0; j < choices.size(); ++j)
  215397. if (names.contains (choices[j], true))
  215398. return choices[j];
  215399. for (j = 0; j < choices.size(); ++j)
  215400. for (i = 0; i < names.size(); i++)
  215401. if (names[i].startsWithIgnoreCase (choices[j]))
  215402. return names[i];
  215403. for (j = 0; j < choices.size(); ++j)
  215404. for (i = 0; i < names.size(); i++)
  215405. if (names[i].containsIgnoreCase (choices[j]))
  215406. return names[i];
  215407. return names[0];
  215408. }
  215409. static const String linux_getDefaultSansSerifFontName()
  215410. {
  215411. StringArray allFonts;
  215412. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  215413. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  215414. }
  215415. static const String linux_getDefaultSerifFontName()
  215416. {
  215417. StringArray allFonts;
  215418. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  215419. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  215420. }
  215421. static const String linux_getDefaultMonospacedFontName()
  215422. {
  215423. StringArray allFonts;
  215424. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  215425. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  215426. }
  215427. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  215428. {
  215429. defaultSans = linux_getDefaultSansSerifFontName();
  215430. defaultSerif = linux_getDefaultSerifFontName();
  215431. defaultFixed = linux_getDefaultMonospacedFontName();
  215432. }
  215433. #endif
  215434. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  215435. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  215436. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215437. // compiled on its own).
  215438. #if JUCE_INCLUDED_FILE
  215439. // These are defined in juce_linux_Messaging.cpp
  215440. extern Display* display;
  215441. extern XContext windowHandleXContext;
  215442. namespace Atoms
  215443. {
  215444. enum ProtocolItems
  215445. {
  215446. TAKE_FOCUS = 0,
  215447. DELETE_WINDOW = 1,
  215448. PING = 2
  215449. };
  215450. static Atom Protocols, ProtocolList[3], ChangeState, State,
  215451. ActiveWin, Pid, WindowType, WindowState,
  215452. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  215453. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  215454. XdndActionDescription, XdndActionCopy,
  215455. allowedActions[5],
  215456. allowedMimeTypes[2];
  215457. const unsigned long DndVersion = 3;
  215458. static void initialiseAtoms()
  215459. {
  215460. static bool atomsInitialised = false;
  215461. if (! atomsInitialised)
  215462. {
  215463. atomsInitialised = true;
  215464. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  215465. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  215466. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  215467. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  215468. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  215469. State = XInternAtom (display, "WM_STATE", True);
  215470. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  215471. Pid = XInternAtom (display, "_NET_WM_PID", False);
  215472. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  215473. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  215474. XdndAware = XInternAtom (display, "XdndAware", False);
  215475. XdndEnter = XInternAtom (display, "XdndEnter", False);
  215476. XdndLeave = XInternAtom (display, "XdndLeave", False);
  215477. XdndPosition = XInternAtom (display, "XdndPosition", False);
  215478. XdndStatus = XInternAtom (display, "XdndStatus", False);
  215479. XdndDrop = XInternAtom (display, "XdndDrop", False);
  215480. XdndFinished = XInternAtom (display, "XdndFinished", False);
  215481. XdndSelection = XInternAtom (display, "XdndSelection", False);
  215482. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  215483. XdndActionList = XInternAtom (display, "XdndActionList", False);
  215484. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  215485. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  215486. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  215487. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  215488. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  215489. allowedActions[1] = XdndActionCopy;
  215490. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  215491. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  215492. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  215493. }
  215494. }
  215495. }
  215496. namespace Keys
  215497. {
  215498. enum MouseButtons
  215499. {
  215500. NoButton = 0,
  215501. LeftButton = 1,
  215502. MiddleButton = 2,
  215503. RightButton = 3,
  215504. WheelUp = 4,
  215505. WheelDown = 5
  215506. };
  215507. static int AltMask = 0;
  215508. static int NumLockMask = 0;
  215509. static bool numLock = false;
  215510. static bool capsLock = false;
  215511. static char keyStates [32];
  215512. static const int extendedKeyModifier = 0x10000000;
  215513. }
  215514. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  215515. {
  215516. int keysym;
  215517. if (keyCode & Keys::extendedKeyModifier)
  215518. {
  215519. keysym = 0xff00 | (keyCode & 0xff);
  215520. }
  215521. else
  215522. {
  215523. keysym = keyCode;
  215524. if (keysym == (XK_Tab & 0xff)
  215525. || keysym == (XK_Return & 0xff)
  215526. || keysym == (XK_Escape & 0xff)
  215527. || keysym == (XK_BackSpace & 0xff))
  215528. {
  215529. keysym |= 0xff00;
  215530. }
  215531. }
  215532. ScopedXLock xlock;
  215533. const int keycode = XKeysymToKeycode (display, keysym);
  215534. const int keybyte = keycode >> 3;
  215535. const int keybit = (1 << (keycode & 7));
  215536. return (Keys::keyStates [keybyte] & keybit) != 0;
  215537. }
  215538. #if JUCE_USE_XSHM
  215539. namespace XSHMHelpers
  215540. {
  215541. static int trappedErrorCode = 0;
  215542. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  215543. {
  215544. trappedErrorCode = err->error_code;
  215545. return 0;
  215546. }
  215547. static bool isShmAvailable() throw()
  215548. {
  215549. static bool isChecked = false;
  215550. static bool isAvailable = false;
  215551. if (! isChecked)
  215552. {
  215553. isChecked = true;
  215554. int major, minor;
  215555. Bool pixmaps;
  215556. ScopedXLock xlock;
  215557. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  215558. {
  215559. trappedErrorCode = 0;
  215560. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  215561. XShmSegmentInfo segmentInfo;
  215562. zerostruct (segmentInfo);
  215563. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  215564. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  215565. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215566. xImage->bytes_per_line * xImage->height,
  215567. IPC_CREAT | 0777)) >= 0)
  215568. {
  215569. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215570. if (segmentInfo.shmaddr != (void*) -1)
  215571. {
  215572. segmentInfo.readOnly = False;
  215573. xImage->data = segmentInfo.shmaddr;
  215574. XSync (display, False);
  215575. if (XShmAttach (display, &segmentInfo) != 0)
  215576. {
  215577. XSync (display, False);
  215578. XShmDetach (display, &segmentInfo);
  215579. isAvailable = true;
  215580. }
  215581. }
  215582. XFlush (display);
  215583. XDestroyImage (xImage);
  215584. shmdt (segmentInfo.shmaddr);
  215585. }
  215586. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215587. XSetErrorHandler (oldHandler);
  215588. if (trappedErrorCode != 0)
  215589. isAvailable = false;
  215590. }
  215591. }
  215592. return isAvailable;
  215593. }
  215594. }
  215595. #endif
  215596. #if JUCE_USE_XRENDER
  215597. namespace XRender
  215598. {
  215599. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  215600. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  215601. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  215602. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  215603. static tXRenderQueryVersion xRenderQueryVersion = 0;
  215604. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  215605. static tXRenderFindFormat xRenderFindFormat = 0;
  215606. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  215607. static bool isAvailable()
  215608. {
  215609. static bool hasLoaded = false;
  215610. if (! hasLoaded)
  215611. {
  215612. ScopedXLock xlock;
  215613. hasLoaded = true;
  215614. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  215615. if (h != 0)
  215616. {
  215617. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  215618. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  215619. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  215620. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  215621. }
  215622. if (xRenderQueryVersion != 0
  215623. && xRenderFindStandardFormat != 0
  215624. && xRenderFindFormat != 0
  215625. && xRenderFindVisualFormat != 0)
  215626. {
  215627. int major, minor;
  215628. if (xRenderQueryVersion (display, &major, &minor))
  215629. return true;
  215630. }
  215631. xRenderQueryVersion = 0;
  215632. }
  215633. return xRenderQueryVersion != 0;
  215634. }
  215635. static XRenderPictFormat* findPictureFormat()
  215636. {
  215637. ScopedXLock xlock;
  215638. XRenderPictFormat* pictFormat = 0;
  215639. if (isAvailable())
  215640. {
  215641. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  215642. if (pictFormat == 0)
  215643. {
  215644. XRenderPictFormat desiredFormat;
  215645. desiredFormat.type = PictTypeDirect;
  215646. desiredFormat.depth = 32;
  215647. desiredFormat.direct.alphaMask = 0xff;
  215648. desiredFormat.direct.redMask = 0xff;
  215649. desiredFormat.direct.greenMask = 0xff;
  215650. desiredFormat.direct.blueMask = 0xff;
  215651. desiredFormat.direct.alpha = 24;
  215652. desiredFormat.direct.red = 16;
  215653. desiredFormat.direct.green = 8;
  215654. desiredFormat.direct.blue = 0;
  215655. pictFormat = xRenderFindFormat (display,
  215656. PictFormatType | PictFormatDepth
  215657. | PictFormatRedMask | PictFormatRed
  215658. | PictFormatGreenMask | PictFormatGreen
  215659. | PictFormatBlueMask | PictFormatBlue
  215660. | PictFormatAlphaMask | PictFormatAlpha,
  215661. &desiredFormat,
  215662. 0);
  215663. }
  215664. }
  215665. return pictFormat;
  215666. }
  215667. }
  215668. #endif
  215669. namespace Visuals
  215670. {
  215671. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  215672. {
  215673. ScopedXLock xlock;
  215674. Visual* visual = 0;
  215675. int numVisuals = 0;
  215676. long desiredMask = VisualNoMask;
  215677. XVisualInfo desiredVisual;
  215678. desiredVisual.screen = DefaultScreen (display);
  215679. desiredVisual.depth = desiredDepth;
  215680. desiredMask = VisualScreenMask | VisualDepthMask;
  215681. if (desiredDepth == 32)
  215682. {
  215683. desiredVisual.c_class = TrueColor;
  215684. desiredVisual.red_mask = 0x00FF0000;
  215685. desiredVisual.green_mask = 0x0000FF00;
  215686. desiredVisual.blue_mask = 0x000000FF;
  215687. desiredVisual.bits_per_rgb = 8;
  215688. desiredMask |= VisualClassMask;
  215689. desiredMask |= VisualRedMaskMask;
  215690. desiredMask |= VisualGreenMaskMask;
  215691. desiredMask |= VisualBlueMaskMask;
  215692. desiredMask |= VisualBitsPerRGBMask;
  215693. }
  215694. XVisualInfo* xvinfos = XGetVisualInfo (display,
  215695. desiredMask,
  215696. &desiredVisual,
  215697. &numVisuals);
  215698. if (xvinfos != 0)
  215699. {
  215700. for (int i = 0; i < numVisuals; i++)
  215701. {
  215702. if (xvinfos[i].depth == desiredDepth)
  215703. {
  215704. visual = xvinfos[i].visual;
  215705. break;
  215706. }
  215707. }
  215708. XFree (xvinfos);
  215709. }
  215710. return visual;
  215711. }
  215712. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  215713. {
  215714. Visual* visual = 0;
  215715. if (desiredDepth == 32)
  215716. {
  215717. #if JUCE_USE_XSHM
  215718. if (XSHMHelpers::isShmAvailable())
  215719. {
  215720. #if JUCE_USE_XRENDER
  215721. if (XRender::isAvailable())
  215722. {
  215723. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  215724. if (pictFormat != 0)
  215725. {
  215726. int numVisuals = 0;
  215727. XVisualInfo desiredVisual;
  215728. desiredVisual.screen = DefaultScreen (display);
  215729. desiredVisual.depth = 32;
  215730. desiredVisual.bits_per_rgb = 8;
  215731. XVisualInfo* xvinfos = XGetVisualInfo (display,
  215732. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  215733. &desiredVisual, &numVisuals);
  215734. if (xvinfos != 0)
  215735. {
  215736. for (int i = 0; i < numVisuals; ++i)
  215737. {
  215738. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  215739. if (pictVisualFormat != 0
  215740. && pictVisualFormat->type == PictTypeDirect
  215741. && pictVisualFormat->direct.alphaMask)
  215742. {
  215743. visual = xvinfos[i].visual;
  215744. matchedDepth = 32;
  215745. break;
  215746. }
  215747. }
  215748. XFree (xvinfos);
  215749. }
  215750. }
  215751. }
  215752. #endif
  215753. if (visual == 0)
  215754. {
  215755. visual = findVisualWithDepth (32);
  215756. if (visual != 0)
  215757. matchedDepth = 32;
  215758. }
  215759. }
  215760. #endif
  215761. }
  215762. if (visual == 0 && desiredDepth >= 24)
  215763. {
  215764. visual = findVisualWithDepth (24);
  215765. if (visual != 0)
  215766. matchedDepth = 24;
  215767. }
  215768. if (visual == 0 && desiredDepth >= 16)
  215769. {
  215770. visual = findVisualWithDepth (16);
  215771. if (visual != 0)
  215772. matchedDepth = 16;
  215773. }
  215774. return visual;
  215775. }
  215776. }
  215777. class XBitmapImage : public Image
  215778. {
  215779. public:
  215780. XBitmapImage (const PixelFormat format_, const int w, const int h,
  215781. const bool clearImage, const int imageDepth_, Visual* visual)
  215782. : Image (format_, w, h),
  215783. imageDepth (imageDepth_),
  215784. gc (None)
  215785. {
  215786. jassert (format_ == RGB || format_ == ARGB);
  215787. pixelStride = (format_ == RGB) ? 3 : 4;
  215788. lineStride = ((w * pixelStride + 3) & ~3);
  215789. ScopedXLock xlock;
  215790. #if JUCE_USE_XSHM
  215791. usingXShm = false;
  215792. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  215793. {
  215794. zerostruct (segmentInfo);
  215795. segmentInfo.shmid = -1;
  215796. segmentInfo.shmaddr = (char *) -1;
  215797. segmentInfo.readOnly = False;
  215798. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  215799. if (xImage != 0)
  215800. {
  215801. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215802. xImage->bytes_per_line * xImage->height,
  215803. IPC_CREAT | 0777)) >= 0)
  215804. {
  215805. if (segmentInfo.shmid != -1)
  215806. {
  215807. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215808. if (segmentInfo.shmaddr != (void*) -1)
  215809. {
  215810. segmentInfo.readOnly = False;
  215811. xImage->data = segmentInfo.shmaddr;
  215812. imageData = (uint8*) segmentInfo.shmaddr;
  215813. if (XShmAttach (display, &segmentInfo) != 0)
  215814. {
  215815. usingXShm = true;
  215816. }
  215817. else
  215818. {
  215819. jassertfalse
  215820. }
  215821. }
  215822. else
  215823. {
  215824. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215825. }
  215826. }
  215827. }
  215828. }
  215829. }
  215830. if (! usingXShm)
  215831. #endif
  215832. {
  215833. imageDataAllocated.malloc (lineStride * h);
  215834. imageData = imageDataAllocated;
  215835. if (format_ == ARGB && clearImage)
  215836. zeromem (imageData, h * lineStride);
  215837. xImage = (XImage*) juce_calloc (sizeof (XImage));
  215838. xImage->width = w;
  215839. xImage->height = h;
  215840. xImage->xoffset = 0;
  215841. xImage->format = ZPixmap;
  215842. xImage->data = (char*) imageData;
  215843. xImage->byte_order = ImageByteOrder (display);
  215844. xImage->bitmap_unit = BitmapUnit (display);
  215845. xImage->bitmap_bit_order = BitmapBitOrder (display);
  215846. xImage->bitmap_pad = 32;
  215847. xImage->depth = pixelStride * 8;
  215848. xImage->bytes_per_line = lineStride;
  215849. xImage->bits_per_pixel = pixelStride * 8;
  215850. xImage->red_mask = 0x00FF0000;
  215851. xImage->green_mask = 0x0000FF00;
  215852. xImage->blue_mask = 0x000000FF;
  215853. if (imageDepth == 16)
  215854. {
  215855. const int pixelStride = 2;
  215856. const int lineStride = ((w * pixelStride + 3) & ~3);
  215857. imageData16Bit.malloc (lineStride * h);
  215858. xImage->data = imageData16Bit;
  215859. xImage->bitmap_pad = 16;
  215860. xImage->depth = pixelStride * 8;
  215861. xImage->bytes_per_line = lineStride;
  215862. xImage->bits_per_pixel = pixelStride * 8;
  215863. xImage->red_mask = visual->red_mask;
  215864. xImage->green_mask = visual->green_mask;
  215865. xImage->blue_mask = visual->blue_mask;
  215866. }
  215867. if (! XInitImage (xImage))
  215868. {
  215869. jassertfalse
  215870. }
  215871. }
  215872. }
  215873. ~XBitmapImage()
  215874. {
  215875. ScopedXLock xlock;
  215876. if (gc != None)
  215877. XFreeGC (display, gc);
  215878. #if JUCE_USE_XSHM
  215879. if (usingXShm)
  215880. {
  215881. XShmDetach (display, &segmentInfo);
  215882. XFlush (display);
  215883. XDestroyImage (xImage);
  215884. shmdt (segmentInfo.shmaddr);
  215885. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215886. }
  215887. else
  215888. #endif
  215889. {
  215890. xImage->data = 0;
  215891. XDestroyImage (xImage);
  215892. }
  215893. }
  215894. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  215895. {
  215896. ScopedXLock xlock;
  215897. if (gc == None)
  215898. {
  215899. XGCValues gcvalues;
  215900. gcvalues.foreground = None;
  215901. gcvalues.background = None;
  215902. gcvalues.function = GXcopy;
  215903. gcvalues.plane_mask = AllPlanes;
  215904. gcvalues.clip_mask = None;
  215905. gcvalues.graphics_exposures = False;
  215906. gc = XCreateGC (display, window,
  215907. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  215908. &gcvalues);
  215909. }
  215910. if (imageDepth == 16)
  215911. {
  215912. const uint32 rMask = xImage->red_mask;
  215913. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  215914. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  215915. const uint32 gMask = xImage->green_mask;
  215916. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  215917. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  215918. const uint32 bMask = xImage->blue_mask;
  215919. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  215920. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  215921. const Image::BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  215922. for (int y = sy; y < sy + dh; ++y)
  215923. {
  215924. const uint8* p = srcData.getPixelPointer (sx, y);
  215925. for (int x = sx; x < sx + dw; ++x)
  215926. {
  215927. const PixelRGB* const pixel = (const PixelRGB*) p;
  215928. p += srcData.pixelStride;
  215929. XPutPixel (xImage, x, y,
  215930. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  215931. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  215932. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  215933. }
  215934. }
  215935. }
  215936. // blit results to screen.
  215937. #if JUCE_USE_XSHM
  215938. if (usingXShm)
  215939. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  215940. else
  215941. #endif
  215942. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  215943. }
  215944. juce_UseDebuggingNewOperator
  215945. private:
  215946. XImage* xImage;
  215947. const int imageDepth;
  215948. HeapBlock <char> imageData16Bit;
  215949. GC gc;
  215950. #if JUCE_USE_XSHM
  215951. XShmSegmentInfo segmentInfo;
  215952. bool usingXShm;
  215953. #endif
  215954. static int getShiftNeeded (const uint32 mask) throw()
  215955. {
  215956. for (int i = 32; --i >= 0;)
  215957. if (((mask >> i) & 1) != 0)
  215958. return i - 7;
  215959. jassertfalse
  215960. return 0;
  215961. }
  215962. };
  215963. class LinuxComponentPeer : public ComponentPeer
  215964. {
  215965. public:
  215966. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  215967. : ComponentPeer (component, windowStyleFlags),
  215968. windowH (0),
  215969. parentWindow (0),
  215970. wx (0),
  215971. wy (0),
  215972. ww (0),
  215973. wh (0),
  215974. fullScreen (false),
  215975. mapped (false),
  215976. visual (0),
  215977. depth (0)
  215978. {
  215979. // it's dangerous to create a window on a thread other than the message thread..
  215980. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215981. repainter = new LinuxRepaintManager (this);
  215982. createWindow();
  215983. setTitle (component->getName());
  215984. }
  215985. ~LinuxComponentPeer()
  215986. {
  215987. // it's dangerous to delete a window on a thread other than the message thread..
  215988. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215989. deleteIconPixmaps();
  215990. destroyWindow();
  215991. windowH = 0;
  215992. }
  215993. void* getNativeHandle() const
  215994. {
  215995. return (void*) windowH;
  215996. }
  215997. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  215998. {
  215999. XPointer peer = 0;
  216000. ScopedXLock xlock;
  216001. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  216002. {
  216003. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  216004. peer = 0;
  216005. }
  216006. return (LinuxComponentPeer*) peer;
  216007. }
  216008. void setVisible (bool shouldBeVisible)
  216009. {
  216010. ScopedXLock xlock;
  216011. if (shouldBeVisible)
  216012. XMapWindow (display, windowH);
  216013. else
  216014. XUnmapWindow (display, windowH);
  216015. }
  216016. void setTitle (const String& title)
  216017. {
  216018. setWindowTitle (windowH, title);
  216019. }
  216020. void setPosition (int x, int y)
  216021. {
  216022. setBounds (x, y, ww, wh, false);
  216023. }
  216024. void setSize (int w, int h)
  216025. {
  216026. setBounds (wx, wy, w, h, false);
  216027. }
  216028. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  216029. {
  216030. fullScreen = isNowFullScreen;
  216031. if (windowH != 0)
  216032. {
  216033. Component::SafePointer<Component> deletionChecker (component);
  216034. wx = x;
  216035. wy = y;
  216036. ww = jmax (1, w);
  216037. wh = jmax (1, h);
  216038. ScopedXLock xlock;
  216039. // Make sure the Window manager does what we want
  216040. XSizeHints* hints = XAllocSizeHints();
  216041. hints->flags = USSize | USPosition;
  216042. hints->width = ww;
  216043. hints->height = wh;
  216044. hints->x = wx;
  216045. hints->y = wy;
  216046. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  216047. {
  216048. hints->min_width = hints->max_width = hints->width;
  216049. hints->min_height = hints->max_height = hints->height;
  216050. hints->flags |= PMinSize | PMaxSize;
  216051. }
  216052. XSetWMNormalHints (display, windowH, hints);
  216053. XFree (hints);
  216054. XMoveResizeWindow (display, windowH,
  216055. wx - windowBorder.getLeft(),
  216056. wy - windowBorder.getTop(), ww, wh);
  216057. if (deletionChecker != 0)
  216058. {
  216059. updateBorderSize();
  216060. handleMovedOrResized();
  216061. }
  216062. }
  216063. }
  216064. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  216065. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  216066. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  216067. {
  216068. return relativePosition + getScreenPosition();
  216069. }
  216070. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  216071. {
  216072. return screenPosition - getScreenPosition();
  216073. }
  216074. void setMinimised (bool shouldBeMinimised)
  216075. {
  216076. if (shouldBeMinimised)
  216077. {
  216078. Window root = RootWindow (display, DefaultScreen (display));
  216079. XClientMessageEvent clientMsg;
  216080. clientMsg.display = display;
  216081. clientMsg.window = windowH;
  216082. clientMsg.type = ClientMessage;
  216083. clientMsg.format = 32;
  216084. clientMsg.message_type = Atoms::ChangeState;
  216085. clientMsg.data.l[0] = IconicState;
  216086. ScopedXLock xlock;
  216087. XSendEvent (display, root, false,
  216088. SubstructureRedirectMask | SubstructureNotifyMask,
  216089. (XEvent*) &clientMsg);
  216090. }
  216091. else
  216092. {
  216093. setVisible (true);
  216094. }
  216095. }
  216096. bool isMinimised() const
  216097. {
  216098. bool minimised = false;
  216099. unsigned char* stateProp;
  216100. unsigned long nitems, bytesLeft;
  216101. Atom actualType;
  216102. int actualFormat;
  216103. ScopedXLock xlock;
  216104. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  216105. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  216106. &stateProp) == Success
  216107. && actualType == Atoms::State
  216108. && actualFormat == 32
  216109. && nitems > 0)
  216110. {
  216111. if (((unsigned long*) stateProp)[0] == IconicState)
  216112. minimised = true;
  216113. XFree (stateProp);
  216114. }
  216115. return minimised;
  216116. }
  216117. void setFullScreen (const bool shouldBeFullScreen)
  216118. {
  216119. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  216120. setMinimised (false);
  216121. if (fullScreen != shouldBeFullScreen)
  216122. {
  216123. if (shouldBeFullScreen)
  216124. r = Desktop::getInstance().getMainMonitorArea();
  216125. if (! r.isEmpty())
  216126. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  216127. getComponent()->repaint();
  216128. }
  216129. }
  216130. bool isFullScreen() const
  216131. {
  216132. return fullScreen;
  216133. }
  216134. bool isChildWindowOf (Window possibleParent) const
  216135. {
  216136. Window* windowList = 0;
  216137. uint32 windowListSize = 0;
  216138. Window parent, root;
  216139. ScopedXLock xlock;
  216140. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  216141. {
  216142. if (windowList != 0)
  216143. XFree (windowList);
  216144. return parent == possibleParent;
  216145. }
  216146. return false;
  216147. }
  216148. bool isFrontWindow() const
  216149. {
  216150. Window* windowList = 0;
  216151. uint32 windowListSize = 0;
  216152. bool result = false;
  216153. ScopedXLock xlock;
  216154. Window parent, root = RootWindow (display, DefaultScreen (display));
  216155. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  216156. {
  216157. for (int i = windowListSize; --i >= 0;)
  216158. {
  216159. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  216160. if (peer != 0)
  216161. {
  216162. result = (peer == this);
  216163. break;
  216164. }
  216165. }
  216166. }
  216167. if (windowList != 0)
  216168. XFree (windowList);
  216169. return result;
  216170. }
  216171. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  216172. {
  216173. int x = position.getX();
  216174. int y = position.getY();
  216175. if (((unsigned int) x) >= (unsigned int) ww
  216176. || ((unsigned int) y) >= (unsigned int) wh)
  216177. return false;
  216178. bool inFront = false;
  216179. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  216180. {
  216181. Component* const c = Desktop::getInstance().getComponent (i);
  216182. if (inFront)
  216183. {
  216184. if (c->contains (x + wx - c->getScreenX(),
  216185. y + wy - c->getScreenY()))
  216186. {
  216187. return false;
  216188. }
  216189. }
  216190. else if (c == getComponent())
  216191. {
  216192. inFront = true;
  216193. }
  216194. }
  216195. if (trueIfInAChildWindow)
  216196. return true;
  216197. ::Window root, child;
  216198. unsigned int bw, depth;
  216199. int wx, wy, w, h;
  216200. ScopedXLock xlock;
  216201. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216202. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  216203. &bw, &depth))
  216204. {
  216205. return false;
  216206. }
  216207. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  216208. return false;
  216209. return child == None;
  216210. }
  216211. const BorderSize getFrameSize() const
  216212. {
  216213. return BorderSize();
  216214. }
  216215. bool setAlwaysOnTop (bool alwaysOnTop)
  216216. {
  216217. if (windowH != 0)
  216218. {
  216219. const bool wasVisible = component->isVisible();
  216220. if (wasVisible)
  216221. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  216222. {
  216223. ScopedXLock xlock;
  216224. XSetWindowAttributes swa;
  216225. swa.override_redirect = alwaysOnTop ? True : False;
  216226. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  216227. }
  216228. if (wasVisible)
  216229. setVisible (true);
  216230. }
  216231. return true;
  216232. }
  216233. void toFront (bool makeActive)
  216234. {
  216235. if (makeActive)
  216236. {
  216237. setVisible (true);
  216238. grabFocus();
  216239. }
  216240. XEvent ev;
  216241. ev.xclient.type = ClientMessage;
  216242. ev.xclient.serial = 0;
  216243. ev.xclient.send_event = True;
  216244. ev.xclient.message_type = Atoms::ActiveWin;
  216245. ev.xclient.window = windowH;
  216246. ev.xclient.format = 32;
  216247. ev.xclient.data.l[0] = 2;
  216248. ev.xclient.data.l[1] = CurrentTime;
  216249. ev.xclient.data.l[2] = 0;
  216250. ev.xclient.data.l[3] = 0;
  216251. ev.xclient.data.l[4] = 0;
  216252. {
  216253. ScopedXLock xlock;
  216254. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  216255. False,
  216256. SubstructureRedirectMask | SubstructureNotifyMask,
  216257. &ev);
  216258. XWindowAttributes attr;
  216259. XGetWindowAttributes (display, windowH, &attr);
  216260. if (attr.override_redirect)
  216261. XRaiseWindow (display, windowH);
  216262. XSync (display, False);
  216263. }
  216264. handleBroughtToFront();
  216265. }
  216266. void toBehind (ComponentPeer* other)
  216267. {
  216268. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  216269. jassert (otherPeer != 0); // wrong type of window?
  216270. if (otherPeer != 0)
  216271. {
  216272. setMinimised (false);
  216273. Window newStack[] = { otherPeer->windowH, windowH };
  216274. ScopedXLock xlock;
  216275. XRestackWindows (display, newStack, 2);
  216276. }
  216277. }
  216278. bool isFocused() const
  216279. {
  216280. int revert;
  216281. Window focusedWindow = 0;
  216282. ScopedXLock xlock;
  216283. XGetInputFocus (display, &focusedWindow, &revert);
  216284. return focusedWindow == windowH;
  216285. }
  216286. void grabFocus()
  216287. {
  216288. XWindowAttributes atts;
  216289. ScopedXLock xlock;
  216290. if (windowH != 0
  216291. && XGetWindowAttributes (display, windowH, &atts)
  216292. && atts.map_state == IsViewable
  216293. && ! isFocused())
  216294. {
  216295. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  216296. isActiveApplication = true;
  216297. }
  216298. }
  216299. void textInputRequired (const Point<int>&)
  216300. {
  216301. }
  216302. void repaint (int x, int y, int w, int h)
  216303. {
  216304. if (Rectangle<int>::intersectRectangles (x, y, w, h,
  216305. 0, 0,
  216306. getComponent()->getWidth(),
  216307. getComponent()->getHeight()))
  216308. {
  216309. repainter->repaint (x, y, w, h);
  216310. }
  216311. }
  216312. void performAnyPendingRepaintsNow()
  216313. {
  216314. repainter->performAnyPendingRepaintsNow();
  216315. }
  216316. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  216317. {
  216318. ScopedXLock xlock;
  216319. const int width = image.getWidth();
  216320. const int height = image.getHeight();
  216321. HeapBlock <char> colour (width * height);
  216322. int index = 0;
  216323. for (int y = 0; y < height; ++y)
  216324. for (int x = 0; x < width; ++x)
  216325. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  216326. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  216327. 0, colour.getData(),
  216328. width, height, 32, 0);
  216329. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  216330. width, height, 24);
  216331. GC gc = XCreateGC (display, pixmap, 0, 0);
  216332. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  216333. XFreeGC (display, gc);
  216334. return pixmap;
  216335. }
  216336. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  216337. {
  216338. ScopedXLock xlock;
  216339. const int width = image.getWidth();
  216340. const int height = image.getHeight();
  216341. const int stride = (width + 7) >> 3;
  216342. HeapBlock <char> mask;
  216343. mask.calloc (stride * height);
  216344. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216345. for (int y = 0; y < height; ++y)
  216346. {
  216347. for (int x = 0; x < width; ++x)
  216348. {
  216349. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216350. const int offset = y * stride + (x >> 3);
  216351. if (image.getPixelAt (x, y).getAlpha() >= 128)
  216352. mask[offset] |= bit;
  216353. }
  216354. }
  216355. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  216356. mask.getData(), width, height, 1, 0, 1);
  216357. }
  216358. void setIcon (const Image& newIcon)
  216359. {
  216360. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  216361. HeapBlock <unsigned long> data (dataSize);
  216362. int index = 0;
  216363. data[index++] = newIcon.getWidth();
  216364. data[index++] = newIcon.getHeight();
  216365. for (int y = 0; y < newIcon.getHeight(); ++y)
  216366. for (int x = 0; x < newIcon.getWidth(); ++x)
  216367. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  216368. ScopedXLock xlock;
  216369. XChangeProperty (display, windowH,
  216370. XInternAtom (display, "_NET_WM_ICON", False),
  216371. XA_CARDINAL, 32, PropModeReplace,
  216372. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  216373. deleteIconPixmaps();
  216374. XWMHints* wmHints = XGetWMHints (display, windowH);
  216375. if (wmHints == 0)
  216376. wmHints = XAllocWMHints();
  216377. wmHints->flags |= IconPixmapHint | IconMaskHint;
  216378. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  216379. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  216380. XSetWMHints (display, windowH, wmHints);
  216381. XFree (wmHints);
  216382. XSync (display, False);
  216383. }
  216384. void deleteIconPixmaps()
  216385. {
  216386. ScopedXLock xlock;
  216387. XWMHints* wmHints = XGetWMHints (display, windowH);
  216388. if (wmHints != 0)
  216389. {
  216390. if ((wmHints->flags & IconPixmapHint) != 0)
  216391. {
  216392. wmHints->flags &= ~IconPixmapHint;
  216393. XFreePixmap (display, wmHints->icon_pixmap);
  216394. }
  216395. if ((wmHints->flags & IconMaskHint) != 0)
  216396. {
  216397. wmHints->flags &= ~IconMaskHint;
  216398. XFreePixmap (display, wmHints->icon_mask);
  216399. }
  216400. XSetWMHints (display, windowH, wmHints);
  216401. XFree (wmHints);
  216402. }
  216403. }
  216404. void handleWindowMessage (XEvent* event)
  216405. {
  216406. switch (event->xany.type)
  216407. {
  216408. case 2: // 'KeyPress'
  216409. {
  216410. ScopedXLock xlock;
  216411. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  216412. updateKeyStates (keyEvent->keycode, true);
  216413. char utf8 [64];
  216414. zeromem (utf8, sizeof (utf8));
  216415. KeySym sym;
  216416. {
  216417. const char* oldLocale = ::setlocale (LC_ALL, 0);
  216418. ::setlocale (LC_ALL, "");
  216419. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  216420. ::setlocale (LC_ALL, oldLocale);
  216421. }
  216422. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  216423. int keyCode = (int) unicodeChar;
  216424. if (keyCode < 0x20)
  216425. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  216426. const ModifierKeys oldMods (currentModifiers);
  216427. bool keyPressed = false;
  216428. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  216429. if ((sym & 0xff00) == 0xff00)
  216430. {
  216431. // Translate keypad
  216432. if (sym == XK_KP_Divide)
  216433. keyCode = XK_slash;
  216434. else if (sym == XK_KP_Multiply)
  216435. keyCode = XK_asterisk;
  216436. else if (sym == XK_KP_Subtract)
  216437. keyCode = XK_hyphen;
  216438. else if (sym == XK_KP_Add)
  216439. keyCode = XK_plus;
  216440. else if (sym == XK_KP_Enter)
  216441. keyCode = XK_Return;
  216442. else if (sym == XK_KP_Decimal)
  216443. keyCode = Keys::numLock ? XK_period : XK_Delete;
  216444. else if (sym == XK_KP_0)
  216445. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  216446. else if (sym == XK_KP_1)
  216447. keyCode = Keys::numLock ? XK_1 : XK_End;
  216448. else if (sym == XK_KP_2)
  216449. keyCode = Keys::numLock ? XK_2 : XK_Down;
  216450. else if (sym == XK_KP_3)
  216451. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  216452. else if (sym == XK_KP_4)
  216453. keyCode = Keys::numLock ? XK_4 : XK_Left;
  216454. else if (sym == XK_KP_5)
  216455. keyCode = XK_5;
  216456. else if (sym == XK_KP_6)
  216457. keyCode = Keys::numLock ? XK_6 : XK_Right;
  216458. else if (sym == XK_KP_7)
  216459. keyCode = Keys::numLock ? XK_7 : XK_Home;
  216460. else if (sym == XK_KP_8)
  216461. keyCode = Keys::numLock ? XK_8 : XK_Up;
  216462. else if (sym == XK_KP_9)
  216463. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  216464. switch (sym)
  216465. {
  216466. case XK_Left:
  216467. case XK_Right:
  216468. case XK_Up:
  216469. case XK_Down:
  216470. case XK_Page_Up:
  216471. case XK_Page_Down:
  216472. case XK_End:
  216473. case XK_Home:
  216474. case XK_Delete:
  216475. case XK_Insert:
  216476. keyPressed = true;
  216477. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  216478. break;
  216479. case XK_Tab:
  216480. case XK_Return:
  216481. case XK_Escape:
  216482. case XK_BackSpace:
  216483. keyPressed = true;
  216484. keyCode &= 0xff;
  216485. break;
  216486. default:
  216487. {
  216488. if (sym >= XK_F1 && sym <= XK_F16)
  216489. {
  216490. keyPressed = true;
  216491. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  216492. }
  216493. break;
  216494. }
  216495. }
  216496. }
  216497. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  216498. keyPressed = true;
  216499. if (oldMods != currentModifiers)
  216500. handleModifierKeysChange();
  216501. if (keyDownChange)
  216502. handleKeyUpOrDown (true);
  216503. if (keyPressed)
  216504. handleKeyPress (keyCode, unicodeChar);
  216505. break;
  216506. }
  216507. case KeyRelease:
  216508. {
  216509. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  216510. updateKeyStates (keyEvent->keycode, false);
  216511. ScopedXLock xlock;
  216512. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  216513. const ModifierKeys oldMods (currentModifiers);
  216514. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  216515. if (oldMods != currentModifiers)
  216516. handleModifierKeysChange();
  216517. if (keyDownChange)
  216518. handleKeyUpOrDown (false);
  216519. break;
  216520. }
  216521. case ButtonPress:
  216522. {
  216523. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  216524. updateKeyModifiers (buttonPressEvent->state);
  216525. bool buttonMsg = false;
  216526. const int map = pointerMap [buttonPressEvent->button - Button1];
  216527. if (map == Keys::WheelUp || map == Keys::WheelDown)
  216528. {
  216529. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  216530. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  216531. }
  216532. if (map == Keys::LeftButton)
  216533. {
  216534. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  216535. buttonMsg = true;
  216536. }
  216537. else if (map == Keys::RightButton)
  216538. {
  216539. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  216540. buttonMsg = true;
  216541. }
  216542. else if (map == Keys::MiddleButton)
  216543. {
  216544. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  216545. buttonMsg = true;
  216546. }
  216547. if (buttonMsg)
  216548. {
  216549. toFront (true);
  216550. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  216551. getEventTime (buttonPressEvent->time));
  216552. }
  216553. clearLastMousePos();
  216554. break;
  216555. }
  216556. case ButtonRelease:
  216557. {
  216558. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  216559. updateKeyModifiers (buttonRelEvent->state);
  216560. const int map = pointerMap [buttonRelEvent->button - Button1];
  216561. if (map == Keys::LeftButton)
  216562. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  216563. else if (map == Keys::RightButton)
  216564. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  216565. else if (map == Keys::MiddleButton)
  216566. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  216567. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  216568. getEventTime (buttonRelEvent->time));
  216569. clearLastMousePos();
  216570. break;
  216571. }
  216572. case MotionNotify:
  216573. {
  216574. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  216575. updateKeyModifiers (movedEvent->state);
  216576. const Point<int> mousePos (Desktop::getMousePosition());
  216577. if (lastMousePos != mousePos)
  216578. {
  216579. lastMousePos = mousePos;
  216580. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  216581. {
  216582. Window wRoot = 0, wParent = 0;
  216583. {
  216584. ScopedXLock xlock;
  216585. unsigned int numChildren;
  216586. Window* wChild = 0;
  216587. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  216588. }
  216589. if (wParent != 0
  216590. && wParent != windowH
  216591. && wParent != wRoot)
  216592. {
  216593. parentWindow = wParent;
  216594. updateBounds();
  216595. }
  216596. else
  216597. {
  216598. parentWindow = 0;
  216599. }
  216600. }
  216601. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  216602. }
  216603. break;
  216604. }
  216605. case EnterNotify:
  216606. {
  216607. clearLastMousePos();
  216608. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  216609. if (! currentModifiers.isAnyMouseButtonDown())
  216610. {
  216611. updateKeyModifiers (enterEvent->state);
  216612. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  216613. }
  216614. break;
  216615. }
  216616. case LeaveNotify:
  216617. {
  216618. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  216619. // Suppress the normal leave if we've got a pointer grab, or if
  216620. // it's a bogus one caused by clicking a mouse button when running
  216621. // in a Window manager
  216622. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  216623. || leaveEvent->mode == NotifyUngrab)
  216624. {
  216625. updateKeyModifiers (leaveEvent->state);
  216626. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  216627. }
  216628. break;
  216629. }
  216630. case FocusIn:
  216631. {
  216632. isActiveApplication = true;
  216633. if (isFocused())
  216634. handleFocusGain();
  216635. break;
  216636. }
  216637. case FocusOut:
  216638. {
  216639. isActiveApplication = false;
  216640. if (! isFocused())
  216641. handleFocusLoss();
  216642. break;
  216643. }
  216644. case Expose:
  216645. {
  216646. // Batch together all pending expose events
  216647. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  216648. XEvent nextEvent;
  216649. ScopedXLock xlock;
  216650. if (exposeEvent->window != windowH)
  216651. {
  216652. Window child;
  216653. XTranslateCoordinates (display, exposeEvent->window, windowH,
  216654. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  216655. &child);
  216656. }
  216657. repaint (exposeEvent->x, exposeEvent->y,
  216658. exposeEvent->width, exposeEvent->height);
  216659. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  216660. {
  216661. XPeekEvent (display, (XEvent*) &nextEvent);
  216662. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  216663. break;
  216664. XNextEvent (display, (XEvent*) &nextEvent);
  216665. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  216666. repaint (nextExposeEvent->x, nextExposeEvent->y,
  216667. nextExposeEvent->width, nextExposeEvent->height);
  216668. }
  216669. break;
  216670. }
  216671. case CirculateNotify:
  216672. case CreateNotify:
  216673. case DestroyNotify:
  216674. // Think we can ignore these
  216675. break;
  216676. case ConfigureNotify:
  216677. {
  216678. updateBounds();
  216679. updateBorderSize();
  216680. handleMovedOrResized();
  216681. // if the native title bar is dragged, need to tell any active menus, etc.
  216682. if ((styleFlags & windowHasTitleBar) != 0
  216683. && component->isCurrentlyBlockedByAnotherModalComponent())
  216684. {
  216685. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  216686. if (currentModalComp != 0)
  216687. currentModalComp->inputAttemptWhenModal();
  216688. }
  216689. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  216690. if (confEvent->window == windowH
  216691. && confEvent->above != 0
  216692. && isFrontWindow())
  216693. {
  216694. handleBroughtToFront();
  216695. }
  216696. break;
  216697. }
  216698. case ReparentNotify:
  216699. {
  216700. parentWindow = 0;
  216701. Window wRoot = 0;
  216702. Window* wChild = 0;
  216703. unsigned int numChildren;
  216704. {
  216705. ScopedXLock xlock;
  216706. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  216707. }
  216708. if (parentWindow == windowH || parentWindow == wRoot)
  216709. parentWindow = 0;
  216710. updateBounds();
  216711. updateBorderSize();
  216712. handleMovedOrResized();
  216713. break;
  216714. }
  216715. case GravityNotify:
  216716. {
  216717. updateBounds();
  216718. updateBorderSize();
  216719. handleMovedOrResized();
  216720. break;
  216721. }
  216722. case MapNotify:
  216723. mapped = true;
  216724. handleBroughtToFront();
  216725. break;
  216726. case UnmapNotify:
  216727. mapped = false;
  216728. break;
  216729. case MappingNotify:
  216730. {
  216731. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  216732. if (mappingEvent->request != MappingPointer)
  216733. {
  216734. // Deal with modifier/keyboard mapping
  216735. ScopedXLock xlock;
  216736. XRefreshKeyboardMapping (mappingEvent);
  216737. updateModifierMappings();
  216738. }
  216739. break;
  216740. }
  216741. case ClientMessage:
  216742. {
  216743. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  216744. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  216745. {
  216746. const Atom atom = (Atom) clientMsg->data.l[0];
  216747. if (atom == Atoms::ProtocolList [Atoms::PING])
  216748. {
  216749. Window root = RootWindow (display, DefaultScreen (display));
  216750. event->xclient.window = root;
  216751. XSendEvent (display, root, False, NoEventMask, event);
  216752. XFlush (display);
  216753. }
  216754. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  216755. {
  216756. XWindowAttributes atts;
  216757. ScopedXLock xlock;
  216758. if (clientMsg->window != 0
  216759. && XGetWindowAttributes (display, clientMsg->window, &atts))
  216760. {
  216761. if (atts.map_state == IsViewable)
  216762. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  216763. }
  216764. }
  216765. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  216766. {
  216767. handleUserClosingWindow();
  216768. }
  216769. }
  216770. else if (clientMsg->message_type == Atoms::XdndEnter)
  216771. {
  216772. handleDragAndDropEnter (clientMsg);
  216773. }
  216774. else if (clientMsg->message_type == Atoms::XdndLeave)
  216775. {
  216776. resetDragAndDrop();
  216777. }
  216778. else if (clientMsg->message_type == Atoms::XdndPosition)
  216779. {
  216780. handleDragAndDropPosition (clientMsg);
  216781. }
  216782. else if (clientMsg->message_type == Atoms::XdndDrop)
  216783. {
  216784. handleDragAndDropDrop (clientMsg);
  216785. }
  216786. else if (clientMsg->message_type == Atoms::XdndStatus)
  216787. {
  216788. handleDragAndDropStatus (clientMsg);
  216789. }
  216790. else if (clientMsg->message_type == Atoms::XdndFinished)
  216791. {
  216792. resetDragAndDrop();
  216793. }
  216794. break;
  216795. }
  216796. case SelectionNotify:
  216797. handleDragAndDropSelection (event);
  216798. break;
  216799. case SelectionClear:
  216800. case SelectionRequest:
  216801. break;
  216802. default:
  216803. #if JUCE_USE_XSHM
  216804. {
  216805. ScopedXLock xlock;
  216806. if (event->xany.type == XShmGetEventBase (display))
  216807. repainter->notifyPaintCompleted();
  216808. }
  216809. #endif
  216810. break;
  216811. }
  216812. }
  216813. void showMouseCursor (Cursor cursor) throw()
  216814. {
  216815. ScopedXLock xlock;
  216816. XDefineCursor (display, windowH, cursor);
  216817. }
  216818. void setTaskBarIcon (const Image& image)
  216819. {
  216820. ScopedXLock xlock;
  216821. taskbarImage = image.createCopy();
  216822. Screen* const screen = XDefaultScreenOfDisplay (display);
  216823. const int screenNumber = XScreenNumberOfScreen (screen);
  216824. String screenAtom ("_NET_SYSTEM_TRAY_S");
  216825. screenAtom << screenNumber;
  216826. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  216827. XGrabServer (display);
  216828. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  216829. if (managerWin != None)
  216830. XSelectInput (display, managerWin, StructureNotifyMask);
  216831. XUngrabServer (display);
  216832. XFlush (display);
  216833. if (managerWin != None)
  216834. {
  216835. XEvent ev;
  216836. zerostruct (ev);
  216837. ev.xclient.type = ClientMessage;
  216838. ev.xclient.window = managerWin;
  216839. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  216840. ev.xclient.format = 32;
  216841. ev.xclient.data.l[0] = CurrentTime;
  216842. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  216843. ev.xclient.data.l[2] = windowH;
  216844. ev.xclient.data.l[3] = 0;
  216845. ev.xclient.data.l[4] = 0;
  216846. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  216847. XSync (display, False);
  216848. }
  216849. // For older KDE's ...
  216850. long atomData = 1;
  216851. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  216852. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  216853. // For more recent KDE's...
  216854. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  216855. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  216856. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  216857. XSizeHints* hints = XAllocSizeHints();
  216858. hints->flags = PMinSize;
  216859. hints->min_width = 22;
  216860. hints->min_height = 22;
  216861. XSetWMNormalHints (display, windowH, hints);
  216862. XFree (hints);
  216863. }
  216864. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  216865. juce_UseDebuggingNewOperator
  216866. bool dontRepaint;
  216867. static ModifierKeys currentModifiers;
  216868. static bool isActiveApplication;
  216869. private:
  216870. class LinuxRepaintManager : public Timer
  216871. {
  216872. public:
  216873. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  216874. : peer (peer_),
  216875. lastTimeImageUsed (0)
  216876. {
  216877. #if JUCE_USE_XSHM
  216878. shmCompletedDrawing = true;
  216879. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  216880. if (useARGBImagesForRendering)
  216881. {
  216882. ScopedXLock xlock;
  216883. XShmSegmentInfo segmentinfo;
  216884. XImage* const testImage
  216885. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  216886. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  216887. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  216888. XDestroyImage (testImage);
  216889. }
  216890. #endif
  216891. }
  216892. ~LinuxRepaintManager()
  216893. {
  216894. }
  216895. void timerCallback()
  216896. {
  216897. #if JUCE_USE_XSHM
  216898. if (! shmCompletedDrawing)
  216899. return;
  216900. #endif
  216901. if (! regionsNeedingRepaint.isEmpty())
  216902. {
  216903. stopTimer();
  216904. performAnyPendingRepaintsNow();
  216905. }
  216906. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  216907. {
  216908. stopTimer();
  216909. image = 0;
  216910. }
  216911. }
  216912. void repaint (int x, int y, int w, int h)
  216913. {
  216914. if (! isTimerRunning())
  216915. startTimer (repaintTimerPeriod);
  216916. regionsNeedingRepaint.add (x, y, w, h);
  216917. }
  216918. void performAnyPendingRepaintsNow()
  216919. {
  216920. #if JUCE_USE_XSHM
  216921. if (! shmCompletedDrawing)
  216922. {
  216923. startTimer (repaintTimerPeriod);
  216924. return;
  216925. }
  216926. #endif
  216927. peer->clearMaskedRegion();
  216928. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  216929. regionsNeedingRepaint.clear();
  216930. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  216931. if (! totalArea.isEmpty())
  216932. {
  216933. if (image == 0 || image->getWidth() < totalArea.getWidth()
  216934. || image->getHeight() < totalArea.getHeight())
  216935. {
  216936. #if JUCE_USE_XSHM
  216937. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  216938. : Image::RGB,
  216939. #else
  216940. image = new XBitmapImage (Image::RGB,
  216941. #endif
  216942. (totalArea.getWidth() + 31) & ~31,
  216943. (totalArea.getHeight() + 31) & ~31,
  216944. false,
  216945. peer->depth,
  216946. peer->visual);
  216947. }
  216948. startTimer (repaintTimerPeriod);
  216949. LowLevelGraphicsSoftwareRenderer context (*image);
  216950. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  216951. if (context.clipToRectangleList (originalRepaintRegion))
  216952. {
  216953. if (peer->depth == 32)
  216954. {
  216955. RectangleList::Iterator i (originalRepaintRegion);
  216956. while (i.next())
  216957. {
  216958. const Rectangle<int>& r = *i.getRectangle();
  216959. image->clear (r.getX() - totalArea.getX(), r.getY() - totalArea.getY(), r.getWidth(), r.getHeight());
  216960. }
  216961. }
  216962. peer->handlePaint (context);
  216963. }
  216964. if (! peer->maskedRegion.isEmpty())
  216965. originalRepaintRegion.subtract (peer->maskedRegion);
  216966. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  216967. {
  216968. #if JUCE_USE_XSHM
  216969. shmCompletedDrawing = false;
  216970. #endif
  216971. const Rectangle<int>& r = *i.getRectangle();
  216972. image->blitToWindow (peer->windowH,
  216973. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  216974. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  216975. }
  216976. }
  216977. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  216978. startTimer (repaintTimerPeriod);
  216979. }
  216980. #if JUCE_USE_XSHM
  216981. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  216982. #endif
  216983. private:
  216984. enum { repaintTimerPeriod = 1000 / 100 };
  216985. LinuxComponentPeer* const peer;
  216986. ScopedPointer <XBitmapImage> image;
  216987. uint32 lastTimeImageUsed;
  216988. RectangleList regionsNeedingRepaint;
  216989. #if JUCE_USE_XSHM
  216990. bool useARGBImagesForRendering, shmCompletedDrawing;
  216991. #endif
  216992. LinuxRepaintManager (const LinuxRepaintManager&);
  216993. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  216994. };
  216995. ScopedPointer <LinuxRepaintManager> repainter;
  216996. friend class LinuxRepaintManager;
  216997. Window windowH, parentWindow;
  216998. int wx, wy, ww, wh;
  216999. ScopedPointer<Image> taskbarImage;
  217000. bool fullScreen, mapped;
  217001. Visual* visual;
  217002. int depth;
  217003. BorderSize windowBorder;
  217004. struct MotifWmHints
  217005. {
  217006. unsigned long flags;
  217007. unsigned long functions;
  217008. unsigned long decorations;
  217009. long input_mode;
  217010. unsigned long status;
  217011. };
  217012. static void updateKeyStates (const int keycode, const bool press) throw()
  217013. {
  217014. const int keybyte = keycode >> 3;
  217015. const int keybit = (1 << (keycode & 7));
  217016. if (press)
  217017. Keys::keyStates [keybyte] |= keybit;
  217018. else
  217019. Keys::keyStates [keybyte] &= ~keybit;
  217020. }
  217021. static void updateKeyModifiers (const int status) throw()
  217022. {
  217023. int keyMods = 0;
  217024. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  217025. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  217026. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  217027. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  217028. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  217029. Keys::capsLock = ((status & LockMask) != 0);
  217030. }
  217031. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  217032. {
  217033. int modifier = 0;
  217034. bool isModifier = true;
  217035. switch (sym)
  217036. {
  217037. case XK_Shift_L:
  217038. case XK_Shift_R:
  217039. modifier = ModifierKeys::shiftModifier;
  217040. break;
  217041. case XK_Control_L:
  217042. case XK_Control_R:
  217043. modifier = ModifierKeys::ctrlModifier;
  217044. break;
  217045. case XK_Alt_L:
  217046. case XK_Alt_R:
  217047. modifier = ModifierKeys::altModifier;
  217048. break;
  217049. case XK_Num_Lock:
  217050. if (press)
  217051. Keys::numLock = ! Keys::numLock;
  217052. break;
  217053. case XK_Caps_Lock:
  217054. if (press)
  217055. Keys::capsLock = ! Keys::capsLock;
  217056. break;
  217057. case XK_Scroll_Lock:
  217058. break;
  217059. default:
  217060. isModifier = false;
  217061. break;
  217062. }
  217063. if (modifier != 0)
  217064. {
  217065. if (press)
  217066. currentModifiers = currentModifiers.withFlags (modifier);
  217067. else
  217068. currentModifiers = currentModifiers.withoutFlags (modifier);
  217069. }
  217070. return isModifier;
  217071. }
  217072. // Alt and Num lock are not defined by standard X
  217073. // modifier constants: check what they're mapped to
  217074. static void updateModifierMappings() throw()
  217075. {
  217076. ScopedXLock xlock;
  217077. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  217078. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  217079. Keys::AltMask = 0;
  217080. Keys::NumLockMask = 0;
  217081. XModifierKeymap* mapping = XGetModifierMapping (display);
  217082. if (mapping)
  217083. {
  217084. for (int i = 0; i < 8; i++)
  217085. {
  217086. if (mapping->modifiermap [i << 1] == altLeftCode)
  217087. Keys::AltMask = 1 << i;
  217088. else if (mapping->modifiermap [i << 1] == numLockCode)
  217089. Keys::NumLockMask = 1 << i;
  217090. }
  217091. XFreeModifiermap (mapping);
  217092. }
  217093. }
  217094. void removeWindowDecorations (Window wndH)
  217095. {
  217096. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217097. if (hints != None)
  217098. {
  217099. MotifWmHints motifHints;
  217100. zerostruct (motifHints);
  217101. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  217102. motifHints.decorations = 0;
  217103. ScopedXLock xlock;
  217104. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217105. (unsigned char*) &motifHints, 4);
  217106. }
  217107. hints = XInternAtom (display, "_WIN_HINTS", True);
  217108. if (hints != None)
  217109. {
  217110. long gnomeHints = 0;
  217111. ScopedXLock xlock;
  217112. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217113. (unsigned char*) &gnomeHints, 1);
  217114. }
  217115. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  217116. if (hints != None)
  217117. {
  217118. long kwmHints = 2; /*KDE_tinyDecoration*/
  217119. ScopedXLock xlock;
  217120. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217121. (unsigned char*) &kwmHints, 1);
  217122. }
  217123. }
  217124. void addWindowButtons (Window wndH)
  217125. {
  217126. ScopedXLock xlock;
  217127. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217128. if (hints != None)
  217129. {
  217130. MotifWmHints motifHints;
  217131. zerostruct (motifHints);
  217132. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  217133. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  217134. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  217135. if ((styleFlags & windowHasCloseButton) != 0)
  217136. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  217137. if ((styleFlags & windowHasMinimiseButton) != 0)
  217138. {
  217139. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  217140. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  217141. }
  217142. if ((styleFlags & windowHasMaximiseButton) != 0)
  217143. {
  217144. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  217145. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  217146. }
  217147. if ((styleFlags & windowIsResizable) != 0)
  217148. {
  217149. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  217150. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  217151. }
  217152. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  217153. }
  217154. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  217155. if (hints != None)
  217156. {
  217157. int netHints [6];
  217158. int num = 0;
  217159. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  217160. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  217161. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  217162. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  217163. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  217164. (unsigned char*) &netHints, num);
  217165. }
  217166. }
  217167. void setWindowType (Window wndH)
  217168. {
  217169. int netHints [2];
  217170. int numHints = 0;
  217171. if ((styleFlags & windowIsTemporary) != 0
  217172. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  217173. {
  217174. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  217175. }
  217176. else
  217177. {
  217178. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  217179. }
  217180. if (netHints [numHints] != 0)
  217181. ++numHints;
  217182. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  217183. if (netHints [numHints] != 0)
  217184. ++numHints;
  217185. XChangeProperty (display, wndH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  217186. (unsigned char*) &netHints, numHints);
  217187. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  217188. {
  217189. Atom skipTaskbar = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", False);
  217190. XChangeProperty (display, wndH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  217191. (unsigned char*) &skipTaskbar, 1);
  217192. }
  217193. }
  217194. void createWindow()
  217195. {
  217196. ScopedXLock xlock;
  217197. Atoms::initialiseAtoms();
  217198. resetDragAndDrop();
  217199. // Get defaults for various properties
  217200. const int screen = DefaultScreen (display);
  217201. Window root = RootWindow (display, screen);
  217202. // Try to obtain a 32-bit visual or fallback to 24 or 16
  217203. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  217204. if (visual == 0)
  217205. {
  217206. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  217207. Process::terminate();
  217208. }
  217209. // Create and install a colormap suitable fr our visual
  217210. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  217211. XInstallColormap (display, colormap);
  217212. // Set up the window attributes
  217213. XSetWindowAttributes swa;
  217214. swa.border_pixel = 0;
  217215. swa.background_pixmap = None;
  217216. swa.colormap = colormap;
  217217. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  217218. swa.event_mask = getAllEventsMask();
  217219. Window wndH = XCreateWindow (display, root,
  217220. 0, 0, 1, 1,
  217221. 0, depth, InputOutput, visual,
  217222. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  217223. &swa);
  217224. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  217225. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  217226. GrabModeAsync, GrabModeAsync, None, None);
  217227. // Set the window context to identify the window handle object
  217228. if (XSaveContext (display, (XID) wndH, windowHandleXContext, (XPointer) this))
  217229. {
  217230. // Failed
  217231. jassertfalse
  217232. Logger::outputDebugString ("Failed to create context information for window.\n");
  217233. XDestroyWindow (display, wndH);
  217234. wndH = 0;
  217235. }
  217236. // Set window manager hints
  217237. XWMHints* wmHints = XAllocWMHints();
  217238. wmHints->flags = InputHint | StateHint;
  217239. wmHints->input = True; // Locally active input model
  217240. wmHints->initial_state = NormalState;
  217241. XSetWMHints (display, wndH, wmHints);
  217242. XFree (wmHints);
  217243. // Set the window type
  217244. setWindowType (wndH);
  217245. // Define decoration
  217246. if ((styleFlags & windowHasTitleBar) == 0)
  217247. removeWindowDecorations (wndH);
  217248. else
  217249. addWindowButtons (wndH);
  217250. // Set window name
  217251. setWindowTitle (wndH, getComponent()->getName());
  217252. // Associate the PID, allowing to be shut down when something goes wrong
  217253. unsigned long pid = getpid();
  217254. XChangeProperty (display, wndH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  217255. (unsigned char*) &pid, 1);
  217256. // Set window manager protocols
  217257. XChangeProperty (display, wndH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  217258. (unsigned char*) Atoms::ProtocolList, 2);
  217259. // Set drag and drop flags
  217260. XChangeProperty (display, wndH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  217261. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  217262. XChangeProperty (display, wndH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  217263. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  217264. XChangeProperty (display, wndH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  217265. (const unsigned char*) "", 0);
  217266. unsigned long dndVersion = Atoms::DndVersion;
  217267. XChangeProperty (display, wndH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  217268. (const unsigned char*) &dndVersion, 1);
  217269. // Initialise the pointer and keyboard mapping
  217270. // This is not the same as the logical pointer mapping the X server uses:
  217271. // we don't mess with this.
  217272. static bool mappingInitialised = false;
  217273. if (! mappingInitialised)
  217274. {
  217275. mappingInitialised = true;
  217276. const int numButtons = XGetPointerMapping (display, 0, 0);
  217277. if (numButtons == 2)
  217278. {
  217279. pointerMap[0] = Keys::LeftButton;
  217280. pointerMap[1] = Keys::RightButton;
  217281. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  217282. }
  217283. else if (numButtons >= 3)
  217284. {
  217285. pointerMap[0] = Keys::LeftButton;
  217286. pointerMap[1] = Keys::MiddleButton;
  217287. pointerMap[2] = Keys::RightButton;
  217288. if (numButtons >= 5)
  217289. {
  217290. pointerMap[3] = Keys::WheelUp;
  217291. pointerMap[4] = Keys::WheelDown;
  217292. }
  217293. }
  217294. updateModifierMappings();
  217295. }
  217296. windowH = wndH;
  217297. }
  217298. void destroyWindow()
  217299. {
  217300. ScopedXLock xlock;
  217301. XPointer handlePointer;
  217302. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  217303. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  217304. XDestroyWindow (display, windowH);
  217305. // Wait for it to complete and then remove any events for this
  217306. // window from the event queue.
  217307. XSync (display, false);
  217308. XEvent event;
  217309. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  217310. {}
  217311. }
  217312. static int getAllEventsMask() throw()
  217313. {
  217314. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  217315. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  217316. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  217317. }
  217318. static int64 getEventTime (::Time t)
  217319. {
  217320. static int64 eventTimeOffset = 0x12345678;
  217321. const int64 thisMessageTime = t;
  217322. if (eventTimeOffset == 0x12345678)
  217323. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  217324. return eventTimeOffset + thisMessageTime;
  217325. }
  217326. static void setWindowTitle (Window xwin, const String& title)
  217327. {
  217328. XTextProperty nameProperty;
  217329. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  217330. ScopedXLock xlock;
  217331. if (XStringListToTextProperty (strings, 1, &nameProperty))
  217332. {
  217333. XSetWMName (display, xwin, &nameProperty);
  217334. XSetWMIconName (display, xwin, &nameProperty);
  217335. XFree (nameProperty.value);
  217336. }
  217337. }
  217338. void updateBorderSize()
  217339. {
  217340. if ((styleFlags & windowHasTitleBar) == 0)
  217341. {
  217342. windowBorder = BorderSize (0);
  217343. }
  217344. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  217345. {
  217346. ScopedXLock xlock;
  217347. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  217348. if (hints != None)
  217349. {
  217350. unsigned char* data = 0;
  217351. unsigned long nitems, bytesLeft;
  217352. Atom actualType;
  217353. int actualFormat;
  217354. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  217355. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  217356. &data) == Success)
  217357. {
  217358. const unsigned long* const sizes = (const unsigned long*) data;
  217359. if (actualFormat == 32)
  217360. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  217361. (int) sizes[3], (int) sizes[1]);
  217362. XFree (data);
  217363. }
  217364. }
  217365. }
  217366. }
  217367. void updateBounds()
  217368. {
  217369. jassert (windowH != 0);
  217370. if (windowH != 0)
  217371. {
  217372. Window root, child;
  217373. unsigned int bw, depth;
  217374. ScopedXLock xlock;
  217375. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  217376. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  217377. &bw, &depth))
  217378. {
  217379. wx = wy = ww = wh = 0;
  217380. }
  217381. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  217382. {
  217383. wx = wy = 0;
  217384. }
  217385. }
  217386. }
  217387. void resetDragAndDrop()
  217388. {
  217389. dragAndDropFiles.clear();
  217390. lastDropPos = Point<int> (-1, -1);
  217391. dragAndDropCurrentMimeType = 0;
  217392. dragAndDropSourceWindow = 0;
  217393. srcMimeTypeAtomList.clear();
  217394. }
  217395. void sendDragAndDropMessage (XClientMessageEvent& msg)
  217396. {
  217397. msg.type = ClientMessage;
  217398. msg.display = display;
  217399. msg.window = dragAndDropSourceWindow;
  217400. msg.format = 32;
  217401. msg.data.l[0] = windowH;
  217402. ScopedXLock xlock;
  217403. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  217404. }
  217405. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  217406. {
  217407. XClientMessageEvent msg;
  217408. zerostruct (msg);
  217409. msg.message_type = Atoms::XdndStatus;
  217410. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  217411. msg.data.l[4] = dropAction;
  217412. sendDragAndDropMessage (msg);
  217413. }
  217414. void sendDragAndDropLeave()
  217415. {
  217416. XClientMessageEvent msg;
  217417. zerostruct (msg);
  217418. msg.message_type = Atoms::XdndLeave;
  217419. sendDragAndDropMessage (msg);
  217420. }
  217421. void sendDragAndDropFinish()
  217422. {
  217423. XClientMessageEvent msg;
  217424. zerostruct (msg);
  217425. msg.message_type = Atoms::XdndFinished;
  217426. sendDragAndDropMessage (msg);
  217427. }
  217428. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  217429. {
  217430. if ((clientMsg->data.l[1] & 1) == 0)
  217431. {
  217432. sendDragAndDropLeave();
  217433. if (dragAndDropFiles.size() > 0)
  217434. handleFileDragExit (dragAndDropFiles);
  217435. dragAndDropFiles.clear();
  217436. }
  217437. }
  217438. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  217439. {
  217440. if (dragAndDropSourceWindow == 0)
  217441. return;
  217442. dragAndDropSourceWindow = clientMsg->data.l[0];
  217443. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  217444. (int) clientMsg->data.l[2] & 0xffff);
  217445. dropPos -= getScreenPosition();
  217446. if (lastDropPos != dropPos)
  217447. {
  217448. lastDropPos = dropPos;
  217449. dragAndDropTimestamp = clientMsg->data.l[3];
  217450. Atom targetAction = Atoms::XdndActionCopy;
  217451. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  217452. {
  217453. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  217454. {
  217455. targetAction = Atoms::allowedActions[i];
  217456. break;
  217457. }
  217458. }
  217459. sendDragAndDropStatus (true, targetAction);
  217460. if (dragAndDropFiles.size() == 0)
  217461. updateDraggedFileList (clientMsg);
  217462. if (dragAndDropFiles.size() > 0)
  217463. handleFileDragMove (dragAndDropFiles, dropPos);
  217464. }
  217465. }
  217466. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  217467. {
  217468. if (dragAndDropFiles.size() == 0)
  217469. updateDraggedFileList (clientMsg);
  217470. const StringArray files (dragAndDropFiles);
  217471. const Point<int> lastPos (lastDropPos);
  217472. sendDragAndDropFinish();
  217473. resetDragAndDrop();
  217474. if (files.size() > 0)
  217475. handleFileDragDrop (files, lastPos);
  217476. }
  217477. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  217478. {
  217479. dragAndDropFiles.clear();
  217480. srcMimeTypeAtomList.clear();
  217481. dragAndDropCurrentMimeType = 0;
  217482. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  217483. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  217484. {
  217485. dragAndDropSourceWindow = 0;
  217486. return;
  217487. }
  217488. dragAndDropSourceWindow = clientMsg->data.l[0];
  217489. if ((clientMsg->data.l[1] & 1) != 0)
  217490. {
  217491. Atom actual;
  217492. int format;
  217493. unsigned long count = 0, remaining = 0;
  217494. unsigned char* data = 0;
  217495. ScopedXLock xlock;
  217496. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  217497. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  217498. &count, &remaining, &data);
  217499. if (data != 0)
  217500. {
  217501. if (actual == XA_ATOM && format == 32 && count != 0)
  217502. {
  217503. const unsigned long* const types = (const unsigned long*) data;
  217504. for (unsigned int i = 0; i < count; ++i)
  217505. if (types[i] != None)
  217506. srcMimeTypeAtomList.add (types[i]);
  217507. }
  217508. XFree (data);
  217509. }
  217510. }
  217511. if (srcMimeTypeAtomList.size() == 0)
  217512. {
  217513. for (int i = 2; i < 5; ++i)
  217514. if (clientMsg->data.l[i] != None)
  217515. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  217516. if (srcMimeTypeAtomList.size() == 0)
  217517. {
  217518. dragAndDropSourceWindow = 0;
  217519. return;
  217520. }
  217521. }
  217522. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  217523. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  217524. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  217525. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  217526. handleDragAndDropPosition (clientMsg);
  217527. }
  217528. void handleDragAndDropSelection (const XEvent* const evt)
  217529. {
  217530. dragAndDropFiles.clear();
  217531. if (evt->xselection.property != 0)
  217532. {
  217533. StringArray lines;
  217534. {
  217535. MemoryBlock dropData;
  217536. for (;;)
  217537. {
  217538. Atom actual;
  217539. uint8* data = 0;
  217540. unsigned long count = 0, remaining = 0;
  217541. int format = 0;
  217542. ScopedXLock xlock;
  217543. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  217544. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  217545. &format, &count, &remaining, &data) == Success)
  217546. {
  217547. dropData.append (data, count * format / 8);
  217548. XFree (data);
  217549. if (remaining == 0)
  217550. break;
  217551. }
  217552. else
  217553. {
  217554. XFree (data);
  217555. break;
  217556. }
  217557. }
  217558. lines.addLines (dropData.toString());
  217559. }
  217560. for (int i = 0; i < lines.size(); ++i)
  217561. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  217562. dragAndDropFiles.trim();
  217563. dragAndDropFiles.removeEmptyStrings();
  217564. }
  217565. }
  217566. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  217567. {
  217568. dragAndDropFiles.clear();
  217569. if (dragAndDropSourceWindow != None
  217570. && dragAndDropCurrentMimeType != 0)
  217571. {
  217572. dragAndDropTimestamp = clientMsg->data.l[2];
  217573. ScopedXLock xlock;
  217574. XConvertSelection (display,
  217575. Atoms::XdndSelection,
  217576. dragAndDropCurrentMimeType,
  217577. XInternAtom (display, "JXSelectionWindowProperty", 0),
  217578. windowH,
  217579. dragAndDropTimestamp);
  217580. }
  217581. }
  217582. StringArray dragAndDropFiles;
  217583. int dragAndDropTimestamp;
  217584. Point<int> lastDropPos;
  217585. Atom dragAndDropCurrentMimeType;
  217586. Window dragAndDropSourceWindow;
  217587. Array <Atom> srcMimeTypeAtomList;
  217588. static int pointerMap[5];
  217589. static Point<int> lastMousePos;
  217590. static void clearLastMousePos() throw()
  217591. {
  217592. lastMousePos = Point<int> (0x100000, 0x100000);
  217593. }
  217594. };
  217595. ModifierKeys LinuxComponentPeer::currentModifiers;
  217596. bool LinuxComponentPeer::isActiveApplication = false;
  217597. int LinuxComponentPeer::pointerMap[5];
  217598. Point<int> LinuxComponentPeer::lastMousePos;
  217599. bool Process::isForegroundProcess()
  217600. {
  217601. return LinuxComponentPeer::isActiveApplication;
  217602. }
  217603. void ModifierKeys::updateCurrentModifiers() throw()
  217604. {
  217605. currentModifiers = LinuxComponentPeer::currentModifiers;
  217606. }
  217607. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  217608. {
  217609. Window root, child;
  217610. int x, y, winx, winy;
  217611. unsigned int mask;
  217612. int mouseMods = 0;
  217613. ScopedXLock xlock;
  217614. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  217615. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  217616. {
  217617. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  217618. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  217619. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  217620. }
  217621. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  217622. return LinuxComponentPeer::currentModifiers;
  217623. }
  217624. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  217625. {
  217626. if (enableOrDisable)
  217627. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  217628. }
  217629. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  217630. {
  217631. return new LinuxComponentPeer (this, styleFlags);
  217632. }
  217633. // (this callback is hooked up in the messaging code)
  217634. void juce_windowMessageReceive (XEvent* event)
  217635. {
  217636. if (event->xany.window != None)
  217637. {
  217638. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  217639. if (ComponentPeer::isValidPeer (peer))
  217640. peer->handleWindowMessage (event);
  217641. }
  217642. else
  217643. {
  217644. switch (event->xany.type)
  217645. {
  217646. case KeymapNotify:
  217647. {
  217648. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  217649. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  217650. break;
  217651. }
  217652. default:
  217653. break;
  217654. }
  217655. }
  217656. }
  217657. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  217658. {
  217659. if (display == 0)
  217660. return;
  217661. #if JUCE_USE_XINERAMA
  217662. int major_opcode, first_event, first_error;
  217663. ScopedXLock xlock;
  217664. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  217665. {
  217666. typedef Bool (*tXineramaIsActive) (Display*);
  217667. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  217668. static tXineramaIsActive xXineramaIsActive = 0;
  217669. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  217670. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  217671. {
  217672. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  217673. if (h != 0)
  217674. {
  217675. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  217676. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  217677. }
  217678. }
  217679. if (xXineramaIsActive != 0
  217680. && xXineramaQueryScreens != 0
  217681. && xXineramaIsActive (display))
  217682. {
  217683. int numMonitors = 0;
  217684. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  217685. if (screens != 0)
  217686. {
  217687. for (int i = numMonitors; --i >= 0;)
  217688. {
  217689. int index = screens[i].screen_number;
  217690. if (index >= 0)
  217691. {
  217692. while (monitorCoords.size() < index)
  217693. monitorCoords.add (Rectangle<int>());
  217694. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  217695. screens[i].y_org,
  217696. screens[i].width,
  217697. screens[i].height));
  217698. }
  217699. }
  217700. XFree (screens);
  217701. }
  217702. }
  217703. }
  217704. if (monitorCoords.size() == 0)
  217705. #endif
  217706. {
  217707. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  217708. if (hints != None)
  217709. {
  217710. const int numMonitors = ScreenCount (display);
  217711. for (int i = 0; i < numMonitors; ++i)
  217712. {
  217713. Window root = RootWindow (display, i);
  217714. unsigned long nitems, bytesLeft;
  217715. Atom actualType;
  217716. int actualFormat;
  217717. unsigned char* data = 0;
  217718. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  217719. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  217720. &data) == Success)
  217721. {
  217722. const long* const position = (const long*) data;
  217723. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  217724. monitorCoords.add (Rectangle<int> (position[0], position[1],
  217725. position[2], position[3]));
  217726. XFree (data);
  217727. }
  217728. }
  217729. }
  217730. if (monitorCoords.size() == 0)
  217731. {
  217732. monitorCoords.add (Rectangle<int> (0, 0,
  217733. DisplayWidth (display, DefaultScreen (display)),
  217734. DisplayHeight (display, DefaultScreen (display))));
  217735. }
  217736. }
  217737. }
  217738. void Desktop::createMouseInputSources()
  217739. {
  217740. mouseSources.add (new MouseInputSource (0, true));
  217741. }
  217742. bool Desktop::canUseSemiTransparentWindows() throw()
  217743. {
  217744. int matchedDepth = 0;
  217745. const int desiredDepth = 32;
  217746. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  217747. && (matchedDepth == desiredDepth);
  217748. }
  217749. const Point<int> Desktop::getMousePosition()
  217750. {
  217751. Window root, child;
  217752. int x, y, winx, winy;
  217753. unsigned int mask;
  217754. ScopedXLock xlock;
  217755. if (XQueryPointer (display,
  217756. RootWindow (display, DefaultScreen (display)),
  217757. &root, &child,
  217758. &x, &y, &winx, &winy, &mask) == False)
  217759. {
  217760. // Pointer not on the default screen
  217761. x = y = -1;
  217762. }
  217763. return Point<int> (x, y);
  217764. }
  217765. void Desktop::setMousePosition (const Point<int>& newPosition)
  217766. {
  217767. ScopedXLock xlock;
  217768. Window root = RootWindow (display, DefaultScreen (display));
  217769. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  217770. }
  217771. static bool screenSaverAllowed = true;
  217772. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  217773. {
  217774. if (screenSaverAllowed != isEnabled)
  217775. {
  217776. screenSaverAllowed = isEnabled;
  217777. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  217778. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  217779. if (xScreenSaverSuspend == 0)
  217780. {
  217781. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  217782. if (h != 0)
  217783. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  217784. }
  217785. ScopedXLock xlock;
  217786. if (xScreenSaverSuspend != 0)
  217787. xScreenSaverSuspend (display, ! isEnabled);
  217788. }
  217789. }
  217790. bool Desktop::isScreenSaverEnabled() throw()
  217791. {
  217792. return screenSaverAllowed;
  217793. }
  217794. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  217795. {
  217796. ScopedXLock xlock;
  217797. const unsigned int imageW = image.getWidth();
  217798. const unsigned int imageH = image.getHeight();
  217799. #if JUCE_USE_XCURSOR
  217800. {
  217801. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  217802. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  217803. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  217804. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  217805. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  217806. static tXcursorImageCreate xXcursorImageCreate = 0;
  217807. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  217808. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  217809. static bool hasBeenLoaded = false;
  217810. if (! hasBeenLoaded)
  217811. {
  217812. hasBeenLoaded = true;
  217813. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  217814. if (h != 0)
  217815. {
  217816. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  217817. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  217818. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  217819. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  217820. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  217821. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  217822. || ! xXcursorSupportsARGB (display))
  217823. xXcursorSupportsARGB = 0;
  217824. }
  217825. }
  217826. if (xXcursorSupportsARGB != 0)
  217827. {
  217828. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  217829. if (xcImage != 0)
  217830. {
  217831. xcImage->xhot = hotspotX;
  217832. xcImage->yhot = hotspotY;
  217833. XcursorPixel* dest = xcImage->pixels;
  217834. for (int y = 0; y < (int) imageH; ++y)
  217835. for (int x = 0; x < (int) imageW; ++x)
  217836. *dest++ = image.getPixelAt (x, y).getARGB();
  217837. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  217838. xXcursorImageDestroy (xcImage);
  217839. if (result != 0)
  217840. return result;
  217841. }
  217842. }
  217843. }
  217844. #endif
  217845. Window root = RootWindow (display, DefaultScreen (display));
  217846. unsigned int cursorW, cursorH;
  217847. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  217848. return 0;
  217849. Image im (Image::ARGB, cursorW, cursorH, true);
  217850. {
  217851. Graphics g (im);
  217852. if (imageW > cursorW || imageH > cursorH)
  217853. {
  217854. hotspotX = (hotspotX * cursorW) / imageW;
  217855. hotspotY = (hotspotY * cursorH) / imageH;
  217856. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  217857. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  217858. false);
  217859. }
  217860. else
  217861. {
  217862. g.drawImageAt (&image, 0, 0);
  217863. }
  217864. }
  217865. const int stride = (cursorW + 7) >> 3;
  217866. HeapBlock <char> maskPlane, sourcePlane;
  217867. maskPlane.calloc (stride * cursorH);
  217868. sourcePlane.calloc (stride * cursorH);
  217869. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  217870. for (int y = cursorH; --y >= 0;)
  217871. {
  217872. for (int x = cursorW; --x >= 0;)
  217873. {
  217874. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  217875. const int offset = y * stride + (x >> 3);
  217876. const Colour c (im.getPixelAt (x, y));
  217877. if (c.getAlpha() >= 128)
  217878. maskPlane[offset] |= mask;
  217879. if (c.getBrightness() >= 0.5f)
  217880. sourcePlane[offset] |= mask;
  217881. }
  217882. }
  217883. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  217884. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  217885. XColor white, black;
  217886. black.red = black.green = black.blue = 0;
  217887. white.red = white.green = white.blue = 0xffff;
  217888. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  217889. XFreePixmap (display, sourcePixmap);
  217890. XFreePixmap (display, maskPixmap);
  217891. return result;
  217892. }
  217893. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  217894. {
  217895. ScopedXLock xlock;
  217896. if (cursorHandle != 0)
  217897. XFreeCursor (display, (Cursor) cursorHandle);
  217898. }
  217899. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  217900. {
  217901. unsigned int shape;
  217902. switch (type)
  217903. {
  217904. case NormalCursor: return None; // Use parent cursor
  217905. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  217906. case WaitCursor: shape = XC_watch; break;
  217907. case IBeamCursor: shape = XC_xterm; break;
  217908. case PointingHandCursor: shape = XC_hand2; break;
  217909. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  217910. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  217911. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  217912. case TopEdgeResizeCursor: shape = XC_top_side; break;
  217913. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  217914. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  217915. case RightEdgeResizeCursor: shape = XC_right_side; break;
  217916. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  217917. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  217918. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  217919. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  217920. case CrosshairCursor: shape = XC_crosshair; break;
  217921. case DraggingHandCursor:
  217922. {
  217923. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  217924. 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,
  217925. 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 };
  217926. const int dragHandDataSize = 99;
  217927. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize));
  217928. return createMouseCursorFromImage (*im, 8, 7);
  217929. }
  217930. case CopyingCursor:
  217931. {
  217932. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  217933. 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,
  217934. 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,
  217935. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  217936. const int copyCursorSize = 119;
  217937. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize));
  217938. return createMouseCursorFromImage (*im, 1, 3);
  217939. }
  217940. default:
  217941. jassertfalse;
  217942. return None;
  217943. }
  217944. ScopedXLock xlock;
  217945. return (void*) XCreateFontCursor (display, shape);
  217946. }
  217947. void MouseCursor::showInWindow (ComponentPeer* peer) const
  217948. {
  217949. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  217950. if (lp != 0)
  217951. lp->showMouseCursor ((Cursor) getHandle());
  217952. }
  217953. void MouseCursor::showInAllWindows() const
  217954. {
  217955. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  217956. showInWindow (ComponentPeer::getPeer (i));
  217957. }
  217958. Image* juce_createIconForFile (const File& file)
  217959. {
  217960. return 0;
  217961. }
  217962. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  217963. {
  217964. return new Image (format, imageWidth, imageHeight, clearImage);
  217965. }
  217966. #if JUCE_OPENGL
  217967. class WindowedGLContext : public OpenGLContext
  217968. {
  217969. public:
  217970. WindowedGLContext (Component* const component,
  217971. const OpenGLPixelFormat& pixelFormat_,
  217972. GLXContext sharedContext)
  217973. : renderContext (0),
  217974. embeddedWindow (0),
  217975. pixelFormat (pixelFormat_)
  217976. {
  217977. jassert (component != 0);
  217978. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  217979. if (peer == 0)
  217980. return;
  217981. ScopedXLock xlock;
  217982. XSync (display, False);
  217983. GLint attribs [64];
  217984. int n = 0;
  217985. attribs[n++] = GLX_RGBA;
  217986. attribs[n++] = GLX_DOUBLEBUFFER;
  217987. attribs[n++] = GLX_RED_SIZE;
  217988. attribs[n++] = pixelFormat.redBits;
  217989. attribs[n++] = GLX_GREEN_SIZE;
  217990. attribs[n++] = pixelFormat.greenBits;
  217991. attribs[n++] = GLX_BLUE_SIZE;
  217992. attribs[n++] = pixelFormat.blueBits;
  217993. attribs[n++] = GLX_ALPHA_SIZE;
  217994. attribs[n++] = pixelFormat.alphaBits;
  217995. attribs[n++] = GLX_DEPTH_SIZE;
  217996. attribs[n++] = pixelFormat.depthBufferBits;
  217997. attribs[n++] = GLX_STENCIL_SIZE;
  217998. attribs[n++] = pixelFormat.stencilBufferBits;
  217999. attribs[n++] = GLX_ACCUM_RED_SIZE;
  218000. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  218001. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  218002. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  218003. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  218004. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  218005. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  218006. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  218007. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  218008. attribs[n++] = None;
  218009. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  218010. if (bestVisual == 0)
  218011. return;
  218012. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  218013. Window windowH = (Window) peer->getNativeHandle();
  218014. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  218015. XSetWindowAttributes swa;
  218016. swa.colormap = colourMap;
  218017. swa.border_pixel = 0;
  218018. swa.event_mask = ExposureMask | StructureNotifyMask;
  218019. embeddedWindow = XCreateWindow (display, windowH,
  218020. 0, 0, 1, 1, 0,
  218021. bestVisual->depth,
  218022. InputOutput,
  218023. bestVisual->visual,
  218024. CWBorderPixel | CWColormap | CWEventMask,
  218025. &swa);
  218026. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  218027. XMapWindow (display, embeddedWindow);
  218028. XFreeColormap (display, colourMap);
  218029. XFree (bestVisual);
  218030. XSync (display, False);
  218031. }
  218032. ~WindowedGLContext()
  218033. {
  218034. makeInactive();
  218035. ScopedXLock xlock;
  218036. glXDestroyContext (display, renderContext);
  218037. XUnmapWindow (display, embeddedWindow);
  218038. XDestroyWindow (display, embeddedWindow);
  218039. }
  218040. bool makeActive() const throw()
  218041. {
  218042. jassert (renderContext != 0);
  218043. ScopedXLock xlock;
  218044. return glXMakeCurrent (display, embeddedWindow, renderContext)
  218045. && XSync (display, False);
  218046. }
  218047. bool makeInactive() const throw()
  218048. {
  218049. ScopedXLock xlock;
  218050. return (! isActive()) || glXMakeCurrent (display, None, 0);
  218051. }
  218052. bool isActive() const throw()
  218053. {
  218054. ScopedXLock xlock;
  218055. return glXGetCurrentContext() == renderContext;
  218056. }
  218057. const OpenGLPixelFormat getPixelFormat() const
  218058. {
  218059. return pixelFormat;
  218060. }
  218061. void* getRawContext() const throw()
  218062. {
  218063. return renderContext;
  218064. }
  218065. void updateWindowPosition (int x, int y, int w, int h, int)
  218066. {
  218067. ScopedXLock xlock;
  218068. XMoveResizeWindow (display, embeddedWindow,
  218069. x, y, jmax (1, w), jmax (1, h));
  218070. }
  218071. void swapBuffers()
  218072. {
  218073. ScopedXLock xlock;
  218074. glXSwapBuffers (display, embeddedWindow);
  218075. }
  218076. bool setSwapInterval (const int numFramesPerSwap)
  218077. {
  218078. // xxx needs doing..
  218079. return false;
  218080. }
  218081. int getSwapInterval() const
  218082. {
  218083. // xxx needs doing..
  218084. return 0;
  218085. }
  218086. void repaint()
  218087. {
  218088. }
  218089. juce_UseDebuggingNewOperator
  218090. GLXContext renderContext;
  218091. private:
  218092. Window embeddedWindow;
  218093. OpenGLPixelFormat pixelFormat;
  218094. WindowedGLContext (const WindowedGLContext&);
  218095. WindowedGLContext& operator= (const WindowedGLContext&);
  218096. };
  218097. OpenGLContext* OpenGLComponent::createContext()
  218098. {
  218099. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  218100. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  218101. return (c->renderContext != 0) ? c.release() : 0;
  218102. }
  218103. void juce_glViewport (const int w, const int h)
  218104. {
  218105. glViewport (0, 0, w, h);
  218106. }
  218107. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  218108. OwnedArray <OpenGLPixelFormat>& results)
  218109. {
  218110. results.add (new OpenGLPixelFormat()); // xxx
  218111. }
  218112. #endif
  218113. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  218114. {
  218115. jassertfalse // not implemented!
  218116. return false;
  218117. }
  218118. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  218119. {
  218120. jassertfalse // not implemented!
  218121. return false;
  218122. }
  218123. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  218124. {
  218125. if (! isOnDesktop ())
  218126. addToDesktop (0);
  218127. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218128. if (wp != 0)
  218129. {
  218130. wp->setTaskBarIcon (newImage);
  218131. setVisible (true);
  218132. toFront (false);
  218133. repaint();
  218134. }
  218135. }
  218136. void SystemTrayIconComponent::paint (Graphics& g)
  218137. {
  218138. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218139. if (wp != 0)
  218140. {
  218141. const Image* const image = wp->getTaskbarIcon();
  218142. if (image != 0)
  218143. {
  218144. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  218145. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  218146. false);
  218147. }
  218148. }
  218149. }
  218150. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  218151. {
  218152. // xxx not yet implemented!
  218153. }
  218154. void PlatformUtilities::beep()
  218155. {
  218156. std::cout << "\a" << std::flush;
  218157. }
  218158. bool AlertWindow::showNativeDialogBox (const String& title,
  218159. const String& bodyText,
  218160. bool isOkCancel)
  218161. {
  218162. // use a non-native one for the time being..
  218163. if (isOkCancel)
  218164. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  218165. else
  218166. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  218167. return true;
  218168. }
  218169. const int KeyPress::spaceKey = XK_space & 0xff;
  218170. const int KeyPress::returnKey = XK_Return & 0xff;
  218171. const int KeyPress::escapeKey = XK_Escape & 0xff;
  218172. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  218173. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  218174. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  218175. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  218176. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  218177. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  218178. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  218179. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  218180. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  218181. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  218182. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  218183. const int KeyPress::tabKey = XK_Tab & 0xff;
  218184. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  218185. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  218186. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  218187. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  218188. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  218189. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  218190. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  218191. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  218192. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  218193. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  218194. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  218195. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  218196. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  218197. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  218198. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  218199. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  218200. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  218201. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  218202. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  218203. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  218204. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  218205. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  218206. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  218207. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  218208. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  218209. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  218210. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  218211. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  218212. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  218213. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  218214. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  218215. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  218216. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  218217. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  218218. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  218219. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  218220. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  218221. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  218222. #endif
  218223. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  218224. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  218225. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218226. // compiled on its own).
  218227. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  218228. static const int maxNumChans = 64;
  218229. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  218230. {
  218231. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  218232. snd_pcm_hw_params_t* hwParams;
  218233. snd_pcm_hw_params_alloca (&hwParams);
  218234. for (int i = 0; ratesToTry[i] != 0; ++i)
  218235. {
  218236. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  218237. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  218238. {
  218239. rates.addIfNotAlreadyThere (ratesToTry[i]);
  218240. }
  218241. }
  218242. }
  218243. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  218244. {
  218245. snd_pcm_hw_params_t *params;
  218246. snd_pcm_hw_params_alloca (&params);
  218247. if (snd_pcm_hw_params_any (handle, params) >= 0)
  218248. {
  218249. snd_pcm_hw_params_get_channels_min (params, minChans);
  218250. snd_pcm_hw_params_get_channels_max (params, maxChans);
  218251. }
  218252. }
  218253. static void getDeviceProperties (const String& deviceID,
  218254. unsigned int& minChansOut,
  218255. unsigned int& maxChansOut,
  218256. unsigned int& minChansIn,
  218257. unsigned int& maxChansIn,
  218258. Array <int>& rates)
  218259. {
  218260. if (deviceID.isEmpty())
  218261. return;
  218262. snd_ctl_t* handle;
  218263. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  218264. {
  218265. snd_pcm_info_t* info;
  218266. snd_pcm_info_alloca (&info);
  218267. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  218268. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  218269. snd_pcm_info_set_subdevice (info, 0);
  218270. if (snd_ctl_pcm_info (handle, info) >= 0)
  218271. {
  218272. snd_pcm_t* pcmHandle;
  218273. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218274. {
  218275. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  218276. getDeviceSampleRates (pcmHandle, rates);
  218277. snd_pcm_close (pcmHandle);
  218278. }
  218279. }
  218280. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  218281. if (snd_ctl_pcm_info (handle, info) >= 0)
  218282. {
  218283. snd_pcm_t* pcmHandle;
  218284. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218285. {
  218286. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  218287. if (rates.size() == 0)
  218288. getDeviceSampleRates (pcmHandle, rates);
  218289. snd_pcm_close (pcmHandle);
  218290. }
  218291. }
  218292. snd_ctl_close (handle);
  218293. }
  218294. }
  218295. class ALSADevice
  218296. {
  218297. public:
  218298. ALSADevice (const String& deviceID,
  218299. const bool forInput)
  218300. : handle (0),
  218301. bitDepth (16),
  218302. numChannelsRunning (0),
  218303. isInput (forInput),
  218304. sampleFormat (AudioDataConverters::int16LE)
  218305. {
  218306. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  218307. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  218308. SND_PCM_ASYNC));
  218309. }
  218310. ~ALSADevice()
  218311. {
  218312. if (handle != 0)
  218313. snd_pcm_close (handle);
  218314. }
  218315. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  218316. {
  218317. if (handle == 0)
  218318. return false;
  218319. snd_pcm_hw_params_t* hwParams;
  218320. snd_pcm_hw_params_alloca (&hwParams);
  218321. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  218322. return false;
  218323. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  218324. isInterleaved = false;
  218325. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  218326. isInterleaved = true;
  218327. else
  218328. {
  218329. jassertfalse
  218330. return false;
  218331. }
  218332. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  218333. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  218334. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  218335. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  218336. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  218337. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  218338. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  218339. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  218340. bitDepth = 0;
  218341. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  218342. {
  218343. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  218344. {
  218345. bitDepth = formatsToTry [i + 1];
  218346. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  218347. break;
  218348. }
  218349. }
  218350. if (bitDepth == 0)
  218351. {
  218352. error = "device doesn't support a compatible PCM format";
  218353. DBG ("ALSA error: " + error + "\n");
  218354. return false;
  218355. }
  218356. int dir = 0;
  218357. unsigned int periods = 4;
  218358. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  218359. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  218360. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  218361. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  218362. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  218363. || failed (snd_pcm_hw_params (handle, hwParams)))
  218364. {
  218365. return false;
  218366. }
  218367. snd_pcm_sw_params_t* swParams;
  218368. snd_pcm_sw_params_alloca (&swParams);
  218369. snd_pcm_uframes_t boundary;
  218370. if (failed (snd_pcm_sw_params_current (handle, swParams))
  218371. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  218372. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  218373. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  218374. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  218375. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  218376. || failed (snd_pcm_sw_params (handle, swParams)))
  218377. {
  218378. return false;
  218379. }
  218380. /*
  218381. #if JUCE_DEBUG
  218382. // enable this to dump the config of the devices that get opened
  218383. snd_output_t* out;
  218384. snd_output_stdio_attach (&out, stderr, 0);
  218385. snd_pcm_hw_params_dump (hwParams, out);
  218386. snd_pcm_sw_params_dump (swParams, out);
  218387. #endif
  218388. */
  218389. numChannelsRunning = numChannels;
  218390. return true;
  218391. }
  218392. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  218393. {
  218394. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  218395. float** const data = outputChannelBuffer.getArrayOfChannels();
  218396. if (isInterleaved)
  218397. {
  218398. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218399. float* interleaved = static_cast <float*> (scratch.getData());
  218400. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  218401. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218402. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  218403. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218404. return false;
  218405. }
  218406. else
  218407. {
  218408. for (int i = 0; i < numChannelsRunning; ++i)
  218409. if (data[i] != 0)
  218410. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  218411. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  218412. if (failed (num))
  218413. {
  218414. if (num == -EPIPE)
  218415. {
  218416. if (failed (snd_pcm_prepare (handle)))
  218417. return false;
  218418. }
  218419. else if (num != -ESTRPIPE)
  218420. return false;
  218421. }
  218422. }
  218423. return true;
  218424. }
  218425. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  218426. {
  218427. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  218428. float** const data = inputChannelBuffer.getArrayOfChannels();
  218429. if (isInterleaved)
  218430. {
  218431. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218432. float* interleaved = static_cast <float*> (scratch.getData());
  218433. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  218434. if (failed (num))
  218435. {
  218436. if (num == -EPIPE)
  218437. {
  218438. if (failed (snd_pcm_prepare (handle)))
  218439. return false;
  218440. }
  218441. else if (num != -ESTRPIPE)
  218442. return false;
  218443. }
  218444. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218445. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  218446. }
  218447. else
  218448. {
  218449. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  218450. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218451. return false;
  218452. for (int i = 0; i < numChannelsRunning; ++i)
  218453. if (data[i] != 0)
  218454. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  218455. }
  218456. return true;
  218457. }
  218458. juce_UseDebuggingNewOperator
  218459. snd_pcm_t* handle;
  218460. String error;
  218461. int bitDepth, numChannelsRunning;
  218462. private:
  218463. const bool isInput;
  218464. bool isInterleaved;
  218465. MemoryBlock scratch;
  218466. AudioDataConverters::DataFormat sampleFormat;
  218467. bool failed (const int errorNum)
  218468. {
  218469. if (errorNum >= 0)
  218470. return false;
  218471. error = snd_strerror (errorNum);
  218472. DBG ("ALSA error: " + error + "\n");
  218473. return true;
  218474. }
  218475. };
  218476. class ALSAThread : public Thread
  218477. {
  218478. public:
  218479. ALSAThread (const String& inputId_,
  218480. const String& outputId_)
  218481. : Thread ("Juce ALSA"),
  218482. sampleRate (0),
  218483. bufferSize (0),
  218484. callback (0),
  218485. inputId (inputId_),
  218486. outputId (outputId_),
  218487. outputDevice (0),
  218488. inputDevice (0),
  218489. numCallbacks (0),
  218490. inputChannelBuffer (1, 1),
  218491. outputChannelBuffer (1, 1)
  218492. {
  218493. initialiseRatesAndChannels();
  218494. }
  218495. ~ALSAThread()
  218496. {
  218497. close();
  218498. }
  218499. void open (BigInteger inputChannels,
  218500. BigInteger outputChannels,
  218501. const double sampleRate_,
  218502. const int bufferSize_)
  218503. {
  218504. close();
  218505. error = String::empty;
  218506. sampleRate = sampleRate_;
  218507. bufferSize = bufferSize_;
  218508. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  218509. inputChannelBuffer.clear();
  218510. inputChannelDataForCallback.clear();
  218511. currentInputChans.clear();
  218512. if (inputChannels.getHighestBit() >= 0)
  218513. {
  218514. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  218515. {
  218516. if (inputChannels[i])
  218517. {
  218518. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  218519. currentInputChans.setBit (i);
  218520. }
  218521. }
  218522. }
  218523. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  218524. outputChannelBuffer.clear();
  218525. outputChannelDataForCallback.clear();
  218526. currentOutputChans.clear();
  218527. if (outputChannels.getHighestBit() >= 0)
  218528. {
  218529. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  218530. {
  218531. if (outputChannels[i])
  218532. {
  218533. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  218534. currentOutputChans.setBit (i);
  218535. }
  218536. }
  218537. }
  218538. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  218539. {
  218540. outputDevice = new ALSADevice (outputId, false);
  218541. if (outputDevice->error.isNotEmpty())
  218542. {
  218543. error = outputDevice->error;
  218544. deleteAndZero (outputDevice);
  218545. return;
  218546. }
  218547. currentOutputChans.setRange (0, minChansOut, true);
  218548. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  218549. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  218550. bufferSize))
  218551. {
  218552. error = outputDevice->error;
  218553. deleteAndZero (outputDevice);
  218554. return;
  218555. }
  218556. }
  218557. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  218558. {
  218559. inputDevice = new ALSADevice (inputId, true);
  218560. if (inputDevice->error.isNotEmpty())
  218561. {
  218562. error = inputDevice->error;
  218563. deleteAndZero (inputDevice);
  218564. return;
  218565. }
  218566. currentInputChans.setRange (0, minChansIn, true);
  218567. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  218568. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  218569. bufferSize))
  218570. {
  218571. error = inputDevice->error;
  218572. deleteAndZero (inputDevice);
  218573. return;
  218574. }
  218575. }
  218576. if (outputDevice == 0 && inputDevice == 0)
  218577. {
  218578. error = "no channels";
  218579. return;
  218580. }
  218581. if (outputDevice != 0 && inputDevice != 0)
  218582. {
  218583. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  218584. }
  218585. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  218586. return;
  218587. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  218588. return;
  218589. startThread (9);
  218590. int count = 1000;
  218591. while (numCallbacks == 0)
  218592. {
  218593. sleep (5);
  218594. if (--count < 0 || ! isThreadRunning())
  218595. {
  218596. error = "device didn't start";
  218597. break;
  218598. }
  218599. }
  218600. }
  218601. void close()
  218602. {
  218603. stopThread (6000);
  218604. deleteAndZero (inputDevice);
  218605. deleteAndZero (outputDevice);
  218606. inputChannelBuffer.setSize (1, 1);
  218607. outputChannelBuffer.setSize (1, 1);
  218608. numCallbacks = 0;
  218609. }
  218610. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  218611. {
  218612. const ScopedLock sl (callbackLock);
  218613. callback = newCallback;
  218614. }
  218615. void run()
  218616. {
  218617. while (! threadShouldExit())
  218618. {
  218619. if (inputDevice != 0)
  218620. {
  218621. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  218622. {
  218623. DBG ("ALSA: read failure");
  218624. break;
  218625. }
  218626. }
  218627. if (threadShouldExit())
  218628. break;
  218629. {
  218630. const ScopedLock sl (callbackLock);
  218631. ++numCallbacks;
  218632. if (callback != 0)
  218633. {
  218634. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  218635. inputChannelDataForCallback.size(),
  218636. outputChannelDataForCallback.getRawDataPointer(),
  218637. outputChannelDataForCallback.size(),
  218638. bufferSize);
  218639. }
  218640. else
  218641. {
  218642. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  218643. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  218644. }
  218645. }
  218646. if (outputDevice != 0)
  218647. {
  218648. failed (snd_pcm_wait (outputDevice->handle, 2000));
  218649. if (threadShouldExit())
  218650. break;
  218651. failed (snd_pcm_avail_update (outputDevice->handle));
  218652. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  218653. {
  218654. DBG ("ALSA: write failure");
  218655. break;
  218656. }
  218657. }
  218658. }
  218659. }
  218660. int getBitDepth() const throw()
  218661. {
  218662. if (outputDevice != 0)
  218663. return outputDevice->bitDepth;
  218664. if (inputDevice != 0)
  218665. return inputDevice->bitDepth;
  218666. return 16;
  218667. }
  218668. juce_UseDebuggingNewOperator
  218669. String error;
  218670. double sampleRate;
  218671. int bufferSize;
  218672. BigInteger currentInputChans, currentOutputChans;
  218673. Array <int> sampleRates;
  218674. StringArray channelNamesOut, channelNamesIn;
  218675. AudioIODeviceCallback* callback;
  218676. private:
  218677. const String inputId, outputId;
  218678. ALSADevice* outputDevice;
  218679. ALSADevice* inputDevice;
  218680. int numCallbacks;
  218681. CriticalSection callbackLock;
  218682. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  218683. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  218684. unsigned int minChansOut, maxChansOut;
  218685. unsigned int minChansIn, maxChansIn;
  218686. bool failed (const int errorNum) throw()
  218687. {
  218688. if (errorNum >= 0)
  218689. return false;
  218690. error = snd_strerror (errorNum);
  218691. DBG ("ALSA error: " + error + "\n");
  218692. return true;
  218693. }
  218694. void initialiseRatesAndChannels() throw()
  218695. {
  218696. sampleRates.clear();
  218697. channelNamesOut.clear();
  218698. channelNamesIn.clear();
  218699. minChansOut = 0;
  218700. maxChansOut = 0;
  218701. minChansIn = 0;
  218702. maxChansIn = 0;
  218703. unsigned int dummy = 0;
  218704. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  218705. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  218706. unsigned int i;
  218707. for (i = 0; i < maxChansOut; ++i)
  218708. channelNamesOut.add ("channel " + String ((int) i + 1));
  218709. for (i = 0; i < maxChansIn; ++i)
  218710. channelNamesIn.add ("channel " + String ((int) i + 1));
  218711. }
  218712. };
  218713. class ALSAAudioIODevice : public AudioIODevice
  218714. {
  218715. public:
  218716. ALSAAudioIODevice (const String& deviceName,
  218717. const String& inputId_,
  218718. const String& outputId_)
  218719. : AudioIODevice (deviceName, "ALSA"),
  218720. inputId (inputId_),
  218721. outputId (outputId_),
  218722. isOpen_ (false),
  218723. isStarted (false),
  218724. internal (new ALSAThread (inputId_, outputId_))
  218725. {
  218726. }
  218727. ~ALSAAudioIODevice()
  218728. {
  218729. }
  218730. const StringArray getOutputChannelNames()
  218731. {
  218732. return internal->channelNamesOut;
  218733. }
  218734. const StringArray getInputChannelNames()
  218735. {
  218736. return internal->channelNamesIn;
  218737. }
  218738. int getNumSampleRates()
  218739. {
  218740. return internal->sampleRates.size();
  218741. }
  218742. double getSampleRate (int index)
  218743. {
  218744. return internal->sampleRates [index];
  218745. }
  218746. int getNumBufferSizesAvailable()
  218747. {
  218748. return 50;
  218749. }
  218750. int getBufferSizeSamples (int index)
  218751. {
  218752. int n = 16;
  218753. for (int i = 0; i < index; ++i)
  218754. n += n < 64 ? 16
  218755. : (n < 512 ? 32
  218756. : (n < 1024 ? 64
  218757. : (n < 2048 ? 128 : 256)));
  218758. return n;
  218759. }
  218760. int getDefaultBufferSize()
  218761. {
  218762. return 512;
  218763. }
  218764. const String open (const BigInteger& inputChannels,
  218765. const BigInteger& outputChannels,
  218766. double sampleRate,
  218767. int bufferSizeSamples)
  218768. {
  218769. close();
  218770. if (bufferSizeSamples <= 0)
  218771. bufferSizeSamples = getDefaultBufferSize();
  218772. if (sampleRate <= 0)
  218773. {
  218774. for (int i = 0; i < getNumSampleRates(); ++i)
  218775. {
  218776. if (getSampleRate (i) >= 44100)
  218777. {
  218778. sampleRate = getSampleRate (i);
  218779. break;
  218780. }
  218781. }
  218782. }
  218783. internal->open (inputChannels, outputChannels,
  218784. sampleRate, bufferSizeSamples);
  218785. isOpen_ = internal->error.isEmpty();
  218786. return internal->error;
  218787. }
  218788. void close()
  218789. {
  218790. stop();
  218791. internal->close();
  218792. isOpen_ = false;
  218793. }
  218794. bool isOpen()
  218795. {
  218796. return isOpen_;
  218797. }
  218798. int getCurrentBufferSizeSamples()
  218799. {
  218800. return internal->bufferSize;
  218801. }
  218802. double getCurrentSampleRate()
  218803. {
  218804. return internal->sampleRate;
  218805. }
  218806. int getCurrentBitDepth()
  218807. {
  218808. return internal->getBitDepth();
  218809. }
  218810. const BigInteger getActiveOutputChannels() const
  218811. {
  218812. return internal->currentOutputChans;
  218813. }
  218814. const BigInteger getActiveInputChannels() const
  218815. {
  218816. return internal->currentInputChans;
  218817. }
  218818. int getOutputLatencyInSamples()
  218819. {
  218820. return 0;
  218821. }
  218822. int getInputLatencyInSamples()
  218823. {
  218824. return 0;
  218825. }
  218826. void start (AudioIODeviceCallback* callback)
  218827. {
  218828. if (! isOpen_)
  218829. callback = 0;
  218830. internal->setCallback (callback);
  218831. if (callback != 0)
  218832. callback->audioDeviceAboutToStart (this);
  218833. isStarted = (callback != 0);
  218834. }
  218835. void stop()
  218836. {
  218837. AudioIODeviceCallback* const oldCallback = internal->callback;
  218838. start (0);
  218839. if (oldCallback != 0)
  218840. oldCallback->audioDeviceStopped();
  218841. }
  218842. bool isPlaying()
  218843. {
  218844. return isStarted && internal->error.isEmpty();
  218845. }
  218846. const String getLastError()
  218847. {
  218848. return internal->error;
  218849. }
  218850. String inputId, outputId;
  218851. private:
  218852. bool isOpen_, isStarted;
  218853. ScopedPointer<ALSAThread> internal;
  218854. };
  218855. class ALSAAudioIODeviceType : public AudioIODeviceType
  218856. {
  218857. public:
  218858. ALSAAudioIODeviceType()
  218859. : AudioIODeviceType ("ALSA"),
  218860. hasScanned (false)
  218861. {
  218862. }
  218863. ~ALSAAudioIODeviceType()
  218864. {
  218865. }
  218866. void scanForDevices()
  218867. {
  218868. if (hasScanned)
  218869. return;
  218870. hasScanned = true;
  218871. inputNames.clear();
  218872. inputIds.clear();
  218873. outputNames.clear();
  218874. outputIds.clear();
  218875. snd_ctl_t* handle;
  218876. snd_ctl_card_info_t* info;
  218877. snd_ctl_card_info_alloca (&info);
  218878. int cardNum = -1;
  218879. while (outputIds.size() + inputIds.size() <= 32)
  218880. {
  218881. snd_card_next (&cardNum);
  218882. if (cardNum < 0)
  218883. break;
  218884. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  218885. {
  218886. if (snd_ctl_card_info (handle, info) >= 0)
  218887. {
  218888. String cardId (snd_ctl_card_info_get_id (info));
  218889. if (cardId.removeCharacters ("0123456789").isEmpty())
  218890. cardId = String (cardNum);
  218891. int device = -1;
  218892. for (;;)
  218893. {
  218894. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  218895. break;
  218896. String id, name;
  218897. id << "hw:" << cardId << ',' << device;
  218898. bool isInput, isOutput;
  218899. if (testDevice (id, isInput, isOutput))
  218900. {
  218901. name << snd_ctl_card_info_get_name (info);
  218902. if (name.isEmpty())
  218903. name = id;
  218904. if (isInput)
  218905. {
  218906. inputNames.add (name);
  218907. inputIds.add (id);
  218908. }
  218909. if (isOutput)
  218910. {
  218911. outputNames.add (name);
  218912. outputIds.add (id);
  218913. }
  218914. }
  218915. }
  218916. }
  218917. snd_ctl_close (handle);
  218918. }
  218919. }
  218920. inputNames.appendNumbersToDuplicates (false, true);
  218921. outputNames.appendNumbersToDuplicates (false, true);
  218922. }
  218923. const StringArray getDeviceNames (bool wantInputNames) const
  218924. {
  218925. jassert (hasScanned); // need to call scanForDevices() before doing this
  218926. return wantInputNames ? inputNames : outputNames;
  218927. }
  218928. int getDefaultDeviceIndex (bool forInput) const
  218929. {
  218930. jassert (hasScanned); // need to call scanForDevices() before doing this
  218931. return 0;
  218932. }
  218933. bool hasSeparateInputsAndOutputs() const { return true; }
  218934. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  218935. {
  218936. jassert (hasScanned); // need to call scanForDevices() before doing this
  218937. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  218938. if (d == 0)
  218939. return -1;
  218940. return asInput ? inputIds.indexOf (d->inputId)
  218941. : outputIds.indexOf (d->outputId);
  218942. }
  218943. AudioIODevice* createDevice (const String& outputDeviceName,
  218944. const String& inputDeviceName)
  218945. {
  218946. jassert (hasScanned); // need to call scanForDevices() before doing this
  218947. const int inputIndex = inputNames.indexOf (inputDeviceName);
  218948. const int outputIndex = outputNames.indexOf (outputDeviceName);
  218949. String deviceName (outputIndex >= 0 ? outputDeviceName
  218950. : inputDeviceName);
  218951. if (inputIndex >= 0 || outputIndex >= 0)
  218952. return new ALSAAudioIODevice (deviceName,
  218953. inputIds [inputIndex],
  218954. outputIds [outputIndex]);
  218955. return 0;
  218956. }
  218957. juce_UseDebuggingNewOperator
  218958. private:
  218959. StringArray inputNames, outputNames, inputIds, outputIds;
  218960. bool hasScanned;
  218961. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  218962. {
  218963. unsigned int minChansOut = 0, maxChansOut = 0;
  218964. unsigned int minChansIn = 0, maxChansIn = 0;
  218965. Array <int> rates;
  218966. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  218967. DBG ("ALSA device: " + id
  218968. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  218969. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  218970. + " rates=" + String (rates.size()));
  218971. isInput = maxChansIn > 0;
  218972. isOutput = maxChansOut > 0;
  218973. return (isInput || isOutput) && rates.size() > 0;
  218974. }
  218975. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  218976. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  218977. };
  218978. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  218979. {
  218980. return new ALSAAudioIODeviceType();
  218981. }
  218982. #endif
  218983. /*** End of inlined file: juce_linux_Audio.cpp ***/
  218984. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  218985. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218986. // compiled on its own).
  218987. #ifdef JUCE_INCLUDED_FILE
  218988. #if JUCE_JACK
  218989. static void* juce_libjack_handle = 0;
  218990. void* juce_load_jack_function (const char* const name)
  218991. {
  218992. if (juce_libjack_handle == 0)
  218993. return 0;
  218994. return dlsym (juce_libjack_handle, name);
  218995. }
  218996. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  218997. typedef return_type (*fn_name##_ptr_t)argument_types; \
  218998. return_type fn_name argument_types { \
  218999. static fn_name##_ptr_t fn = 0; \
  219000. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  219001. if (fn) return (*fn)arguments; \
  219002. else return 0; \
  219003. }
  219004. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  219005. typedef void (*fn_name##_ptr_t)argument_types; \
  219006. void fn_name argument_types { \
  219007. static fn_name##_ptr_t fn = 0; \
  219008. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  219009. if (fn) (*fn)arguments; \
  219010. }
  219011. 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));
  219012. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  219013. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  219014. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  219015. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  219016. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  219017. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  219018. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  219019. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  219020. 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));
  219021. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  219022. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  219023. 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));
  219024. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  219025. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  219026. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  219027. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  219028. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  219029. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  219030. #if JUCE_DEBUG
  219031. #define JACK_LOGGING_ENABLED 1
  219032. #endif
  219033. #if JACK_LOGGING_ENABLED
  219034. static void jack_Log (const String& s)
  219035. {
  219036. std::cerr << s << std::endl;
  219037. }
  219038. static void dumpJackErrorMessage (const jack_status_t status) throw()
  219039. {
  219040. if (status & JackServerFailed || status & JackServerError)
  219041. jack_Log ("Unable to connect to JACK server");
  219042. if (status & JackVersionError)
  219043. jack_Log ("Client's protocol version does not match");
  219044. if (status & JackInvalidOption)
  219045. jack_Log ("The operation contained an invalid or unsupported option");
  219046. if (status & JackNameNotUnique)
  219047. jack_Log ("The desired client name was not unique");
  219048. if (status & JackNoSuchClient)
  219049. jack_Log ("Requested client does not exist");
  219050. if (status & JackInitFailure)
  219051. jack_Log ("Unable to initialize client");
  219052. }
  219053. #else
  219054. #define dumpJackErrorMessage(a) {}
  219055. #define jack_Log(...) {}
  219056. #endif
  219057. #ifndef JUCE_JACK_CLIENT_NAME
  219058. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  219059. #endif
  219060. class JackAudioIODevice : public AudioIODevice
  219061. {
  219062. public:
  219063. JackAudioIODevice (const String& deviceName,
  219064. const String& inputId_,
  219065. const String& outputId_)
  219066. : AudioIODevice (deviceName, "JACK"),
  219067. inputId (inputId_),
  219068. outputId (outputId_),
  219069. isOpen_ (false),
  219070. callback (0),
  219071. totalNumberOfInputChannels (0),
  219072. totalNumberOfOutputChannels (0)
  219073. {
  219074. jassert (deviceName.isNotEmpty());
  219075. jack_status_t status;
  219076. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  219077. if (client == 0)
  219078. {
  219079. dumpJackErrorMessage (status);
  219080. }
  219081. else
  219082. {
  219083. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  219084. // open input ports
  219085. const StringArray inputChannels (getInputChannelNames());
  219086. for (int i = 0; i < inputChannels.size(); i++)
  219087. {
  219088. String inputName;
  219089. inputName << "in_" << ++totalNumberOfInputChannels;
  219090. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  219091. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  219092. }
  219093. // open output ports
  219094. const StringArray outputChannels (getOutputChannelNames());
  219095. for (int i = 0; i < outputChannels.size (); i++)
  219096. {
  219097. String outputName;
  219098. outputName << "out_" << ++totalNumberOfOutputChannels;
  219099. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  219100. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  219101. }
  219102. inChans.calloc (totalNumberOfInputChannels + 2);
  219103. outChans.calloc (totalNumberOfOutputChannels + 2);
  219104. }
  219105. }
  219106. ~JackAudioIODevice()
  219107. {
  219108. close();
  219109. if (client != 0)
  219110. {
  219111. JUCE_NAMESPACE::jack_client_close (client);
  219112. client = 0;
  219113. }
  219114. }
  219115. const StringArray getChannelNames (bool forInput) const
  219116. {
  219117. StringArray names;
  219118. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  219119. forInput ? JackPortIsInput : JackPortIsOutput);
  219120. if (ports != 0)
  219121. {
  219122. int j = 0;
  219123. while (ports[j] != 0)
  219124. {
  219125. const String portName (ports [j++]);
  219126. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219127. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  219128. }
  219129. free (ports);
  219130. }
  219131. return names;
  219132. }
  219133. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  219134. const StringArray getInputChannelNames() { return getChannelNames (true); }
  219135. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  219136. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  219137. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  219138. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  219139. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  219140. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  219141. double sampleRate, int bufferSizeSamples)
  219142. {
  219143. if (client == 0)
  219144. {
  219145. lastError = "No JACK client running";
  219146. return lastError;
  219147. }
  219148. lastError = String::empty;
  219149. close();
  219150. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  219151. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  219152. JUCE_NAMESPACE::jack_activate (client);
  219153. isOpen_ = true;
  219154. if (! inputChannels.isZero())
  219155. {
  219156. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219157. if (ports != 0)
  219158. {
  219159. const int numInputChannels = inputChannels.getHighestBit() + 1;
  219160. for (int i = 0; i < numInputChannels; ++i)
  219161. {
  219162. const String portName (ports[i]);
  219163. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219164. {
  219165. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  219166. if (error != 0)
  219167. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219168. }
  219169. }
  219170. free (ports);
  219171. }
  219172. }
  219173. if (! outputChannels.isZero())
  219174. {
  219175. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219176. if (ports != 0)
  219177. {
  219178. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  219179. for (int i = 0; i < numOutputChannels; ++i)
  219180. {
  219181. const String portName (ports[i]);
  219182. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219183. {
  219184. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  219185. if (error != 0)
  219186. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219187. }
  219188. }
  219189. free (ports);
  219190. }
  219191. }
  219192. return lastError;
  219193. }
  219194. void close()
  219195. {
  219196. stop();
  219197. if (client != 0)
  219198. {
  219199. JUCE_NAMESPACE::jack_deactivate (client);
  219200. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  219201. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  219202. }
  219203. isOpen_ = false;
  219204. }
  219205. void start (AudioIODeviceCallback* newCallback)
  219206. {
  219207. if (isOpen_ && newCallback != callback)
  219208. {
  219209. if (newCallback != 0)
  219210. newCallback->audioDeviceAboutToStart (this);
  219211. AudioIODeviceCallback* const oldCallback = callback;
  219212. {
  219213. const ScopedLock sl (callbackLock);
  219214. callback = newCallback;
  219215. }
  219216. if (oldCallback != 0)
  219217. oldCallback->audioDeviceStopped();
  219218. }
  219219. }
  219220. void stop()
  219221. {
  219222. start (0);
  219223. }
  219224. bool isOpen() { return isOpen_; }
  219225. bool isPlaying() { return callback != 0; }
  219226. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  219227. double getCurrentSampleRate() { return getSampleRate (0); }
  219228. int getCurrentBitDepth() { return 32; }
  219229. const String getLastError() { return lastError; }
  219230. const BigInteger getActiveOutputChannels() const
  219231. {
  219232. BigInteger outputBits;
  219233. for (int i = 0; i < outputPorts.size(); i++)
  219234. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  219235. outputBits.setBit (i);
  219236. return outputBits;
  219237. }
  219238. const BigInteger getActiveInputChannels() const
  219239. {
  219240. BigInteger inputBits;
  219241. for (int i = 0; i < inputPorts.size(); i++)
  219242. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  219243. inputBits.setBit (i);
  219244. return inputBits;
  219245. }
  219246. int getOutputLatencyInSamples()
  219247. {
  219248. int latency = 0;
  219249. for (int i = 0; i < outputPorts.size(); i++)
  219250. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  219251. return latency;
  219252. }
  219253. int getInputLatencyInSamples()
  219254. {
  219255. int latency = 0;
  219256. for (int i = 0; i < inputPorts.size(); i++)
  219257. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  219258. return latency;
  219259. }
  219260. String inputId, outputId;
  219261. private:
  219262. void process (const int numSamples)
  219263. {
  219264. int i, numActiveInChans = 0, numActiveOutChans = 0;
  219265. for (i = 0; i < totalNumberOfInputChannels; ++i)
  219266. {
  219267. jack_default_audio_sample_t* in
  219268. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  219269. if (in != 0)
  219270. inChans [numActiveInChans++] = (float*) in;
  219271. }
  219272. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  219273. {
  219274. jack_default_audio_sample_t* out
  219275. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  219276. if (out != 0)
  219277. outChans [numActiveOutChans++] = (float*) out;
  219278. }
  219279. const ScopedLock sl (callbackLock);
  219280. if (callback != 0)
  219281. {
  219282. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  219283. outChans, numActiveOutChans, numSamples);
  219284. }
  219285. else
  219286. {
  219287. for (i = 0; i < numActiveOutChans; ++i)
  219288. zeromem (outChans[i], sizeof (float) * numSamples);
  219289. }
  219290. }
  219291. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  219292. {
  219293. if (callbackArgument != 0)
  219294. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  219295. return 0;
  219296. }
  219297. static void threadInitCallback (void* callbackArgument)
  219298. {
  219299. jack_Log ("JackAudioIODevice::initialise");
  219300. }
  219301. static void shutdownCallback (void* callbackArgument)
  219302. {
  219303. jack_Log ("JackAudioIODevice::shutdown");
  219304. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  219305. if (device != 0)
  219306. {
  219307. device->client = 0;
  219308. device->close();
  219309. }
  219310. }
  219311. static void errorCallback (const char* msg)
  219312. {
  219313. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  219314. }
  219315. bool isOpen_;
  219316. jack_client_t* client;
  219317. String lastError;
  219318. AudioIODeviceCallback* callback;
  219319. CriticalSection callbackLock;
  219320. HeapBlock <float*> inChans, outChans;
  219321. int totalNumberOfInputChannels;
  219322. int totalNumberOfOutputChannels;
  219323. VoidArray inputPorts, outputPorts;
  219324. };
  219325. class JackAudioIODeviceType : public AudioIODeviceType
  219326. {
  219327. public:
  219328. JackAudioIODeviceType()
  219329. : AudioIODeviceType ("JACK"),
  219330. hasScanned (false)
  219331. {
  219332. }
  219333. ~JackAudioIODeviceType()
  219334. {
  219335. }
  219336. void scanForDevices()
  219337. {
  219338. hasScanned = true;
  219339. inputNames.clear();
  219340. inputIds.clear();
  219341. outputNames.clear();
  219342. outputIds.clear();
  219343. if (juce_libjack_handle == 0)
  219344. {
  219345. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  219346. if (juce_libjack_handle == 0)
  219347. return;
  219348. }
  219349. // open a dummy client
  219350. jack_status_t status;
  219351. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  219352. if (client == 0)
  219353. {
  219354. dumpJackErrorMessage (status);
  219355. }
  219356. else
  219357. {
  219358. // scan for output devices
  219359. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219360. if (ports != 0)
  219361. {
  219362. int j = 0;
  219363. while (ports[j] != 0)
  219364. {
  219365. String clientName (ports[j]);
  219366. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219367. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219368. && ! inputNames.contains (clientName))
  219369. {
  219370. inputNames.add (clientName);
  219371. inputIds.add (ports [j]);
  219372. }
  219373. ++j;
  219374. }
  219375. free (ports);
  219376. }
  219377. // scan for input devices
  219378. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219379. if (ports != 0)
  219380. {
  219381. int j = 0;
  219382. while (ports[j] != 0)
  219383. {
  219384. String clientName (ports[j]);
  219385. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219386. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219387. && ! outputNames.contains (clientName))
  219388. {
  219389. outputNames.add (clientName);
  219390. outputIds.add (ports [j]);
  219391. }
  219392. ++j;
  219393. }
  219394. free (ports);
  219395. }
  219396. JUCE_NAMESPACE::jack_client_close (client);
  219397. }
  219398. }
  219399. const StringArray getDeviceNames (bool wantInputNames) const
  219400. {
  219401. jassert (hasScanned); // need to call scanForDevices() before doing this
  219402. return wantInputNames ? inputNames : outputNames;
  219403. }
  219404. int getDefaultDeviceIndex (bool forInput) const
  219405. {
  219406. jassert (hasScanned); // need to call scanForDevices() before doing this
  219407. return 0;
  219408. }
  219409. bool hasSeparateInputsAndOutputs() const { return true; }
  219410. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  219411. {
  219412. jassert (hasScanned); // need to call scanForDevices() before doing this
  219413. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  219414. if (d == 0)
  219415. return -1;
  219416. return asInput ? inputIds.indexOf (d->inputId)
  219417. : outputIds.indexOf (d->outputId);
  219418. }
  219419. AudioIODevice* createDevice (const String& outputDeviceName,
  219420. const String& inputDeviceName)
  219421. {
  219422. jassert (hasScanned); // need to call scanForDevices() before doing this
  219423. const int inputIndex = inputNames.indexOf (inputDeviceName);
  219424. const int outputIndex = outputNames.indexOf (outputDeviceName);
  219425. if (inputIndex >= 0 || outputIndex >= 0)
  219426. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  219427. : inputDeviceName,
  219428. inputIds [inputIndex],
  219429. outputIds [outputIndex]);
  219430. return 0;
  219431. }
  219432. juce_UseDebuggingNewOperator
  219433. private:
  219434. StringArray inputNames, outputNames, inputIds, outputIds;
  219435. bool hasScanned;
  219436. JackAudioIODeviceType (const JackAudioIODeviceType&);
  219437. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  219438. };
  219439. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  219440. {
  219441. return new JackAudioIODeviceType();
  219442. }
  219443. #else // if JACK is turned off..
  219444. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  219445. #endif
  219446. #endif
  219447. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  219448. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  219449. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219450. // compiled on its own).
  219451. #if JUCE_INCLUDED_FILE
  219452. #if JUCE_ALSA
  219453. static snd_seq_t* iterateDevices (const bool forInput,
  219454. StringArray& deviceNamesFound,
  219455. const int deviceIndexToOpen)
  219456. {
  219457. snd_seq_t* returnedHandle = 0;
  219458. snd_seq_t* seqHandle;
  219459. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  219460. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  219461. {
  219462. snd_seq_system_info_t* systemInfo;
  219463. snd_seq_client_info_t* clientInfo;
  219464. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  219465. {
  219466. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  219467. && snd_seq_client_info_malloc (&clientInfo) == 0)
  219468. {
  219469. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  219470. while (--numClients >= 0 && returnedHandle == 0)
  219471. {
  219472. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  219473. {
  219474. snd_seq_port_info_t* portInfo;
  219475. if (snd_seq_port_info_malloc (&portInfo) == 0)
  219476. {
  219477. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  219478. const int client = snd_seq_client_info_get_client (clientInfo);
  219479. snd_seq_port_info_set_client (portInfo, client);
  219480. snd_seq_port_info_set_port (portInfo, -1);
  219481. while (--numPorts >= 0)
  219482. {
  219483. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  219484. && (snd_seq_port_info_get_capability (portInfo)
  219485. & (forInput ? SND_SEQ_PORT_CAP_READ
  219486. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  219487. {
  219488. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  219489. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  219490. {
  219491. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  219492. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  219493. if (sourcePort != -1)
  219494. {
  219495. snd_seq_set_client_name (seqHandle,
  219496. forInput ? "Juce Midi Input"
  219497. : "Juce Midi Output");
  219498. const int portId
  219499. = snd_seq_create_simple_port (seqHandle,
  219500. forInput ? "Juce Midi In Port"
  219501. : "Juce Midi Out Port",
  219502. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  219503. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  219504. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  219505. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  219506. returnedHandle = seqHandle;
  219507. }
  219508. }
  219509. }
  219510. }
  219511. snd_seq_port_info_free (portInfo);
  219512. }
  219513. }
  219514. }
  219515. snd_seq_client_info_free (clientInfo);
  219516. }
  219517. snd_seq_system_info_free (systemInfo);
  219518. }
  219519. if (returnedHandle == 0)
  219520. snd_seq_close (seqHandle);
  219521. }
  219522. deviceNamesFound.appendNumbersToDuplicates (true, true);
  219523. return returnedHandle;
  219524. }
  219525. static snd_seq_t* createDevice (const bool forInput,
  219526. const String& deviceNameToOpen)
  219527. {
  219528. snd_seq_t* seqHandle = 0;
  219529. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  219530. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  219531. {
  219532. snd_seq_set_client_name (seqHandle,
  219533. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  219534. const int portId
  219535. = snd_seq_create_simple_port (seqHandle,
  219536. forInput ? "in"
  219537. : "out",
  219538. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  219539. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  219540. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  219541. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  219542. if (portId < 0)
  219543. {
  219544. snd_seq_close (seqHandle);
  219545. seqHandle = 0;
  219546. }
  219547. }
  219548. return seqHandle;
  219549. }
  219550. class MidiOutputDevice
  219551. {
  219552. public:
  219553. MidiOutputDevice (MidiOutput* const midiOutput_,
  219554. snd_seq_t* const seqHandle_)
  219555. :
  219556. midiOutput (midiOutput_),
  219557. seqHandle (seqHandle_),
  219558. maxEventSize (16 * 1024)
  219559. {
  219560. jassert (seqHandle != 0 && midiOutput != 0);
  219561. snd_midi_event_new (maxEventSize, &midiParser);
  219562. }
  219563. ~MidiOutputDevice()
  219564. {
  219565. snd_midi_event_free (midiParser);
  219566. snd_seq_close (seqHandle);
  219567. }
  219568. void sendMessageNow (const MidiMessage& message)
  219569. {
  219570. if (message.getRawDataSize() > maxEventSize)
  219571. {
  219572. maxEventSize = message.getRawDataSize();
  219573. snd_midi_event_free (midiParser);
  219574. snd_midi_event_new (maxEventSize, &midiParser);
  219575. }
  219576. snd_seq_event_t event;
  219577. snd_seq_ev_clear (&event);
  219578. snd_midi_event_encode (midiParser,
  219579. message.getRawData(),
  219580. message.getRawDataSize(),
  219581. &event);
  219582. snd_midi_event_reset_encode (midiParser);
  219583. snd_seq_ev_set_source (&event, 0);
  219584. snd_seq_ev_set_subs (&event);
  219585. snd_seq_ev_set_direct (&event);
  219586. snd_seq_event_output (seqHandle, &event);
  219587. snd_seq_drain_output (seqHandle);
  219588. }
  219589. juce_UseDebuggingNewOperator
  219590. private:
  219591. MidiOutput* const midiOutput;
  219592. snd_seq_t* const seqHandle;
  219593. snd_midi_event_t* midiParser;
  219594. int maxEventSize;
  219595. };
  219596. const StringArray MidiOutput::getDevices()
  219597. {
  219598. StringArray devices;
  219599. iterateDevices (false, devices, -1);
  219600. return devices;
  219601. }
  219602. int MidiOutput::getDefaultDeviceIndex()
  219603. {
  219604. return 0;
  219605. }
  219606. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  219607. {
  219608. MidiOutput* newDevice = 0;
  219609. StringArray devices;
  219610. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  219611. if (handle != 0)
  219612. {
  219613. newDevice = new MidiOutput();
  219614. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  219615. }
  219616. return newDevice;
  219617. }
  219618. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  219619. {
  219620. MidiOutput* newDevice = 0;
  219621. snd_seq_t* const handle = createDevice (false, deviceName);
  219622. if (handle != 0)
  219623. {
  219624. newDevice = new MidiOutput();
  219625. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  219626. }
  219627. return newDevice;
  219628. }
  219629. MidiOutput::~MidiOutput()
  219630. {
  219631. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  219632. delete device;
  219633. }
  219634. void MidiOutput::reset()
  219635. {
  219636. }
  219637. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  219638. {
  219639. return false;
  219640. }
  219641. void MidiOutput::setVolume (float leftVol, float rightVol)
  219642. {
  219643. }
  219644. void MidiOutput::sendMessageNow (const MidiMessage& message)
  219645. {
  219646. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  219647. }
  219648. class MidiInputThread : public Thread
  219649. {
  219650. public:
  219651. MidiInputThread (MidiInput* const midiInput_,
  219652. snd_seq_t* const seqHandle_,
  219653. MidiInputCallback* const callback_)
  219654. : Thread ("Juce MIDI Input"),
  219655. midiInput (midiInput_),
  219656. seqHandle (seqHandle_),
  219657. callback (callback_)
  219658. {
  219659. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  219660. }
  219661. ~MidiInputThread()
  219662. {
  219663. snd_seq_close (seqHandle);
  219664. }
  219665. void run()
  219666. {
  219667. const int maxEventSize = 16 * 1024;
  219668. snd_midi_event_t* midiParser;
  219669. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  219670. {
  219671. HeapBlock <uint8> buffer (maxEventSize);
  219672. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  219673. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  219674. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  219675. while (! threadShouldExit())
  219676. {
  219677. if (poll (pfd, numPfds, 500) > 0)
  219678. {
  219679. snd_seq_event_t* inputEvent = 0;
  219680. snd_seq_nonblock (seqHandle, 1);
  219681. do
  219682. {
  219683. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  219684. {
  219685. // xxx what about SYSEXes that are too big for the buffer?
  219686. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  219687. snd_midi_event_reset_decode (midiParser);
  219688. if (numBytes > 0)
  219689. {
  219690. const MidiMessage message ((const uint8*) buffer,
  219691. numBytes,
  219692. Time::getMillisecondCounter() * 0.001);
  219693. callback->handleIncomingMidiMessage (midiInput, message);
  219694. }
  219695. snd_seq_free_event (inputEvent);
  219696. }
  219697. }
  219698. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  219699. snd_seq_free_event (inputEvent);
  219700. }
  219701. }
  219702. snd_midi_event_free (midiParser);
  219703. }
  219704. };
  219705. juce_UseDebuggingNewOperator
  219706. private:
  219707. MidiInput* const midiInput;
  219708. snd_seq_t* const seqHandle;
  219709. MidiInputCallback* const callback;
  219710. };
  219711. MidiInput::MidiInput (const String& name_)
  219712. : name (name_),
  219713. internal (0)
  219714. {
  219715. }
  219716. MidiInput::~MidiInput()
  219717. {
  219718. stop();
  219719. MidiInputThread* const thread = (MidiInputThread*) internal;
  219720. delete thread;
  219721. }
  219722. void MidiInput::start()
  219723. {
  219724. ((MidiInputThread*) internal)->startThread();
  219725. }
  219726. void MidiInput::stop()
  219727. {
  219728. ((MidiInputThread*) internal)->stopThread (3000);
  219729. }
  219730. int MidiInput::getDefaultDeviceIndex()
  219731. {
  219732. return 0;
  219733. }
  219734. const StringArray MidiInput::getDevices()
  219735. {
  219736. StringArray devices;
  219737. iterateDevices (true, devices, -1);
  219738. return devices;
  219739. }
  219740. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  219741. {
  219742. MidiInput* newDevice = 0;
  219743. StringArray devices;
  219744. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  219745. if (handle != 0)
  219746. {
  219747. newDevice = new MidiInput (devices [deviceIndex]);
  219748. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  219749. }
  219750. return newDevice;
  219751. }
  219752. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  219753. {
  219754. MidiInput* newDevice = 0;
  219755. snd_seq_t* const handle = createDevice (true, deviceName);
  219756. if (handle != 0)
  219757. {
  219758. newDevice = new MidiInput (deviceName);
  219759. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  219760. }
  219761. return newDevice;
  219762. }
  219763. #else
  219764. // (These are just stub functions if ALSA is unavailable...)
  219765. const StringArray MidiOutput::getDevices() { return StringArray(); }
  219766. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  219767. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  219768. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  219769. MidiOutput::~MidiOutput() {}
  219770. void MidiOutput::reset() {}
  219771. bool MidiOutput::getVolume (float&, float&) { return false; }
  219772. void MidiOutput::setVolume (float, float) {}
  219773. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  219774. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  219775. MidiInput::~MidiInput() {}
  219776. void MidiInput::start() {}
  219777. void MidiInput::stop() {}
  219778. int MidiInput::getDefaultDeviceIndex() { return 0; }
  219779. const StringArray MidiInput::getDevices() { return StringArray(); }
  219780. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  219781. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  219782. #endif
  219783. #endif
  219784. /*** End of inlined file: juce_linux_Midi.cpp ***/
  219785. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  219786. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219787. // compiled on its own).
  219788. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  219789. AudioCDReader::AudioCDReader()
  219790. : AudioFormatReader (0, "CD Audio")
  219791. {
  219792. }
  219793. const StringArray AudioCDReader::getAvailableCDNames()
  219794. {
  219795. StringArray names;
  219796. return names;
  219797. }
  219798. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  219799. {
  219800. return 0;
  219801. }
  219802. AudioCDReader::~AudioCDReader()
  219803. {
  219804. }
  219805. void AudioCDReader::refreshTrackLengths()
  219806. {
  219807. }
  219808. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  219809. int64 startSampleInFile, int numSamples)
  219810. {
  219811. return false;
  219812. }
  219813. bool AudioCDReader::isCDStillPresent() const
  219814. {
  219815. return false;
  219816. }
  219817. int AudioCDReader::getNumTracks() const
  219818. {
  219819. return 0;
  219820. }
  219821. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  219822. {
  219823. return 0;
  219824. }
  219825. bool AudioCDReader::isTrackAudio (int trackNum) const
  219826. {
  219827. return false;
  219828. }
  219829. void AudioCDReader::enableIndexScanning (bool b)
  219830. {
  219831. }
  219832. int AudioCDReader::getLastIndex() const
  219833. {
  219834. return 0;
  219835. }
  219836. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  219837. {
  219838. return Array<int>();
  219839. }
  219840. int AudioCDReader::getCDDBId()
  219841. {
  219842. return 0;
  219843. }
  219844. #endif
  219845. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  219846. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  219847. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219848. // compiled on its own).
  219849. #if JUCE_INCLUDED_FILE
  219850. void FileChooser::showPlatformDialog (Array<File>& results,
  219851. const String& title,
  219852. const File& file,
  219853. const String& filters,
  219854. bool isDirectory,
  219855. bool selectsFiles,
  219856. bool isSave,
  219857. bool warnAboutOverwritingExistingFiles,
  219858. bool selectMultipleFiles,
  219859. FilePreviewComponent* previewComponent)
  219860. {
  219861. const String separator (":");
  219862. String command ("zenity --file-selection");
  219863. if (title.isNotEmpty())
  219864. command << " --title=\"" << title << "\"";
  219865. if (file != File::nonexistent)
  219866. command << " --filename=\"" << file.getFullPathName () << "\"";
  219867. if (isDirectory)
  219868. command << " --directory";
  219869. if (isSave)
  219870. command << " --save";
  219871. if (selectMultipleFiles)
  219872. command << " --multiple --separator=\"" << separator << "\"";
  219873. command << " 2>&1";
  219874. MemoryOutputStream result;
  219875. int status = -1;
  219876. FILE* stream = popen (command.toUTF8(), "r");
  219877. if (stream != 0)
  219878. {
  219879. for (;;)
  219880. {
  219881. char buffer [1024];
  219882. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  219883. if (bytesRead <= 0)
  219884. break;
  219885. result.write (buffer, bytesRead);
  219886. }
  219887. status = pclose (stream);
  219888. }
  219889. if (status == 0)
  219890. {
  219891. StringArray tokens;
  219892. if (selectMultipleFiles)
  219893. tokens.addTokens (result.toUTF8(), separator, String::empty);
  219894. else
  219895. tokens.add (result.toUTF8());
  219896. for (int i = 0; i < tokens.size(); i++)
  219897. results.add (File (tokens[i]));
  219898. return;
  219899. }
  219900. //xxx ain't got one!
  219901. jassertfalse
  219902. }
  219903. #endif
  219904. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  219905. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  219906. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219907. // compiled on its own).
  219908. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  219909. /*
  219910. Sorry.. This class isn't implemented on Linux!
  219911. */
  219912. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  219913. : browser (0),
  219914. blankPageShown (false),
  219915. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  219916. {
  219917. setOpaque (true);
  219918. }
  219919. WebBrowserComponent::~WebBrowserComponent()
  219920. {
  219921. }
  219922. void WebBrowserComponent::goToURL (const String& url,
  219923. const StringArray* headers,
  219924. const MemoryBlock* postData)
  219925. {
  219926. lastURL = url;
  219927. lastHeaders.clear();
  219928. if (headers != 0)
  219929. lastHeaders = *headers;
  219930. lastPostData.setSize (0);
  219931. if (postData != 0)
  219932. lastPostData = *postData;
  219933. blankPageShown = false;
  219934. }
  219935. void WebBrowserComponent::stop()
  219936. {
  219937. }
  219938. void WebBrowserComponent::goBack()
  219939. {
  219940. lastURL = String::empty;
  219941. blankPageShown = false;
  219942. }
  219943. void WebBrowserComponent::goForward()
  219944. {
  219945. lastURL = String::empty;
  219946. }
  219947. void WebBrowserComponent::refresh()
  219948. {
  219949. }
  219950. void WebBrowserComponent::paint (Graphics& g)
  219951. {
  219952. g.fillAll (Colours::white);
  219953. }
  219954. void WebBrowserComponent::checkWindowAssociation()
  219955. {
  219956. }
  219957. void WebBrowserComponent::reloadLastURL()
  219958. {
  219959. if (lastURL.isNotEmpty())
  219960. {
  219961. goToURL (lastURL, &lastHeaders, &lastPostData);
  219962. lastURL = String::empty;
  219963. }
  219964. }
  219965. void WebBrowserComponent::parentHierarchyChanged()
  219966. {
  219967. checkWindowAssociation();
  219968. }
  219969. void WebBrowserComponent::resized()
  219970. {
  219971. }
  219972. void WebBrowserComponent::visibilityChanged()
  219973. {
  219974. checkWindowAssociation();
  219975. }
  219976. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  219977. {
  219978. return true;
  219979. }
  219980. #endif
  219981. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  219982. #endif
  219983. END_JUCE_NAMESPACE
  219984. #endif
  219985. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  219986. #endif
  219987. #if JUCE_MAC || JUCE_IPHONE
  219988. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  219989. /*
  219990. This file wraps together all the mac-specific code, so that
  219991. we can include all the native headers just once, and compile all our
  219992. platform-specific stuff in one big lump, keeping it out of the way of
  219993. the rest of the codebase.
  219994. */
  219995. #if JUCE_MAC || JUCE_IPHONE
  219996. BEGIN_JUCE_NAMESPACE
  219997. #undef Point
  219998. #define JUCE_INCLUDED_FILE 1
  219999. // Now include the actual code files..
  220000. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  220001. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  220002. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  220003. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  220004. cross-linked so that when you make a call to a class that you thought was private, it ends up
  220005. actually calling into a similarly named class in the other module's address space.
  220006. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  220007. have unique names, and should avoid this problem.
  220008. If you're using the amalgamated version, you can just set this macro to something unique before
  220009. you include juce_amalgamated.cpp.
  220010. */
  220011. #ifndef JUCE_ObjCExtraSuffix
  220012. #define JUCE_ObjCExtraSuffix 3
  220013. #endif
  220014. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  220015. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  220016. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  220017. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  220018. /*** Start of inlined file: juce_mac_Strings.mm ***/
  220019. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220020. // compiled on its own).
  220021. #if JUCE_INCLUDED_FILE
  220022. static const String nsStringToJuce (NSString* s)
  220023. {
  220024. return String::fromUTF8 ([s UTF8String]);
  220025. }
  220026. static NSString* juceStringToNS (const String& s)
  220027. {
  220028. return [NSString stringWithUTF8String: s.toUTF8()];
  220029. }
  220030. static const String convertUTF16ToString (const UniChar* utf16)
  220031. {
  220032. String s;
  220033. while (*utf16 != 0)
  220034. s += (juce_wchar) *utf16++;
  220035. return s;
  220036. }
  220037. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  220038. {
  220039. String result;
  220040. if (cfString != 0)
  220041. {
  220042. CFRange range = { 0, CFStringGetLength (cfString) };
  220043. HeapBlock <UniChar> u (range.length + 1);
  220044. CFStringGetCharacters (cfString, range, u);
  220045. u[range.length] = 0;
  220046. result = convertUTF16ToString (u);
  220047. }
  220048. return result;
  220049. }
  220050. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  220051. {
  220052. const int len = s.length();
  220053. HeapBlock <UniChar> temp (len + 2);
  220054. for (int i = 0; i <= len; ++i)
  220055. temp[i] = s[i];
  220056. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  220057. }
  220058. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  220059. {
  220060. #if JUCE_IPHONE
  220061. const ScopedAutoReleasePool pool;
  220062. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  220063. #else
  220064. UnicodeMapping map;
  220065. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220066. kUnicodeNoSubset,
  220067. kTextEncodingDefaultFormat);
  220068. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220069. kUnicodeCanonicalCompVariant,
  220070. kTextEncodingDefaultFormat);
  220071. map.mappingVersion = kUnicodeUseLatestMapping;
  220072. UnicodeToTextInfo conversionInfo = 0;
  220073. String result;
  220074. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  220075. {
  220076. const int len = s.length();
  220077. HeapBlock <UniChar> tempIn, tempOut;
  220078. tempIn.calloc (len + 2);
  220079. tempOut.calloc (len + 2);
  220080. for (int i = 0; i <= len; ++i)
  220081. tempIn[i] = s[i];
  220082. ByteCount bytesRead = 0;
  220083. ByteCount outputBufferSize = 0;
  220084. if (ConvertFromUnicodeToText (conversionInfo,
  220085. len * sizeof (UniChar), tempIn,
  220086. kUnicodeDefaultDirectionMask,
  220087. 0, 0, 0, 0,
  220088. len * sizeof (UniChar), &bytesRead,
  220089. &outputBufferSize, tempOut) == noErr)
  220090. {
  220091. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  220092. juce_wchar* t = result;
  220093. unsigned int i;
  220094. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  220095. t[i] = (juce_wchar) tempOut[i];
  220096. t[i] = 0;
  220097. }
  220098. DisposeUnicodeToTextInfo (&conversionInfo);
  220099. }
  220100. return result;
  220101. #endif
  220102. }
  220103. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220104. void SystemClipboard::copyTextToClipboard (const String& text)
  220105. {
  220106. #if JUCE_IPHONE
  220107. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  220108. forPasteboardType: @"public.text"];
  220109. #else
  220110. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  220111. owner: nil];
  220112. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  220113. forType: NSStringPboardType];
  220114. #endif
  220115. }
  220116. const String SystemClipboard::getTextFromClipboard()
  220117. {
  220118. #if JUCE_IPHONE
  220119. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  220120. #else
  220121. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  220122. #endif
  220123. return text == 0 ? String::empty
  220124. : nsStringToJuce (text);
  220125. }
  220126. #endif
  220127. #endif
  220128. /*** End of inlined file: juce_mac_Strings.mm ***/
  220129. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  220130. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220131. // compiled on its own).
  220132. #if JUCE_INCLUDED_FILE
  220133. namespace SystemStatsHelpers
  220134. {
  220135. static int64 highResTimerFrequency = 0;
  220136. static double highResTimerToMillisecRatio = 0;
  220137. #if JUCE_INTEL
  220138. static void juce_getCpuVendor (char* const v) throw()
  220139. {
  220140. int vendor[4];
  220141. zerostruct (vendor);
  220142. int dummy = 0;
  220143. asm ("mov %%ebx, %%esi \n\t"
  220144. "cpuid \n\t"
  220145. "xchg %%esi, %%ebx"
  220146. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  220147. memcpy (v, vendor, 16);
  220148. }
  220149. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  220150. {
  220151. unsigned int cpu = 0;
  220152. unsigned int ext = 0;
  220153. unsigned int family = 0;
  220154. unsigned int dummy = 0;
  220155. asm ("mov %%ebx, %%esi \n\t"
  220156. "cpuid \n\t"
  220157. "xchg %%esi, %%ebx"
  220158. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  220159. familyModel = family;
  220160. extFeatures = ext;
  220161. return cpu;
  220162. }
  220163. struct CPUFlags
  220164. {
  220165. bool hasMMX : 1;
  220166. bool hasSSE : 1;
  220167. bool hasSSE2 : 1;
  220168. bool has3DNow : 1;
  220169. };
  220170. static CPUFlags cpuFlags;
  220171. #endif
  220172. }
  220173. void SystemStats::initialiseStats() throw()
  220174. {
  220175. using namespace SystemStatsHelpers;
  220176. static bool initialised = false;
  220177. if (! initialised)
  220178. {
  220179. initialised = true;
  220180. #if JUCE_MAC
  220181. // extremely annoying: adding this line stops the apple menu items from working. Of
  220182. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  220183. // any events.
  220184. //NSApplicationLoad();
  220185. [NSApplication sharedApplication];
  220186. #endif
  220187. #if JUCE_INTEL
  220188. {
  220189. unsigned int familyModel, extFeatures;
  220190. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  220191. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  220192. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  220193. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  220194. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  220195. }
  220196. #endif
  220197. mach_timebase_info_data_t timebase;
  220198. (void) mach_timebase_info (&timebase);
  220199. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  220200. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  220201. String s (SystemStats::getJUCEVersion());
  220202. rlimit lim;
  220203. getrlimit (RLIMIT_NOFILE, &lim);
  220204. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  220205. setrlimit (RLIMIT_NOFILE, &lim);
  220206. }
  220207. }
  220208. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  220209. {
  220210. return MacOSX;
  220211. }
  220212. const String SystemStats::getOperatingSystemName() throw()
  220213. {
  220214. return "Mac OS X";
  220215. }
  220216. bool SystemStats::isOperatingSystem64Bit() throw()
  220217. {
  220218. #if JUCE_64BIT
  220219. return true;
  220220. #else
  220221. //xxx not sure how to find this out?..
  220222. return false;
  220223. #endif
  220224. }
  220225. int SystemStats::getMemorySizeInMegabytes() throw()
  220226. {
  220227. uint64 mem = 0;
  220228. size_t memSize = sizeof (mem);
  220229. int mib[] = { CTL_HW, HW_MEMSIZE };
  220230. sysctl (mib, 2, &mem, &memSize, 0, 0);
  220231. return (int) (mem / (1024 * 1024));
  220232. }
  220233. bool SystemStats::hasMMX() throw()
  220234. {
  220235. #if JUCE_INTEL
  220236. return SystemStatsHelpers::cpuFlags.hasMMX;
  220237. #else
  220238. return false;
  220239. #endif
  220240. }
  220241. bool SystemStats::hasSSE() throw()
  220242. {
  220243. #if JUCE_INTEL
  220244. return SystemStatsHelpers::cpuFlags.hasSSE;
  220245. #else
  220246. return false;
  220247. #endif
  220248. }
  220249. bool SystemStats::hasSSE2() throw()
  220250. {
  220251. #if JUCE_INTEL
  220252. return SystemStatsHelpers::cpuFlags.hasSSE2;
  220253. #else
  220254. return false;
  220255. #endif
  220256. }
  220257. bool SystemStats::has3DNow() throw()
  220258. {
  220259. #if JUCE_INTEL
  220260. return SystemStatsHelpers::cpuFlags.has3DNow;
  220261. #else
  220262. return false;
  220263. #endif
  220264. }
  220265. const String SystemStats::getCpuVendor() throw()
  220266. {
  220267. #if JUCE_INTEL
  220268. char v [16];
  220269. SystemStatsHelpers::juce_getCpuVendor (v);
  220270. return String (v, 16);
  220271. #else
  220272. return String::empty;
  220273. #endif
  220274. }
  220275. int SystemStats::getCpuSpeedInMegaherz() throw()
  220276. {
  220277. uint64 speedHz = 0;
  220278. size_t speedSize = sizeof (speedHz);
  220279. int mib[] = { CTL_HW, HW_CPU_FREQ };
  220280. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  220281. #if JUCE_BIG_ENDIAN
  220282. if (speedSize == 4)
  220283. speedHz >>= 32;
  220284. #endif
  220285. return (int) (speedHz / 1000000);
  220286. }
  220287. int SystemStats::getNumCpus() throw()
  220288. {
  220289. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  220290. return (int) [[NSProcessInfo processInfo] activeProcessorCount];
  220291. #else
  220292. return MPProcessors();
  220293. #endif
  220294. }
  220295. const String SystemStats::getLogonName()
  220296. {
  220297. return nsStringToJuce (NSUserName());
  220298. }
  220299. const String SystemStats::getFullUserName()
  220300. {
  220301. return nsStringToJuce (NSFullUserName());
  220302. }
  220303. uint32 juce_millisecondsSinceStartup() throw()
  220304. {
  220305. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  220306. }
  220307. double Time::getMillisecondCounterHiRes() throw()
  220308. {
  220309. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  220310. }
  220311. int64 Time::getHighResolutionTicks() throw()
  220312. {
  220313. return (int64) mach_absolute_time();
  220314. }
  220315. int64 Time::getHighResolutionTicksPerSecond() throw()
  220316. {
  220317. return SystemStatsHelpers::highResTimerFrequency;
  220318. }
  220319. int64 SystemStats::getClockCycleCounter() throw()
  220320. {
  220321. return (int64) mach_absolute_time();
  220322. }
  220323. bool Time::setSystemTimeToThisTime() const throw()
  220324. {
  220325. jassertfalse
  220326. return false;
  220327. }
  220328. int SystemStats::getPageSize() throw()
  220329. {
  220330. return (int) NSPageSize();
  220331. }
  220332. void PlatformUtilities::fpuReset()
  220333. {
  220334. }
  220335. #endif
  220336. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  220337. /*** Start of inlined file: juce_mac_Network.mm ***/
  220338. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220339. // compiled on its own).
  220340. #if JUCE_INCLUDED_FILE
  220341. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  220342. {
  220343. #ifndef IFT_ETHER
  220344. #define IFT_ETHER 6
  220345. #endif
  220346. ifaddrs* addrs = 0;
  220347. int numResults = 0;
  220348. if (getifaddrs (&addrs) == 0)
  220349. {
  220350. const ifaddrs* cursor = addrs;
  220351. while (cursor != 0 && numResults < maxNum)
  220352. {
  220353. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  220354. if (sto->ss_family == AF_LINK)
  220355. {
  220356. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  220357. if (sadd->sdl_type == IFT_ETHER)
  220358. {
  220359. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  220360. uint64 a = 0;
  220361. for (int i = 6; --i >= 0;)
  220362. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  220363. *addresses++ = (int64) a;
  220364. ++numResults;
  220365. }
  220366. }
  220367. cursor = cursor->ifa_next;
  220368. }
  220369. freeifaddrs (addrs);
  220370. }
  220371. return numResults;
  220372. }
  220373. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  220374. const String& emailSubject,
  220375. const String& bodyText,
  220376. const StringArray& filesToAttach)
  220377. {
  220378. #if JUCE_IPHONE
  220379. //xxx probably need to use MFMailComposeViewController
  220380. jassertfalse
  220381. return false;
  220382. #else
  220383. const ScopedAutoReleasePool pool;
  220384. String script;
  220385. script << "tell application \"Mail\"\r\n"
  220386. "set newMessage to make new outgoing message with properties {subject:\""
  220387. << emailSubject.replace ("\"", "\\\"")
  220388. << "\", content:\""
  220389. << bodyText.replace ("\"", "\\\"")
  220390. << "\" & return & return}\r\n"
  220391. "tell newMessage\r\n"
  220392. "set visible to true\r\n"
  220393. "set sender to \"sdfsdfsdfewf\"\r\n"
  220394. "make new to recipient at end of to recipients with properties {address:\""
  220395. << targetEmailAddress
  220396. << "\"}\r\n";
  220397. for (int i = 0; i < filesToAttach.size(); ++i)
  220398. {
  220399. script << "tell content\r\n"
  220400. "make new attachment with properties {file name:\""
  220401. << filesToAttach[i].replace ("\"", "\\\"")
  220402. << "\"} at after the last paragraph\r\n"
  220403. "end tell\r\n";
  220404. }
  220405. script << "end tell\r\n"
  220406. "end tell\r\n";
  220407. NSAppleScript* s = [[NSAppleScript alloc]
  220408. initWithSource: juceStringToNS (script)];
  220409. NSDictionary* error = 0;
  220410. const bool ok = [s executeAndReturnError: &error] != nil;
  220411. [s release];
  220412. return ok;
  220413. #endif
  220414. }
  220415. END_JUCE_NAMESPACE
  220416. using namespace JUCE_NAMESPACE;
  220417. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  220418. @interface JuceURLConnection : NSObject
  220419. {
  220420. @public
  220421. NSURLRequest* request;
  220422. NSURLConnection* connection;
  220423. NSMutableData* data;
  220424. Thread* runLoopThread;
  220425. bool initialised, hasFailed, hasFinished;
  220426. int position;
  220427. int64 contentLength;
  220428. NSLock* dataLock;
  220429. }
  220430. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  220431. - (void) dealloc;
  220432. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  220433. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  220434. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  220435. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  220436. - (BOOL) isOpen;
  220437. - (int) read: (char*) dest numBytes: (int) num;
  220438. - (int) readPosition;
  220439. - (void) stop;
  220440. - (void) createConnection;
  220441. @end
  220442. class JuceURLConnectionMessageThread : public Thread
  220443. {
  220444. JuceURLConnection* owner;
  220445. public:
  220446. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  220447. : Thread ("http connection"),
  220448. owner (owner_)
  220449. {
  220450. }
  220451. ~JuceURLConnectionMessageThread()
  220452. {
  220453. stopThread (10000);
  220454. }
  220455. void run()
  220456. {
  220457. [owner createConnection];
  220458. while (! threadShouldExit())
  220459. {
  220460. const ScopedAutoReleasePool pool;
  220461. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  220462. }
  220463. }
  220464. };
  220465. @implementation JuceURLConnection
  220466. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  220467. withCallback: (URL::OpenStreamProgressCallback*) callback
  220468. withContext: (void*) context;
  220469. {
  220470. [super init];
  220471. request = req;
  220472. [request retain];
  220473. data = [[NSMutableData data] retain];
  220474. dataLock = [[NSLock alloc] init];
  220475. connection = 0;
  220476. initialised = false;
  220477. hasFailed = false;
  220478. hasFinished = false;
  220479. contentLength = -1;
  220480. runLoopThread = new JuceURLConnectionMessageThread (self);
  220481. runLoopThread->startThread();
  220482. while (runLoopThread->isThreadRunning() && ! initialised)
  220483. {
  220484. if (callback != 0)
  220485. callback (context, -1, (int) [[request HTTPBody] length]);
  220486. Thread::sleep (1);
  220487. }
  220488. return self;
  220489. }
  220490. - (void) dealloc
  220491. {
  220492. [self stop];
  220493. deleteAndZero (runLoopThread);
  220494. [connection release];
  220495. [data release];
  220496. [dataLock release];
  220497. [request release];
  220498. [super dealloc];
  220499. }
  220500. - (void) createConnection
  220501. {
  220502. connection = [[NSURLConnection alloc] initWithRequest: request
  220503. delegate: [self retain]];
  220504. if (connection == nil)
  220505. runLoopThread->signalThreadShouldExit();
  220506. }
  220507. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  220508. {
  220509. (void) conn;
  220510. [dataLock lock];
  220511. [data setLength: 0];
  220512. [dataLock unlock];
  220513. initialised = true;
  220514. contentLength = [response expectedContentLength];
  220515. }
  220516. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  220517. {
  220518. (void) conn;
  220519. DBG (nsStringToJuce ([error description]));
  220520. hasFailed = true;
  220521. initialised = true;
  220522. if (runLoopThread != 0)
  220523. runLoopThread->signalThreadShouldExit();
  220524. }
  220525. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  220526. {
  220527. (void) conn;
  220528. [dataLock lock];
  220529. [data appendData: newData];
  220530. [dataLock unlock];
  220531. initialised = true;
  220532. }
  220533. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  220534. {
  220535. (void) conn;
  220536. hasFinished = true;
  220537. initialised = true;
  220538. if (runLoopThread != 0)
  220539. runLoopThread->signalThreadShouldExit();
  220540. }
  220541. - (BOOL) isOpen
  220542. {
  220543. return connection != 0 && ! hasFailed;
  220544. }
  220545. - (int) readPosition
  220546. {
  220547. return position;
  220548. }
  220549. - (int) read: (char*) dest numBytes: (int) numNeeded
  220550. {
  220551. int numDone = 0;
  220552. while (numNeeded > 0)
  220553. {
  220554. int available = jmin (numNeeded, (int) [data length]);
  220555. if (available > 0)
  220556. {
  220557. [dataLock lock];
  220558. [data getBytes: dest length: available];
  220559. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  220560. [dataLock unlock];
  220561. numDone += available;
  220562. numNeeded -= available;
  220563. dest += available;
  220564. }
  220565. else
  220566. {
  220567. if (hasFailed || hasFinished)
  220568. break;
  220569. Thread::sleep (1);
  220570. }
  220571. }
  220572. position += numDone;
  220573. return numDone;
  220574. }
  220575. - (void) stop
  220576. {
  220577. [connection cancel];
  220578. if (runLoopThread != 0)
  220579. runLoopThread->stopThread (10000);
  220580. }
  220581. @end
  220582. BEGIN_JUCE_NAMESPACE
  220583. void* juce_openInternetFile (const String& url,
  220584. const String& headers,
  220585. const MemoryBlock& postData,
  220586. const bool isPost,
  220587. URL::OpenStreamProgressCallback* callback,
  220588. void* callbackContext,
  220589. int timeOutMs)
  220590. {
  220591. const ScopedAutoReleasePool pool;
  220592. NSMutableURLRequest* req = [NSMutableURLRequest
  220593. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  220594. cachePolicy: NSURLRequestUseProtocolCachePolicy
  220595. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  220596. if (req == nil)
  220597. return 0;
  220598. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  220599. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  220600. StringArray headerLines;
  220601. headerLines.addLines (headers);
  220602. headerLines.removeEmptyStrings (true);
  220603. for (int i = 0; i < headerLines.size(); ++i)
  220604. {
  220605. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  220606. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  220607. if (key.isNotEmpty() && value.isNotEmpty())
  220608. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  220609. }
  220610. if (isPost && postData.getSize() > 0)
  220611. {
  220612. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  220613. length: postData.getSize()]];
  220614. }
  220615. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  220616. withCallback: callback
  220617. withContext: callbackContext];
  220618. if ([s isOpen])
  220619. return s;
  220620. [s release];
  220621. return 0;
  220622. }
  220623. void juce_closeInternetFile (void* handle)
  220624. {
  220625. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220626. if (s != 0)
  220627. {
  220628. const ScopedAutoReleasePool pool;
  220629. [s stop];
  220630. [s release];
  220631. }
  220632. }
  220633. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  220634. {
  220635. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220636. if (s != 0)
  220637. {
  220638. const ScopedAutoReleasePool pool;
  220639. return [s read: (char*) buffer numBytes: bytesToRead];
  220640. }
  220641. return 0;
  220642. }
  220643. int64 juce_getInternetFileContentLength (void* handle)
  220644. {
  220645. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220646. if (s != 0)
  220647. return s->contentLength;
  220648. return -1;
  220649. }
  220650. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  220651. {
  220652. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220653. if (s != 0)
  220654. return [s readPosition];
  220655. return 0;
  220656. }
  220657. #endif
  220658. /*** End of inlined file: juce_mac_Network.mm ***/
  220659. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  220660. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220661. // compiled on its own).
  220662. #if JUCE_INCLUDED_FILE
  220663. struct NamedPipeInternal
  220664. {
  220665. String pipeInName, pipeOutName;
  220666. int pipeIn, pipeOut;
  220667. bool volatile createdPipe, blocked, stopReadOperation;
  220668. static void signalHandler (int) {}
  220669. };
  220670. void NamedPipe::cancelPendingReads()
  220671. {
  220672. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  220673. {
  220674. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220675. intern->stopReadOperation = true;
  220676. char buffer [1] = { 0 };
  220677. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  220678. (void) bytesWritten;
  220679. int timeout = 2000;
  220680. while (intern->blocked && --timeout >= 0)
  220681. Thread::sleep (2);
  220682. intern->stopReadOperation = false;
  220683. }
  220684. }
  220685. void NamedPipe::close()
  220686. {
  220687. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220688. if (intern != 0)
  220689. {
  220690. internal = 0;
  220691. if (intern->pipeIn != -1)
  220692. ::close (intern->pipeIn);
  220693. if (intern->pipeOut != -1)
  220694. ::close (intern->pipeOut);
  220695. if (intern->createdPipe)
  220696. {
  220697. unlink (intern->pipeInName.toUTF8());
  220698. unlink (intern->pipeOutName.toUTF8());
  220699. }
  220700. delete intern;
  220701. }
  220702. }
  220703. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  220704. {
  220705. close();
  220706. NamedPipeInternal* const intern = new NamedPipeInternal();
  220707. internal = intern;
  220708. intern->createdPipe = createPipe;
  220709. intern->blocked = false;
  220710. intern->stopReadOperation = false;
  220711. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  220712. siginterrupt (SIGPIPE, 1);
  220713. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  220714. intern->pipeInName = pipePath + "_in";
  220715. intern->pipeOutName = pipePath + "_out";
  220716. intern->pipeIn = -1;
  220717. intern->pipeOut = -1;
  220718. if (createPipe)
  220719. {
  220720. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  220721. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  220722. {
  220723. delete intern;
  220724. internal = 0;
  220725. return false;
  220726. }
  220727. }
  220728. return true;
  220729. }
  220730. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  220731. {
  220732. int bytesRead = -1;
  220733. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220734. if (intern != 0)
  220735. {
  220736. intern->blocked = true;
  220737. if (intern->pipeIn == -1)
  220738. {
  220739. if (intern->createdPipe)
  220740. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  220741. else
  220742. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  220743. if (intern->pipeIn == -1)
  220744. {
  220745. intern->blocked = false;
  220746. return -1;
  220747. }
  220748. }
  220749. bytesRead = 0;
  220750. char* p = (char*) destBuffer;
  220751. while (bytesRead < maxBytesToRead)
  220752. {
  220753. const int bytesThisTime = maxBytesToRead - bytesRead;
  220754. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  220755. if (numRead <= 0 || intern->stopReadOperation)
  220756. {
  220757. bytesRead = -1;
  220758. break;
  220759. }
  220760. bytesRead += numRead;
  220761. p += bytesRead;
  220762. }
  220763. intern->blocked = false;
  220764. }
  220765. return bytesRead;
  220766. }
  220767. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  220768. {
  220769. int bytesWritten = -1;
  220770. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220771. if (intern != 0)
  220772. {
  220773. if (intern->pipeOut == -1)
  220774. {
  220775. if (intern->createdPipe)
  220776. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  220777. else
  220778. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  220779. if (intern->pipeOut == -1)
  220780. {
  220781. return -1;
  220782. }
  220783. }
  220784. const char* p = (const char*) sourceBuffer;
  220785. bytesWritten = 0;
  220786. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  220787. while (bytesWritten < numBytesToWrite
  220788. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  220789. {
  220790. const int bytesThisTime = numBytesToWrite - bytesWritten;
  220791. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  220792. if (numWritten <= 0)
  220793. {
  220794. bytesWritten = -1;
  220795. break;
  220796. }
  220797. bytesWritten += numWritten;
  220798. p += bytesWritten;
  220799. }
  220800. }
  220801. return bytesWritten;
  220802. }
  220803. #endif
  220804. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  220805. /*** Start of inlined file: juce_mac_Threads.mm ***/
  220806. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220807. // compiled on its own).
  220808. #if JUCE_INCLUDED_FILE
  220809. /*
  220810. Note that a lot of methods that you'd expect to find in this file actually
  220811. live in juce_posix_SharedCode.h!
  220812. */
  220813. void JUCE_API juce_threadEntryPoint (void*);
  220814. void* threadEntryProc (void* userData)
  220815. {
  220816. const ScopedAutoReleasePool pool;
  220817. juce_threadEntryPoint (userData);
  220818. return 0;
  220819. }
  220820. void* juce_createThread (void* userData)
  220821. {
  220822. pthread_t handle = 0;
  220823. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  220824. {
  220825. pthread_detach (handle);
  220826. return (void*) handle;
  220827. }
  220828. return 0;
  220829. }
  220830. void juce_killThread (void* handle)
  220831. {
  220832. if (handle != 0)
  220833. pthread_cancel ((pthread_t) handle);
  220834. }
  220835. void juce_setCurrentThreadName (const String& /*name*/)
  220836. {
  220837. }
  220838. bool juce_setThreadPriority (void* handle, int priority)
  220839. {
  220840. if (handle == 0)
  220841. handle = (void*) pthread_self();
  220842. struct sched_param param;
  220843. int policy;
  220844. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  220845. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  220846. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  220847. }
  220848. Thread::ThreadID Thread::getCurrentThreadId()
  220849. {
  220850. return static_cast <ThreadID> (pthread_self());
  220851. }
  220852. void Thread::yield()
  220853. {
  220854. sched_yield();
  220855. }
  220856. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  220857. {
  220858. // xxx
  220859. jassertfalse
  220860. }
  220861. bool Process::isForegroundProcess()
  220862. {
  220863. #if JUCE_MAC
  220864. return [NSApp isActive];
  220865. #else
  220866. return true; // xxx change this if more than one app is ever possible on the iPhone!
  220867. #endif
  220868. }
  220869. void Process::raisePrivilege()
  220870. {
  220871. jassertfalse
  220872. }
  220873. void Process::lowerPrivilege()
  220874. {
  220875. jassertfalse
  220876. }
  220877. void Process::terminate()
  220878. {
  220879. exit (0);
  220880. }
  220881. void Process::setPriority (ProcessPriority)
  220882. {
  220883. // xxx
  220884. }
  220885. #endif
  220886. /*** End of inlined file: juce_mac_Threads.mm ***/
  220887. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  220888. /*
  220889. This file contains posix routines that are common to both the Linux and Mac builds.
  220890. It gets included directly in the cpp files for these platforms.
  220891. */
  220892. CriticalSection::CriticalSection() throw()
  220893. {
  220894. pthread_mutexattr_t atts;
  220895. pthread_mutexattr_init (&atts);
  220896. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  220897. pthread_mutex_init (&internal, &atts);
  220898. }
  220899. CriticalSection::~CriticalSection() throw()
  220900. {
  220901. pthread_mutex_destroy (&internal);
  220902. }
  220903. void CriticalSection::enter() const throw()
  220904. {
  220905. pthread_mutex_lock (&internal);
  220906. }
  220907. bool CriticalSection::tryEnter() const throw()
  220908. {
  220909. return pthread_mutex_trylock (&internal) == 0;
  220910. }
  220911. void CriticalSection::exit() const throw()
  220912. {
  220913. pthread_mutex_unlock (&internal);
  220914. }
  220915. class WaitableEventImpl
  220916. {
  220917. public:
  220918. WaitableEventImpl (const bool manualReset_)
  220919. : triggered (false),
  220920. manualReset (manualReset_)
  220921. {
  220922. pthread_cond_init (&condition, 0);
  220923. pthread_mutex_init (&mutex, 0);
  220924. }
  220925. ~WaitableEventImpl()
  220926. {
  220927. pthread_cond_destroy (&condition);
  220928. pthread_mutex_destroy (&mutex);
  220929. }
  220930. bool wait (const int timeOutMillisecs) throw()
  220931. {
  220932. pthread_mutex_lock (&mutex);
  220933. if (! triggered)
  220934. {
  220935. if (timeOutMillisecs < 0)
  220936. {
  220937. do
  220938. {
  220939. pthread_cond_wait (&condition, &mutex);
  220940. }
  220941. while (! triggered);
  220942. }
  220943. else
  220944. {
  220945. struct timeval now;
  220946. gettimeofday (&now, 0);
  220947. struct timespec time;
  220948. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  220949. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  220950. if (time.tv_nsec >= 1000000000)
  220951. {
  220952. time.tv_nsec -= 1000000000;
  220953. time.tv_sec++;
  220954. }
  220955. do
  220956. {
  220957. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  220958. {
  220959. pthread_mutex_unlock (&mutex);
  220960. return false;
  220961. }
  220962. }
  220963. while (! triggered);
  220964. }
  220965. }
  220966. if (! manualReset)
  220967. triggered = false;
  220968. pthread_mutex_unlock (&mutex);
  220969. return true;
  220970. }
  220971. void signal() throw()
  220972. {
  220973. pthread_mutex_lock (&mutex);
  220974. triggered = true;
  220975. pthread_cond_broadcast (&condition);
  220976. pthread_mutex_unlock (&mutex);
  220977. }
  220978. void reset() throw()
  220979. {
  220980. pthread_mutex_lock (&mutex);
  220981. triggered = false;
  220982. pthread_mutex_unlock (&mutex);
  220983. }
  220984. private:
  220985. pthread_cond_t condition;
  220986. pthread_mutex_t mutex;
  220987. bool triggered;
  220988. const bool manualReset;
  220989. WaitableEventImpl (const WaitableEventImpl&);
  220990. WaitableEventImpl& operator= (const WaitableEventImpl&);
  220991. };
  220992. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  220993. : internal (new WaitableEventImpl (manualReset))
  220994. {
  220995. }
  220996. WaitableEvent::~WaitableEvent() throw()
  220997. {
  220998. delete static_cast <WaitableEventImpl*> (internal);
  220999. }
  221000. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  221001. {
  221002. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  221003. }
  221004. void WaitableEvent::signal() const throw()
  221005. {
  221006. static_cast <WaitableEventImpl*> (internal)->signal();
  221007. }
  221008. void WaitableEvent::reset() const throw()
  221009. {
  221010. static_cast <WaitableEventImpl*> (internal)->reset();
  221011. }
  221012. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  221013. {
  221014. struct timespec time;
  221015. time.tv_sec = millisecs / 1000;
  221016. time.tv_nsec = (millisecs % 1000) * 1000000;
  221017. nanosleep (&time, 0);
  221018. }
  221019. const juce_wchar File::separator = '/';
  221020. const String File::separatorString ("/");
  221021. const File File::getCurrentWorkingDirectory()
  221022. {
  221023. HeapBlock<char> heapBuffer;
  221024. char localBuffer [1024];
  221025. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  221026. int bufferSize = 4096;
  221027. while (cwd == 0 && errno == ERANGE)
  221028. {
  221029. heapBuffer.malloc (bufferSize);
  221030. cwd = getcwd (heapBuffer, bufferSize - 1);
  221031. bufferSize += 1024;
  221032. }
  221033. return File (String::fromUTF8 (cwd));
  221034. }
  221035. bool File::setAsCurrentWorkingDirectory() const
  221036. {
  221037. return chdir (getFullPathName().toUTF8()) == 0;
  221038. }
  221039. static bool juce_stat (const String& fileName, struct stat& info)
  221040. {
  221041. return fileName.isNotEmpty()
  221042. && (stat (fileName.toUTF8(), &info) == 0);
  221043. }
  221044. bool File::isDirectory() const
  221045. {
  221046. struct stat info;
  221047. return fullPath.isEmpty()
  221048. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  221049. }
  221050. bool File::exists() const
  221051. {
  221052. return fullPath.isNotEmpty()
  221053. && access (fullPath.toUTF8(), F_OK) == 0;
  221054. }
  221055. bool File::existsAsFile() const
  221056. {
  221057. return exists() && ! isDirectory();
  221058. }
  221059. int64 File::getSize() const
  221060. {
  221061. struct stat info;
  221062. return juce_stat (fullPath, info) ? info.st_size : 0;
  221063. }
  221064. bool File::hasWriteAccess() const
  221065. {
  221066. if (exists())
  221067. return access (fullPath.toUTF8(), W_OK) == 0;
  221068. if ((! isDirectory()) && fullPath.containsChar (separator))
  221069. return getParentDirectory().hasWriteAccess();
  221070. return false;
  221071. }
  221072. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  221073. {
  221074. struct stat info;
  221075. const int res = stat (fullPath.toUTF8(), &info);
  221076. if (res != 0)
  221077. return false;
  221078. info.st_mode &= 0777; // Just permissions
  221079. if (shouldBeReadOnly)
  221080. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  221081. else
  221082. // Give everybody write permission?
  221083. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  221084. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  221085. }
  221086. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  221087. {
  221088. modificationTime = 0;
  221089. accessTime = 0;
  221090. creationTime = 0;
  221091. struct stat info;
  221092. const int res = stat (fullPath.toUTF8(), &info);
  221093. if (res == 0)
  221094. {
  221095. modificationTime = (int64) info.st_mtime * 1000;
  221096. accessTime = (int64) info.st_atime * 1000;
  221097. creationTime = (int64) info.st_ctime * 1000;
  221098. }
  221099. }
  221100. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  221101. {
  221102. struct utimbuf times;
  221103. times.actime = (time_t) (accessTime / 1000);
  221104. times.modtime = (time_t) (modificationTime / 1000);
  221105. return utime (fullPath.toUTF8(), &times) == 0;
  221106. }
  221107. bool File::deleteFile() const
  221108. {
  221109. if (! exists())
  221110. return true;
  221111. else if (isDirectory())
  221112. return rmdir (fullPath.toUTF8()) == 0;
  221113. else
  221114. return remove (fullPath.toUTF8()) == 0;
  221115. }
  221116. bool File::moveInternal (const File& dest) const
  221117. {
  221118. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  221119. return true;
  221120. if (hasWriteAccess() && copyInternal (dest))
  221121. {
  221122. if (deleteFile())
  221123. return true;
  221124. dest.deleteFile();
  221125. }
  221126. return false;
  221127. }
  221128. void File::createDirectoryInternal (const String& fileName) const
  221129. {
  221130. mkdir (fileName.toUTF8(), 0777);
  221131. }
  221132. void* juce_fileOpen (const File& file, bool forWriting)
  221133. {
  221134. int flags = O_RDONLY;
  221135. if (forWriting)
  221136. {
  221137. if (file.exists())
  221138. {
  221139. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  221140. if (f != -1)
  221141. lseek (f, 0, SEEK_END);
  221142. return (void*) f;
  221143. }
  221144. else
  221145. {
  221146. flags = O_RDWR + O_CREAT;
  221147. }
  221148. }
  221149. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  221150. }
  221151. void juce_fileClose (void* handle)
  221152. {
  221153. if (handle != 0)
  221154. close ((int) (pointer_sized_int) handle);
  221155. }
  221156. int juce_fileRead (void* handle, void* buffer, int size)
  221157. {
  221158. if (handle != 0)
  221159. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  221160. return 0;
  221161. }
  221162. int juce_fileWrite (void* handle, const void* buffer, int size)
  221163. {
  221164. if (handle != 0)
  221165. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  221166. return 0;
  221167. }
  221168. int64 juce_fileSetPosition (void* handle, int64 pos)
  221169. {
  221170. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  221171. return pos;
  221172. return -1;
  221173. }
  221174. int64 FileOutputStream::getPositionInternal() const
  221175. {
  221176. if (fileHandle != 0)
  221177. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  221178. return -1;
  221179. }
  221180. void FileOutputStream::flushInternal()
  221181. {
  221182. if (fileHandle != 0)
  221183. fsync ((int) (pointer_sized_int) fileHandle);
  221184. }
  221185. const File juce_getExecutableFile()
  221186. {
  221187. Dl_info exeInfo;
  221188. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  221189. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  221190. }
  221191. // if this file doesn't exist, find a parent of it that does..
  221192. static bool juce_doStatFS (File f, struct statfs& result)
  221193. {
  221194. for (int i = 5; --i >= 0;)
  221195. {
  221196. if (f.exists())
  221197. break;
  221198. f = f.getParentDirectory();
  221199. }
  221200. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  221201. }
  221202. int64 File::getBytesFreeOnVolume() const
  221203. {
  221204. struct statfs buf;
  221205. if (juce_doStatFS (*this, buf))
  221206. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  221207. return 0;
  221208. }
  221209. int64 File::getVolumeTotalSize() const
  221210. {
  221211. struct statfs buf;
  221212. if (juce_doStatFS (*this, buf))
  221213. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  221214. return 0;
  221215. }
  221216. const String File::getVolumeLabel() const
  221217. {
  221218. #if JUCE_MAC
  221219. struct VolAttrBuf
  221220. {
  221221. u_int32_t length;
  221222. attrreference_t mountPointRef;
  221223. char mountPointSpace [MAXPATHLEN];
  221224. } attrBuf;
  221225. struct attrlist attrList;
  221226. zerostruct (attrList);
  221227. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  221228. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  221229. File f (*this);
  221230. for (;;)
  221231. {
  221232. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  221233. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  221234. (int) attrBuf.mountPointRef.attr_length);
  221235. const File parent (f.getParentDirectory());
  221236. if (f == parent)
  221237. break;
  221238. f = parent;
  221239. }
  221240. #endif
  221241. return String::empty;
  221242. }
  221243. int File::getVolumeSerialNumber() const
  221244. {
  221245. return 0; // xxx
  221246. }
  221247. void juce_runSystemCommand (const String& command)
  221248. {
  221249. int result = system (command.toUTF8());
  221250. (void) result;
  221251. }
  221252. const String juce_getOutputFromCommand (const String& command)
  221253. {
  221254. // slight bodge here, as we just pipe the output into a temp file and read it...
  221255. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  221256. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  221257. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  221258. String result (tempFile.loadFileAsString());
  221259. tempFile.deleteFile();
  221260. return result;
  221261. }
  221262. class InterProcessLock::Pimpl
  221263. {
  221264. public:
  221265. Pimpl (const String& name, const int timeOutMillisecs)
  221266. : handle (0), refCount (1)
  221267. {
  221268. #if JUCE_MAC
  221269. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  221270. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  221271. #else
  221272. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  221273. #endif
  221274. temp.create();
  221275. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  221276. if (handle != 0)
  221277. {
  221278. struct flock fl;
  221279. zerostruct (fl);
  221280. fl.l_whence = SEEK_SET;
  221281. fl.l_type = F_WRLCK;
  221282. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  221283. for (;;)
  221284. {
  221285. const int result = fcntl (handle, F_SETLK, &fl);
  221286. if (result >= 0)
  221287. return;
  221288. if (errno != EINTR)
  221289. {
  221290. if (timeOutMillisecs == 0
  221291. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  221292. break;
  221293. Thread::sleep (10);
  221294. }
  221295. }
  221296. }
  221297. closeFile();
  221298. }
  221299. ~Pimpl()
  221300. {
  221301. closeFile();
  221302. }
  221303. void closeFile()
  221304. {
  221305. if (handle != 0)
  221306. {
  221307. struct flock fl;
  221308. zerostruct (fl);
  221309. fl.l_whence = SEEK_SET;
  221310. fl.l_type = F_UNLCK;
  221311. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  221312. {}
  221313. close (handle);
  221314. handle = 0;
  221315. }
  221316. }
  221317. int handle, refCount;
  221318. };
  221319. InterProcessLock::InterProcessLock (const String& name_)
  221320. : name (name_)
  221321. {
  221322. }
  221323. InterProcessLock::~InterProcessLock()
  221324. {
  221325. }
  221326. bool InterProcessLock::enter (const int timeOutMillisecs)
  221327. {
  221328. const ScopedLock sl (lock);
  221329. if (pimpl == 0)
  221330. {
  221331. pimpl = new Pimpl (name, timeOutMillisecs);
  221332. if (pimpl->handle == 0)
  221333. pimpl = 0;
  221334. }
  221335. else
  221336. {
  221337. pimpl->refCount++;
  221338. }
  221339. return pimpl != 0;
  221340. }
  221341. void InterProcessLock::exit()
  221342. {
  221343. const ScopedLock sl (lock);
  221344. // Trying to release the lock too many times!
  221345. jassert (pimpl != 0);
  221346. if (pimpl != 0 && --(pimpl->refCount) == 0)
  221347. pimpl = 0;
  221348. }
  221349. /*** End of inlined file: juce_posix_SharedCode.h ***/
  221350. /*** Start of inlined file: juce_mac_Files.mm ***/
  221351. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221352. // compiled on its own).
  221353. #if JUCE_INCLUDED_FILE
  221354. /*
  221355. Note that a lot of methods that you'd expect to find in this file actually
  221356. live in juce_posix_SharedCode.h!
  221357. */
  221358. bool File::copyInternal (const File& dest) const
  221359. {
  221360. const ScopedAutoReleasePool pool;
  221361. NSFileManager* fm = [NSFileManager defaultManager];
  221362. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  221363. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221364. && [fm copyItemAtPath: juceStringToNS (fullPath)
  221365. toPath: juceStringToNS (dest.getFullPathName())
  221366. error: nil];
  221367. #else
  221368. && [fm copyPath: juceStringToNS (fullPath)
  221369. toPath: juceStringToNS (dest.getFullPathName())
  221370. handler: nil];
  221371. #endif
  221372. }
  221373. void File::findFileSystemRoots (Array<File>& destArray)
  221374. {
  221375. destArray.add (File ("/"));
  221376. }
  221377. static bool isFileOnDriveType (const File& f, const char* const* types)
  221378. {
  221379. struct statfs buf;
  221380. if (juce_doStatFS (f, buf))
  221381. {
  221382. const String type (buf.f_fstypename);
  221383. while (*types != 0)
  221384. if (type.equalsIgnoreCase (*types++))
  221385. return true;
  221386. }
  221387. return false;
  221388. }
  221389. bool File::isOnCDRomDrive() const
  221390. {
  221391. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  221392. return isFileOnDriveType (*this, cdTypes);
  221393. }
  221394. bool File::isOnHardDisk() const
  221395. {
  221396. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  221397. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  221398. }
  221399. bool File::isOnRemovableDrive() const
  221400. {
  221401. #if JUCE_IPHONE
  221402. return false; // xxx is this possible?
  221403. #else
  221404. const ScopedAutoReleasePool pool;
  221405. BOOL removable = false;
  221406. [[NSWorkspace sharedWorkspace]
  221407. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  221408. isRemovable: &removable
  221409. isWritable: nil
  221410. isUnmountable: nil
  221411. description: nil
  221412. type: nil];
  221413. return removable;
  221414. #endif
  221415. }
  221416. static bool juce_isHiddenFile (const String& path)
  221417. {
  221418. #if JUCE_IPHONE
  221419. return File (path).getFileName().startsWithChar ('.');
  221420. #else
  221421. FSRef ref;
  221422. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  221423. return false;
  221424. FSCatalogInfo info;
  221425. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  221426. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  221427. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  221428. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  221429. #endif
  221430. }
  221431. bool File::isHidden() const
  221432. {
  221433. return juce_isHiddenFile (getFullPathName());
  221434. }
  221435. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  221436. const File File::getSpecialLocation (const SpecialLocationType type)
  221437. {
  221438. const ScopedAutoReleasePool pool;
  221439. String resultPath;
  221440. switch (type)
  221441. {
  221442. case userHomeDirectory:
  221443. resultPath = nsStringToJuce (NSHomeDirectory());
  221444. break;
  221445. case userDocumentsDirectory:
  221446. resultPath = "~/Documents";
  221447. break;
  221448. case userDesktopDirectory:
  221449. resultPath = "~/Desktop";
  221450. break;
  221451. case userApplicationDataDirectory:
  221452. resultPath = "~/Library";
  221453. break;
  221454. case commonApplicationDataDirectory:
  221455. resultPath = "/Library";
  221456. break;
  221457. case globalApplicationsDirectory:
  221458. resultPath = "/Applications";
  221459. break;
  221460. case userMusicDirectory:
  221461. resultPath = "~/Music";
  221462. break;
  221463. case userMoviesDirectory:
  221464. resultPath = "~/Movies";
  221465. break;
  221466. case tempDirectory:
  221467. {
  221468. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  221469. tmp.createDirectory();
  221470. return tmp.getFullPathName();
  221471. }
  221472. case invokedExecutableFile:
  221473. if (juce_Argv0 != 0)
  221474. return File (String::fromUTF8 (juce_Argv0));
  221475. // deliberate fall-through...
  221476. case currentExecutableFile:
  221477. return juce_getExecutableFile();
  221478. case currentApplicationFile:
  221479. {
  221480. const File exe (juce_getExecutableFile());
  221481. const File parent (exe.getParentDirectory());
  221482. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  221483. ? parent.getParentDirectory().getParentDirectory()
  221484. : exe;
  221485. }
  221486. default:
  221487. jassertfalse // unknown type?
  221488. break;
  221489. }
  221490. if (resultPath.isNotEmpty())
  221491. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  221492. return File::nonexistent;
  221493. }
  221494. const String File::getVersion() const
  221495. {
  221496. const ScopedAutoReleasePool pool;
  221497. String result;
  221498. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  221499. if (bundle != 0)
  221500. {
  221501. NSDictionary* info = [bundle infoDictionary];
  221502. if (info != 0)
  221503. {
  221504. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  221505. if (name != nil)
  221506. result = nsStringToJuce (name);
  221507. }
  221508. }
  221509. return result;
  221510. }
  221511. const File File::getLinkedTarget() const
  221512. {
  221513. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  221514. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  221515. #else
  221516. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  221517. #endif
  221518. if (dest != nil)
  221519. return File (nsStringToJuce (dest));
  221520. return *this;
  221521. }
  221522. bool File::moveToTrash() const
  221523. {
  221524. if (! exists())
  221525. return true;
  221526. #if JUCE_IPHONE
  221527. return deleteFile(); //xxx is there a trashcan on the iPhone?
  221528. #else
  221529. const ScopedAutoReleasePool pool;
  221530. NSString* p = juceStringToNS (getFullPathName());
  221531. return [[NSWorkspace sharedWorkspace]
  221532. performFileOperation: NSWorkspaceRecycleOperation
  221533. source: [p stringByDeletingLastPathComponent]
  221534. destination: @""
  221535. files: [NSArray arrayWithObject: [p lastPathComponent]]
  221536. tag: nil ];
  221537. #endif
  221538. }
  221539. class DirectoryIterator::NativeIterator::Pimpl
  221540. {
  221541. public:
  221542. Pimpl (const File& directory, const String& wildCard_)
  221543. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  221544. wildCard (wildCard_),
  221545. enumerator (0)
  221546. {
  221547. ScopedAutoReleasePool pool;
  221548. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  221549. wildcardUTF8 = wildCard.toUTF8();
  221550. }
  221551. ~Pimpl()
  221552. {
  221553. [enumerator release];
  221554. }
  221555. bool next (String& filenameFound,
  221556. bool* const isDir, bool* const isHidden, int64* const fileSize,
  221557. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  221558. {
  221559. ScopedAutoReleasePool pool;
  221560. for (;;)
  221561. {
  221562. NSString* file;
  221563. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  221564. return false;
  221565. [enumerator skipDescendents];
  221566. filenameFound = nsStringToJuce (file);
  221567. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  221568. continue;
  221569. const String path (parentDir + filenameFound);
  221570. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  221571. {
  221572. struct stat info;
  221573. const bool statOk = juce_stat (path, info);
  221574. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  221575. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  221576. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  221577. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  221578. }
  221579. if (isHidden != 0)
  221580. *isHidden = juce_isHiddenFile (path);
  221581. if (isReadOnly != 0)
  221582. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  221583. return true;
  221584. }
  221585. }
  221586. private:
  221587. String parentDir, wildCard;
  221588. const char* wildcardUTF8;
  221589. NSDirectoryEnumerator* enumerator;
  221590. Pimpl (const Pimpl&);
  221591. Pimpl& operator= (const Pimpl&);
  221592. };
  221593. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  221594. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  221595. {
  221596. }
  221597. DirectoryIterator::NativeIterator::~NativeIterator()
  221598. {
  221599. }
  221600. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  221601. bool* const isDir, bool* const isHidden, int64* const fileSize,
  221602. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  221603. {
  221604. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  221605. }
  221606. bool juce_launchExecutable (const String& pathAndArguments)
  221607. {
  221608. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  221609. const int cpid = fork();
  221610. if (cpid == 0)
  221611. {
  221612. // Child process
  221613. if (execve (argv[0], (char**) argv, 0) < 0)
  221614. exit (0);
  221615. }
  221616. else
  221617. {
  221618. if (cpid < 0)
  221619. return false;
  221620. }
  221621. return true;
  221622. }
  221623. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  221624. {
  221625. #if JUCE_IPHONE
  221626. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  221627. #else
  221628. const ScopedAutoReleasePool pool;
  221629. if (parameters.isEmpty())
  221630. {
  221631. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  221632. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  221633. }
  221634. bool ok = false;
  221635. FSRef ref;
  221636. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  221637. {
  221638. if (PlatformUtilities::isBundle (fileName))
  221639. {
  221640. NSMutableArray* urls = [NSMutableArray array];
  221641. StringArray docs;
  221642. docs.addTokens (parameters, true);
  221643. for (int i = 0; i < docs.size(); ++i)
  221644. [urls addObject: juceStringToNS (docs[i])];
  221645. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  221646. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  221647. options: 0
  221648. additionalEventParamDescriptor: nil
  221649. launchIdentifiers: nil];
  221650. }
  221651. else
  221652. {
  221653. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  221654. }
  221655. }
  221656. return ok;
  221657. #endif
  221658. }
  221659. void File::revealToUser() const
  221660. {
  221661. #if ! JUCE_IPHONE
  221662. if (exists())
  221663. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  221664. else if (getParentDirectory().exists())
  221665. getParentDirectory().revealToUser();
  221666. #endif
  221667. }
  221668. #if ! JUCE_IPHONE
  221669. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  221670. {
  221671. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  221672. }
  221673. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  221674. {
  221675. char path [2048];
  221676. zerostruct (path);
  221677. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  221678. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  221679. return String::empty;
  221680. }
  221681. #endif
  221682. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  221683. {
  221684. const ScopedAutoReleasePool pool;
  221685. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  221686. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  221687. #else
  221688. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  221689. #endif
  221690. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  221691. return [fileDict fileHFSTypeCode];
  221692. }
  221693. bool PlatformUtilities::isBundle (const String& filename)
  221694. {
  221695. #if JUCE_IPHONE
  221696. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  221697. #else
  221698. const ScopedAutoReleasePool pool;
  221699. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  221700. #endif
  221701. }
  221702. #endif
  221703. /*** End of inlined file: juce_mac_Files.mm ***/
  221704. #if JUCE_IPHONE
  221705. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  221706. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221707. // compiled on its own).
  221708. #if JUCE_INCLUDED_FILE
  221709. static JUCEApplication* juce_intialisingApp;
  221710. END_JUCE_NAMESPACE
  221711. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  221712. {
  221713. }
  221714. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  221715. - (void) applicationWillResignActive: (UIApplication*) application;
  221716. @end
  221717. @implementation JuceAppStartupDelegate
  221718. - (void) applicationDidFinishLaunching: (UIApplication*) application
  221719. {
  221720. String dummy;
  221721. if (! juce_intialisingApp->initialiseApp (dummy))
  221722. exit (0);
  221723. }
  221724. - (void) applicationWillResignActive: (UIApplication*) application
  221725. {
  221726. JUCEApplication::shutdownAppAndClearUp();
  221727. }
  221728. @end
  221729. BEGIN_JUCE_NAMESPACE
  221730. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  221731. {
  221732. juce_intialisingApp = app;
  221733. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  221734. }
  221735. ScopedAutoReleasePool::ScopedAutoReleasePool()
  221736. {
  221737. pool = [[NSAutoreleasePool alloc] init];
  221738. }
  221739. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  221740. {
  221741. [((NSAutoreleasePool*) pool) release];
  221742. }
  221743. void PlatformUtilities::beep()
  221744. {
  221745. //xxx
  221746. //AudioServicesPlaySystemSound ();
  221747. }
  221748. void PlatformUtilities::addItemToDock (const File& file)
  221749. {
  221750. }
  221751. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  221752. END_JUCE_NAMESPACE
  221753. @interface JuceAlertBoxDelegate : NSObject
  221754. {
  221755. @public
  221756. bool clickedOk;
  221757. }
  221758. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  221759. @end
  221760. @implementation JuceAlertBoxDelegate
  221761. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  221762. {
  221763. clickedOk = (buttonIndex == 0);
  221764. alertView.hidden = true;
  221765. }
  221766. @end
  221767. BEGIN_JUCE_NAMESPACE
  221768. // (This function is used directly by other bits of code)
  221769. bool juce_iPhoneShowModalAlert (const String& title,
  221770. const String& bodyText,
  221771. NSString* okButtonText,
  221772. NSString* cancelButtonText)
  221773. {
  221774. const ScopedAutoReleasePool pool;
  221775. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  221776. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  221777. message: juceStringToNS (bodyText)
  221778. delegate: callback
  221779. cancelButtonTitle: okButtonText
  221780. otherButtonTitles: cancelButtonText, nil];
  221781. [alert retain];
  221782. [alert show];
  221783. while (! alert.hidden && alert.superview != nil)
  221784. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  221785. const bool result = callback->clickedOk;
  221786. [alert release];
  221787. [callback release];
  221788. return result;
  221789. }
  221790. bool AlertWindow::showNativeDialogBox (const String& title,
  221791. const String& bodyText,
  221792. bool isOkCancel)
  221793. {
  221794. return juce_iPhoneShowModalAlert (title, bodyText,
  221795. @"OK",
  221796. isOkCancel ? @"Cancel" : nil);
  221797. }
  221798. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221799. {
  221800. jassertfalse // no such thing on the iphone!
  221801. return false;
  221802. }
  221803. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221804. {
  221805. jassertfalse // no such thing on the iphone!
  221806. return false;
  221807. }
  221808. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221809. {
  221810. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  221811. }
  221812. bool Desktop::isScreenSaverEnabled() throw()
  221813. {
  221814. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  221815. }
  221816. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  221817. {
  221818. const ScopedAutoReleasePool pool;
  221819. monitorCoords.clear();
  221820. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  221821. : [[UIScreen mainScreen] bounds];
  221822. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  221823. (int) r.origin.y,
  221824. (int) r.size.width,
  221825. (int) r.size.height));
  221826. }
  221827. #endif
  221828. #endif
  221829. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  221830. #else
  221831. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  221832. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221833. // compiled on its own).
  221834. #if JUCE_INCLUDED_FILE
  221835. ScopedAutoReleasePool::ScopedAutoReleasePool()
  221836. {
  221837. pool = [[NSAutoreleasePool alloc] init];
  221838. }
  221839. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  221840. {
  221841. [((NSAutoreleasePool*) pool) release];
  221842. }
  221843. void PlatformUtilities::beep()
  221844. {
  221845. NSBeep();
  221846. }
  221847. void PlatformUtilities::addItemToDock (const File& file)
  221848. {
  221849. // check that it's not already there...
  221850. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  221851. .containsIgnoreCase (file.getFullPathName()))
  221852. {
  221853. 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>"
  221854. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  221855. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  221856. }
  221857. }
  221858. int PlatformUtilities::getOSXMinorVersionNumber()
  221859. {
  221860. SInt32 versionMinor = 0;
  221861. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  221862. (void) err;
  221863. jassert (err == noErr);
  221864. return (int) versionMinor;
  221865. }
  221866. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  221867. bool AlertWindow::showNativeDialogBox (const String& title,
  221868. const String& bodyText,
  221869. bool isOkCancel)
  221870. {
  221871. const ScopedAutoReleasePool pool;
  221872. return NSRunAlertPanel (juceStringToNS (title),
  221873. juceStringToNS (bodyText),
  221874. @"Ok",
  221875. isOkCancel ? @"Cancel" : nil,
  221876. nil) == NSAlertDefaultReturn;
  221877. }
  221878. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  221879. {
  221880. if (files.size() == 0)
  221881. return false;
  221882. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  221883. if (draggingSource == 0)
  221884. {
  221885. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  221886. return false;
  221887. }
  221888. Component* sourceComp = draggingSource->getComponentUnderMouse();
  221889. if (sourceComp == 0)
  221890. {
  221891. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  221892. return false;
  221893. }
  221894. const ScopedAutoReleasePool pool;
  221895. NSView* view = (NSView*) sourceComp->getWindowHandle();
  221896. if (view == 0)
  221897. return false;
  221898. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  221899. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  221900. owner: nil];
  221901. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  221902. for (int i = 0; i < files.size(); ++i)
  221903. [filesArray addObject: juceStringToNS (files[i])];
  221904. [pboard setPropertyList: filesArray
  221905. forType: NSFilenamesPboardType];
  221906. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  221907. fromView: nil];
  221908. dragPosition.x -= 16;
  221909. dragPosition.y -= 16;
  221910. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  221911. at: dragPosition
  221912. offset: NSMakeSize (0, 0)
  221913. event: [[view window] currentEvent]
  221914. pasteboard: pboard
  221915. source: view
  221916. slideBack: YES];
  221917. return true;
  221918. }
  221919. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  221920. {
  221921. jassertfalse // not implemented!
  221922. return false;
  221923. }
  221924. bool Desktop::canUseSemiTransparentWindows() throw()
  221925. {
  221926. return true;
  221927. }
  221928. const Point<int> Desktop::getMousePosition()
  221929. {
  221930. const ScopedAutoReleasePool pool;
  221931. const NSPoint p ([NSEvent mouseLocation]);
  221932. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  221933. }
  221934. void Desktop::setMousePosition (const Point<int>& newPosition)
  221935. {
  221936. // this rubbish needs to be done around the warp call, to avoid causing a
  221937. // bizarre glitch..
  221938. CGAssociateMouseAndMouseCursorPosition (false);
  221939. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  221940. CGAssociateMouseAndMouseCursorPosition (true);
  221941. }
  221942. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  221943. class ScreenSaverDefeater : public Timer,
  221944. public DeletedAtShutdown
  221945. {
  221946. public:
  221947. ScreenSaverDefeater()
  221948. {
  221949. startTimer (10000);
  221950. timerCallback();
  221951. }
  221952. ~ScreenSaverDefeater() {}
  221953. void timerCallback()
  221954. {
  221955. if (Process::isForegroundProcess())
  221956. UpdateSystemActivity (UsrActivity);
  221957. }
  221958. };
  221959. static ScreenSaverDefeater* screenSaverDefeater = 0;
  221960. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221961. {
  221962. if (isEnabled)
  221963. {
  221964. deleteAndZero (screenSaverDefeater);
  221965. }
  221966. else if (screenSaverDefeater == 0)
  221967. {
  221968. screenSaverDefeater = new ScreenSaverDefeater();
  221969. }
  221970. }
  221971. bool Desktop::isScreenSaverEnabled() throw()
  221972. {
  221973. return screenSaverDefeater == 0;
  221974. }
  221975. #else
  221976. static IOPMAssertionID screenSaverDisablerID = 0;
  221977. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221978. {
  221979. if (isEnabled)
  221980. {
  221981. if (screenSaverDisablerID != 0)
  221982. {
  221983. IOPMAssertionRelease (screenSaverDisablerID);
  221984. screenSaverDisablerID = 0;
  221985. }
  221986. }
  221987. else
  221988. {
  221989. if (screenSaverDisablerID == 0)
  221990. {
  221991. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221992. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  221993. CFSTR ("Juce"), &screenSaverDisablerID);
  221994. #else
  221995. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  221996. &screenSaverDisablerID);
  221997. #endif
  221998. }
  221999. }
  222000. }
  222001. bool Desktop::isScreenSaverEnabled() throw()
  222002. {
  222003. return screenSaverDisablerID == 0;
  222004. }
  222005. #endif
  222006. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  222007. {
  222008. const ScopedAutoReleasePool pool;
  222009. monitorCoords.clear();
  222010. NSArray* screens = [NSScreen screens];
  222011. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  222012. for (unsigned int i = 0; i < [screens count]; ++i)
  222013. {
  222014. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  222015. NSRect r = clipToWorkArea ? [s visibleFrame]
  222016. : [s frame];
  222017. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  222018. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  222019. (int) r.size.width,
  222020. (int) r.size.height));
  222021. }
  222022. jassert (monitorCoords.size() > 0);
  222023. }
  222024. #endif
  222025. #endif
  222026. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  222027. #endif
  222028. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  222029. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222030. // compiled on its own).
  222031. #if JUCE_INCLUDED_FILE
  222032. void Logger::outputDebugString (const String& text) throw()
  222033. {
  222034. std::cerr << text << std::endl;
  222035. }
  222036. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  222037. {
  222038. static char testResult = 0;
  222039. if (testResult == 0)
  222040. {
  222041. struct kinfo_proc info;
  222042. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  222043. size_t sz = sizeof (info);
  222044. sysctl (m, 4, &info, &sz, 0, 0);
  222045. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  222046. }
  222047. return testResult > 0;
  222048. }
  222049. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  222050. {
  222051. return juce_isRunningUnderDebugger();
  222052. }
  222053. #endif
  222054. /*** End of inlined file: juce_mac_Debugging.mm ***/
  222055. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222056. #if JUCE_IPHONE
  222057. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  222058. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222059. // compiled on its own).
  222060. #if JUCE_INCLUDED_FILE
  222061. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222062. #define SUPPORT_10_4_FONTS 1
  222063. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  222064. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  222065. #define SUPPORT_ONLY_10_4_FONTS 1
  222066. #endif
  222067. END_JUCE_NAMESPACE
  222068. @interface NSFont (PrivateHack)
  222069. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  222070. @end
  222071. BEGIN_JUCE_NAMESPACE
  222072. #endif
  222073. class MacTypeface : public Typeface
  222074. {
  222075. public:
  222076. MacTypeface (const Font& font)
  222077. : Typeface (font.getTypefaceName())
  222078. {
  222079. const ScopedAutoReleasePool pool;
  222080. renderingTransform = CGAffineTransformIdentity;
  222081. bool needsItalicTransform = false;
  222082. #if JUCE_IPHONE
  222083. NSString* fontName = juceStringToNS (font.getTypefaceName());
  222084. if (font.isItalic() || font.isBold())
  222085. {
  222086. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  222087. for (NSString* i in familyFonts)
  222088. {
  222089. const String fn (nsStringToJuce (i));
  222090. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  222091. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  222092. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  222093. || afterDash.containsIgnoreCase ("italic")
  222094. || fn.endsWithIgnoreCase ("oblique")
  222095. || fn.endsWithIgnoreCase ("italic");
  222096. if (probablyBold == font.isBold()
  222097. && probablyItalic == font.isItalic())
  222098. {
  222099. fontName = i;
  222100. needsItalicTransform = false;
  222101. break;
  222102. }
  222103. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  222104. {
  222105. fontName = i;
  222106. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  222107. }
  222108. }
  222109. if (needsItalicTransform)
  222110. renderingTransform.c = 0.15f;
  222111. }
  222112. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  222113. const int ascender = abs (CGFontGetAscent (fontRef));
  222114. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  222115. ascent = ascender / totalHeight;
  222116. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222117. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  222118. #else
  222119. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  222120. if (font.isItalic())
  222121. {
  222122. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  222123. toHaveTrait: NSItalicFontMask];
  222124. if (newFont == nsFont)
  222125. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  222126. nsFont = newFont;
  222127. }
  222128. if (font.isBold())
  222129. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  222130. [nsFont retain];
  222131. ascent = fabsf ((float) [nsFont ascender]);
  222132. float totalSize = ascent + fabsf ((float) [nsFont descender]);
  222133. ascent /= totalSize;
  222134. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  222135. if (needsItalicTransform)
  222136. {
  222137. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  222138. renderingTransform.c = 0.15f;
  222139. }
  222140. #if SUPPORT_ONLY_10_4_FONTS
  222141. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222142. if (atsFont == 0)
  222143. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222144. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222145. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  222146. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222147. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222148. #else
  222149. #if SUPPORT_10_4_FONTS
  222150. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222151. {
  222152. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222153. if (atsFont == 0)
  222154. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222155. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222156. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  222157. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222158. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222159. }
  222160. else
  222161. #endif
  222162. {
  222163. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  222164. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  222165. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222166. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  222167. }
  222168. #endif
  222169. #endif
  222170. }
  222171. ~MacTypeface()
  222172. {
  222173. #if ! JUCE_IPHONE
  222174. [nsFont release];
  222175. #endif
  222176. if (fontRef != 0)
  222177. CGFontRelease (fontRef);
  222178. }
  222179. float getAscent() const
  222180. {
  222181. return ascent;
  222182. }
  222183. float getDescent() const
  222184. {
  222185. return 1.0f - ascent;
  222186. }
  222187. float getStringWidth (const String& text)
  222188. {
  222189. if (fontRef == 0 || text.isEmpty())
  222190. return 0;
  222191. const int length = text.length();
  222192. HeapBlock <CGGlyph> glyphs;
  222193. createGlyphsForString (text, length, glyphs);
  222194. float x = 0;
  222195. #if SUPPORT_ONLY_10_4_FONTS
  222196. HeapBlock <NSSize> advances (length);
  222197. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222198. for (int i = 0; i < length; ++i)
  222199. x += advances[i].width;
  222200. #else
  222201. #if SUPPORT_10_4_FONTS
  222202. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222203. {
  222204. HeapBlock <NSSize> advances (length);
  222205. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  222206. for (int i = 0; i < length; ++i)
  222207. x += advances[i].width;
  222208. }
  222209. else
  222210. #endif
  222211. {
  222212. HeapBlock <int> advances (length);
  222213. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222214. for (int i = 0; i < length; ++i)
  222215. x += advances[i];
  222216. }
  222217. #endif
  222218. return x * unitsToHeightScaleFactor;
  222219. }
  222220. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  222221. {
  222222. xOffsets.add (0);
  222223. if (fontRef == 0 || text.isEmpty())
  222224. return;
  222225. const int length = text.length();
  222226. HeapBlock <CGGlyph> glyphs;
  222227. createGlyphsForString (text, length, glyphs);
  222228. #if SUPPORT_ONLY_10_4_FONTS
  222229. HeapBlock <NSSize> advances (length);
  222230. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222231. int x = 0;
  222232. for (int i = 0; i < length; ++i)
  222233. {
  222234. x += advances[i].width;
  222235. xOffsets.add (x * unitsToHeightScaleFactor);
  222236. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  222237. }
  222238. #else
  222239. #if SUPPORT_10_4_FONTS
  222240. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222241. {
  222242. HeapBlock <NSSize> advances (length);
  222243. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222244. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  222245. float x = 0;
  222246. for (int i = 0; i < length; ++i)
  222247. {
  222248. x += advances[i].width;
  222249. xOffsets.add (x * unitsToHeightScaleFactor);
  222250. resultGlyphs.add (nsGlyphs[i]);
  222251. }
  222252. }
  222253. else
  222254. #endif
  222255. {
  222256. HeapBlock <int> advances (length);
  222257. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222258. {
  222259. int x = 0;
  222260. for (int i = 0; i < length; ++i)
  222261. {
  222262. x += advances [i];
  222263. xOffsets.add (x * unitsToHeightScaleFactor);
  222264. resultGlyphs.add (glyphs[i]);
  222265. }
  222266. }
  222267. }
  222268. #endif
  222269. }
  222270. bool getOutlineForGlyph (int glyphNumber, Path& path)
  222271. {
  222272. #if JUCE_IPHONE
  222273. return false;
  222274. #else
  222275. if (nsFont == 0)
  222276. return false;
  222277. // we might need to apply a transform to the path, so it mustn't have anything else in it
  222278. jassert (path.isEmpty());
  222279. const ScopedAutoReleasePool pool;
  222280. NSBezierPath* bez = [NSBezierPath bezierPath];
  222281. [bez moveToPoint: NSMakePoint (0, 0)];
  222282. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  222283. inFont: nsFont];
  222284. for (int i = 0; i < [bez elementCount]; ++i)
  222285. {
  222286. NSPoint p[3];
  222287. switch ([bez elementAtIndex: i associatedPoints: p])
  222288. {
  222289. case NSMoveToBezierPathElement:
  222290. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  222291. break;
  222292. case NSLineToBezierPathElement:
  222293. path.lineTo ((float) p[0].x, (float) -p[0].y);
  222294. break;
  222295. case NSCurveToBezierPathElement:
  222296. 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);
  222297. break;
  222298. case NSClosePathBezierPathElement:
  222299. path.closeSubPath();
  222300. break;
  222301. default:
  222302. jassertfalse
  222303. break;
  222304. }
  222305. }
  222306. path.applyTransform (pathTransform);
  222307. return true;
  222308. #endif
  222309. }
  222310. juce_UseDebuggingNewOperator
  222311. CGFontRef fontRef;
  222312. float fontHeightToCGSizeFactor;
  222313. CGAffineTransform renderingTransform;
  222314. private:
  222315. float ascent, unitsToHeightScaleFactor;
  222316. #if JUCE_IPHONE
  222317. #else
  222318. NSFont* nsFont;
  222319. AffineTransform pathTransform;
  222320. #endif
  222321. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  222322. {
  222323. #if SUPPORT_10_4_FONTS
  222324. #if ! SUPPORT_ONLY_10_4_FONTS
  222325. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222326. #endif
  222327. {
  222328. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  222329. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222330. for (int i = 0; i < length; ++i)
  222331. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  222332. return;
  222333. }
  222334. #endif
  222335. #if ! SUPPORT_ONLY_10_4_FONTS
  222336. if (charToGlyphMapper == 0)
  222337. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  222338. glyphs.malloc (length);
  222339. for (int i = 0; i < length; ++i)
  222340. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  222341. #endif
  222342. }
  222343. #if ! SUPPORT_ONLY_10_4_FONTS
  222344. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  222345. class CharToGlyphMapper
  222346. {
  222347. public:
  222348. CharToGlyphMapper (CGFontRef fontRef)
  222349. : segCount (0), endCode (0), startCode (0), idDelta (0),
  222350. idRangeOffset (0), glyphIndexes (0)
  222351. {
  222352. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  222353. if (cmapTable != 0)
  222354. {
  222355. const int numSubtables = getValue16 (cmapTable, 2);
  222356. for (int i = 0; i < numSubtables; ++i)
  222357. {
  222358. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  222359. {
  222360. const int offset = getValue32 (cmapTable, i * 8 + 8);
  222361. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  222362. {
  222363. const int length = getValue16 (cmapTable, offset + 2);
  222364. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  222365. segCount = segCountX2 / 2;
  222366. const int endCodeOffset = offset + 14;
  222367. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  222368. const int idDeltaOffset = startCodeOffset + segCountX2;
  222369. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  222370. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  222371. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  222372. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  222373. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  222374. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  222375. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  222376. }
  222377. break;
  222378. }
  222379. }
  222380. CFRelease (cmapTable);
  222381. }
  222382. }
  222383. ~CharToGlyphMapper()
  222384. {
  222385. if (endCode != 0)
  222386. {
  222387. CFRelease (endCode);
  222388. CFRelease (startCode);
  222389. CFRelease (idDelta);
  222390. CFRelease (idRangeOffset);
  222391. CFRelease (glyphIndexes);
  222392. }
  222393. }
  222394. int getGlyphForCharacter (const juce_wchar c) const
  222395. {
  222396. for (int i = 0; i < segCount; ++i)
  222397. {
  222398. if (getValue16 (endCode, i * 2) >= c)
  222399. {
  222400. const int start = getValue16 (startCode, i * 2);
  222401. if (start > c)
  222402. break;
  222403. const int delta = getValue16 (idDelta, i * 2);
  222404. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  222405. if (rangeOffset == 0)
  222406. return delta + c;
  222407. else
  222408. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  222409. }
  222410. }
  222411. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  222412. return jmax (-1, c - 29);
  222413. }
  222414. private:
  222415. int segCount;
  222416. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  222417. static uint16 getValue16 (CFDataRef data, const int index)
  222418. {
  222419. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  222420. }
  222421. static uint32 getValue32 (CFDataRef data, const int index)
  222422. {
  222423. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  222424. }
  222425. };
  222426. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  222427. #endif
  222428. MacTypeface (const MacTypeface&);
  222429. MacTypeface& operator= (const MacTypeface&);
  222430. };
  222431. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  222432. {
  222433. return new MacTypeface (font);
  222434. }
  222435. const StringArray Font::findAllTypefaceNames()
  222436. {
  222437. StringArray names;
  222438. const ScopedAutoReleasePool pool;
  222439. #if JUCE_IPHONE
  222440. NSArray* fonts = [UIFont familyNames];
  222441. #else
  222442. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  222443. #endif
  222444. for (unsigned int i = 0; i < [fonts count]; ++i)
  222445. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  222446. names.sort (true);
  222447. return names;
  222448. }
  222449. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  222450. {
  222451. #if JUCE_IPHONE
  222452. defaultSans = "Helvetica";
  222453. defaultSerif = "Times New Roman";
  222454. defaultFixed = "Courier New";
  222455. #else
  222456. defaultSans = "Lucida Grande";
  222457. defaultSerif = "Times New Roman";
  222458. defaultFixed = "Monaco";
  222459. #endif
  222460. }
  222461. #endif
  222462. /*** End of inlined file: juce_mac_Fonts.mm ***/
  222463. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  222464. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222465. // compiled on its own).
  222466. #if JUCE_INCLUDED_FILE
  222467. class CoreGraphicsImage : public Image
  222468. {
  222469. public:
  222470. CoreGraphicsImage (const PixelFormat format_,
  222471. const int imageWidth_,
  222472. const int imageHeight_,
  222473. const bool clearImage)
  222474. : Image (format_, imageWidth_, imageHeight_, clearImage)
  222475. {
  222476. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  222477. : CGColorSpaceCreateDeviceRGB();
  222478. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  222479. colourSpace, getCGImageFlags (*this));
  222480. CGColorSpaceRelease (colourSpace);
  222481. }
  222482. ~CoreGraphicsImage()
  222483. {
  222484. CGContextRelease (context);
  222485. }
  222486. LowLevelGraphicsContext* createLowLevelContext();
  222487. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  222488. {
  222489. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  222490. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  222491. {
  222492. return CGBitmapContextCreateImage (nativeImage->context);
  222493. }
  222494. else
  222495. {
  222496. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  222497. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  222498. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  222499. 8, srcData.pixelStride * 8, srcData.lineStride,
  222500. colourSpace, getCGImageFlags (juceImage), provider,
  222501. 0, true, kCGRenderingIntentDefault);
  222502. CGDataProviderRelease (provider);
  222503. return imageRef;
  222504. }
  222505. }
  222506. #if JUCE_MAC
  222507. static NSImage* createNSImage (const Image& image)
  222508. {
  222509. const ScopedAutoReleasePool pool;
  222510. NSImage* im = [[NSImage alloc] init];
  222511. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  222512. [im lockFocus];
  222513. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  222514. CGImageRef imageRef = createImage (image, false, colourSpace);
  222515. CGColorSpaceRelease (colourSpace);
  222516. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  222517. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  222518. CGImageRelease (imageRef);
  222519. [im unlockFocus];
  222520. return im;
  222521. }
  222522. #endif
  222523. CGContextRef context;
  222524. private:
  222525. static CGBitmapInfo getCGImageFlags (const Image& image)
  222526. {
  222527. #if JUCE_BIG_ENDIAN
  222528. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  222529. #else
  222530. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  222531. #endif
  222532. }
  222533. };
  222534. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  222535. {
  222536. #if USE_COREGRAPHICS_RENDERING
  222537. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  222538. #else
  222539. return new Image (format, imageWidth, imageHeight, clearImage);
  222540. #endif
  222541. }
  222542. class CoreGraphicsContext : public LowLevelGraphicsContext
  222543. {
  222544. public:
  222545. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  222546. : context (context_),
  222547. flipHeight (flipHeight_),
  222548. state (new SavedState()),
  222549. numGradientLookupEntries (0)
  222550. {
  222551. CGContextRetain (context);
  222552. CGContextSaveGState(context);
  222553. CGContextSetShouldSmoothFonts (context, true);
  222554. CGContextSetShouldAntialias (context, true);
  222555. CGContextSetBlendMode (context, kCGBlendModeNormal);
  222556. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  222557. greyColourSpace = CGColorSpaceCreateDeviceGray();
  222558. gradientCallbacks.version = 0;
  222559. gradientCallbacks.evaluate = gradientCallback;
  222560. gradientCallbacks.releaseInfo = 0;
  222561. setFont (Font());
  222562. }
  222563. ~CoreGraphicsContext()
  222564. {
  222565. CGContextRestoreGState (context);
  222566. CGContextRelease (context);
  222567. CGColorSpaceRelease (rgbColourSpace);
  222568. CGColorSpaceRelease (greyColourSpace);
  222569. }
  222570. bool isVectorDevice() const { return false; }
  222571. void setOrigin (int x, int y)
  222572. {
  222573. CGContextTranslateCTM (context, x, -y);
  222574. }
  222575. bool clipToRectangle (const Rectangle<int>& r)
  222576. {
  222577. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  222578. return ! isClipEmpty();
  222579. }
  222580. bool clipToRectangleList (const RectangleList& clipRegion)
  222581. {
  222582. if (clipRegion.isEmpty())
  222583. {
  222584. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  222585. return false;
  222586. }
  222587. else
  222588. {
  222589. const int numRects = clipRegion.getNumRectangles();
  222590. HeapBlock <CGRect> rects (numRects);
  222591. for (int i = 0; i < numRects; ++i)
  222592. {
  222593. const Rectangle<int>& r = clipRegion.getRectangle(i);
  222594. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  222595. }
  222596. CGContextClipToRects (context, rects, numRects);
  222597. return ! isClipEmpty();
  222598. }
  222599. }
  222600. void excludeClipRectangle (const Rectangle<int>& r)
  222601. {
  222602. RectangleList remaining (getClipBounds());
  222603. remaining.subtract (r);
  222604. clipToRectangleList (remaining);
  222605. }
  222606. void clipToPath (const Path& path, const AffineTransform& transform)
  222607. {
  222608. createPath (path, transform);
  222609. CGContextClip (context);
  222610. }
  222611. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  222612. {
  222613. if (! transform.isSingularity())
  222614. {
  222615. ScopedPointer<Image> imageToDelete;
  222616. const Image* singleChannelImage = &sourceImage;
  222617. if (sourceImage.getFormat() != Image::SingleChannel)
  222618. {
  222619. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  222620. singleChannelImage = imageToDelete;
  222621. }
  222622. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  222623. flip();
  222624. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  222625. applyTransform (t);
  222626. CGRect r = CGRectMake (srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  222627. CGContextClipToMask (context, r, image);
  222628. applyTransform (t.inverted());
  222629. flip();
  222630. CGImageRelease (image);
  222631. }
  222632. }
  222633. bool clipRegionIntersects (const Rectangle<int>& r)
  222634. {
  222635. return getClipBounds().intersects (r);
  222636. }
  222637. const Rectangle<int> getClipBounds() const
  222638. {
  222639. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  222640. return Rectangle<int> (roundToInt (bounds.origin.x),
  222641. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  222642. roundToInt (bounds.size.width),
  222643. roundToInt (bounds.size.height));
  222644. }
  222645. bool isClipEmpty() const
  222646. {
  222647. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  222648. }
  222649. void saveState()
  222650. {
  222651. CGContextSaveGState (context);
  222652. stateStack.add (new SavedState (*state));
  222653. }
  222654. void restoreState()
  222655. {
  222656. CGContextRestoreGState (context);
  222657. SavedState* const top = stateStack.getLast();
  222658. if (top != 0)
  222659. {
  222660. state = top;
  222661. stateStack.removeLast (1, false);
  222662. }
  222663. else
  222664. {
  222665. jassertfalse // trying to pop with an empty stack!
  222666. }
  222667. }
  222668. void setFill (const FillType& fillType)
  222669. {
  222670. state->fillType = fillType;
  222671. if (fillType.isColour())
  222672. {
  222673. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  222674. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  222675. CGContextSetAlpha (context, 1.0f);
  222676. }
  222677. }
  222678. void setOpacity (float newOpacity)
  222679. {
  222680. state->fillType.setOpacity (newOpacity);
  222681. setFill (state->fillType);
  222682. }
  222683. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  222684. {
  222685. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  222686. ? kCGInterpolationLow
  222687. : kCGInterpolationHigh);
  222688. }
  222689. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  222690. {
  222691. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  222692. if (replaceExistingContents)
  222693. {
  222694. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  222695. CGContextClearRect (context, cgRect);
  222696. #else
  222697. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222698. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  222699. CGContextClearRect (context, cgRect);
  222700. else
  222701. #endif
  222702. CGContextSetBlendMode (context, kCGBlendModeCopy);
  222703. #endif
  222704. fillRect (r, false);
  222705. CGContextSetBlendMode (context, kCGBlendModeNormal);
  222706. }
  222707. else
  222708. {
  222709. if (state->fillType.isColour())
  222710. {
  222711. CGContextFillRect (context, cgRect);
  222712. }
  222713. else if (state->fillType.isGradient())
  222714. {
  222715. CGContextSaveGState (context);
  222716. CGContextClipToRect (context, cgRect);
  222717. drawGradient();
  222718. CGContextRestoreGState (context);
  222719. }
  222720. else
  222721. {
  222722. CGContextSaveGState (context);
  222723. CGContextClipToRect (context, cgRect);
  222724. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  222725. CGContextRestoreGState (context);
  222726. }
  222727. }
  222728. }
  222729. void fillPath (const Path& path, const AffineTransform& transform)
  222730. {
  222731. CGContextSaveGState (context);
  222732. if (state->fillType.isColour())
  222733. {
  222734. flip();
  222735. applyTransform (transform);
  222736. createPath (path);
  222737. if (path.isUsingNonZeroWinding())
  222738. CGContextFillPath (context);
  222739. else
  222740. CGContextEOFillPath (context);
  222741. }
  222742. else
  222743. {
  222744. createPath (path, transform);
  222745. if (path.isUsingNonZeroWinding())
  222746. CGContextClip (context);
  222747. else
  222748. CGContextEOClip (context);
  222749. if (state->fillType.isGradient())
  222750. drawGradient();
  222751. else
  222752. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  222753. }
  222754. CGContextRestoreGState (context);
  222755. }
  222756. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  222757. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  222758. {
  222759. jassert (sourceImage.getBounds().contains (srcClip));
  222760. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  222761. CGImageRef image = fullImage;
  222762. if (srcClip != sourceImage.getBounds())
  222763. {
  222764. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  222765. srcClip.getWidth(), srcClip.getHeight()));
  222766. CGImageRelease (fullImage);
  222767. }
  222768. CGContextSaveGState (context);
  222769. CGContextSetAlpha (context, state->fillType.getOpacity());
  222770. flip();
  222771. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  222772. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  222773. if (fillEntireClipAsTiles)
  222774. {
  222775. #if JUCE_IPHONE
  222776. CGContextDrawTiledImage (context, imageRect, image);
  222777. #else
  222778. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  222779. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  222780. // if it's doing a transformation - it's quicker to just draw lots of images manually
  222781. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  222782. CGContextDrawTiledImage (context, imageRect, image);
  222783. else
  222784. #endif
  222785. {
  222786. // Fallback to manually doing a tiled fill on 10.4
  222787. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  222788. const int iw = srcClip.getWidth();
  222789. const int ih = srcClip.getHeight();
  222790. int x = 0, y = 0;
  222791. while (x > clip.origin.x) x -= iw;
  222792. while (y > clip.origin.y) y -= ih;
  222793. const int right = (int) (clip.origin.x + clip.size.width);
  222794. const int bottom = (int) (clip.origin.y + clip.size.height);
  222795. while (y < bottom)
  222796. {
  222797. for (int x2 = x; x2 < right; x2 += iw)
  222798. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  222799. y += ih;
  222800. }
  222801. }
  222802. #endif
  222803. }
  222804. else
  222805. {
  222806. CGContextDrawImage (context, imageRect, image);
  222807. }
  222808. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  222809. CGContextRestoreGState (context);
  222810. }
  222811. void drawLine (double x1, double y1, double x2, double y2)
  222812. {
  222813. CGContextSetLineCap (context, kCGLineCapSquare);
  222814. CGContextSetLineWidth (context, 1.0f);
  222815. CGContextSetRGBStrokeColor (context,
  222816. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  222817. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  222818. CGPoint line[] = { { (CGFloat) x1, flipHeight - (CGFloat) y1 },
  222819. { (CGFloat) x2, flipHeight - (CGFloat) y2 } };
  222820. CGContextStrokeLineSegments (context, line, 1);
  222821. }
  222822. void drawVerticalLine (const int x, double top, double bottom)
  222823. {
  222824. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  222825. CGContextFillRect (context, CGRectMake (x, flipHeight - (float) bottom, 1.0f, (float) (bottom - top)));
  222826. #else
  222827. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  222828. // the x co-ord slightly to trick it..
  222829. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - (float) bottom, 1.0f + 1.0f / 256.0f, (float) (bottom - top)));
  222830. #endif
  222831. }
  222832. void drawHorizontalLine (const int y, double left, double right)
  222833. {
  222834. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  222835. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + 1.0f), (float) (right - left), 1.0f));
  222836. #else
  222837. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  222838. // the x co-ord slightly to trick it..
  222839. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), (float) (right - left), 1.0f + 1.0f / 256.0f));
  222840. #endif
  222841. }
  222842. void setFont (const Font& newFont)
  222843. {
  222844. if (state->font != newFont)
  222845. {
  222846. state->fontRef = 0;
  222847. state->font = newFont;
  222848. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  222849. if (mf != 0)
  222850. {
  222851. state->fontRef = mf->fontRef;
  222852. CGContextSetFont (context, state->fontRef);
  222853. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  222854. state->fontTransform = mf->renderingTransform;
  222855. state->fontTransform.a *= state->font.getHorizontalScale();
  222856. CGContextSetTextMatrix (context, state->fontTransform);
  222857. }
  222858. }
  222859. }
  222860. const Font getFont()
  222861. {
  222862. return state->font;
  222863. }
  222864. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  222865. {
  222866. if (state->fontRef != 0 && state->fillType.isColour())
  222867. {
  222868. if (transform.isOnlyTranslation())
  222869. {
  222870. CGGlyph g = glyphNumber;
  222871. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  222872. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  222873. }
  222874. else
  222875. {
  222876. CGContextSaveGState (context);
  222877. flip();
  222878. applyTransform (transform);
  222879. CGAffineTransform t = state->fontTransform;
  222880. t.d = -t.d;
  222881. CGContextSetTextMatrix (context, t);
  222882. CGGlyph g = glyphNumber;
  222883. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  222884. CGContextSetTextMatrix (context, state->fontTransform);
  222885. CGContextRestoreGState (context);
  222886. }
  222887. }
  222888. else
  222889. {
  222890. Path p;
  222891. Font& f = state->font;
  222892. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  222893. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  222894. .followedBy (transform));
  222895. }
  222896. }
  222897. private:
  222898. CGContextRef context;
  222899. const CGFloat flipHeight;
  222900. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  222901. CGFunctionCallbacks gradientCallbacks;
  222902. struct SavedState
  222903. {
  222904. SavedState()
  222905. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  222906. {
  222907. }
  222908. SavedState (const SavedState& other)
  222909. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  222910. fontTransform (other.fontTransform)
  222911. {
  222912. }
  222913. ~SavedState()
  222914. {
  222915. }
  222916. FillType fillType;
  222917. Font font;
  222918. CGFontRef fontRef;
  222919. CGAffineTransform fontTransform;
  222920. };
  222921. ScopedPointer <SavedState> state;
  222922. OwnedArray <SavedState> stateStack;
  222923. HeapBlock <PixelARGB> gradientLookupTable;
  222924. int numGradientLookupEntries;
  222925. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  222926. {
  222927. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  222928. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  222929. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  222930. colour.unpremultiply();
  222931. outData[0] = colour.getRed() / 255.0f;
  222932. outData[1] = colour.getGreen() / 255.0f;
  222933. outData[2] = colour.getBlue() / 255.0f;
  222934. outData[3] = colour.getAlpha() / 255.0f;
  222935. }
  222936. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  222937. {
  222938. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  222939. --numGradientLookupEntries;
  222940. CGShadingRef result = 0;
  222941. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  222942. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  222943. if (gradient.isRadial)
  222944. {
  222945. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  222946. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  222947. function, true, true);
  222948. }
  222949. else
  222950. {
  222951. result = CGShadingCreateAxial (rgbColourSpace, p1,
  222952. CGPointMake (gradient.x2, gradient.y2),
  222953. function, true, true);
  222954. }
  222955. CGFunctionRelease (function);
  222956. return result;
  222957. }
  222958. void drawGradient()
  222959. {
  222960. flip();
  222961. applyTransform (state->fillType.transform);
  222962. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  222963. // you draw a gradient with high quality interp enabled).
  222964. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  222965. CGContextSetAlpha (context, state->fillType.getOpacity());
  222966. CGContextDrawShading (context, shading);
  222967. CGShadingRelease (shading);
  222968. }
  222969. void createPath (const Path& path) const
  222970. {
  222971. CGContextBeginPath (context);
  222972. Path::Iterator i (path);
  222973. while (i.next())
  222974. {
  222975. switch (i.elementType)
  222976. {
  222977. case Path::Iterator::startNewSubPath:
  222978. CGContextMoveToPoint (context, i.x1, i.y1);
  222979. break;
  222980. case Path::Iterator::lineTo:
  222981. CGContextAddLineToPoint (context, i.x1, i.y1);
  222982. break;
  222983. case Path::Iterator::quadraticTo:
  222984. CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2);
  222985. break;
  222986. case Path::Iterator::cubicTo:
  222987. CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  222988. break;
  222989. case Path::Iterator::closePath:
  222990. CGContextClosePath (context); break;
  222991. default:
  222992. jassertfalse
  222993. break;
  222994. }
  222995. }
  222996. }
  222997. void createPath (const Path& path, const AffineTransform& transform) const
  222998. {
  222999. CGContextBeginPath (context);
  223000. Path::Iterator i (path);
  223001. while (i.next())
  223002. {
  223003. switch (i.elementType)
  223004. {
  223005. case Path::Iterator::startNewSubPath:
  223006. transform.transformPoint (i.x1, i.y1);
  223007. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  223008. break;
  223009. case Path::Iterator::lineTo:
  223010. transform.transformPoint (i.x1, i.y1);
  223011. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  223012. break;
  223013. case Path::Iterator::quadraticTo:
  223014. transform.transformPoint (i.x1, i.y1);
  223015. transform.transformPoint (i.x2, i.y2);
  223016. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  223017. break;
  223018. case Path::Iterator::cubicTo:
  223019. transform.transformPoint (i.x1, i.y1);
  223020. transform.transformPoint (i.x2, i.y2);
  223021. transform.transformPoint (i.x3, i.y3);
  223022. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  223023. break;
  223024. case Path::Iterator::closePath:
  223025. CGContextClosePath (context); break;
  223026. default:
  223027. jassertfalse
  223028. break;
  223029. }
  223030. }
  223031. }
  223032. void flip() const
  223033. {
  223034. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  223035. }
  223036. void applyTransform (const AffineTransform& transform) const
  223037. {
  223038. CGAffineTransform t;
  223039. t.a = transform.mat00;
  223040. t.b = transform.mat10;
  223041. t.c = transform.mat01;
  223042. t.d = transform.mat11;
  223043. t.tx = transform.mat02;
  223044. t.ty = transform.mat12;
  223045. CGContextConcatCTM (context, t);
  223046. }
  223047. CoreGraphicsContext (const CoreGraphicsContext&);
  223048. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  223049. };
  223050. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  223051. {
  223052. return new CoreGraphicsContext (context, imageHeight);
  223053. }
  223054. #endif
  223055. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  223056. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  223057. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223058. // compiled on its own).
  223059. #if JUCE_INCLUDED_FILE
  223060. class UIViewComponentPeer;
  223061. END_JUCE_NAMESPACE
  223062. #define JuceUIView MakeObjCClassName(JuceUIView)
  223063. @interface JuceUIView : UIView <UITextFieldDelegate>
  223064. {
  223065. @public
  223066. UIViewComponentPeer* owner;
  223067. UITextField *hiddenTextField;
  223068. }
  223069. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  223070. - (void) dealloc;
  223071. - (void) drawRect: (CGRect) r;
  223072. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  223073. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  223074. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  223075. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  223076. - (BOOL) becomeFirstResponder;
  223077. - (BOOL) resignFirstResponder;
  223078. - (BOOL) canBecomeFirstResponder;
  223079. - (void) asyncRepaint: (id) rect;
  223080. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  223081. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  223082. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  223083. @end
  223084. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  223085. @interface JuceUIWindow : UIWindow
  223086. {
  223087. @private
  223088. UIViewComponentPeer* owner;
  223089. bool isZooming;
  223090. }
  223091. - (void) setOwner: (UIViewComponentPeer*) owner;
  223092. - (void) becomeKeyWindow;
  223093. @end
  223094. BEGIN_JUCE_NAMESPACE
  223095. class UIViewComponentPeer : public ComponentPeer,
  223096. public FocusChangeListener
  223097. {
  223098. public:
  223099. UIViewComponentPeer (Component* const component,
  223100. const int windowStyleFlags,
  223101. UIView* viewToAttachTo);
  223102. ~UIViewComponentPeer();
  223103. void* getNativeHandle() const;
  223104. void setVisible (bool shouldBeVisible);
  223105. void setTitle (const String& title);
  223106. void setPosition (int x, int y);
  223107. void setSize (int w, int h);
  223108. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  223109. const Rectangle<int> getBounds() const;
  223110. const Rectangle<int> getBounds (const bool global) const;
  223111. const Point<int> getScreenPosition() const;
  223112. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  223113. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  223114. void setMinimised (bool shouldBeMinimised);
  223115. bool isMinimised() const;
  223116. void setFullScreen (bool shouldBeFullScreen);
  223117. bool isFullScreen() const;
  223118. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  223119. const BorderSize getFrameSize() const;
  223120. bool setAlwaysOnTop (bool alwaysOnTop);
  223121. void toFront (bool makeActiveWindow);
  223122. void toBehind (ComponentPeer* other);
  223123. void setIcon (const Image& newIcon);
  223124. virtual void drawRect (CGRect r);
  223125. virtual bool canBecomeKeyWindow();
  223126. virtual bool windowShouldClose();
  223127. virtual void redirectMovedOrResized();
  223128. virtual CGRect constrainRect (CGRect r);
  223129. virtual void viewFocusGain();
  223130. virtual void viewFocusLoss();
  223131. bool isFocused() const;
  223132. void grabFocus();
  223133. void textInputRequired (const Point<int>& position);
  223134. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  223135. virtual BOOL textFieldShouldClear();
  223136. virtual BOOL textFieldShouldReturn();
  223137. void updateHiddenTextContent (TextInputTarget* target);
  223138. void globalFocusChanged (Component*);
  223139. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  223140. void repaint (int x, int y, int w, int h);
  223141. void performAnyPendingRepaintsNow();
  223142. juce_UseDebuggingNewOperator
  223143. UIWindow* window;
  223144. JuceUIView* view;
  223145. bool isSharedWindow, fullScreen, insideDrawRect;
  223146. static ModifierKeys currentModifiers;
  223147. static int64 getMouseTime (UIEvent* e)
  223148. {
  223149. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  223150. + (int64) ([e timestamp] * 1000.0);
  223151. }
  223152. Array <UITouch*> currentTouches;
  223153. };
  223154. END_JUCE_NAMESPACE
  223155. @implementation JuceUIView
  223156. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  223157. withFrame: (CGRect) frame
  223158. {
  223159. [super initWithFrame: frame];
  223160. owner = owner_;
  223161. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  223162. [self addSubview: hiddenTextField];
  223163. hiddenTextField.delegate = self;
  223164. return self;
  223165. }
  223166. - (void) dealloc
  223167. {
  223168. [hiddenTextField removeFromSuperview];
  223169. [hiddenTextField release];
  223170. [super dealloc];
  223171. }
  223172. - (void) drawRect: (CGRect) r
  223173. {
  223174. if (owner != 0)
  223175. owner->drawRect (r);
  223176. }
  223177. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  223178. {
  223179. return false;
  223180. }
  223181. ModifierKeys UIViewComponentPeer::currentModifiers;
  223182. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  223183. {
  223184. return UIViewComponentPeer::currentModifiers;
  223185. }
  223186. void ModifierKeys::updateCurrentModifiers() throw()
  223187. {
  223188. currentModifiers = UIViewComponentPeer::currentModifiers;
  223189. }
  223190. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  223191. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  223192. {
  223193. if (owner != 0)
  223194. owner->handleTouches (event, true, false, false);
  223195. }
  223196. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  223197. {
  223198. if (owner != 0)
  223199. owner->handleTouches (event, false, false, false);
  223200. }
  223201. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  223202. {
  223203. if (owner != 0)
  223204. owner->handleTouches (event, false, true, false);
  223205. }
  223206. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  223207. {
  223208. if (owner != 0)
  223209. owner->handleTouches (event, false, true, true);
  223210. [self touchesEnded: touches withEvent: event];
  223211. }
  223212. - (BOOL) becomeFirstResponder
  223213. {
  223214. if (owner != 0)
  223215. owner->viewFocusGain();
  223216. return true;
  223217. }
  223218. - (BOOL) resignFirstResponder
  223219. {
  223220. if (owner != 0)
  223221. owner->viewFocusLoss();
  223222. return true;
  223223. }
  223224. - (BOOL) canBecomeFirstResponder
  223225. {
  223226. return owner != 0 && owner->canBecomeKeyWindow();
  223227. }
  223228. - (void) asyncRepaint: (id) rect
  223229. {
  223230. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  223231. [self setNeedsDisplayInRect: *r];
  223232. }
  223233. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  223234. {
  223235. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  223236. nsStringToJuce (text));
  223237. }
  223238. - (BOOL) textFieldShouldClear: (UITextField*) textField
  223239. {
  223240. return owner->textFieldShouldClear();
  223241. }
  223242. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  223243. {
  223244. return owner->textFieldShouldReturn();
  223245. }
  223246. @end
  223247. @implementation JuceUIWindow
  223248. - (void) setOwner: (UIViewComponentPeer*) owner_
  223249. {
  223250. owner = owner_;
  223251. isZooming = false;
  223252. }
  223253. - (void) becomeKeyWindow
  223254. {
  223255. [super becomeKeyWindow];
  223256. if (owner != 0)
  223257. owner->grabFocus();
  223258. }
  223259. @end
  223260. BEGIN_JUCE_NAMESPACE
  223261. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  223262. const int windowStyleFlags,
  223263. UIView* viewToAttachTo)
  223264. : ComponentPeer (component, windowStyleFlags),
  223265. window (0),
  223266. view (0),
  223267. isSharedWindow (viewToAttachTo != 0),
  223268. fullScreen (false),
  223269. insideDrawRect (false)
  223270. {
  223271. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  223272. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  223273. if (isSharedWindow)
  223274. {
  223275. window = [viewToAttachTo window];
  223276. [viewToAttachTo addSubview: view];
  223277. setVisible (component->isVisible());
  223278. }
  223279. else
  223280. {
  223281. r.origin.x = (float) component->getX();
  223282. r.origin.y = (float) component->getY();
  223283. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  223284. window = [[JuceUIWindow alloc] init];
  223285. window.frame = r;
  223286. window.opaque = component->isOpaque();
  223287. view.opaque = component->isOpaque();
  223288. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223289. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223290. [((JuceUIWindow*) window) setOwner: this];
  223291. if (component->isAlwaysOnTop())
  223292. window.windowLevel = UIWindowLevelAlert;
  223293. [window addSubview: view];
  223294. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223295. view.hidden = ! component->isVisible();
  223296. window.hidden = ! component->isVisible();
  223297. view.multipleTouchEnabled = YES;
  223298. }
  223299. setTitle (component->getName());
  223300. Desktop::getInstance().addFocusChangeListener (this);
  223301. }
  223302. UIViewComponentPeer::~UIViewComponentPeer()
  223303. {
  223304. Desktop::getInstance().removeFocusChangeListener (this);
  223305. view->owner = 0;
  223306. [view removeFromSuperview];
  223307. [view release];
  223308. if (! isSharedWindow)
  223309. {
  223310. [((JuceUIWindow*) window) setOwner: 0];
  223311. [window release];
  223312. }
  223313. }
  223314. void* UIViewComponentPeer::getNativeHandle() const
  223315. {
  223316. return view;
  223317. }
  223318. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  223319. {
  223320. view.hidden = ! shouldBeVisible;
  223321. if (! isSharedWindow)
  223322. window.hidden = ! shouldBeVisible;
  223323. }
  223324. void UIViewComponentPeer::setTitle (const String& title)
  223325. {
  223326. // xxx is this possible?
  223327. }
  223328. void UIViewComponentPeer::setPosition (int x, int y)
  223329. {
  223330. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  223331. }
  223332. void UIViewComponentPeer::setSize (int w, int h)
  223333. {
  223334. setBounds (component->getX(), component->getY(), w, h, false);
  223335. }
  223336. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  223337. {
  223338. fullScreen = isNowFullScreen;
  223339. w = jmax (0, w);
  223340. h = jmax (0, h);
  223341. CGRect r;
  223342. r.origin.x = (float) x;
  223343. r.origin.y = (float) y;
  223344. r.size.width = (float) w;
  223345. r.size.height = (float) h;
  223346. if (isSharedWindow)
  223347. {
  223348. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  223349. if ([view frame].size.width != r.size.width
  223350. || [view frame].size.height != r.size.height)
  223351. [view setNeedsDisplay];
  223352. view.frame = r;
  223353. }
  223354. else
  223355. {
  223356. window.frame = r;
  223357. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223358. }
  223359. }
  223360. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  223361. {
  223362. CGRect r = [view frame];
  223363. if (global && [view window] != 0)
  223364. {
  223365. r = [view convertRect: r toView: nil];
  223366. CGRect wr = [[view window] frame];
  223367. r.origin.x += wr.origin.x;
  223368. r.origin.y += wr.origin.y;
  223369. }
  223370. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  223371. (int) r.size.width, (int) r.size.height);
  223372. }
  223373. const Rectangle<int> UIViewComponentPeer::getBounds() const
  223374. {
  223375. return getBounds (! isSharedWindow);
  223376. }
  223377. const Point<int> UIViewComponentPeer::getScreenPosition() const
  223378. {
  223379. return getBounds (true).getPosition();
  223380. }
  223381. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  223382. {
  223383. return relativePosition + getScreenPosition();
  223384. }
  223385. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  223386. {
  223387. return screenPosition - getScreenPosition();
  223388. }
  223389. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  223390. {
  223391. if (constrainer != 0)
  223392. {
  223393. CGRect current = [window frame];
  223394. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  223395. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  223396. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  223397. (int) r.size.width, (int) r.size.height);
  223398. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  223399. (int) current.size.width, (int) current.size.height);
  223400. constrainer->checkBounds (pos, original,
  223401. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  223402. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  223403. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  223404. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  223405. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  223406. r.origin.x = pos.getX();
  223407. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  223408. r.size.width = pos.getWidth();
  223409. r.size.height = pos.getHeight();
  223410. }
  223411. return r;
  223412. }
  223413. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  223414. {
  223415. // xxx
  223416. }
  223417. bool UIViewComponentPeer::isMinimised() const
  223418. {
  223419. return false;
  223420. }
  223421. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  223422. {
  223423. if (! isSharedWindow)
  223424. {
  223425. Rectangle<int> r (lastNonFullscreenBounds);
  223426. setMinimised (false);
  223427. if (fullScreen != shouldBeFullScreen)
  223428. {
  223429. if (shouldBeFullScreen)
  223430. r = Desktop::getInstance().getMainMonitorArea();
  223431. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  223432. if (r != getComponent()->getBounds() && ! r.isEmpty())
  223433. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  223434. }
  223435. }
  223436. }
  223437. bool UIViewComponentPeer::isFullScreen() const
  223438. {
  223439. return fullScreen;
  223440. }
  223441. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  223442. {
  223443. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  223444. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  223445. return false;
  223446. CGPoint p;
  223447. p.x = (float) position.getX();
  223448. p.y = (float) position.getY();
  223449. UIView* v = [view hitTest: p withEvent: nil];
  223450. if (trueIfInAChildWindow)
  223451. return v != nil;
  223452. return v == view;
  223453. }
  223454. const BorderSize UIViewComponentPeer::getFrameSize() const
  223455. {
  223456. BorderSize b;
  223457. if (! isSharedWindow)
  223458. {
  223459. CGRect v = [view convertRect: [view frame] toView: nil];
  223460. CGRect w = [window frame];
  223461. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  223462. b.setBottom ((int) v.origin.y);
  223463. b.setLeft ((int) v.origin.x);
  223464. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  223465. }
  223466. return b;
  223467. }
  223468. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  223469. {
  223470. if (! isSharedWindow)
  223471. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  223472. return true;
  223473. }
  223474. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  223475. {
  223476. if (isSharedWindow)
  223477. [[view superview] bringSubviewToFront: view];
  223478. if (window != 0 && component->isVisible())
  223479. [window makeKeyAndVisible];
  223480. }
  223481. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  223482. {
  223483. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  223484. jassert (otherPeer != 0); // wrong type of window?
  223485. if (otherPeer != 0)
  223486. {
  223487. if (isSharedWindow)
  223488. {
  223489. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  223490. }
  223491. else
  223492. {
  223493. jassertfalse // don't know how to do this
  223494. }
  223495. }
  223496. }
  223497. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  223498. {
  223499. // to do..
  223500. }
  223501. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  223502. {
  223503. NSArray* touches = [[event touchesForView: view] allObjects];
  223504. for (unsigned int i = 0; i < [touches count]; ++i)
  223505. {
  223506. UITouch* touch = [touches objectAtIndex: i];
  223507. CGPoint p = [touch locationInView: view];
  223508. const Point<int> pos ((int) p.x, (int) p.y);
  223509. juce_lastMousePos = pos + getScreenPosition();
  223510. const int64 time = getMouseTime (event);
  223511. int touchIndex = currentTouches.indexOf (touch);
  223512. if (touchIndex < 0)
  223513. {
  223514. touchIndex = currentTouches.size();
  223515. currentTouches.add (touch);
  223516. }
  223517. if (isDown)
  223518. {
  223519. currentModifiers = currentModifiers.withoutMouseButtons();
  223520. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  223521. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  223522. }
  223523. else if (isUp)
  223524. {
  223525. currentModifiers = currentModifiers.withoutMouseButtons();
  223526. currentTouches.remove (touchIndex);
  223527. }
  223528. if (isCancel)
  223529. currentTouches.clear();
  223530. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  223531. }
  223532. }
  223533. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  223534. void UIViewComponentPeer::viewFocusGain()
  223535. {
  223536. if (currentlyFocusedPeer != this)
  223537. {
  223538. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  223539. currentlyFocusedPeer->handleFocusLoss();
  223540. currentlyFocusedPeer = this;
  223541. handleFocusGain();
  223542. }
  223543. }
  223544. void UIViewComponentPeer::viewFocusLoss()
  223545. {
  223546. if (currentlyFocusedPeer == this)
  223547. {
  223548. currentlyFocusedPeer = 0;
  223549. handleFocusLoss();
  223550. }
  223551. }
  223552. void juce_HandleProcessFocusChange()
  223553. {
  223554. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  223555. {
  223556. if (Process::isForegroundProcess())
  223557. {
  223558. currentlyFocusedPeer->handleFocusGain();
  223559. ComponentPeer::bringModalComponentToFront();
  223560. }
  223561. else
  223562. {
  223563. currentlyFocusedPeer->handleFocusLoss();
  223564. // turn kiosk mode off if we lose focus..
  223565. Desktop::getInstance().setKioskModeComponent (0);
  223566. }
  223567. }
  223568. }
  223569. bool UIViewComponentPeer::isFocused() const
  223570. {
  223571. return isSharedWindow ? this == currentlyFocusedPeer
  223572. : (window != 0 && [window isKeyWindow]);
  223573. }
  223574. void UIViewComponentPeer::grabFocus()
  223575. {
  223576. if (window != 0)
  223577. {
  223578. [window makeKeyWindow];
  223579. viewFocusGain();
  223580. }
  223581. }
  223582. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  223583. {
  223584. }
  223585. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  223586. {
  223587. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  223588. }
  223589. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  223590. {
  223591. TextInputTarget* const target = findCurrentTextInputTarget();
  223592. if (target != 0)
  223593. {
  223594. const Range<int> currentSelection (target->getHighlightedRegion());
  223595. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  223596. if (currentSelection.isEmpty())
  223597. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  223598. target->insertTextAtCaret (text);
  223599. updateHiddenTextContent (target);
  223600. }
  223601. return NO;
  223602. }
  223603. BOOL UIViewComponentPeer::textFieldShouldClear()
  223604. {
  223605. TextInputTarget* const target = findCurrentTextInputTarget();
  223606. if (target != 0)
  223607. {
  223608. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  223609. target->insertTextAtCaret (String::empty);
  223610. updateHiddenTextContent (target);
  223611. }
  223612. return YES;
  223613. }
  223614. BOOL UIViewComponentPeer::textFieldShouldReturn()
  223615. {
  223616. TextInputTarget* const target = findCurrentTextInputTarget();
  223617. if (target != 0)
  223618. {
  223619. target->insertTextAtCaret ("\n");
  223620. updateHiddenTextContent (target);
  223621. }
  223622. return YES;
  223623. }
  223624. void UIViewComponentPeer::globalFocusChanged (Component*)
  223625. {
  223626. TextInputTarget* const target = findCurrentTextInputTarget();
  223627. if (target != 0)
  223628. {
  223629. Component* comp = dynamic_cast<Component*> (target);
  223630. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  223631. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  223632. updateHiddenTextContent (target);
  223633. [view->hiddenTextField becomeFirstResponder];
  223634. }
  223635. else
  223636. {
  223637. [view->hiddenTextField resignFirstResponder];
  223638. }
  223639. }
  223640. void UIViewComponentPeer::drawRect (CGRect r)
  223641. {
  223642. if (r.size.width < 1.0f || r.size.height < 1.0f)
  223643. return;
  223644. CGContextRef cg = UIGraphicsGetCurrentContext();
  223645. if (! component->isOpaque())
  223646. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  223647. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  223648. CoreGraphicsContext g (cg, view.bounds.size.height);
  223649. insideDrawRect = true;
  223650. handlePaint (g);
  223651. insideDrawRect = false;
  223652. }
  223653. bool UIViewComponentPeer::canBecomeKeyWindow()
  223654. {
  223655. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  223656. }
  223657. bool UIViewComponentPeer::windowShouldClose()
  223658. {
  223659. if (! isValidPeer (this))
  223660. return YES;
  223661. handleUserClosingWindow();
  223662. return NO;
  223663. }
  223664. void UIViewComponentPeer::redirectMovedOrResized()
  223665. {
  223666. handleMovedOrResized();
  223667. }
  223668. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  223669. {
  223670. }
  223671. class AsyncRepaintMessage : public CallbackMessage
  223672. {
  223673. public:
  223674. UIViewComponentPeer* const peer;
  223675. const Rectangle<int> rect;
  223676. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  223677. : peer (peer_), rect (rect_)
  223678. {
  223679. }
  223680. void messageCallback()
  223681. {
  223682. if (ComponentPeer::isValidPeer (peer))
  223683. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  223684. }
  223685. };
  223686. void UIViewComponentPeer::repaint (int x, int y, int w, int h)
  223687. {
  223688. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  223689. {
  223690. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  223691. }
  223692. else
  223693. {
  223694. [view setNeedsDisplayInRect: CGRectMake ((float) x, (float) y, (float) w, (float) h)];
  223695. }
  223696. }
  223697. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  223698. {
  223699. }
  223700. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  223701. {
  223702. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  223703. }
  223704. Image* juce_createIconForFile (const File& file)
  223705. {
  223706. return 0;
  223707. }
  223708. void Desktop::createMouseInputSources()
  223709. {
  223710. for (int i = 0; i < 10; ++i)
  223711. mouseSources.add (new MouseInputSource (i, false));
  223712. }
  223713. bool Desktop::canUseSemiTransparentWindows() throw()
  223714. {
  223715. return true;
  223716. }
  223717. const Point<int> Desktop::getMousePosition()
  223718. {
  223719. return juce_lastMousePos;
  223720. }
  223721. void Desktop::setMousePosition (const Point<int>&)
  223722. {
  223723. }
  223724. const int KeyPress::spaceKey = ' ';
  223725. const int KeyPress::returnKey = 0x0d;
  223726. const int KeyPress::escapeKey = 0x1b;
  223727. const int KeyPress::backspaceKey = 0x7f;
  223728. const int KeyPress::leftKey = 0x1000;
  223729. const int KeyPress::rightKey = 0x1001;
  223730. const int KeyPress::upKey = 0x1002;
  223731. const int KeyPress::downKey = 0x1003;
  223732. const int KeyPress::pageUpKey = 0x1004;
  223733. const int KeyPress::pageDownKey = 0x1005;
  223734. const int KeyPress::endKey = 0x1006;
  223735. const int KeyPress::homeKey = 0x1007;
  223736. const int KeyPress::deleteKey = 0x1008;
  223737. const int KeyPress::insertKey = -1;
  223738. const int KeyPress::tabKey = 9;
  223739. const int KeyPress::F1Key = 0x2001;
  223740. const int KeyPress::F2Key = 0x2002;
  223741. const int KeyPress::F3Key = 0x2003;
  223742. const int KeyPress::F4Key = 0x2004;
  223743. const int KeyPress::F5Key = 0x2005;
  223744. const int KeyPress::F6Key = 0x2006;
  223745. const int KeyPress::F7Key = 0x2007;
  223746. const int KeyPress::F8Key = 0x2008;
  223747. const int KeyPress::F9Key = 0x2009;
  223748. const int KeyPress::F10Key = 0x200a;
  223749. const int KeyPress::F11Key = 0x200b;
  223750. const int KeyPress::F12Key = 0x200c;
  223751. const int KeyPress::F13Key = 0x200d;
  223752. const int KeyPress::F14Key = 0x200e;
  223753. const int KeyPress::F15Key = 0x200f;
  223754. const int KeyPress::F16Key = 0x2010;
  223755. const int KeyPress::numberPad0 = 0x30020;
  223756. const int KeyPress::numberPad1 = 0x30021;
  223757. const int KeyPress::numberPad2 = 0x30022;
  223758. const int KeyPress::numberPad3 = 0x30023;
  223759. const int KeyPress::numberPad4 = 0x30024;
  223760. const int KeyPress::numberPad5 = 0x30025;
  223761. const int KeyPress::numberPad6 = 0x30026;
  223762. const int KeyPress::numberPad7 = 0x30027;
  223763. const int KeyPress::numberPad8 = 0x30028;
  223764. const int KeyPress::numberPad9 = 0x30029;
  223765. const int KeyPress::numberPadAdd = 0x3002a;
  223766. const int KeyPress::numberPadSubtract = 0x3002b;
  223767. const int KeyPress::numberPadMultiply = 0x3002c;
  223768. const int KeyPress::numberPadDivide = 0x3002d;
  223769. const int KeyPress::numberPadSeparator = 0x3002e;
  223770. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  223771. const int KeyPress::numberPadEquals = 0x30030;
  223772. const int KeyPress::numberPadDelete = 0x30031;
  223773. const int KeyPress::playKey = 0x30000;
  223774. const int KeyPress::stopKey = 0x30001;
  223775. const int KeyPress::fastForwardKey = 0x30002;
  223776. const int KeyPress::rewindKey = 0x30003;
  223777. #endif
  223778. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  223779. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  223780. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223781. // compiled on its own).
  223782. #if JUCE_INCLUDED_FILE
  223783. struct CallbackMessagePayload
  223784. {
  223785. MessageCallbackFunction* function;
  223786. void* parameter;
  223787. void* volatile result;
  223788. bool volatile hasBeenExecuted;
  223789. };
  223790. END_JUCE_NAMESPACE
  223791. using namespace JUCE_NAMESPACE;
  223792. @interface JuceAppDelegate : NSObject <UIApplicationDelegate>
  223793. {
  223794. }
  223795. - (JuceAppDelegate*) init;
  223796. - (void) dealloc;
  223797. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url;
  223798. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  223799. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  223800. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  223801. - (void) customEvent: (id) data;
  223802. - (void) performCallback: (id) info;
  223803. @end
  223804. @implementation JuceAppDelegate
  223805. - (JuceAppDelegate*) init
  223806. {
  223807. [super init];
  223808. [[UIApplication sharedApplication] setDelegate: self];
  223809. return self;
  223810. }
  223811. - (void) dealloc
  223812. {
  223813. [[UIApplication sharedApplication] setDelegate: nil];
  223814. [super dealloc];
  223815. }
  223816. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url
  223817. {
  223818. if (JUCEApplication::getInstance() != 0)
  223819. {
  223820. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce ([url absoluteString]));
  223821. return YES;
  223822. }
  223823. return NO;
  223824. }
  223825. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  223826. {
  223827. juce_HandleProcessFocusChange();
  223828. }
  223829. - (void) applicationDidResignActive: (NSNotification*) aNotification
  223830. {
  223831. juce_HandleProcessFocusChange();
  223832. }
  223833. - (void) applicationWillUnhide: (NSNotification*) aNotification
  223834. {
  223835. juce_HandleProcessFocusChange();
  223836. }
  223837. - (void) customEvent: (id) n
  223838. {
  223839. NSData* data = (NSData*) n;
  223840. void* message = 0;
  223841. [data getBytes: &message length: sizeof (message)];
  223842. [data release];
  223843. if (message != 0)
  223844. MessageManager::getInstance()->deliverMessage (message);
  223845. }
  223846. - (void) performCallback: (id) info
  223847. {
  223848. if ([info isKindOfClass: [NSData class]])
  223849. {
  223850. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  223851. if (pl != 0)
  223852. {
  223853. pl->result = (*pl->function) (pl->parameter);
  223854. pl->hasBeenExecuted = true;
  223855. }
  223856. }
  223857. else
  223858. {
  223859. jassertfalse // should never get here!
  223860. }
  223861. }
  223862. @end
  223863. BEGIN_JUCE_NAMESPACE
  223864. static JuceAppDelegate* juceAppDelegate = 0;
  223865. void MessageManager::runDispatchLoop()
  223866. {
  223867. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223868. runDispatchLoopUntil (-1);
  223869. }
  223870. void MessageManager::stopDispatchLoop()
  223871. {
  223872. exit (0); // iPhone apps get no mercy..
  223873. }
  223874. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  223875. {
  223876. const ScopedAutoReleasePool pool;
  223877. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223878. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  223879. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  223880. while (! quitMessagePosted)
  223881. {
  223882. const ScopedAutoReleasePool pool;
  223883. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223884. beforeDate: endDate];
  223885. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  223886. break;
  223887. }
  223888. return ! quitMessagePosted;
  223889. }
  223890. static CFRunLoopRef runLoop = 0;
  223891. static CFRunLoopSourceRef runLoopSource = 0;
  223892. static Array <void*, CriticalSection>* pendingMessages = 0;
  223893. static void runLoopSourceCallback (void*)
  223894. {
  223895. if (pendingMessages != 0)
  223896. {
  223897. int numDispatched = 0;
  223898. do
  223899. {
  223900. void* const nextMessage = pendingMessages->remove (0);
  223901. if (nextMessage == 0)
  223902. return;
  223903. const ScopedAutoReleasePool pool;
  223904. MessageManager::getInstance()->deliverMessage (nextMessage);
  223905. } while (++numDispatched <= 4);
  223906. CFRunLoopSourceSignal (runLoopSource);
  223907. CFRunLoopWakeUp (runLoop);
  223908. }
  223909. }
  223910. void MessageManager::doPlatformSpecificInitialisation()
  223911. {
  223912. pendingMessages = new Array <void*, CriticalSection>();
  223913. runLoop = CFRunLoopGetCurrent();
  223914. CFRunLoopSourceContext sourceContext;
  223915. zerostruct (sourceContext);
  223916. sourceContext.perform = runLoopSourceCallback;
  223917. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223918. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223919. if (juceAppDelegate == 0)
  223920. juceAppDelegate = [[JuceAppDelegate alloc] init];
  223921. }
  223922. void MessageManager::doPlatformSpecificShutdown()
  223923. {
  223924. CFRunLoopSourceInvalidate (runLoopSource);
  223925. CFRelease (runLoopSource);
  223926. runLoopSource = 0;
  223927. if (pendingMessages != 0)
  223928. {
  223929. while (pendingMessages->size() > 0)
  223930. delete ((Message*) pendingMessages->remove(0));
  223931. deleteAndZero (pendingMessages);
  223932. }
  223933. if (juceAppDelegate != 0)
  223934. {
  223935. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  223936. [juceAppDelegate release];
  223937. juceAppDelegate = 0;
  223938. }
  223939. }
  223940. bool juce_postMessageToSystemQueue (void* message)
  223941. {
  223942. if (pendingMessages != 0)
  223943. {
  223944. pendingMessages->add (message);
  223945. CFRunLoopSourceSignal (runLoopSource);
  223946. CFRunLoopWakeUp (runLoop);
  223947. }
  223948. return true;
  223949. }
  223950. void MessageManager::broadcastMessage (const String& value) throw()
  223951. {
  223952. }
  223953. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  223954. void* data)
  223955. {
  223956. if (isThisTheMessageThread())
  223957. {
  223958. return (*callback) (data);
  223959. }
  223960. else
  223961. {
  223962. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  223963. // deadlock because the message manager is blocked from running, so can never
  223964. // call your function..
  223965. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  223966. const ScopedAutoReleasePool pool;
  223967. CallbackMessagePayload cmp;
  223968. cmp.function = callback;
  223969. cmp.parameter = data;
  223970. cmp.result = 0;
  223971. cmp.hasBeenExecuted = false;
  223972. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  223973. withObject: [NSData dataWithBytesNoCopy: &cmp
  223974. length: sizeof (cmp)
  223975. freeWhenDone: NO]
  223976. waitUntilDone: YES];
  223977. return cmp.result;
  223978. }
  223979. }
  223980. #endif
  223981. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  223982. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  223983. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223984. // compiled on its own).
  223985. #if JUCE_INCLUDED_FILE
  223986. #if JUCE_MAC
  223987. END_JUCE_NAMESPACE
  223988. using namespace JUCE_NAMESPACE;
  223989. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  223990. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223991. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  223992. #else
  223993. @interface JuceFileChooserDelegate : NSObject
  223994. #endif
  223995. {
  223996. StringArray* filters;
  223997. }
  223998. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  223999. - (void) dealloc;
  224000. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  224001. @end
  224002. @implementation JuceFileChooserDelegate
  224003. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  224004. {
  224005. [super init];
  224006. filters = filters_;
  224007. return self;
  224008. }
  224009. - (void) dealloc
  224010. {
  224011. delete filters;
  224012. [super dealloc];
  224013. }
  224014. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  224015. {
  224016. (void) sender;
  224017. const File f (nsStringToJuce (filename));
  224018. for (int i = filters->size(); --i >= 0;)
  224019. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  224020. return true;
  224021. return f.isDirectory();
  224022. }
  224023. @end
  224024. BEGIN_JUCE_NAMESPACE
  224025. void FileChooser::showPlatformDialog (Array<File>& results,
  224026. const String& title,
  224027. const File& currentFileOrDirectory,
  224028. const String& filter,
  224029. bool selectsDirectory,
  224030. bool selectsFiles,
  224031. bool isSaveDialogue,
  224032. bool warnAboutOverwritingExistingFiles,
  224033. bool selectMultipleFiles,
  224034. FilePreviewComponent* extraInfoComponent)
  224035. {
  224036. const ScopedAutoReleasePool pool;
  224037. StringArray* filters = new StringArray();
  224038. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  224039. filters->trim();
  224040. filters->removeEmptyStrings();
  224041. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  224042. [delegate autorelease];
  224043. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  224044. : [NSOpenPanel openPanel];
  224045. [panel setTitle: juceStringToNS (title)];
  224046. if (! isSaveDialogue)
  224047. {
  224048. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224049. [openPanel setCanChooseDirectories: selectsDirectory];
  224050. [openPanel setCanChooseFiles: selectsFiles];
  224051. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  224052. }
  224053. [panel setDelegate: delegate];
  224054. if (isSaveDialogue || selectsDirectory)
  224055. [panel setCanCreateDirectories: YES];
  224056. String directory, filename;
  224057. if (currentFileOrDirectory.isDirectory())
  224058. {
  224059. directory = currentFileOrDirectory.getFullPathName();
  224060. }
  224061. else
  224062. {
  224063. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  224064. filename = currentFileOrDirectory.getFileName();
  224065. }
  224066. if ([panel runModalForDirectory: juceStringToNS (directory)
  224067. file: juceStringToNS (filename)]
  224068. == NSOKButton)
  224069. {
  224070. if (isSaveDialogue)
  224071. {
  224072. results.add (File (nsStringToJuce ([panel filename])));
  224073. }
  224074. else
  224075. {
  224076. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224077. NSArray* urls = [openPanel filenames];
  224078. for (unsigned int i = 0; i < [urls count]; ++i)
  224079. {
  224080. NSString* f = [urls objectAtIndex: i];
  224081. results.add (File (nsStringToJuce (f)));
  224082. }
  224083. }
  224084. }
  224085. [panel setDelegate: nil];
  224086. }
  224087. #else
  224088. void FileChooser::showPlatformDialog (Array<File>& results,
  224089. const String& title,
  224090. const File& currentFileOrDirectory,
  224091. const String& filter,
  224092. bool selectsDirectory,
  224093. bool selectsFiles,
  224094. bool isSaveDialogue,
  224095. bool warnAboutOverwritingExistingFiles,
  224096. bool selectMultipleFiles,
  224097. FilePreviewComponent* extraInfoComponent)
  224098. {
  224099. const ScopedAutoReleasePool pool;
  224100. jassertfalse //xxx to do
  224101. }
  224102. #endif
  224103. #endif
  224104. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  224105. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  224106. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224107. // compiled on its own).
  224108. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  224109. #if JUCE_MAC
  224110. END_JUCE_NAMESPACE
  224111. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  224112. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  224113. {
  224114. CriticalSection* contextLock;
  224115. bool needsUpdate;
  224116. }
  224117. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  224118. - (bool) makeActive;
  224119. - (void) makeInactive;
  224120. - (void) reshape;
  224121. @end
  224122. @implementation ThreadSafeNSOpenGLView
  224123. - (id) initWithFrame: (NSRect) frameRect
  224124. pixelFormat: (NSOpenGLPixelFormat*) format
  224125. {
  224126. contextLock = new CriticalSection();
  224127. self = [super initWithFrame: frameRect pixelFormat: format];
  224128. if (self != nil)
  224129. [[NSNotificationCenter defaultCenter] addObserver: self
  224130. selector: @selector (_surfaceNeedsUpdate:)
  224131. name: NSViewGlobalFrameDidChangeNotification
  224132. object: self];
  224133. return self;
  224134. }
  224135. - (void) dealloc
  224136. {
  224137. [[NSNotificationCenter defaultCenter] removeObserver: self];
  224138. delete contextLock;
  224139. [super dealloc];
  224140. }
  224141. - (bool) makeActive
  224142. {
  224143. const ScopedLock sl (*contextLock);
  224144. if ([self openGLContext] == 0)
  224145. return false;
  224146. [[self openGLContext] makeCurrentContext];
  224147. if (needsUpdate)
  224148. {
  224149. [super update];
  224150. needsUpdate = false;
  224151. }
  224152. return true;
  224153. }
  224154. - (void) makeInactive
  224155. {
  224156. const ScopedLock sl (*contextLock);
  224157. [NSOpenGLContext clearCurrentContext];
  224158. }
  224159. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  224160. {
  224161. const ScopedLock sl (*contextLock);
  224162. needsUpdate = true;
  224163. }
  224164. - (void) update
  224165. {
  224166. const ScopedLock sl (*contextLock);
  224167. needsUpdate = true;
  224168. }
  224169. - (void) reshape
  224170. {
  224171. const ScopedLock sl (*contextLock);
  224172. needsUpdate = true;
  224173. }
  224174. @end
  224175. BEGIN_JUCE_NAMESPACE
  224176. class WindowedGLContext : public OpenGLContext
  224177. {
  224178. public:
  224179. WindowedGLContext (Component* const component,
  224180. const OpenGLPixelFormat& pixelFormat_,
  224181. NSOpenGLContext* sharedContext)
  224182. : renderContext (0),
  224183. pixelFormat (pixelFormat_)
  224184. {
  224185. jassert (component != 0);
  224186. NSOpenGLPixelFormatAttribute attribs [64];
  224187. int n = 0;
  224188. attribs[n++] = NSOpenGLPFADoubleBuffer;
  224189. attribs[n++] = NSOpenGLPFAAccelerated;
  224190. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  224191. attribs[n++] = NSOpenGLPFAColorSize;
  224192. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  224193. pixelFormat.greenBits,
  224194. pixelFormat.blueBits);
  224195. attribs[n++] = NSOpenGLPFAAlphaSize;
  224196. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  224197. attribs[n++] = NSOpenGLPFADepthSize;
  224198. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  224199. attribs[n++] = NSOpenGLPFAStencilSize;
  224200. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  224201. attribs[n++] = NSOpenGLPFAAccumSize;
  224202. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  224203. pixelFormat.accumulationBufferGreenBits,
  224204. pixelFormat.accumulationBufferBlueBits,
  224205. pixelFormat.accumulationBufferAlphaBits);
  224206. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  224207. attribs[n++] = NSOpenGLPFASampleBuffers;
  224208. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  224209. attribs[n++] = NSOpenGLPFAClosestPolicy;
  224210. attribs[n++] = NSOpenGLPFANoRecovery;
  224211. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  224212. NSOpenGLPixelFormat* format
  224213. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  224214. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224215. pixelFormat: format];
  224216. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  224217. shareContext: sharedContext] autorelease];
  224218. const GLint swapInterval = 1;
  224219. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  224220. [view setOpenGLContext: renderContext];
  224221. [renderContext setView: view];
  224222. [format release];
  224223. viewHolder = new NSViewComponentInternal (view, component);
  224224. }
  224225. ~WindowedGLContext()
  224226. {
  224227. makeInactive();
  224228. [renderContext clearDrawable];
  224229. viewHolder = 0;
  224230. }
  224231. bool makeActive() const throw()
  224232. {
  224233. jassert (renderContext != 0);
  224234. [view makeActive];
  224235. return isActive();
  224236. }
  224237. bool makeInactive() const throw()
  224238. {
  224239. [view makeInactive];
  224240. return true;
  224241. }
  224242. bool isActive() const throw()
  224243. {
  224244. return [NSOpenGLContext currentContext] == renderContext;
  224245. }
  224246. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224247. void* getRawContext() const throw() { return renderContext; }
  224248. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224249. {
  224250. }
  224251. void swapBuffers()
  224252. {
  224253. [renderContext flushBuffer];
  224254. }
  224255. bool setSwapInterval (const int numFramesPerSwap)
  224256. {
  224257. [renderContext setValues: (const GLint*) &numFramesPerSwap
  224258. forParameter: NSOpenGLCPSwapInterval];
  224259. return true;
  224260. }
  224261. int getSwapInterval() const
  224262. {
  224263. GLint numFrames = 0;
  224264. [renderContext getValues: &numFrames
  224265. forParameter: NSOpenGLCPSwapInterval];
  224266. return numFrames;
  224267. }
  224268. void repaint()
  224269. {
  224270. // we need to invalidate the juce view that holds this gl view, to make it
  224271. // cause a repaint callback
  224272. NSView* v = (NSView*) viewHolder->view;
  224273. NSRect r = [v frame];
  224274. // bit of a bodge here.. if we only invalidate the area of the gl component,
  224275. // it's completely covered by the NSOpenGLView, so the OS throws away the
  224276. // repaint message, thus never causing our paint() callback, and never repainting
  224277. // the comp. So invalidating just a little bit around the edge helps..
  224278. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  224279. }
  224280. void* getNativeWindowHandle() const { return viewHolder->view; }
  224281. juce_UseDebuggingNewOperator
  224282. NSOpenGLContext* renderContext;
  224283. ThreadSafeNSOpenGLView* view;
  224284. private:
  224285. OpenGLPixelFormat pixelFormat;
  224286. ScopedPointer <NSViewComponentInternal> viewHolder;
  224287. WindowedGLContext (const WindowedGLContext&);
  224288. WindowedGLContext& operator= (const WindowedGLContext&);
  224289. };
  224290. OpenGLContext* OpenGLComponent::createContext()
  224291. {
  224292. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  224293. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  224294. return (c->renderContext != 0) ? c.release() : 0;
  224295. }
  224296. void* OpenGLComponent::getNativeWindowHandle() const
  224297. {
  224298. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  224299. : 0;
  224300. }
  224301. void juce_glViewport (const int w, const int h)
  224302. {
  224303. glViewport (0, 0, w, h);
  224304. }
  224305. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224306. OwnedArray <OpenGLPixelFormat>& results)
  224307. {
  224308. /* GLint attribs [64];
  224309. int n = 0;
  224310. attribs[n++] = AGL_RGBA;
  224311. attribs[n++] = AGL_DOUBLEBUFFER;
  224312. attribs[n++] = AGL_ACCELERATED;
  224313. attribs[n++] = AGL_NO_RECOVERY;
  224314. attribs[n++] = AGL_NONE;
  224315. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  224316. while (p != 0)
  224317. {
  224318. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  224319. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  224320. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  224321. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  224322. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  224323. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  224324. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  224325. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  224326. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  224327. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  224328. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  224329. results.add (pf);
  224330. p = aglNextPixelFormat (p);
  224331. }*/
  224332. //jassertfalse //xxx can't see how you do this in cocoa!
  224333. }
  224334. #else
  224335. END_JUCE_NAMESPACE
  224336. @interface JuceGLView : UIView
  224337. {
  224338. }
  224339. + (Class) layerClass;
  224340. @end
  224341. @implementation JuceGLView
  224342. + (Class) layerClass
  224343. {
  224344. return [CAEAGLLayer class];
  224345. }
  224346. @end
  224347. BEGIN_JUCE_NAMESPACE
  224348. class GLESContext : public OpenGLContext
  224349. {
  224350. public:
  224351. GLESContext (UIViewComponentPeer* peer,
  224352. Component* const component_,
  224353. const OpenGLPixelFormat& pixelFormat_,
  224354. const GLESContext* const sharedContext,
  224355. NSUInteger apiType)
  224356. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  224357. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  224358. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  224359. {
  224360. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  224361. view.opaque = YES;
  224362. view.hidden = NO;
  224363. view.backgroundColor = [UIColor blackColor];
  224364. view.userInteractionEnabled = NO;
  224365. glLayer = (CAEAGLLayer*) [view layer];
  224366. [peer->view addSubview: view];
  224367. if (sharedContext != 0)
  224368. context = [[EAGLContext alloc] initWithAPI: apiType
  224369. sharegroup: [sharedContext->context sharegroup]];
  224370. else
  224371. context = [[EAGLContext alloc] initWithAPI: apiType];
  224372. createGLBuffers();
  224373. }
  224374. ~GLESContext()
  224375. {
  224376. makeInactive();
  224377. [context release];
  224378. [view removeFromSuperview];
  224379. [view release];
  224380. freeGLBuffers();
  224381. }
  224382. bool makeActive() const throw()
  224383. {
  224384. jassert (context != 0);
  224385. [EAGLContext setCurrentContext: context];
  224386. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224387. return true;
  224388. }
  224389. void swapBuffers()
  224390. {
  224391. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224392. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  224393. }
  224394. bool makeInactive() const throw()
  224395. {
  224396. return [EAGLContext setCurrentContext: nil];
  224397. }
  224398. bool isActive() const throw()
  224399. {
  224400. return [EAGLContext currentContext] == context;
  224401. }
  224402. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224403. void* getRawContext() const throw() { return glLayer; }
  224404. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224405. {
  224406. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  224407. if (lastWidth != w || lastHeight != h)
  224408. {
  224409. lastWidth = w;
  224410. lastHeight = h;
  224411. freeGLBuffers();
  224412. createGLBuffers();
  224413. }
  224414. }
  224415. bool setSwapInterval (const int numFramesPerSwap)
  224416. {
  224417. numFrames = numFramesPerSwap;
  224418. return true;
  224419. }
  224420. int getSwapInterval() const
  224421. {
  224422. return numFrames;
  224423. }
  224424. void repaint()
  224425. {
  224426. }
  224427. void createGLBuffers()
  224428. {
  224429. makeActive();
  224430. glGenFramebuffersOES (1, &frameBufferHandle);
  224431. glGenRenderbuffersOES (1, &colorBufferHandle);
  224432. glGenRenderbuffersOES (1, &depthBufferHandle);
  224433. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224434. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  224435. GLint width, height;
  224436. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  224437. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  224438. if (useDepthBuffer)
  224439. {
  224440. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  224441. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  224442. }
  224443. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224444. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224445. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  224446. if (useDepthBuffer)
  224447. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  224448. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  224449. }
  224450. void freeGLBuffers()
  224451. {
  224452. if (frameBufferHandle != 0)
  224453. {
  224454. glDeleteFramebuffersOES (1, &frameBufferHandle);
  224455. frameBufferHandle = 0;
  224456. }
  224457. if (colorBufferHandle != 0)
  224458. {
  224459. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  224460. colorBufferHandle = 0;
  224461. }
  224462. if (depthBufferHandle != 0)
  224463. {
  224464. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  224465. depthBufferHandle = 0;
  224466. }
  224467. }
  224468. juce_UseDebuggingNewOperator
  224469. private:
  224470. Component::SafePointer<Component> component;
  224471. OpenGLPixelFormat pixelFormat;
  224472. JuceGLView* view;
  224473. CAEAGLLayer* glLayer;
  224474. EAGLContext* context;
  224475. bool useDepthBuffer;
  224476. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  224477. int numFrames;
  224478. int lastWidth, lastHeight;
  224479. GLESContext (const GLESContext&);
  224480. GLESContext& operator= (const GLESContext&);
  224481. };
  224482. OpenGLContext* OpenGLComponent::createContext()
  224483. {
  224484. ScopedAutoReleasePool pool;
  224485. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  224486. if (peer != 0)
  224487. return new GLESContext (peer, this, preferredPixelFormat,
  224488. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  224489. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  224490. return 0;
  224491. }
  224492. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224493. OwnedArray <OpenGLPixelFormat>& /*results*/)
  224494. {
  224495. }
  224496. void juce_glViewport (const int w, const int h)
  224497. {
  224498. glViewport (0, 0, w, h);
  224499. }
  224500. #endif
  224501. #endif
  224502. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  224503. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  224504. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224505. // compiled on its own).
  224506. #if JUCE_INCLUDED_FILE
  224507. #if JUCE_MAC
  224508. namespace MouseCursorHelpers
  224509. {
  224510. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  224511. {
  224512. NSImage* im = CoreGraphicsImage::createNSImage (image);
  224513. NSCursor* c = [[NSCursor alloc] initWithImage: im
  224514. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  224515. [im release];
  224516. return c;
  224517. }
  224518. static void* fromWebKitFile (const char* filename, float hx, float hy)
  224519. {
  224520. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  224521. BufferedInputStream buf (&fileStream, 4096, false);
  224522. PNGImageFormat pngFormat;
  224523. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  224524. if (im != 0)
  224525. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  224526. jassertfalse;
  224527. return 0;
  224528. }
  224529. }
  224530. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  224531. {
  224532. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  224533. }
  224534. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  224535. {
  224536. const ScopedAutoReleasePool pool;
  224537. NSCursor* c = 0;
  224538. switch (type)
  224539. {
  224540. case NormalCursor: c = [NSCursor arrowCursor]; break;
  224541. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  224542. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  224543. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  224544. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  224545. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  224546. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  224547. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  224548. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  224549. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  224550. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  224551. case UpDownResizeCursor:
  224552. case TopEdgeResizeCursor:
  224553. case BottomEdgeResizeCursor:
  224554. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  224555. case TopLeftCornerResizeCursor:
  224556. case BottomRightCornerResizeCursor:
  224557. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  224558. case TopRightCornerResizeCursor:
  224559. case BottomLeftCornerResizeCursor:
  224560. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  224561. case UpDownLeftRightResizeCursor:
  224562. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  224563. default:
  224564. jassertfalse;
  224565. break;
  224566. }
  224567. [c retain];
  224568. return c;
  224569. }
  224570. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  224571. {
  224572. [((NSCursor*) cursorHandle) release];
  224573. }
  224574. void MouseCursor::showInAllWindows() const
  224575. {
  224576. showInWindow (0);
  224577. }
  224578. void MouseCursor::showInWindow (ComponentPeer*) const
  224579. {
  224580. [((NSCursor*) getHandle()) set];
  224581. }
  224582. #else
  224583. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  224584. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  224585. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  224586. void MouseCursor::showInAllWindows() const {}
  224587. void MouseCursor::showInWindow (ComponentPeer*) const {}
  224588. #endif
  224589. #endif
  224590. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  224591. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  224592. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224593. // compiled on its own).
  224594. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224595. #if JUCE_MAC
  224596. END_JUCE_NAMESPACE
  224597. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  224598. @interface DownloadClickDetector : NSObject
  224599. {
  224600. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  224601. }
  224602. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  224603. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  224604. request: (NSURLRequest*) request
  224605. frame: (WebFrame*) frame
  224606. decisionListener: (id<WebPolicyDecisionListener>) listener;
  224607. @end
  224608. @implementation DownloadClickDetector
  224609. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  224610. {
  224611. [super init];
  224612. ownerComponent = ownerComponent_;
  224613. return self;
  224614. }
  224615. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  224616. request: (NSURLRequest*) request
  224617. frame: (WebFrame*) frame
  224618. decisionListener: (id <WebPolicyDecisionListener>) listener
  224619. {
  224620. (void) sender;
  224621. (void) request;
  224622. (void) frame;
  224623. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  224624. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  224625. [listener use];
  224626. else
  224627. [listener ignore];
  224628. }
  224629. @end
  224630. BEGIN_JUCE_NAMESPACE
  224631. class WebBrowserComponentInternal : public NSViewComponent
  224632. {
  224633. public:
  224634. WebBrowserComponentInternal (WebBrowserComponent* owner)
  224635. {
  224636. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224637. frameName: @""
  224638. groupName: @""];
  224639. setView (webView);
  224640. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  224641. [webView setPolicyDelegate: clickListener];
  224642. }
  224643. ~WebBrowserComponentInternal()
  224644. {
  224645. [webView setPolicyDelegate: nil];
  224646. [clickListener release];
  224647. setView (0);
  224648. }
  224649. void goToURL (const String& url,
  224650. const StringArray* headers,
  224651. const MemoryBlock* postData)
  224652. {
  224653. NSMutableURLRequest* r
  224654. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224655. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224656. timeoutInterval: 30.0];
  224657. if (postData != 0 && postData->getSize() > 0)
  224658. {
  224659. [r setHTTPMethod: @"POST"];
  224660. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  224661. length: postData->getSize()]];
  224662. }
  224663. if (headers != 0)
  224664. {
  224665. for (int i = 0; i < headers->size(); ++i)
  224666. {
  224667. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  224668. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  224669. [r setValue: juceStringToNS (headerValue)
  224670. forHTTPHeaderField: juceStringToNS (headerName)];
  224671. }
  224672. }
  224673. stop();
  224674. [[webView mainFrame] loadRequest: r];
  224675. }
  224676. void goBack()
  224677. {
  224678. [webView goBack];
  224679. }
  224680. void goForward()
  224681. {
  224682. [webView goForward];
  224683. }
  224684. void stop()
  224685. {
  224686. [webView stopLoading: nil];
  224687. }
  224688. void refresh()
  224689. {
  224690. [webView reload: nil];
  224691. }
  224692. private:
  224693. WebView* webView;
  224694. DownloadClickDetector* clickListener;
  224695. };
  224696. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224697. : browser (0),
  224698. blankPageShown (false),
  224699. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224700. {
  224701. setOpaque (true);
  224702. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  224703. }
  224704. WebBrowserComponent::~WebBrowserComponent()
  224705. {
  224706. deleteAndZero (browser);
  224707. }
  224708. void WebBrowserComponent::goToURL (const String& url,
  224709. const StringArray* headers,
  224710. const MemoryBlock* postData)
  224711. {
  224712. lastURL = url;
  224713. lastHeaders.clear();
  224714. if (headers != 0)
  224715. lastHeaders = *headers;
  224716. lastPostData.setSize (0);
  224717. if (postData != 0)
  224718. lastPostData = *postData;
  224719. blankPageShown = false;
  224720. browser->goToURL (url, headers, postData);
  224721. }
  224722. void WebBrowserComponent::stop()
  224723. {
  224724. browser->stop();
  224725. }
  224726. void WebBrowserComponent::goBack()
  224727. {
  224728. lastURL = String::empty;
  224729. blankPageShown = false;
  224730. browser->goBack();
  224731. }
  224732. void WebBrowserComponent::goForward()
  224733. {
  224734. lastURL = String::empty;
  224735. browser->goForward();
  224736. }
  224737. void WebBrowserComponent::refresh()
  224738. {
  224739. browser->refresh();
  224740. }
  224741. void WebBrowserComponent::paint (Graphics&)
  224742. {
  224743. }
  224744. void WebBrowserComponent::checkWindowAssociation()
  224745. {
  224746. if (isShowing())
  224747. {
  224748. if (blankPageShown)
  224749. goBack();
  224750. }
  224751. else
  224752. {
  224753. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  224754. {
  224755. // when the component becomes invisible, some stuff like flash
  224756. // carries on playing audio, so we need to force it onto a blank
  224757. // page to avoid this, (and send it back when it's made visible again).
  224758. blankPageShown = true;
  224759. browser->goToURL ("about:blank", 0, 0);
  224760. }
  224761. }
  224762. }
  224763. void WebBrowserComponent::reloadLastURL()
  224764. {
  224765. if (lastURL.isNotEmpty())
  224766. {
  224767. goToURL (lastURL, &lastHeaders, &lastPostData);
  224768. lastURL = String::empty;
  224769. }
  224770. }
  224771. void WebBrowserComponent::parentHierarchyChanged()
  224772. {
  224773. checkWindowAssociation();
  224774. }
  224775. void WebBrowserComponent::resized()
  224776. {
  224777. browser->setSize (getWidth(), getHeight());
  224778. }
  224779. void WebBrowserComponent::visibilityChanged()
  224780. {
  224781. checkWindowAssociation();
  224782. }
  224783. bool WebBrowserComponent::pageAboutToLoad (const String&)
  224784. {
  224785. return true;
  224786. }
  224787. #else
  224788. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224789. {
  224790. }
  224791. WebBrowserComponent::~WebBrowserComponent()
  224792. {
  224793. }
  224794. void WebBrowserComponent::goToURL (const String& url,
  224795. const StringArray* headers,
  224796. const MemoryBlock* postData)
  224797. {
  224798. }
  224799. void WebBrowserComponent::stop()
  224800. {
  224801. }
  224802. void WebBrowserComponent::goBack()
  224803. {
  224804. }
  224805. void WebBrowserComponent::goForward()
  224806. {
  224807. }
  224808. void WebBrowserComponent::refresh()
  224809. {
  224810. }
  224811. void WebBrowserComponent::paint (Graphics& g)
  224812. {
  224813. }
  224814. void WebBrowserComponent::checkWindowAssociation()
  224815. {
  224816. }
  224817. void WebBrowserComponent::reloadLastURL()
  224818. {
  224819. }
  224820. void WebBrowserComponent::parentHierarchyChanged()
  224821. {
  224822. }
  224823. void WebBrowserComponent::resized()
  224824. {
  224825. }
  224826. void WebBrowserComponent::visibilityChanged()
  224827. {
  224828. }
  224829. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224830. {
  224831. return true;
  224832. }
  224833. #endif
  224834. #endif
  224835. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  224836. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  224837. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224838. // compiled on its own).
  224839. #if JUCE_INCLUDED_FILE
  224840. class IPhoneAudioIODevice : public AudioIODevice
  224841. {
  224842. public:
  224843. IPhoneAudioIODevice (const String& deviceName)
  224844. : AudioIODevice (deviceName, "Audio"),
  224845. audioUnit (0),
  224846. isRunning (false),
  224847. callback (0),
  224848. actualBufferSize (0),
  224849. floatData (1, 2)
  224850. {
  224851. numInputChannels = 2;
  224852. numOutputChannels = 2;
  224853. preferredBufferSize = 0;
  224854. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  224855. updateDeviceInfo();
  224856. }
  224857. ~IPhoneAudioIODevice()
  224858. {
  224859. close();
  224860. }
  224861. const StringArray getOutputChannelNames()
  224862. {
  224863. StringArray s;
  224864. s.add ("Left");
  224865. s.add ("Right");
  224866. return s;
  224867. }
  224868. const StringArray getInputChannelNames()
  224869. {
  224870. StringArray s;
  224871. if (audioInputIsAvailable)
  224872. {
  224873. s.add ("Left");
  224874. s.add ("Right");
  224875. }
  224876. return s;
  224877. }
  224878. int getNumSampleRates()
  224879. {
  224880. return 1;
  224881. }
  224882. double getSampleRate (int index)
  224883. {
  224884. return sampleRate;
  224885. }
  224886. int getNumBufferSizesAvailable()
  224887. {
  224888. return 1;
  224889. }
  224890. int getBufferSizeSamples (int index)
  224891. {
  224892. return getDefaultBufferSize();
  224893. }
  224894. int getDefaultBufferSize()
  224895. {
  224896. return 1024;
  224897. }
  224898. const String open (const BigInteger& inputChannels,
  224899. const BigInteger& outputChannels,
  224900. double sampleRate,
  224901. int bufferSize)
  224902. {
  224903. close();
  224904. lastError = String::empty;
  224905. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  224906. // xxx set up channel mapping
  224907. activeOutputChans = outputChannels;
  224908. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  224909. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  224910. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  224911. activeInputChans = inputChannels;
  224912. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  224913. numInputChannels = activeInputChans.countNumberOfSetBits();
  224914. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  224915. AudioSessionSetActive (true);
  224916. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  224917. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  224918. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  224919. fixAudioRouteIfSetToReceiver();
  224920. updateDeviceInfo();
  224921. Float32 bufferDuration = preferredBufferSize / sampleRate;
  224922. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  224923. actualBufferSize = preferredBufferSize;
  224924. prepareFloatBuffers();
  224925. isRunning = true;
  224926. propertyChanged (0, 0, 0); // creates and starts the AU
  224927. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  224928. return lastError;
  224929. }
  224930. void close()
  224931. {
  224932. if (isRunning)
  224933. {
  224934. isRunning = false;
  224935. AudioSessionSetActive (false);
  224936. if (audioUnit != 0)
  224937. {
  224938. AudioComponentInstanceDispose (audioUnit);
  224939. audioUnit = 0;
  224940. }
  224941. }
  224942. }
  224943. bool isOpen()
  224944. {
  224945. return isRunning;
  224946. }
  224947. int getCurrentBufferSizeSamples()
  224948. {
  224949. return actualBufferSize;
  224950. }
  224951. double getCurrentSampleRate()
  224952. {
  224953. return sampleRate;
  224954. }
  224955. int getCurrentBitDepth()
  224956. {
  224957. return 16;
  224958. }
  224959. const BigInteger getActiveOutputChannels() const
  224960. {
  224961. return activeOutputChans;
  224962. }
  224963. const BigInteger getActiveInputChannels() const
  224964. {
  224965. return activeInputChans;
  224966. }
  224967. int getOutputLatencyInSamples()
  224968. {
  224969. return 0; //xxx
  224970. }
  224971. int getInputLatencyInSamples()
  224972. {
  224973. return 0; //xxx
  224974. }
  224975. void start (AudioIODeviceCallback* callback_)
  224976. {
  224977. if (isRunning && callback != callback_)
  224978. {
  224979. if (callback_ != 0)
  224980. callback_->audioDeviceAboutToStart (this);
  224981. const ScopedLock sl (callbackLock);
  224982. callback = callback_;
  224983. }
  224984. }
  224985. void stop()
  224986. {
  224987. if (isRunning)
  224988. {
  224989. AudioIODeviceCallback* lastCallback;
  224990. {
  224991. const ScopedLock sl (callbackLock);
  224992. lastCallback = callback;
  224993. callback = 0;
  224994. }
  224995. if (lastCallback != 0)
  224996. lastCallback->audioDeviceStopped();
  224997. }
  224998. }
  224999. bool isPlaying()
  225000. {
  225001. return isRunning && callback != 0;
  225002. }
  225003. const String getLastError()
  225004. {
  225005. return lastError;
  225006. }
  225007. private:
  225008. CriticalSection callbackLock;
  225009. Float64 sampleRate;
  225010. int numInputChannels, numOutputChannels;
  225011. int preferredBufferSize;
  225012. int actualBufferSize;
  225013. bool isRunning;
  225014. String lastError;
  225015. AudioStreamBasicDescription format;
  225016. AudioUnit audioUnit;
  225017. UInt32 audioInputIsAvailable;
  225018. AudioIODeviceCallback* callback;
  225019. BigInteger activeOutputChans, activeInputChans;
  225020. AudioSampleBuffer floatData;
  225021. float* inputChannels[3];
  225022. float* outputChannels[3];
  225023. bool monoInputChannelNumber, monoOutputChannelNumber;
  225024. void prepareFloatBuffers()
  225025. {
  225026. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  225027. zerostruct (inputChannels);
  225028. zerostruct (outputChannels);
  225029. for (int i = 0; i < numInputChannels; ++i)
  225030. inputChannels[i] = floatData.getSampleData (i);
  225031. for (int i = 0; i < numOutputChannels; ++i)
  225032. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  225033. }
  225034. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225035. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225036. {
  225037. OSStatus err = noErr;
  225038. if (audioInputIsAvailable)
  225039. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  225040. const ScopedLock sl (callbackLock);
  225041. if (callback != 0)
  225042. {
  225043. if (audioInputIsAvailable && numInputChannels > 0)
  225044. {
  225045. short* shortData = (short*) ioData->mBuffers[0].mData;
  225046. if (numInputChannels >= 2)
  225047. {
  225048. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225049. {
  225050. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225051. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  225052. }
  225053. }
  225054. else
  225055. {
  225056. if (monoInputChannelNumber > 0)
  225057. ++shortData;
  225058. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225059. {
  225060. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225061. ++shortData;
  225062. }
  225063. }
  225064. }
  225065. else
  225066. {
  225067. for (int i = numInputChannels; --i >= 0;)
  225068. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  225069. }
  225070. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  225071. outputChannels, numOutputChannels,
  225072. (int) inNumberFrames);
  225073. short* shortData = (short*) ioData->mBuffers[0].mData;
  225074. int n = 0;
  225075. if (numOutputChannels >= 2)
  225076. {
  225077. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225078. {
  225079. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  225080. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  225081. }
  225082. }
  225083. else if (numOutputChannels == 1)
  225084. {
  225085. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225086. {
  225087. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  225088. shortData [n++] = s;
  225089. shortData [n++] = s;
  225090. }
  225091. }
  225092. else
  225093. {
  225094. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225095. }
  225096. }
  225097. else
  225098. {
  225099. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225100. }
  225101. return err;
  225102. }
  225103. void updateDeviceInfo()
  225104. {
  225105. UInt32 size = sizeof (sampleRate);
  225106. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  225107. size = sizeof (audioInputIsAvailable);
  225108. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  225109. }
  225110. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225111. {
  225112. if (! isRunning)
  225113. return;
  225114. if (inPropertyValue != 0)
  225115. {
  225116. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  225117. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  225118. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  225119. SInt32 routeChangeReason;
  225120. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  225121. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  225122. fixAudioRouteIfSetToReceiver();
  225123. }
  225124. updateDeviceInfo();
  225125. createAudioUnit();
  225126. AudioSessionSetActive (true);
  225127. if (audioUnit != 0)
  225128. {
  225129. UInt32 formatSize = sizeof (format);
  225130. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  225131. Float32 bufferDuration = preferredBufferSize / sampleRate;
  225132. UInt32 bufferDurationSize = sizeof (bufferDuration);
  225133. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  225134. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  225135. AudioOutputUnitStart (audioUnit);
  225136. }
  225137. }
  225138. void interruptionListener (UInt32 inInterruption)
  225139. {
  225140. /*if (inInterruption == kAudioSessionBeginInterruption)
  225141. {
  225142. isRunning = false;
  225143. AudioOutputUnitStop (audioUnit);
  225144. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  225145. "This could have been interrupted by another application or by unplugging a headset",
  225146. @"Resume",
  225147. @"Cancel"))
  225148. {
  225149. isRunning = true;
  225150. propertyChanged (0, 0, 0);
  225151. }
  225152. }*/
  225153. if (inInterruption == kAudioSessionEndInterruption)
  225154. {
  225155. isRunning = true;
  225156. AudioSessionSetActive (true);
  225157. AudioOutputUnitStart (audioUnit);
  225158. }
  225159. }
  225160. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225161. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225162. {
  225163. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  225164. }
  225165. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225166. {
  225167. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  225168. }
  225169. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  225170. {
  225171. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  225172. }
  225173. void resetFormat (const int numChannels)
  225174. {
  225175. memset (&format, 0, sizeof (format));
  225176. format.mFormatID = kAudioFormatLinearPCM;
  225177. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  225178. format.mBitsPerChannel = 8 * sizeof (short);
  225179. format.mChannelsPerFrame = 2;
  225180. format.mFramesPerPacket = 1;
  225181. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  225182. }
  225183. bool createAudioUnit()
  225184. {
  225185. if (audioUnit != 0)
  225186. {
  225187. AudioComponentInstanceDispose (audioUnit);
  225188. audioUnit = 0;
  225189. }
  225190. resetFormat (2);
  225191. AudioComponentDescription desc;
  225192. desc.componentType = kAudioUnitType_Output;
  225193. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  225194. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  225195. desc.componentFlags = 0;
  225196. desc.componentFlagsMask = 0;
  225197. AudioComponent comp = AudioComponentFindNext (0, &desc);
  225198. AudioComponentInstanceNew (comp, &audioUnit);
  225199. if (audioUnit == 0)
  225200. return false;
  225201. const UInt32 one = 1;
  225202. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  225203. AudioChannelLayout layout;
  225204. layout.mChannelBitmap = 0;
  225205. layout.mNumberChannelDescriptions = 0;
  225206. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  225207. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  225208. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  225209. AURenderCallbackStruct inputProc;
  225210. inputProc.inputProc = processStatic;
  225211. inputProc.inputProcRefCon = this;
  225212. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  225213. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  225214. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  225215. AudioUnitInitialize (audioUnit);
  225216. return true;
  225217. }
  225218. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  225219. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  225220. static void fixAudioRouteIfSetToReceiver()
  225221. {
  225222. CFStringRef audioRoute = 0;
  225223. UInt32 propertySize = sizeof (audioRoute);
  225224. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  225225. {
  225226. NSString* route = (NSString*) audioRoute;
  225227. //DBG ("audio route: " + nsStringToJuce (route));
  225228. if ([route hasPrefix: @"Receiver"])
  225229. {
  225230. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  225231. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  225232. }
  225233. CFRelease (audioRoute);
  225234. }
  225235. }
  225236. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  225237. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  225238. };
  225239. class IPhoneAudioIODeviceType : public AudioIODeviceType
  225240. {
  225241. public:
  225242. IPhoneAudioIODeviceType()
  225243. : AudioIODeviceType ("iPhone Audio")
  225244. {
  225245. }
  225246. ~IPhoneAudioIODeviceType()
  225247. {
  225248. }
  225249. void scanForDevices()
  225250. {
  225251. }
  225252. const StringArray getDeviceNames (bool wantInputNames) const
  225253. {
  225254. StringArray s;
  225255. s.add ("iPhone Audio");
  225256. return s;
  225257. }
  225258. int getDefaultDeviceIndex (bool forInput) const
  225259. {
  225260. return 0;
  225261. }
  225262. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  225263. {
  225264. return device != 0 ? 0 : -1;
  225265. }
  225266. bool hasSeparateInputsAndOutputs() const { return false; }
  225267. AudioIODevice* createDevice (const String& outputDeviceName,
  225268. const String& inputDeviceName)
  225269. {
  225270. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  225271. {
  225272. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  225273. : inputDeviceName);
  225274. }
  225275. return 0;
  225276. }
  225277. juce_UseDebuggingNewOperator
  225278. private:
  225279. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  225280. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  225281. };
  225282. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  225283. {
  225284. return new IPhoneAudioIODeviceType();
  225285. }
  225286. #endif
  225287. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  225288. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  225289. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225290. // compiled on its own).
  225291. #if JUCE_INCLUDED_FILE
  225292. #if JUCE_MAC
  225293. #undef log
  225294. #define log(a) Logger::writeToLog(a)
  225295. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  225296. {
  225297. if (err == noErr)
  225298. return true;
  225299. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  225300. jassertfalse
  225301. return false;
  225302. }
  225303. #undef OK
  225304. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  225305. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  225306. {
  225307. String result;
  225308. CFStringRef str = 0;
  225309. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  225310. if (str != 0)
  225311. {
  225312. result = PlatformUtilities::cfStringToJuceString (str);
  225313. CFRelease (str);
  225314. str = 0;
  225315. }
  225316. MIDIEntityRef entity = 0;
  225317. MIDIEndpointGetEntity (endpoint, &entity);
  225318. if (entity == 0)
  225319. return result; // probably virtual
  225320. if (result.isEmpty())
  225321. {
  225322. // endpoint name has zero length - try the entity
  225323. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  225324. if (str != 0)
  225325. {
  225326. result += PlatformUtilities::cfStringToJuceString (str);
  225327. CFRelease (str);
  225328. str = 0;
  225329. }
  225330. }
  225331. // now consider the device's name
  225332. MIDIDeviceRef device = 0;
  225333. MIDIEntityGetDevice (entity, &device);
  225334. if (device == 0)
  225335. return result;
  225336. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  225337. if (str != 0)
  225338. {
  225339. const String s (PlatformUtilities::cfStringToJuceString (str));
  225340. CFRelease (str);
  225341. // if an external device has only one entity, throw away
  225342. // the endpoint name and just use the device name
  225343. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  225344. {
  225345. result = s;
  225346. }
  225347. else if (! result.startsWithIgnoreCase (s))
  225348. {
  225349. // prepend the device name to the entity name
  225350. result = (s + " " + result).trimEnd();
  225351. }
  225352. }
  225353. return result;
  225354. }
  225355. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  225356. {
  225357. String result;
  225358. // Does the endpoint have connections?
  225359. CFDataRef connections = 0;
  225360. int numConnections = 0;
  225361. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  225362. if (connections != 0)
  225363. {
  225364. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  225365. if (numConnections > 0)
  225366. {
  225367. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  225368. for (int i = 0; i < numConnections; ++i, ++pid)
  225369. {
  225370. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  225371. MIDIObjectRef connObject;
  225372. MIDIObjectType connObjectType;
  225373. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  225374. if (err == noErr)
  225375. {
  225376. String s;
  225377. if (connObjectType == kMIDIObjectType_ExternalSource
  225378. || connObjectType == kMIDIObjectType_ExternalDestination)
  225379. {
  225380. // Connected to an external device's endpoint (10.3 and later).
  225381. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  225382. }
  225383. else
  225384. {
  225385. // Connected to an external device (10.2) (or something else, catch-all)
  225386. CFStringRef str = 0;
  225387. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  225388. if (str != 0)
  225389. {
  225390. s = PlatformUtilities::cfStringToJuceString (str);
  225391. CFRelease (str);
  225392. }
  225393. }
  225394. if (s.isNotEmpty())
  225395. {
  225396. if (result.isNotEmpty())
  225397. result += ", ";
  225398. result += s;
  225399. }
  225400. }
  225401. }
  225402. }
  225403. CFRelease (connections);
  225404. }
  225405. if (result.isNotEmpty())
  225406. return result;
  225407. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  225408. return getEndpointName (endpoint, false);
  225409. }
  225410. const StringArray MidiOutput::getDevices()
  225411. {
  225412. StringArray s;
  225413. const ItemCount num = MIDIGetNumberOfDestinations();
  225414. for (ItemCount i = 0; i < num; ++i)
  225415. {
  225416. MIDIEndpointRef dest = MIDIGetDestination (i);
  225417. if (dest != 0)
  225418. {
  225419. String name (getConnectedEndpointName (dest));
  225420. if (name.isEmpty())
  225421. name = "<error>";
  225422. s.add (name);
  225423. }
  225424. else
  225425. {
  225426. s.add ("<error>");
  225427. }
  225428. }
  225429. return s;
  225430. }
  225431. int MidiOutput::getDefaultDeviceIndex()
  225432. {
  225433. return 0;
  225434. }
  225435. static MIDIClientRef globalMidiClient;
  225436. static bool hasGlobalClientBeenCreated = false;
  225437. static bool makeSureClientExists()
  225438. {
  225439. if (! hasGlobalClientBeenCreated)
  225440. {
  225441. String name ("JUCE");
  225442. if (JUCEApplication::getInstance() != 0)
  225443. name = JUCEApplication::getInstance()->getApplicationName();
  225444. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  225445. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  225446. CFRelease (appName);
  225447. }
  225448. return hasGlobalClientBeenCreated;
  225449. }
  225450. class MidiPortAndEndpoint
  225451. {
  225452. public:
  225453. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  225454. : port (port_), endPoint (endPoint_)
  225455. {
  225456. }
  225457. ~MidiPortAndEndpoint()
  225458. {
  225459. if (port != 0)
  225460. MIDIPortDispose (port);
  225461. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  225462. MIDIEndpointDispose (endPoint);
  225463. }
  225464. MIDIPortRef port;
  225465. MIDIEndpointRef endPoint;
  225466. };
  225467. MidiOutput* MidiOutput::openDevice (int index)
  225468. {
  225469. MidiOutput* mo = 0;
  225470. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  225471. {
  225472. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  225473. CFStringRef pname;
  225474. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225475. {
  225476. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  225477. if (makeSureClientExists())
  225478. {
  225479. MIDIPortRef port;
  225480. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  225481. {
  225482. mo = new MidiOutput();
  225483. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  225484. }
  225485. }
  225486. CFRelease (pname);
  225487. }
  225488. }
  225489. return mo;
  225490. }
  225491. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  225492. {
  225493. MidiOutput* mo = 0;
  225494. if (makeSureClientExists())
  225495. {
  225496. MIDIEndpointRef endPoint;
  225497. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  225498. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  225499. {
  225500. mo = new MidiOutput();
  225501. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  225502. }
  225503. CFRelease (name);
  225504. }
  225505. return mo;
  225506. }
  225507. MidiOutput::~MidiOutput()
  225508. {
  225509. delete (MidiPortAndEndpoint*) internal;
  225510. }
  225511. void MidiOutput::reset()
  225512. {
  225513. }
  225514. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  225515. {
  225516. return false;
  225517. }
  225518. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  225519. {
  225520. }
  225521. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225522. {
  225523. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  225524. if (message.isSysEx())
  225525. {
  225526. const int maxPacketSize = 256;
  225527. int pos = 0, bytesLeft = message.getRawDataSize();
  225528. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  225529. HeapBlock <MIDIPacketList> packets;
  225530. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  225531. packets->numPackets = numPackets;
  225532. MIDIPacket* p = packets->packet;
  225533. for (int i = 0; i < numPackets; ++i)
  225534. {
  225535. p->timeStamp = 0;
  225536. p->length = jmin (maxPacketSize, bytesLeft);
  225537. memcpy (p->data, message.getRawData() + pos, p->length);
  225538. pos += p->length;
  225539. bytesLeft -= p->length;
  225540. p = MIDIPacketNext (p);
  225541. }
  225542. if (mpe->port != 0)
  225543. MIDISend (mpe->port, mpe->endPoint, packets);
  225544. else
  225545. MIDIReceived (mpe->endPoint, packets);
  225546. }
  225547. else
  225548. {
  225549. MIDIPacketList packets;
  225550. packets.numPackets = 1;
  225551. packets.packet[0].timeStamp = 0;
  225552. packets.packet[0].length = message.getRawDataSize();
  225553. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  225554. if (mpe->port != 0)
  225555. MIDISend (mpe->port, mpe->endPoint, &packets);
  225556. else
  225557. MIDIReceived (mpe->endPoint, &packets);
  225558. }
  225559. }
  225560. const StringArray MidiInput::getDevices()
  225561. {
  225562. StringArray s;
  225563. const ItemCount num = MIDIGetNumberOfSources();
  225564. for (ItemCount i = 0; i < num; ++i)
  225565. {
  225566. MIDIEndpointRef source = MIDIGetSource (i);
  225567. if (source != 0)
  225568. {
  225569. String name (getConnectedEndpointName (source));
  225570. if (name.isEmpty())
  225571. name = "<error>";
  225572. s.add (name);
  225573. }
  225574. else
  225575. {
  225576. s.add ("<error>");
  225577. }
  225578. }
  225579. return s;
  225580. }
  225581. int MidiInput::getDefaultDeviceIndex()
  225582. {
  225583. return 0;
  225584. }
  225585. struct MidiPortAndCallback
  225586. {
  225587. MidiInput* input;
  225588. MidiPortAndEndpoint* portAndEndpoint;
  225589. MidiInputCallback* callback;
  225590. MemoryBlock pendingData;
  225591. int pendingBytes;
  225592. double pendingDataTime;
  225593. bool active;
  225594. void processSysex (const uint8*& d, int& size, const double time)
  225595. {
  225596. if (*d == 0xf0)
  225597. {
  225598. pendingBytes = 0;
  225599. pendingDataTime = time;
  225600. }
  225601. pendingData.ensureSize (pendingBytes + size, false);
  225602. uint8* totalMessage = (uint8*) pendingData.getData();
  225603. uint8* dest = totalMessage + pendingBytes;
  225604. while (size > 0)
  225605. {
  225606. if (pendingBytes > 0 && *d >= 0x80)
  225607. {
  225608. if (*d >= 0xfa || *d == 0xf8)
  225609. {
  225610. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  225611. ++d;
  225612. --size;
  225613. }
  225614. else
  225615. {
  225616. if (*d == 0xf7)
  225617. {
  225618. *dest++ = *d++;
  225619. pendingBytes++;
  225620. --size;
  225621. }
  225622. break;
  225623. }
  225624. }
  225625. else
  225626. {
  225627. *dest++ = *d++;
  225628. pendingBytes++;
  225629. --size;
  225630. }
  225631. }
  225632. if (totalMessage [pendingBytes - 1] == 0xf7)
  225633. {
  225634. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  225635. pendingBytes = 0;
  225636. }
  225637. else
  225638. {
  225639. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  225640. }
  225641. }
  225642. };
  225643. namespace CoreMidiCallbacks
  225644. {
  225645. static CriticalSection callbackLock;
  225646. static VoidArray activeCallbacks;
  225647. }
  225648. static void midiInputProc (const MIDIPacketList* pktlist,
  225649. void* readProcRefCon,
  225650. void* /*srcConnRefCon*/)
  225651. {
  225652. double time = Time::getMillisecondCounterHiRes() * 0.001;
  225653. const double originalTime = time;
  225654. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  225655. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225656. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  225657. {
  225658. const MIDIPacket* packet = &pktlist->packet[0];
  225659. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  225660. {
  225661. const uint8* d = (const uint8*) (packet->data);
  225662. int size = packet->length;
  225663. while (size > 0)
  225664. {
  225665. time = originalTime;
  225666. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  225667. {
  225668. mpc->processSysex (d, size, time);
  225669. }
  225670. else
  225671. {
  225672. int used = 0;
  225673. const MidiMessage m (d, size, used, 0, time);
  225674. if (used <= 0)
  225675. {
  225676. jassertfalse // malformed midi message
  225677. break;
  225678. }
  225679. else
  225680. {
  225681. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  225682. }
  225683. size -= used;
  225684. d += used;
  225685. }
  225686. }
  225687. packet = MIDIPacketNext (packet);
  225688. }
  225689. }
  225690. }
  225691. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225692. {
  225693. MidiInput* mi = 0;
  225694. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  225695. {
  225696. MIDIEndpointRef endPoint = MIDIGetSource (index);
  225697. if (endPoint != 0)
  225698. {
  225699. CFStringRef pname;
  225700. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225701. {
  225702. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  225703. if (makeSureClientExists())
  225704. {
  225705. MIDIPortRef port;
  225706. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  225707. mpc->active = false;
  225708. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  225709. {
  225710. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  225711. {
  225712. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  225713. mpc->callback = callback;
  225714. mpc->pendingBytes = 0;
  225715. mpc->pendingData.ensureSize (128);
  225716. mi = new MidiInput (getDevices() [index]);
  225717. mpc->input = mi;
  225718. mi->internal = mpc;
  225719. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225720. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  225721. }
  225722. else
  225723. {
  225724. OK (MIDIPortDispose (port));
  225725. }
  225726. }
  225727. }
  225728. }
  225729. CFRelease (pname);
  225730. }
  225731. }
  225732. return mi;
  225733. }
  225734. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  225735. {
  225736. MidiInput* mi = 0;
  225737. if (makeSureClientExists())
  225738. {
  225739. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  225740. mpc->active = false;
  225741. MIDIEndpointRef endPoint;
  225742. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  225743. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  225744. {
  225745. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  225746. mpc->callback = callback;
  225747. mpc->pendingBytes = 0;
  225748. mpc->pendingData.ensureSize (128);
  225749. mi = new MidiInput (deviceName);
  225750. mpc->input = mi;
  225751. mi->internal = mpc;
  225752. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225753. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  225754. }
  225755. CFRelease (name);
  225756. }
  225757. return mi;
  225758. }
  225759. MidiInput::MidiInput (const String& name_)
  225760. : name (name_)
  225761. {
  225762. }
  225763. MidiInput::~MidiInput()
  225764. {
  225765. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  225766. mpc->active = false;
  225767. {
  225768. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225769. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  225770. }
  225771. if (mpc->portAndEndpoint->port != 0)
  225772. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  225773. delete mpc->portAndEndpoint;
  225774. delete mpc;
  225775. }
  225776. void MidiInput::start()
  225777. {
  225778. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225779. ((MidiPortAndCallback*) internal)->active = true;
  225780. }
  225781. void MidiInput::stop()
  225782. {
  225783. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225784. ((MidiPortAndCallback*) internal)->active = false;
  225785. }
  225786. #undef log
  225787. #else
  225788. MidiOutput::~MidiOutput()
  225789. {
  225790. }
  225791. void MidiOutput::reset()
  225792. {
  225793. }
  225794. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  225795. {
  225796. return false;
  225797. }
  225798. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  225799. {
  225800. }
  225801. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225802. {
  225803. }
  225804. const StringArray MidiOutput::getDevices()
  225805. {
  225806. return StringArray();
  225807. }
  225808. MidiOutput* MidiOutput::openDevice (int index)
  225809. {
  225810. return 0;
  225811. }
  225812. const StringArray MidiInput::getDevices()
  225813. {
  225814. return StringArray();
  225815. }
  225816. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225817. {
  225818. return 0;
  225819. }
  225820. #endif
  225821. #endif
  225822. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  225823. #else
  225824. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225825. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225826. // compiled on its own).
  225827. #if JUCE_INCLUDED_FILE
  225828. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225829. #define SUPPORT_10_4_FONTS 1
  225830. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225831. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225832. #define SUPPORT_ONLY_10_4_FONTS 1
  225833. #endif
  225834. END_JUCE_NAMESPACE
  225835. @interface NSFont (PrivateHack)
  225836. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225837. @end
  225838. BEGIN_JUCE_NAMESPACE
  225839. #endif
  225840. class MacTypeface : public Typeface
  225841. {
  225842. public:
  225843. MacTypeface (const Font& font)
  225844. : Typeface (font.getTypefaceName())
  225845. {
  225846. const ScopedAutoReleasePool pool;
  225847. renderingTransform = CGAffineTransformIdentity;
  225848. bool needsItalicTransform = false;
  225849. #if JUCE_IPHONE
  225850. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225851. if (font.isItalic() || font.isBold())
  225852. {
  225853. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225854. for (NSString* i in familyFonts)
  225855. {
  225856. const String fn (nsStringToJuce (i));
  225857. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225858. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225859. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225860. || afterDash.containsIgnoreCase ("italic")
  225861. || fn.endsWithIgnoreCase ("oblique")
  225862. || fn.endsWithIgnoreCase ("italic");
  225863. if (probablyBold == font.isBold()
  225864. && probablyItalic == font.isItalic())
  225865. {
  225866. fontName = i;
  225867. needsItalicTransform = false;
  225868. break;
  225869. }
  225870. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225871. {
  225872. fontName = i;
  225873. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225874. }
  225875. }
  225876. if (needsItalicTransform)
  225877. renderingTransform.c = 0.15f;
  225878. }
  225879. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225880. const int ascender = abs (CGFontGetAscent (fontRef));
  225881. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225882. ascent = ascender / totalHeight;
  225883. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225884. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225885. #else
  225886. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225887. if (font.isItalic())
  225888. {
  225889. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225890. toHaveTrait: NSItalicFontMask];
  225891. if (newFont == nsFont)
  225892. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225893. nsFont = newFont;
  225894. }
  225895. if (font.isBold())
  225896. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225897. [nsFont retain];
  225898. ascent = fabsf ((float) [nsFont ascender]);
  225899. float totalSize = ascent + fabsf ((float) [nsFont descender]);
  225900. ascent /= totalSize;
  225901. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225902. if (needsItalicTransform)
  225903. {
  225904. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225905. renderingTransform.c = 0.15f;
  225906. }
  225907. #if SUPPORT_ONLY_10_4_FONTS
  225908. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225909. if (atsFont == 0)
  225910. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225911. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225912. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  225913. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225914. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225915. #else
  225916. #if SUPPORT_10_4_FONTS
  225917. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225918. {
  225919. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225920. if (atsFont == 0)
  225921. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225922. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225923. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  225924. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225925. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225926. }
  225927. else
  225928. #endif
  225929. {
  225930. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225931. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225932. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225933. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225934. }
  225935. #endif
  225936. #endif
  225937. }
  225938. ~MacTypeface()
  225939. {
  225940. #if ! JUCE_IPHONE
  225941. [nsFont release];
  225942. #endif
  225943. if (fontRef != 0)
  225944. CGFontRelease (fontRef);
  225945. }
  225946. float getAscent() const
  225947. {
  225948. return ascent;
  225949. }
  225950. float getDescent() const
  225951. {
  225952. return 1.0f - ascent;
  225953. }
  225954. float getStringWidth (const String& text)
  225955. {
  225956. if (fontRef == 0 || text.isEmpty())
  225957. return 0;
  225958. const int length = text.length();
  225959. HeapBlock <CGGlyph> glyphs;
  225960. createGlyphsForString (text, length, glyphs);
  225961. float x = 0;
  225962. #if SUPPORT_ONLY_10_4_FONTS
  225963. HeapBlock <NSSize> advances (length);
  225964. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225965. for (int i = 0; i < length; ++i)
  225966. x += advances[i].width;
  225967. #else
  225968. #if SUPPORT_10_4_FONTS
  225969. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225970. {
  225971. HeapBlock <NSSize> advances (length);
  225972. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225973. for (int i = 0; i < length; ++i)
  225974. x += advances[i].width;
  225975. }
  225976. else
  225977. #endif
  225978. {
  225979. HeapBlock <int> advances (length);
  225980. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225981. for (int i = 0; i < length; ++i)
  225982. x += advances[i];
  225983. }
  225984. #endif
  225985. return x * unitsToHeightScaleFactor;
  225986. }
  225987. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225988. {
  225989. xOffsets.add (0);
  225990. if (fontRef == 0 || text.isEmpty())
  225991. return;
  225992. const int length = text.length();
  225993. HeapBlock <CGGlyph> glyphs;
  225994. createGlyphsForString (text, length, glyphs);
  225995. #if SUPPORT_ONLY_10_4_FONTS
  225996. HeapBlock <NSSize> advances (length);
  225997. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225998. int x = 0;
  225999. for (int i = 0; i < length; ++i)
  226000. {
  226001. x += advances[i].width;
  226002. xOffsets.add (x * unitsToHeightScaleFactor);
  226003. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226004. }
  226005. #else
  226006. #if SUPPORT_10_4_FONTS
  226007. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226008. {
  226009. HeapBlock <NSSize> advances (length);
  226010. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226011. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226012. float x = 0;
  226013. for (int i = 0; i < length; ++i)
  226014. {
  226015. x += advances[i].width;
  226016. xOffsets.add (x * unitsToHeightScaleFactor);
  226017. resultGlyphs.add (nsGlyphs[i]);
  226018. }
  226019. }
  226020. else
  226021. #endif
  226022. {
  226023. HeapBlock <int> advances (length);
  226024. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226025. {
  226026. int x = 0;
  226027. for (int i = 0; i < length; ++i)
  226028. {
  226029. x += advances [i];
  226030. xOffsets.add (x * unitsToHeightScaleFactor);
  226031. resultGlyphs.add (glyphs[i]);
  226032. }
  226033. }
  226034. }
  226035. #endif
  226036. }
  226037. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226038. {
  226039. #if JUCE_IPHONE
  226040. return false;
  226041. #else
  226042. if (nsFont == 0)
  226043. return false;
  226044. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226045. jassert (path.isEmpty());
  226046. const ScopedAutoReleasePool pool;
  226047. NSBezierPath* bez = [NSBezierPath bezierPath];
  226048. [bez moveToPoint: NSMakePoint (0, 0)];
  226049. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226050. inFont: nsFont];
  226051. for (int i = 0; i < [bez elementCount]; ++i)
  226052. {
  226053. NSPoint p[3];
  226054. switch ([bez elementAtIndex: i associatedPoints: p])
  226055. {
  226056. case NSMoveToBezierPathElement:
  226057. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226058. break;
  226059. case NSLineToBezierPathElement:
  226060. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226061. break;
  226062. case NSCurveToBezierPathElement:
  226063. 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);
  226064. break;
  226065. case NSClosePathBezierPathElement:
  226066. path.closeSubPath();
  226067. break;
  226068. default:
  226069. jassertfalse
  226070. break;
  226071. }
  226072. }
  226073. path.applyTransform (pathTransform);
  226074. return true;
  226075. #endif
  226076. }
  226077. juce_UseDebuggingNewOperator
  226078. CGFontRef fontRef;
  226079. float fontHeightToCGSizeFactor;
  226080. CGAffineTransform renderingTransform;
  226081. private:
  226082. float ascent, unitsToHeightScaleFactor;
  226083. #if JUCE_IPHONE
  226084. #else
  226085. NSFont* nsFont;
  226086. AffineTransform pathTransform;
  226087. #endif
  226088. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226089. {
  226090. #if SUPPORT_10_4_FONTS
  226091. #if ! SUPPORT_ONLY_10_4_FONTS
  226092. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226093. #endif
  226094. {
  226095. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226096. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226097. for (int i = 0; i < length; ++i)
  226098. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226099. return;
  226100. }
  226101. #endif
  226102. #if ! SUPPORT_ONLY_10_4_FONTS
  226103. if (charToGlyphMapper == 0)
  226104. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226105. glyphs.malloc (length);
  226106. for (int i = 0; i < length; ++i)
  226107. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226108. #endif
  226109. }
  226110. #if ! SUPPORT_ONLY_10_4_FONTS
  226111. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226112. class CharToGlyphMapper
  226113. {
  226114. public:
  226115. CharToGlyphMapper (CGFontRef fontRef)
  226116. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226117. idRangeOffset (0), glyphIndexes (0)
  226118. {
  226119. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226120. if (cmapTable != 0)
  226121. {
  226122. const int numSubtables = getValue16 (cmapTable, 2);
  226123. for (int i = 0; i < numSubtables; ++i)
  226124. {
  226125. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226126. {
  226127. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226128. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226129. {
  226130. const int length = getValue16 (cmapTable, offset + 2);
  226131. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226132. segCount = segCountX2 / 2;
  226133. const int endCodeOffset = offset + 14;
  226134. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226135. const int idDeltaOffset = startCodeOffset + segCountX2;
  226136. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226137. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226138. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226139. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226140. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226141. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226142. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226143. }
  226144. break;
  226145. }
  226146. }
  226147. CFRelease (cmapTable);
  226148. }
  226149. }
  226150. ~CharToGlyphMapper()
  226151. {
  226152. if (endCode != 0)
  226153. {
  226154. CFRelease (endCode);
  226155. CFRelease (startCode);
  226156. CFRelease (idDelta);
  226157. CFRelease (idRangeOffset);
  226158. CFRelease (glyphIndexes);
  226159. }
  226160. }
  226161. int getGlyphForCharacter (const juce_wchar c) const
  226162. {
  226163. for (int i = 0; i < segCount; ++i)
  226164. {
  226165. if (getValue16 (endCode, i * 2) >= c)
  226166. {
  226167. const int start = getValue16 (startCode, i * 2);
  226168. if (start > c)
  226169. break;
  226170. const int delta = getValue16 (idDelta, i * 2);
  226171. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226172. if (rangeOffset == 0)
  226173. return delta + c;
  226174. else
  226175. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226176. }
  226177. }
  226178. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226179. return jmax (-1, c - 29);
  226180. }
  226181. private:
  226182. int segCount;
  226183. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226184. static uint16 getValue16 (CFDataRef data, const int index)
  226185. {
  226186. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226187. }
  226188. static uint32 getValue32 (CFDataRef data, const int index)
  226189. {
  226190. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226191. }
  226192. };
  226193. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226194. #endif
  226195. MacTypeface (const MacTypeface&);
  226196. MacTypeface& operator= (const MacTypeface&);
  226197. };
  226198. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226199. {
  226200. return new MacTypeface (font);
  226201. }
  226202. const StringArray Font::findAllTypefaceNames()
  226203. {
  226204. StringArray names;
  226205. const ScopedAutoReleasePool pool;
  226206. #if JUCE_IPHONE
  226207. NSArray* fonts = [UIFont familyNames];
  226208. #else
  226209. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226210. #endif
  226211. for (unsigned int i = 0; i < [fonts count]; ++i)
  226212. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226213. names.sort (true);
  226214. return names;
  226215. }
  226216. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226217. {
  226218. #if JUCE_IPHONE
  226219. defaultSans = "Helvetica";
  226220. defaultSerif = "Times New Roman";
  226221. defaultFixed = "Courier New";
  226222. #else
  226223. defaultSans = "Lucida Grande";
  226224. defaultSerif = "Times New Roman";
  226225. defaultFixed = "Monaco";
  226226. #endif
  226227. }
  226228. #endif
  226229. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226230. // (must go before juce_mac_CoreGraphicsContext.mm)
  226231. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226232. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226233. // compiled on its own).
  226234. #if JUCE_INCLUDED_FILE
  226235. class CoreGraphicsImage : public Image
  226236. {
  226237. public:
  226238. CoreGraphicsImage (const PixelFormat format_,
  226239. const int imageWidth_,
  226240. const int imageHeight_,
  226241. const bool clearImage)
  226242. : Image (format_, imageWidth_, imageHeight_, clearImage)
  226243. {
  226244. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226245. : CGColorSpaceCreateDeviceRGB();
  226246. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  226247. colourSpace, getCGImageFlags (*this));
  226248. CGColorSpaceRelease (colourSpace);
  226249. }
  226250. ~CoreGraphicsImage()
  226251. {
  226252. CGContextRelease (context);
  226253. }
  226254. LowLevelGraphicsContext* createLowLevelContext();
  226255. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226256. {
  226257. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  226258. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226259. {
  226260. return CGBitmapContextCreateImage (nativeImage->context);
  226261. }
  226262. else
  226263. {
  226264. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  226265. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226266. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226267. 8, srcData.pixelStride * 8, srcData.lineStride,
  226268. colourSpace, getCGImageFlags (juceImage), provider,
  226269. 0, true, kCGRenderingIntentDefault);
  226270. CGDataProviderRelease (provider);
  226271. return imageRef;
  226272. }
  226273. }
  226274. #if JUCE_MAC
  226275. static NSImage* createNSImage (const Image& image)
  226276. {
  226277. const ScopedAutoReleasePool pool;
  226278. NSImage* im = [[NSImage alloc] init];
  226279. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226280. [im lockFocus];
  226281. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226282. CGImageRef imageRef = createImage (image, false, colourSpace);
  226283. CGColorSpaceRelease (colourSpace);
  226284. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226285. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226286. CGImageRelease (imageRef);
  226287. [im unlockFocus];
  226288. return im;
  226289. }
  226290. #endif
  226291. CGContextRef context;
  226292. private:
  226293. static CGBitmapInfo getCGImageFlags (const Image& image)
  226294. {
  226295. #if JUCE_BIG_ENDIAN
  226296. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226297. #else
  226298. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226299. #endif
  226300. }
  226301. };
  226302. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  226303. {
  226304. #if USE_COREGRAPHICS_RENDERING
  226305. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  226306. #else
  226307. return new Image (format, imageWidth, imageHeight, clearImage);
  226308. #endif
  226309. }
  226310. class CoreGraphicsContext : public LowLevelGraphicsContext
  226311. {
  226312. public:
  226313. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226314. : context (context_),
  226315. flipHeight (flipHeight_),
  226316. state (new SavedState()),
  226317. numGradientLookupEntries (0)
  226318. {
  226319. CGContextRetain (context);
  226320. CGContextSaveGState(context);
  226321. CGContextSetShouldSmoothFonts (context, true);
  226322. CGContextSetShouldAntialias (context, true);
  226323. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226324. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226325. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226326. gradientCallbacks.version = 0;
  226327. gradientCallbacks.evaluate = gradientCallback;
  226328. gradientCallbacks.releaseInfo = 0;
  226329. setFont (Font());
  226330. }
  226331. ~CoreGraphicsContext()
  226332. {
  226333. CGContextRestoreGState (context);
  226334. CGContextRelease (context);
  226335. CGColorSpaceRelease (rgbColourSpace);
  226336. CGColorSpaceRelease (greyColourSpace);
  226337. }
  226338. bool isVectorDevice() const { return false; }
  226339. void setOrigin (int x, int y)
  226340. {
  226341. CGContextTranslateCTM (context, x, -y);
  226342. }
  226343. bool clipToRectangle (const Rectangle<int>& r)
  226344. {
  226345. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226346. return ! isClipEmpty();
  226347. }
  226348. bool clipToRectangleList (const RectangleList& clipRegion)
  226349. {
  226350. if (clipRegion.isEmpty())
  226351. {
  226352. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226353. return false;
  226354. }
  226355. else
  226356. {
  226357. const int numRects = clipRegion.getNumRectangles();
  226358. HeapBlock <CGRect> rects (numRects);
  226359. for (int i = 0; i < numRects; ++i)
  226360. {
  226361. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226362. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226363. }
  226364. CGContextClipToRects (context, rects, numRects);
  226365. return ! isClipEmpty();
  226366. }
  226367. }
  226368. void excludeClipRectangle (const Rectangle<int>& r)
  226369. {
  226370. RectangleList remaining (getClipBounds());
  226371. remaining.subtract (r);
  226372. clipToRectangleList (remaining);
  226373. }
  226374. void clipToPath (const Path& path, const AffineTransform& transform)
  226375. {
  226376. createPath (path, transform);
  226377. CGContextClip (context);
  226378. }
  226379. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  226380. {
  226381. if (! transform.isSingularity())
  226382. {
  226383. ScopedPointer<Image> imageToDelete;
  226384. const Image* singleChannelImage = &sourceImage;
  226385. if (sourceImage.getFormat() != Image::SingleChannel)
  226386. {
  226387. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  226388. singleChannelImage = imageToDelete;
  226389. }
  226390. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  226391. flip();
  226392. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226393. applyTransform (t);
  226394. CGRect r = CGRectMake (srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  226395. CGContextClipToMask (context, r, image);
  226396. applyTransform (t.inverted());
  226397. flip();
  226398. CGImageRelease (image);
  226399. }
  226400. }
  226401. bool clipRegionIntersects (const Rectangle<int>& r)
  226402. {
  226403. return getClipBounds().intersects (r);
  226404. }
  226405. const Rectangle<int> getClipBounds() const
  226406. {
  226407. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226408. return Rectangle<int> (roundToInt (bounds.origin.x),
  226409. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226410. roundToInt (bounds.size.width),
  226411. roundToInt (bounds.size.height));
  226412. }
  226413. bool isClipEmpty() const
  226414. {
  226415. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  226416. }
  226417. void saveState()
  226418. {
  226419. CGContextSaveGState (context);
  226420. stateStack.add (new SavedState (*state));
  226421. }
  226422. void restoreState()
  226423. {
  226424. CGContextRestoreGState (context);
  226425. SavedState* const top = stateStack.getLast();
  226426. if (top != 0)
  226427. {
  226428. state = top;
  226429. stateStack.removeLast (1, false);
  226430. }
  226431. else
  226432. {
  226433. jassertfalse // trying to pop with an empty stack!
  226434. }
  226435. }
  226436. void setFill (const FillType& fillType)
  226437. {
  226438. state->fillType = fillType;
  226439. if (fillType.isColour())
  226440. {
  226441. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226442. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226443. CGContextSetAlpha (context, 1.0f);
  226444. }
  226445. }
  226446. void setOpacity (float newOpacity)
  226447. {
  226448. state->fillType.setOpacity (newOpacity);
  226449. setFill (state->fillType);
  226450. }
  226451. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226452. {
  226453. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226454. ? kCGInterpolationLow
  226455. : kCGInterpolationHigh);
  226456. }
  226457. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226458. {
  226459. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226460. if (replaceExistingContents)
  226461. {
  226462. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226463. CGContextClearRect (context, cgRect);
  226464. #else
  226465. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226466. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226467. CGContextClearRect (context, cgRect);
  226468. else
  226469. #endif
  226470. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226471. #endif
  226472. fillRect (r, false);
  226473. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226474. }
  226475. else
  226476. {
  226477. if (state->fillType.isColour())
  226478. {
  226479. CGContextFillRect (context, cgRect);
  226480. }
  226481. else if (state->fillType.isGradient())
  226482. {
  226483. CGContextSaveGState (context);
  226484. CGContextClipToRect (context, cgRect);
  226485. drawGradient();
  226486. CGContextRestoreGState (context);
  226487. }
  226488. else
  226489. {
  226490. CGContextSaveGState (context);
  226491. CGContextClipToRect (context, cgRect);
  226492. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  226493. CGContextRestoreGState (context);
  226494. }
  226495. }
  226496. }
  226497. void fillPath (const Path& path, const AffineTransform& transform)
  226498. {
  226499. CGContextSaveGState (context);
  226500. if (state->fillType.isColour())
  226501. {
  226502. flip();
  226503. applyTransform (transform);
  226504. createPath (path);
  226505. if (path.isUsingNonZeroWinding())
  226506. CGContextFillPath (context);
  226507. else
  226508. CGContextEOFillPath (context);
  226509. }
  226510. else
  226511. {
  226512. createPath (path, transform);
  226513. if (path.isUsingNonZeroWinding())
  226514. CGContextClip (context);
  226515. else
  226516. CGContextEOClip (context);
  226517. if (state->fillType.isGradient())
  226518. drawGradient();
  226519. else
  226520. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  226521. }
  226522. CGContextRestoreGState (context);
  226523. }
  226524. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  226525. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226526. {
  226527. jassert (sourceImage.getBounds().contains (srcClip));
  226528. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226529. CGImageRef image = fullImage;
  226530. if (srcClip != sourceImage.getBounds())
  226531. {
  226532. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  226533. srcClip.getWidth(), srcClip.getHeight()));
  226534. CGImageRelease (fullImage);
  226535. }
  226536. CGContextSaveGState (context);
  226537. CGContextSetAlpha (context, state->fillType.getOpacity());
  226538. flip();
  226539. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  226540. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  226541. if (fillEntireClipAsTiles)
  226542. {
  226543. #if JUCE_IPHONE
  226544. CGContextDrawTiledImage (context, imageRect, image);
  226545. #else
  226546. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226547. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226548. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226549. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226550. CGContextDrawTiledImage (context, imageRect, image);
  226551. else
  226552. #endif
  226553. {
  226554. // Fallback to manually doing a tiled fill on 10.4
  226555. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226556. const int iw = srcClip.getWidth();
  226557. const int ih = srcClip.getHeight();
  226558. int x = 0, y = 0;
  226559. while (x > clip.origin.x) x -= iw;
  226560. while (y > clip.origin.y) y -= ih;
  226561. const int right = (int) (clip.origin.x + clip.size.width);
  226562. const int bottom = (int) (clip.origin.y + clip.size.height);
  226563. while (y < bottom)
  226564. {
  226565. for (int x2 = x; x2 < right; x2 += iw)
  226566. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226567. y += ih;
  226568. }
  226569. }
  226570. #endif
  226571. }
  226572. else
  226573. {
  226574. CGContextDrawImage (context, imageRect, image);
  226575. }
  226576. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226577. CGContextRestoreGState (context);
  226578. }
  226579. void drawLine (double x1, double y1, double x2, double y2)
  226580. {
  226581. CGContextSetLineCap (context, kCGLineCapSquare);
  226582. CGContextSetLineWidth (context, 1.0f);
  226583. CGContextSetRGBStrokeColor (context,
  226584. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226585. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226586. CGPoint line[] = { { (CGFloat) x1, flipHeight - (CGFloat) y1 },
  226587. { (CGFloat) x2, flipHeight - (CGFloat) y2 } };
  226588. CGContextStrokeLineSegments (context, line, 1);
  226589. }
  226590. void drawVerticalLine (const int x, double top, double bottom)
  226591. {
  226592. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226593. CGContextFillRect (context, CGRectMake (x, flipHeight - (float) bottom, 1.0f, (float) (bottom - top)));
  226594. #else
  226595. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226596. // the x co-ord slightly to trick it..
  226597. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - (float) bottom, 1.0f + 1.0f / 256.0f, (float) (bottom - top)));
  226598. #endif
  226599. }
  226600. void drawHorizontalLine (const int y, double left, double right)
  226601. {
  226602. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226603. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + 1.0f), (float) (right - left), 1.0f));
  226604. #else
  226605. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226606. // the x co-ord slightly to trick it..
  226607. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), (float) (right - left), 1.0f + 1.0f / 256.0f));
  226608. #endif
  226609. }
  226610. void setFont (const Font& newFont)
  226611. {
  226612. if (state->font != newFont)
  226613. {
  226614. state->fontRef = 0;
  226615. state->font = newFont;
  226616. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226617. if (mf != 0)
  226618. {
  226619. state->fontRef = mf->fontRef;
  226620. CGContextSetFont (context, state->fontRef);
  226621. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226622. state->fontTransform = mf->renderingTransform;
  226623. state->fontTransform.a *= state->font.getHorizontalScale();
  226624. CGContextSetTextMatrix (context, state->fontTransform);
  226625. }
  226626. }
  226627. }
  226628. const Font getFont()
  226629. {
  226630. return state->font;
  226631. }
  226632. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226633. {
  226634. if (state->fontRef != 0 && state->fillType.isColour())
  226635. {
  226636. if (transform.isOnlyTranslation())
  226637. {
  226638. CGGlyph g = glyphNumber;
  226639. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226640. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226641. }
  226642. else
  226643. {
  226644. CGContextSaveGState (context);
  226645. flip();
  226646. applyTransform (transform);
  226647. CGAffineTransform t = state->fontTransform;
  226648. t.d = -t.d;
  226649. CGContextSetTextMatrix (context, t);
  226650. CGGlyph g = glyphNumber;
  226651. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226652. CGContextSetTextMatrix (context, state->fontTransform);
  226653. CGContextRestoreGState (context);
  226654. }
  226655. }
  226656. else
  226657. {
  226658. Path p;
  226659. Font& f = state->font;
  226660. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226661. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226662. .followedBy (transform));
  226663. }
  226664. }
  226665. private:
  226666. CGContextRef context;
  226667. const CGFloat flipHeight;
  226668. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226669. CGFunctionCallbacks gradientCallbacks;
  226670. struct SavedState
  226671. {
  226672. SavedState()
  226673. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226674. {
  226675. }
  226676. SavedState (const SavedState& other)
  226677. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226678. fontTransform (other.fontTransform)
  226679. {
  226680. }
  226681. ~SavedState()
  226682. {
  226683. }
  226684. FillType fillType;
  226685. Font font;
  226686. CGFontRef fontRef;
  226687. CGAffineTransform fontTransform;
  226688. };
  226689. ScopedPointer <SavedState> state;
  226690. OwnedArray <SavedState> stateStack;
  226691. HeapBlock <PixelARGB> gradientLookupTable;
  226692. int numGradientLookupEntries;
  226693. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226694. {
  226695. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226696. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226697. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226698. colour.unpremultiply();
  226699. outData[0] = colour.getRed() / 255.0f;
  226700. outData[1] = colour.getGreen() / 255.0f;
  226701. outData[2] = colour.getBlue() / 255.0f;
  226702. outData[3] = colour.getAlpha() / 255.0f;
  226703. }
  226704. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226705. {
  226706. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  226707. --numGradientLookupEntries;
  226708. CGShadingRef result = 0;
  226709. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226710. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  226711. if (gradient.isRadial)
  226712. {
  226713. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226714. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  226715. function, true, true);
  226716. }
  226717. else
  226718. {
  226719. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226720. CGPointMake (gradient.x2, gradient.y2),
  226721. function, true, true);
  226722. }
  226723. CGFunctionRelease (function);
  226724. return result;
  226725. }
  226726. void drawGradient()
  226727. {
  226728. flip();
  226729. applyTransform (state->fillType.transform);
  226730. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226731. // you draw a gradient with high quality interp enabled).
  226732. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226733. CGContextSetAlpha (context, state->fillType.getOpacity());
  226734. CGContextDrawShading (context, shading);
  226735. CGShadingRelease (shading);
  226736. }
  226737. void createPath (const Path& path) const
  226738. {
  226739. CGContextBeginPath (context);
  226740. Path::Iterator i (path);
  226741. while (i.next())
  226742. {
  226743. switch (i.elementType)
  226744. {
  226745. case Path::Iterator::startNewSubPath:
  226746. CGContextMoveToPoint (context, i.x1, i.y1);
  226747. break;
  226748. case Path::Iterator::lineTo:
  226749. CGContextAddLineToPoint (context, i.x1, i.y1);
  226750. break;
  226751. case Path::Iterator::quadraticTo:
  226752. CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2);
  226753. break;
  226754. case Path::Iterator::cubicTo:
  226755. CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226756. break;
  226757. case Path::Iterator::closePath:
  226758. CGContextClosePath (context); break;
  226759. default:
  226760. jassertfalse
  226761. break;
  226762. }
  226763. }
  226764. }
  226765. void createPath (const Path& path, const AffineTransform& transform) const
  226766. {
  226767. CGContextBeginPath (context);
  226768. Path::Iterator i (path);
  226769. while (i.next())
  226770. {
  226771. switch (i.elementType)
  226772. {
  226773. case Path::Iterator::startNewSubPath:
  226774. transform.transformPoint (i.x1, i.y1);
  226775. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226776. break;
  226777. case Path::Iterator::lineTo:
  226778. transform.transformPoint (i.x1, i.y1);
  226779. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226780. break;
  226781. case Path::Iterator::quadraticTo:
  226782. transform.transformPoint (i.x1, i.y1);
  226783. transform.transformPoint (i.x2, i.y2);
  226784. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226785. break;
  226786. case Path::Iterator::cubicTo:
  226787. transform.transformPoint (i.x1, i.y1);
  226788. transform.transformPoint (i.x2, i.y2);
  226789. transform.transformPoint (i.x3, i.y3);
  226790. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226791. break;
  226792. case Path::Iterator::closePath:
  226793. CGContextClosePath (context); break;
  226794. default:
  226795. jassertfalse
  226796. break;
  226797. }
  226798. }
  226799. }
  226800. void flip() const
  226801. {
  226802. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226803. }
  226804. void applyTransform (const AffineTransform& transform) const
  226805. {
  226806. CGAffineTransform t;
  226807. t.a = transform.mat00;
  226808. t.b = transform.mat10;
  226809. t.c = transform.mat01;
  226810. t.d = transform.mat11;
  226811. t.tx = transform.mat02;
  226812. t.ty = transform.mat12;
  226813. CGContextConcatCTM (context, t);
  226814. }
  226815. CoreGraphicsContext (const CoreGraphicsContext&);
  226816. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  226817. };
  226818. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226819. {
  226820. return new CoreGraphicsContext (context, imageHeight);
  226821. }
  226822. #endif
  226823. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226824. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  226825. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226826. // compiled on its own).
  226827. #if JUCE_INCLUDED_FILE
  226828. class NSViewComponentPeer;
  226829. END_JUCE_NAMESPACE
  226830. #define JuceNSView MakeObjCClassName(JuceNSView)
  226831. @interface JuceNSView : NSView<NSTextInput>
  226832. {
  226833. @public
  226834. NSViewComponentPeer* owner;
  226835. NSNotificationCenter* notificationCenter;
  226836. String* stringBeingComposed;
  226837. bool textWasInserted;
  226838. }
  226839. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  226840. - (void) dealloc;
  226841. - (BOOL) isOpaque;
  226842. - (void) drawRect: (NSRect) r;
  226843. - (void) mouseDown: (NSEvent*) ev;
  226844. - (void) asyncMouseDown: (NSEvent*) ev;
  226845. - (void) mouseUp: (NSEvent*) ev;
  226846. - (void) asyncMouseUp: (NSEvent*) ev;
  226847. - (void) mouseDragged: (NSEvent*) ev;
  226848. - (void) mouseMoved: (NSEvent*) ev;
  226849. - (void) mouseEntered: (NSEvent*) ev;
  226850. - (void) mouseExited: (NSEvent*) ev;
  226851. - (void) rightMouseDown: (NSEvent*) ev;
  226852. - (void) rightMouseDragged: (NSEvent*) ev;
  226853. - (void) rightMouseUp: (NSEvent*) ev;
  226854. - (void) otherMouseDown: (NSEvent*) ev;
  226855. - (void) otherMouseDragged: (NSEvent*) ev;
  226856. - (void) otherMouseUp: (NSEvent*) ev;
  226857. - (void) scrollWheel: (NSEvent*) ev;
  226858. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  226859. - (void) frameChanged: (NSNotification*) n;
  226860. - (void) viewDidMoveToWindow;
  226861. - (void) keyDown: (NSEvent*) ev;
  226862. - (void) keyUp: (NSEvent*) ev;
  226863. // NSTextInput Methods
  226864. - (void) insertText: (id) aString;
  226865. - (void) doCommandBySelector: (SEL) aSelector;
  226866. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  226867. - (void) unmarkText;
  226868. - (BOOL) hasMarkedText;
  226869. - (long) conversationIdentifier;
  226870. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  226871. - (NSRange) markedRange;
  226872. - (NSRange) selectedRange;
  226873. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  226874. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  226875. - (NSArray*) validAttributesForMarkedText;
  226876. - (void) flagsChanged: (NSEvent*) ev;
  226877. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226878. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  226879. #endif
  226880. - (BOOL) becomeFirstResponder;
  226881. - (BOOL) resignFirstResponder;
  226882. - (BOOL) acceptsFirstResponder;
  226883. - (void) asyncRepaint: (id) rect;
  226884. - (NSArray*) getSupportedDragTypes;
  226885. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  226886. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  226887. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  226888. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  226889. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  226890. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  226891. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  226892. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  226893. @end
  226894. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  226895. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226896. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  226897. #else
  226898. @interface JuceNSWindow : NSWindow
  226899. #endif
  226900. {
  226901. @private
  226902. NSViewComponentPeer* owner;
  226903. bool isZooming;
  226904. }
  226905. - (void) setOwner: (NSViewComponentPeer*) owner;
  226906. - (BOOL) canBecomeKeyWindow;
  226907. - (void) becomeKeyWindow;
  226908. - (BOOL) windowShouldClose: (id) window;
  226909. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  226910. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  226911. - (void) zoom: (id) sender;
  226912. @end
  226913. BEGIN_JUCE_NAMESPACE
  226914. class NSViewComponentPeer : public ComponentPeer
  226915. {
  226916. public:
  226917. NSViewComponentPeer (Component* const component,
  226918. const int windowStyleFlags,
  226919. NSView* viewToAttachTo);
  226920. ~NSViewComponentPeer();
  226921. void* getNativeHandle() const;
  226922. void setVisible (bool shouldBeVisible);
  226923. void setTitle (const String& title);
  226924. void setPosition (int x, int y);
  226925. void setSize (int w, int h);
  226926. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  226927. const Rectangle<int> getBounds (const bool global) const;
  226928. const Rectangle<int> getBounds() const;
  226929. const Point<int> getScreenPosition() const;
  226930. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  226931. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  226932. void setMinimised (bool shouldBeMinimised);
  226933. bool isMinimised() const;
  226934. void setFullScreen (bool shouldBeFullScreen);
  226935. bool isFullScreen() const;
  226936. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226937. const BorderSize getFrameSize() const;
  226938. bool setAlwaysOnTop (bool alwaysOnTop);
  226939. void toFront (bool makeActiveWindow);
  226940. void toBehind (ComponentPeer* other);
  226941. void setIcon (const Image& newIcon);
  226942. const StringArray getAvailableRenderingEngines() throw();
  226943. int getCurrentRenderingEngine() throw();
  226944. void setCurrentRenderingEngine (int index) throw();
  226945. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  226946. for example having more than one juce plugin loaded into a host, then when a
  226947. method is called, the actual code that runs might actually be in a different module
  226948. than the one you expect... So any calls to library functions or statics that are
  226949. made inside obj-c methods will probably end up getting executed in a different DLL's
  226950. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  226951. To work around this insanity, I'm only allowing obj-c methods to make calls to
  226952. virtual methods of an object that's known to live inside the right module's space.
  226953. */
  226954. virtual void redirectMouseDown (NSEvent* ev);
  226955. virtual void redirectMouseUp (NSEvent* ev);
  226956. virtual void redirectMouseDrag (NSEvent* ev);
  226957. virtual void redirectMouseMove (NSEvent* ev);
  226958. virtual void redirectMouseEnter (NSEvent* ev);
  226959. virtual void redirectMouseExit (NSEvent* ev);
  226960. virtual void redirectMouseWheel (NSEvent* ev);
  226961. void sendMouseEvent (NSEvent* ev);
  226962. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  226963. virtual bool redirectKeyDown (NSEvent* ev);
  226964. virtual bool redirectKeyUp (NSEvent* ev);
  226965. virtual void redirectModKeyChange (NSEvent* ev);
  226966. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226967. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  226968. #endif
  226969. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  226970. virtual bool isOpaque();
  226971. virtual void drawRect (NSRect r);
  226972. virtual bool canBecomeKeyWindow();
  226973. virtual bool windowShouldClose();
  226974. virtual void redirectMovedOrResized();
  226975. virtual void viewMovedToWindow();
  226976. virtual NSRect constrainRect (NSRect r);
  226977. static void showArrowCursorIfNeeded();
  226978. static void updateModifiers (NSEvent* e);
  226979. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  226980. static int getKeyCodeFromEvent (NSEvent* ev)
  226981. {
  226982. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  226983. int keyCode = unmodified[0];
  226984. if (keyCode == 0x19) // (backwards-tab)
  226985. keyCode = '\t';
  226986. else if (keyCode == 0x03) // (enter)
  226987. keyCode = '\r';
  226988. return keyCode;
  226989. }
  226990. static int64 getMouseTime (NSEvent* e)
  226991. {
  226992. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226993. + (int64) ([e timestamp] * 1000.0);
  226994. }
  226995. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  226996. {
  226997. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  226998. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  226999. }
  227000. static int getModifierForButtonNumber (const NSInteger num)
  227001. {
  227002. return num == 0 ? ModifierKeys::leftButtonModifier
  227003. : (num == 1 ? ModifierKeys::rightButtonModifier
  227004. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  227005. }
  227006. virtual void viewFocusGain();
  227007. virtual void viewFocusLoss();
  227008. bool isFocused() const;
  227009. void grabFocus();
  227010. void textInputRequired (const Point<int>& position);
  227011. void repaint (int x, int y, int w, int h);
  227012. void performAnyPendingRepaintsNow();
  227013. juce_UseDebuggingNewOperator
  227014. NSWindow* window;
  227015. JuceNSView* view;
  227016. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  227017. static ModifierKeys currentModifiers;
  227018. static ComponentPeer* currentlyFocusedPeer;
  227019. static Array<int> keysCurrentlyDown;
  227020. };
  227021. END_JUCE_NAMESPACE
  227022. @implementation JuceNSView
  227023. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  227024. withFrame: (NSRect) frame
  227025. {
  227026. [super initWithFrame: frame];
  227027. owner = owner_;
  227028. stringBeingComposed = 0;
  227029. textWasInserted = false;
  227030. notificationCenter = [NSNotificationCenter defaultCenter];
  227031. [notificationCenter addObserver: self
  227032. selector: @selector (frameChanged:)
  227033. name: NSViewFrameDidChangeNotification
  227034. object: self];
  227035. if (! owner_->isSharedWindow)
  227036. {
  227037. [notificationCenter addObserver: self
  227038. selector: @selector (frameChanged:)
  227039. name: NSWindowDidMoveNotification
  227040. object: owner_->window];
  227041. }
  227042. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  227043. return self;
  227044. }
  227045. - (void) dealloc
  227046. {
  227047. [notificationCenter removeObserver: self];
  227048. delete stringBeingComposed;
  227049. [super dealloc];
  227050. }
  227051. - (void) drawRect: (NSRect) r
  227052. {
  227053. if (owner != 0)
  227054. owner->drawRect (r);
  227055. }
  227056. - (BOOL) isOpaque
  227057. {
  227058. return owner == 0 || owner->isOpaque();
  227059. }
  227060. - (void) mouseDown: (NSEvent*) ev
  227061. {
  227062. // In some host situations, the host will stop modal loops from working
  227063. // correctly if they're called from a mouse event, so we'll trigger
  227064. // the event asynchronously..
  227065. if (JUCEApplication::getInstance() == 0)
  227066. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  227067. withObject: ev
  227068. waitUntilDone: NO];
  227069. else
  227070. [self asyncMouseDown: ev];
  227071. }
  227072. - (void) asyncMouseDown: (NSEvent*) ev
  227073. {
  227074. if (owner != 0)
  227075. owner->redirectMouseDown (ev);
  227076. }
  227077. - (void) mouseUp: (NSEvent*) ev
  227078. {
  227079. // In some host situations, the host will stop modal loops from working
  227080. // correctly if they're called from a mouse event, so we'll trigger
  227081. // the event asynchronously..
  227082. if (JUCEApplication::getInstance() == 0)
  227083. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  227084. withObject: ev
  227085. waitUntilDone: NO];
  227086. else
  227087. [self asyncMouseUp: ev];
  227088. }
  227089. - (void) asyncMouseUp: (NSEvent*) ev
  227090. {
  227091. if (owner != 0)
  227092. owner->redirectMouseUp (ev);
  227093. }
  227094. - (void) mouseDragged: (NSEvent*) ev
  227095. {
  227096. if (owner != 0)
  227097. owner->redirectMouseDrag (ev);
  227098. }
  227099. - (void) mouseMoved: (NSEvent*) ev
  227100. {
  227101. if (owner != 0)
  227102. owner->redirectMouseMove (ev);
  227103. }
  227104. - (void) mouseEntered: (NSEvent*) ev
  227105. {
  227106. if (owner != 0)
  227107. owner->redirectMouseEnter (ev);
  227108. }
  227109. - (void) mouseExited: (NSEvent*) ev
  227110. {
  227111. if (owner != 0)
  227112. owner->redirectMouseExit (ev);
  227113. }
  227114. - (void) rightMouseDown: (NSEvent*) ev
  227115. {
  227116. [self mouseDown: ev];
  227117. }
  227118. - (void) rightMouseDragged: (NSEvent*) ev
  227119. {
  227120. [self mouseDragged: ev];
  227121. }
  227122. - (void) rightMouseUp: (NSEvent*) ev
  227123. {
  227124. [self mouseUp: ev];
  227125. }
  227126. - (void) otherMouseDown: (NSEvent*) ev
  227127. {
  227128. [self mouseDown: ev];
  227129. }
  227130. - (void) otherMouseDragged: (NSEvent*) ev
  227131. {
  227132. [self mouseDragged: ev];
  227133. }
  227134. - (void) otherMouseUp: (NSEvent*) ev
  227135. {
  227136. [self mouseUp: ev];
  227137. }
  227138. - (void) scrollWheel: (NSEvent*) ev
  227139. {
  227140. if (owner != 0)
  227141. owner->redirectMouseWheel (ev);
  227142. }
  227143. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  227144. {
  227145. (void) ev;
  227146. return YES;
  227147. }
  227148. - (void) frameChanged: (NSNotification*) n
  227149. {
  227150. (void) n;
  227151. if (owner != 0)
  227152. owner->redirectMovedOrResized();
  227153. }
  227154. - (void) viewDidMoveToWindow
  227155. {
  227156. if (owner != 0)
  227157. owner->viewMovedToWindow();
  227158. }
  227159. - (void) asyncRepaint: (id) rect
  227160. {
  227161. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  227162. [self setNeedsDisplayInRect: *r];
  227163. }
  227164. - (void) keyDown: (NSEvent*) ev
  227165. {
  227166. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227167. textWasInserted = false;
  227168. if (target != 0)
  227169. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  227170. else
  227171. deleteAndZero (stringBeingComposed);
  227172. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  227173. [super keyDown: ev];
  227174. }
  227175. - (void) keyUp: (NSEvent*) ev
  227176. {
  227177. if (owner == 0 || ! owner->redirectKeyUp (ev))
  227178. [super keyUp: ev];
  227179. }
  227180. - (void) insertText: (id) aString
  227181. {
  227182. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  227183. if ([aString length] > 0)
  227184. {
  227185. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227186. if (target != 0)
  227187. {
  227188. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  227189. textWasInserted = true;
  227190. }
  227191. }
  227192. deleteAndZero (stringBeingComposed);
  227193. }
  227194. - (void) doCommandBySelector: (SEL) aSelector
  227195. {
  227196. (void) aSelector;
  227197. }
  227198. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  227199. {
  227200. (void) selectionRange;
  227201. if (stringBeingComposed == 0)
  227202. stringBeingComposed = new String();
  227203. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  227204. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227205. if (target != 0)
  227206. {
  227207. const Range<int> currentHighlight (target->getHighlightedRegion());
  227208. target->insertTextAtCaret (*stringBeingComposed);
  227209. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  227210. textWasInserted = true;
  227211. }
  227212. }
  227213. - (void) unmarkText
  227214. {
  227215. if (stringBeingComposed != 0)
  227216. {
  227217. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227218. if (target != 0)
  227219. {
  227220. target->insertTextAtCaret (*stringBeingComposed);
  227221. textWasInserted = true;
  227222. }
  227223. }
  227224. deleteAndZero (stringBeingComposed);
  227225. }
  227226. - (BOOL) hasMarkedText
  227227. {
  227228. return stringBeingComposed != 0;
  227229. }
  227230. - (long) conversationIdentifier
  227231. {
  227232. return (long) (pointer_sized_int) self;
  227233. }
  227234. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  227235. {
  227236. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227237. if (target != 0)
  227238. {
  227239. const Range<int> r ((int) theRange.location,
  227240. (int) (theRange.location + theRange.length));
  227241. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  227242. }
  227243. return nil;
  227244. }
  227245. - (NSRange) markedRange
  227246. {
  227247. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  227248. : NSMakeRange (NSNotFound, 0);
  227249. }
  227250. - (NSRange) selectedRange
  227251. {
  227252. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227253. if (target != 0)
  227254. {
  227255. const Range<int> highlight (target->getHighlightedRegion());
  227256. if (! highlight.isEmpty())
  227257. return NSMakeRange (highlight.getStart(), highlight.getLength());
  227258. }
  227259. return NSMakeRange (NSNotFound, 0);
  227260. }
  227261. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  227262. {
  227263. (void) theRange;
  227264. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  227265. if (comp == 0)
  227266. return NSMakeRect (0, 0, 0, 0);
  227267. const Rectangle<int> bounds (comp->getScreenBounds());
  227268. return NSMakeRect (bounds.getX(),
  227269. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  227270. bounds.getWidth(),
  227271. bounds.getHeight());
  227272. }
  227273. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  227274. {
  227275. (void) thePoint;
  227276. return NSNotFound;
  227277. }
  227278. - (NSArray*) validAttributesForMarkedText
  227279. {
  227280. return [NSArray array];
  227281. }
  227282. - (void) flagsChanged: (NSEvent*) ev
  227283. {
  227284. if (owner != 0)
  227285. owner->redirectModKeyChange (ev);
  227286. }
  227287. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227288. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  227289. {
  227290. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  227291. return true;
  227292. return [super performKeyEquivalent: ev];
  227293. }
  227294. #endif
  227295. - (BOOL) becomeFirstResponder
  227296. {
  227297. if (owner != 0)
  227298. owner->viewFocusGain();
  227299. return true;
  227300. }
  227301. - (BOOL) resignFirstResponder
  227302. {
  227303. if (owner != 0)
  227304. owner->viewFocusLoss();
  227305. return true;
  227306. }
  227307. - (BOOL) acceptsFirstResponder
  227308. {
  227309. return owner != 0 && owner->canBecomeKeyWindow();
  227310. }
  227311. - (NSArray*) getSupportedDragTypes
  227312. {
  227313. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  227314. }
  227315. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  227316. {
  227317. return owner != 0 && owner->sendDragCallback (type, sender);
  227318. }
  227319. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  227320. {
  227321. if ([self sendDragCallback: 0 sender: sender])
  227322. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227323. else
  227324. return NSDragOperationNone;
  227325. }
  227326. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  227327. {
  227328. if ([self sendDragCallback: 0 sender: sender])
  227329. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227330. else
  227331. return NSDragOperationNone;
  227332. }
  227333. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  227334. {
  227335. [self sendDragCallback: 1 sender: sender];
  227336. }
  227337. - (void) draggingExited: (id <NSDraggingInfo>) sender
  227338. {
  227339. [self sendDragCallback: 1 sender: sender];
  227340. }
  227341. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  227342. {
  227343. (void) sender;
  227344. return YES;
  227345. }
  227346. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  227347. {
  227348. return [self sendDragCallback: 2 sender: sender];
  227349. }
  227350. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  227351. {
  227352. (void) sender;
  227353. }
  227354. @end
  227355. @implementation JuceNSWindow
  227356. - (void) setOwner: (NSViewComponentPeer*) owner_
  227357. {
  227358. owner = owner_;
  227359. isZooming = false;
  227360. }
  227361. - (BOOL) canBecomeKeyWindow
  227362. {
  227363. return owner != 0 && owner->canBecomeKeyWindow();
  227364. }
  227365. - (void) becomeKeyWindow
  227366. {
  227367. [super becomeKeyWindow];
  227368. if (owner != 0)
  227369. owner->grabFocus();
  227370. }
  227371. - (BOOL) windowShouldClose: (id) window
  227372. {
  227373. (void) window;
  227374. return owner == 0 || owner->windowShouldClose();
  227375. }
  227376. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  227377. {
  227378. (void) screen;
  227379. if (owner != 0)
  227380. frameRect = owner->constrainRect (frameRect);
  227381. return frameRect;
  227382. }
  227383. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  227384. {
  227385. (void) window;
  227386. if (isZooming)
  227387. return proposedFrameSize;
  227388. NSRect frameRect = [self frame];
  227389. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  227390. frameRect.size = proposedFrameSize;
  227391. if (owner != 0)
  227392. frameRect = owner->constrainRect (frameRect);
  227393. return frameRect.size;
  227394. }
  227395. - (void) zoom: (id) sender
  227396. {
  227397. isZooming = true;
  227398. [super zoom: sender];
  227399. isZooming = false;
  227400. }
  227401. - (void) windowWillMove: (NSNotification*) notification
  227402. {
  227403. (void) notification;
  227404. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  227405. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  227406. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  227407. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  227408. }
  227409. @end
  227410. BEGIN_JUCE_NAMESPACE
  227411. ModifierKeys NSViewComponentPeer::currentModifiers;
  227412. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  227413. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  227414. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227415. {
  227416. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  227417. return true;
  227418. if (keyCode >= 'A' && keyCode <= 'Z'
  227419. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  227420. return true;
  227421. if (keyCode >= 'a' && keyCode <= 'z'
  227422. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  227423. return true;
  227424. return false;
  227425. }
  227426. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  227427. {
  227428. int m = 0;
  227429. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  227430. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  227431. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  227432. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  227433. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  227434. }
  227435. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  227436. {
  227437. updateModifiers (ev);
  227438. int keyCode = getKeyCodeFromEvent (ev);
  227439. if (keyCode != 0)
  227440. {
  227441. if (isKeyDown)
  227442. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  227443. else
  227444. keysCurrentlyDown.removeValue (keyCode);
  227445. }
  227446. }
  227447. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227448. {
  227449. return NSViewComponentPeer::currentModifiers;
  227450. }
  227451. void ModifierKeys::updateCurrentModifiers() throw()
  227452. {
  227453. currentModifiers = NSViewComponentPeer::currentModifiers;
  227454. }
  227455. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  227456. const int windowStyleFlags,
  227457. NSView* viewToAttachTo)
  227458. : ComponentPeer (component_, windowStyleFlags),
  227459. window (0),
  227460. view (0),
  227461. isSharedWindow (viewToAttachTo != 0),
  227462. fullScreen (false),
  227463. insideDrawRect (false),
  227464. #if USE_COREGRAPHICS_RENDERING
  227465. usingCoreGraphics (true),
  227466. #else
  227467. usingCoreGraphics (false),
  227468. #endif
  227469. recursiveToFrontCall (false)
  227470. {
  227471. NSRect r;
  227472. r.origin.x = 0;
  227473. r.origin.y = 0;
  227474. r.size.width = (float) component->getWidth();
  227475. r.size.height = (float) component->getHeight();
  227476. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  227477. [view setPostsFrameChangedNotifications: YES];
  227478. if (isSharedWindow)
  227479. {
  227480. window = [viewToAttachTo window];
  227481. [viewToAttachTo addSubview: view];
  227482. setVisible (component->isVisible());
  227483. }
  227484. else
  227485. {
  227486. r.origin.x = (float) component->getX();
  227487. r.origin.y = (float) component->getY();
  227488. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  227489. unsigned int style = 0;
  227490. if ((windowStyleFlags & windowHasTitleBar) == 0)
  227491. style = NSBorderlessWindowMask;
  227492. else
  227493. style = NSTitledWindowMask;
  227494. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  227495. style |= NSMiniaturizableWindowMask;
  227496. if ((windowStyleFlags & windowHasCloseButton) != 0)
  227497. style |= NSClosableWindowMask;
  227498. if ((windowStyleFlags & windowIsResizable) != 0)
  227499. style |= NSResizableWindowMask;
  227500. window = [[JuceNSWindow alloc] initWithContentRect: r
  227501. styleMask: style
  227502. backing: NSBackingStoreBuffered
  227503. defer: YES];
  227504. [((JuceNSWindow*) window) setOwner: this];
  227505. [window orderOut: nil];
  227506. [window setDelegate: (JuceNSWindow*) window];
  227507. [window setOpaque: component->isOpaque()];
  227508. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  227509. if (component->isAlwaysOnTop())
  227510. [window setLevel: NSFloatingWindowLevel];
  227511. [window setContentView: view];
  227512. [window setAutodisplay: YES];
  227513. [window setAcceptsMouseMovedEvents: YES];
  227514. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  227515. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  227516. [window setReleasedWhenClosed: YES];
  227517. [window retain];
  227518. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  227519. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  227520. }
  227521. setTitle (component->getName());
  227522. }
  227523. NSViewComponentPeer::~NSViewComponentPeer()
  227524. {
  227525. view->owner = 0;
  227526. [view removeFromSuperview];
  227527. [view release];
  227528. if (! isSharedWindow)
  227529. {
  227530. [((JuceNSWindow*) window) setOwner: 0];
  227531. [window close];
  227532. [window release];
  227533. }
  227534. }
  227535. void* NSViewComponentPeer::getNativeHandle() const
  227536. {
  227537. return view;
  227538. }
  227539. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  227540. {
  227541. if (isSharedWindow)
  227542. {
  227543. [view setHidden: ! shouldBeVisible];
  227544. }
  227545. else
  227546. {
  227547. if (shouldBeVisible)
  227548. {
  227549. [window orderFront: nil];
  227550. handleBroughtToFront();
  227551. }
  227552. else
  227553. {
  227554. [window orderOut: nil];
  227555. }
  227556. }
  227557. }
  227558. void NSViewComponentPeer::setTitle (const String& title)
  227559. {
  227560. const ScopedAutoReleasePool pool;
  227561. if (! isSharedWindow)
  227562. [window setTitle: juceStringToNS (title)];
  227563. }
  227564. void NSViewComponentPeer::setPosition (int x, int y)
  227565. {
  227566. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227567. }
  227568. void NSViewComponentPeer::setSize (int w, int h)
  227569. {
  227570. setBounds (component->getX(), component->getY(), w, h, false);
  227571. }
  227572. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  227573. {
  227574. fullScreen = isNowFullScreen;
  227575. w = jmax (0, w);
  227576. h = jmax (0, h);
  227577. NSRect r;
  227578. r.origin.x = (float) x;
  227579. r.origin.y = (float) y;
  227580. r.size.width = (float) w;
  227581. r.size.height = (float) h;
  227582. if (isSharedWindow)
  227583. {
  227584. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227585. if ([view frame].size.width != r.size.width
  227586. || [view frame].size.height != r.size.height)
  227587. [view setNeedsDisplay: true];
  227588. [view setFrame: r];
  227589. }
  227590. else
  227591. {
  227592. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  227593. [window setFrame: [window frameRectForContentRect: r]
  227594. display: true];
  227595. }
  227596. }
  227597. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  227598. {
  227599. NSRect r = [view frame];
  227600. if (global && [view window] != 0)
  227601. {
  227602. r = [view convertRect: r toView: nil];
  227603. NSRect wr = [[view window] frame];
  227604. r.origin.x += wr.origin.x;
  227605. r.origin.y += wr.origin.y;
  227606. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  227607. }
  227608. else
  227609. {
  227610. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  227611. }
  227612. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  227613. }
  227614. const Rectangle<int> NSViewComponentPeer::getBounds() const
  227615. {
  227616. return getBounds (! isSharedWindow);
  227617. }
  227618. const Point<int> NSViewComponentPeer::getScreenPosition() const
  227619. {
  227620. return getBounds (true).getPosition();
  227621. }
  227622. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227623. {
  227624. return relativePosition + getScreenPosition();
  227625. }
  227626. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227627. {
  227628. return screenPosition - getScreenPosition();
  227629. }
  227630. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  227631. {
  227632. if (constrainer != 0)
  227633. {
  227634. NSRect current = [window frame];
  227635. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  227636. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  227637. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227638. (int) r.size.width, (int) r.size.height);
  227639. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227640. (int) current.size.width, (int) current.size.height);
  227641. constrainer->checkBounds (pos, original,
  227642. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227643. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227644. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227645. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227646. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227647. r.origin.x = pos.getX();
  227648. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  227649. r.size.width = pos.getWidth();
  227650. r.size.height = pos.getHeight();
  227651. }
  227652. return r;
  227653. }
  227654. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227655. {
  227656. if (! isSharedWindow)
  227657. {
  227658. if (shouldBeMinimised)
  227659. [window miniaturize: nil];
  227660. else
  227661. [window deminiaturize: nil];
  227662. }
  227663. }
  227664. bool NSViewComponentPeer::isMinimised() const
  227665. {
  227666. return window != 0 && [window isMiniaturized];
  227667. }
  227668. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227669. {
  227670. if (! isSharedWindow)
  227671. {
  227672. Rectangle<int> r (lastNonFullscreenBounds);
  227673. setMinimised (false);
  227674. if (fullScreen != shouldBeFullScreen)
  227675. {
  227676. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  227677. {
  227678. fullScreen = true;
  227679. [window performZoom: nil];
  227680. }
  227681. else
  227682. {
  227683. if (shouldBeFullScreen)
  227684. r = Desktop::getInstance().getMainMonitorArea();
  227685. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227686. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227687. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227688. }
  227689. }
  227690. }
  227691. }
  227692. bool NSViewComponentPeer::isFullScreen() const
  227693. {
  227694. return fullScreen;
  227695. }
  227696. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227697. {
  227698. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227699. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227700. return false;
  227701. NSPoint p;
  227702. p.x = (float) position.getX();
  227703. p.y = (float) position.getY();
  227704. NSView* v = [view hitTest: p];
  227705. if (trueIfInAChildWindow)
  227706. return v != nil;
  227707. return v == view;
  227708. }
  227709. const BorderSize NSViewComponentPeer::getFrameSize() const
  227710. {
  227711. BorderSize b;
  227712. if (! isSharedWindow)
  227713. {
  227714. NSRect v = [view convertRect: [view frame] toView: nil];
  227715. NSRect w = [window frame];
  227716. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227717. b.setBottom ((int) v.origin.y);
  227718. b.setLeft ((int) v.origin.x);
  227719. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227720. }
  227721. return b;
  227722. }
  227723. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227724. {
  227725. if (! isSharedWindow)
  227726. {
  227727. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  227728. : NSNormalWindowLevel];
  227729. }
  227730. return true;
  227731. }
  227732. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  227733. {
  227734. if (isSharedWindow)
  227735. {
  227736. [[view superview] addSubview: view
  227737. positioned: NSWindowAbove
  227738. relativeTo: nil];
  227739. }
  227740. if (window != 0 && component->isVisible())
  227741. {
  227742. if (makeActiveWindow)
  227743. [window makeKeyAndOrderFront: nil];
  227744. else
  227745. [window orderFront: nil];
  227746. if (! recursiveToFrontCall)
  227747. {
  227748. recursiveToFrontCall = true;
  227749. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  227750. handleBroughtToFront();
  227751. recursiveToFrontCall = false;
  227752. }
  227753. }
  227754. }
  227755. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  227756. {
  227757. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  227758. jassert (otherPeer != 0); // wrong type of window?
  227759. if (otherPeer != 0)
  227760. {
  227761. if (isSharedWindow)
  227762. {
  227763. [[view superview] addSubview: view
  227764. positioned: NSWindowBelow
  227765. relativeTo: otherPeer->view];
  227766. }
  227767. else
  227768. {
  227769. [window orderWindow: NSWindowBelow
  227770. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  227771. : nil ];
  227772. }
  227773. }
  227774. }
  227775. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227776. {
  227777. // to do..
  227778. }
  227779. void NSViewComponentPeer::viewFocusGain()
  227780. {
  227781. if (currentlyFocusedPeer != this)
  227782. {
  227783. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227784. currentlyFocusedPeer->handleFocusLoss();
  227785. currentlyFocusedPeer = this;
  227786. handleFocusGain();
  227787. }
  227788. }
  227789. void NSViewComponentPeer::viewFocusLoss()
  227790. {
  227791. if (currentlyFocusedPeer == this)
  227792. {
  227793. currentlyFocusedPeer = 0;
  227794. handleFocusLoss();
  227795. }
  227796. }
  227797. void juce_HandleProcessFocusChange()
  227798. {
  227799. NSViewComponentPeer::keysCurrentlyDown.clear();
  227800. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  227801. {
  227802. if (Process::isForegroundProcess())
  227803. {
  227804. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  227805. ComponentPeer::bringModalComponentToFront();
  227806. }
  227807. else
  227808. {
  227809. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  227810. // turn kiosk mode off if we lose focus..
  227811. Desktop::getInstance().setKioskModeComponent (0);
  227812. }
  227813. }
  227814. }
  227815. bool NSViewComponentPeer::isFocused() const
  227816. {
  227817. return isSharedWindow ? this == currentlyFocusedPeer
  227818. : (window != 0 && [window isKeyWindow]);
  227819. }
  227820. void NSViewComponentPeer::grabFocus()
  227821. {
  227822. if (window != 0)
  227823. {
  227824. [window makeKeyWindow];
  227825. [window makeFirstResponder: view];
  227826. viewFocusGain();
  227827. }
  227828. }
  227829. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  227830. {
  227831. }
  227832. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  227833. {
  227834. String unicode (nsStringToJuce ([ev characters]));
  227835. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  227836. int keyCode = getKeyCodeFromEvent (ev);
  227837. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  227838. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  227839. if (unicode.isNotEmpty() || keyCode != 0)
  227840. {
  227841. if (isKeyDown)
  227842. {
  227843. bool used = false;
  227844. while (unicode.length() > 0)
  227845. {
  227846. juce_wchar textCharacter = unicode[0];
  227847. unicode = unicode.substring (1);
  227848. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  227849. textCharacter = 0;
  227850. used = handleKeyUpOrDown (true) || used;
  227851. used = handleKeyPress (keyCode, textCharacter) || used;
  227852. }
  227853. return used;
  227854. }
  227855. else
  227856. {
  227857. if (handleKeyUpOrDown (false))
  227858. return true;
  227859. }
  227860. }
  227861. return false;
  227862. }
  227863. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  227864. {
  227865. updateKeysDown (ev, true);
  227866. bool used = handleKeyEvent (ev, true);
  227867. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  227868. {
  227869. // for command keys, the key-up event is thrown away, so simulate one..
  227870. updateKeysDown (ev, false);
  227871. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  227872. }
  227873. // (If we're running modally, don't allow unused keystrokes to be passed
  227874. // along to other blocked views..)
  227875. if (Component::getCurrentlyModalComponent() != 0)
  227876. used = true;
  227877. return used;
  227878. }
  227879. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  227880. {
  227881. updateKeysDown (ev, false);
  227882. return handleKeyEvent (ev, false)
  227883. || Component::getCurrentlyModalComponent() != 0;
  227884. }
  227885. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  227886. {
  227887. keysCurrentlyDown.clear();
  227888. handleKeyUpOrDown (true);
  227889. updateModifiers (ev);
  227890. handleModifierKeysChange();
  227891. }
  227892. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227893. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  227894. {
  227895. if ([ev type] == NSKeyDown)
  227896. return redirectKeyDown (ev);
  227897. else if ([ev type] == NSKeyUp)
  227898. return redirectKeyUp (ev);
  227899. return false;
  227900. }
  227901. #endif
  227902. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  227903. {
  227904. updateModifiers (ev);
  227905. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  227906. }
  227907. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  227908. {
  227909. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  227910. sendMouseEvent (ev);
  227911. }
  227912. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  227913. {
  227914. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  227915. sendMouseEvent (ev);
  227916. showArrowCursorIfNeeded();
  227917. }
  227918. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  227919. {
  227920. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  227921. sendMouseEvent (ev);
  227922. }
  227923. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  227924. {
  227925. currentModifiers = currentModifiers.withoutMouseButtons();
  227926. sendMouseEvent (ev);
  227927. showArrowCursorIfNeeded();
  227928. }
  227929. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  227930. {
  227931. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  227932. currentModifiers = currentModifiers.withoutMouseButtons();
  227933. sendMouseEvent (ev);
  227934. }
  227935. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  227936. {
  227937. currentModifiers = currentModifiers.withoutMouseButtons();
  227938. sendMouseEvent (ev);
  227939. }
  227940. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  227941. {
  227942. updateModifiers (ev);
  227943. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev),
  227944. [ev deltaX] * 10.0f, [ev deltaY] * 10.0f);
  227945. }
  227946. void NSViewComponentPeer::showArrowCursorIfNeeded()
  227947. {
  227948. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  227949. if (mouse.getComponentUnderMouse() == 0
  227950. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  227951. {
  227952. [[NSCursor arrowCursor] set];
  227953. }
  227954. }
  227955. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  227956. {
  227957. NSString* bestType
  227958. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  227959. if (bestType == nil)
  227960. return false;
  227961. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  227962. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  227963. StringArray files;
  227964. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  227965. if (list == nil)
  227966. return false;
  227967. if ([list isKindOfClass: [NSArray class]])
  227968. {
  227969. NSArray* items = (NSArray*) list;
  227970. for (unsigned int i = 0; i < [items count]; ++i)
  227971. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  227972. }
  227973. if (files.size() == 0)
  227974. return false;
  227975. if (type == 0)
  227976. handleFileDragMove (files, pos);
  227977. else if (type == 1)
  227978. handleFileDragExit (files);
  227979. else if (type == 2)
  227980. handleFileDragDrop (files, pos);
  227981. return true;
  227982. }
  227983. bool NSViewComponentPeer::isOpaque()
  227984. {
  227985. return component == 0 || component->isOpaque();
  227986. }
  227987. void NSViewComponentPeer::drawRect (NSRect r)
  227988. {
  227989. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227990. return;
  227991. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  227992. if (! component->isOpaque())
  227993. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227994. #if USE_COREGRAPHICS_RENDERING
  227995. if (usingCoreGraphics)
  227996. {
  227997. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  227998. insideDrawRect = true;
  227999. handlePaint (context);
  228000. insideDrawRect = false;
  228001. }
  228002. else
  228003. #endif
  228004. {
  228005. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  228006. (int) (r.size.width + 0.5f),
  228007. (int) (r.size.height + 0.5f),
  228008. ! getComponent()->isOpaque());
  228009. LowLevelGraphicsSoftwareRenderer context (temp);
  228010. context.setOrigin (-roundToInt (r.origin.x),
  228011. -roundToInt ([view frame].size.height - (r.origin.y + r.size.height)));
  228012. const NSRect* rects = 0;
  228013. NSInteger numRects = 0;
  228014. [view getRectsBeingDrawn: &rects count: &numRects];
  228015. RectangleList clip;
  228016. for (int i = 0; i < numRects; ++i)
  228017. {
  228018. clip.addWithoutMerging (Rectangle<int> (roundToInt (rects[i].origin.x),
  228019. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  228020. roundToInt (rects[i].size.width),
  228021. roundToInt (rects[i].size.height)));
  228022. }
  228023. if (context.clipToRectangleList (clip))
  228024. {
  228025. insideDrawRect = true;
  228026. handlePaint (context);
  228027. insideDrawRect = false;
  228028. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228029. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  228030. CGColorSpaceRelease (colourSpace);
  228031. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  228032. CGImageRelease (image);
  228033. }
  228034. }
  228035. }
  228036. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  228037. {
  228038. StringArray s;
  228039. s.add ("Software Renderer");
  228040. #if USE_COREGRAPHICS_RENDERING
  228041. s.add ("CoreGraphics Renderer");
  228042. #endif
  228043. return s;
  228044. }
  228045. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  228046. {
  228047. return usingCoreGraphics ? 1 : 0;
  228048. }
  228049. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  228050. {
  228051. #if USE_COREGRAPHICS_RENDERING
  228052. if (usingCoreGraphics != (index > 0))
  228053. {
  228054. usingCoreGraphics = index > 0;
  228055. [view setNeedsDisplay: true];
  228056. }
  228057. #endif
  228058. }
  228059. bool NSViewComponentPeer::canBecomeKeyWindow()
  228060. {
  228061. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228062. }
  228063. bool NSViewComponentPeer::windowShouldClose()
  228064. {
  228065. if (! isValidPeer (this))
  228066. return YES;
  228067. handleUserClosingWindow();
  228068. return NO;
  228069. }
  228070. void NSViewComponentPeer::redirectMovedOrResized()
  228071. {
  228072. handleMovedOrResized();
  228073. }
  228074. void NSViewComponentPeer::viewMovedToWindow()
  228075. {
  228076. if (isSharedWindow)
  228077. window = [view window];
  228078. }
  228079. void Desktop::createMouseInputSources()
  228080. {
  228081. mouseSources.add (new MouseInputSource (0, true));
  228082. }
  228083. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228084. {
  228085. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  228086. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  228087. // is apparently still available in 64-bit apps..
  228088. if (enableOrDisable)
  228089. {
  228090. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  228091. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  228092. }
  228093. else
  228094. {
  228095. SetSystemUIMode (kUIModeNormal, 0);
  228096. }
  228097. }
  228098. class AsyncRepaintMessage : public CallbackMessage
  228099. {
  228100. public:
  228101. NSViewComponentPeer* const peer;
  228102. const Rectangle<int> rect;
  228103. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228104. : peer (peer_), rect (rect_)
  228105. {
  228106. }
  228107. void messageCallback()
  228108. {
  228109. if (ComponentPeer::isValidPeer (peer))
  228110. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  228111. }
  228112. };
  228113. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  228114. {
  228115. if (insideDrawRect)
  228116. {
  228117. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  228118. }
  228119. else
  228120. {
  228121. [view setNeedsDisplayInRect: NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  228122. (float) w, (float) h)];
  228123. }
  228124. }
  228125. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  228126. {
  228127. [view displayIfNeeded];
  228128. }
  228129. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228130. {
  228131. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  228132. }
  228133. Image* juce_createIconForFile (const File& file)
  228134. {
  228135. const ScopedAutoReleasePool pool;
  228136. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  228137. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  228138. [NSGraphicsContext saveGraphicsState];
  228139. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  228140. [image drawAtPoint: NSMakePoint (0, 0)
  228141. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  228142. operation: NSCompositeSourceOver fraction: 1.0f];
  228143. [[NSGraphicsContext currentContext] flushGraphics];
  228144. [NSGraphicsContext restoreGraphicsState];
  228145. return result;
  228146. }
  228147. const int KeyPress::spaceKey = ' ';
  228148. const int KeyPress::returnKey = 0x0d;
  228149. const int KeyPress::escapeKey = 0x1b;
  228150. const int KeyPress::backspaceKey = 0x7f;
  228151. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  228152. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  228153. const int KeyPress::upKey = NSUpArrowFunctionKey;
  228154. const int KeyPress::downKey = NSDownArrowFunctionKey;
  228155. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  228156. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  228157. const int KeyPress::endKey = NSEndFunctionKey;
  228158. const int KeyPress::homeKey = NSHomeFunctionKey;
  228159. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  228160. const int KeyPress::insertKey = -1;
  228161. const int KeyPress::tabKey = 9;
  228162. const int KeyPress::F1Key = NSF1FunctionKey;
  228163. const int KeyPress::F2Key = NSF2FunctionKey;
  228164. const int KeyPress::F3Key = NSF3FunctionKey;
  228165. const int KeyPress::F4Key = NSF4FunctionKey;
  228166. const int KeyPress::F5Key = NSF5FunctionKey;
  228167. const int KeyPress::F6Key = NSF6FunctionKey;
  228168. const int KeyPress::F7Key = NSF7FunctionKey;
  228169. const int KeyPress::F8Key = NSF8FunctionKey;
  228170. const int KeyPress::F9Key = NSF9FunctionKey;
  228171. const int KeyPress::F10Key = NSF10FunctionKey;
  228172. const int KeyPress::F11Key = NSF1FunctionKey;
  228173. const int KeyPress::F12Key = NSF12FunctionKey;
  228174. const int KeyPress::F13Key = NSF13FunctionKey;
  228175. const int KeyPress::F14Key = NSF14FunctionKey;
  228176. const int KeyPress::F15Key = NSF15FunctionKey;
  228177. const int KeyPress::F16Key = NSF16FunctionKey;
  228178. const int KeyPress::numberPad0 = 0x30020;
  228179. const int KeyPress::numberPad1 = 0x30021;
  228180. const int KeyPress::numberPad2 = 0x30022;
  228181. const int KeyPress::numberPad3 = 0x30023;
  228182. const int KeyPress::numberPad4 = 0x30024;
  228183. const int KeyPress::numberPad5 = 0x30025;
  228184. const int KeyPress::numberPad6 = 0x30026;
  228185. const int KeyPress::numberPad7 = 0x30027;
  228186. const int KeyPress::numberPad8 = 0x30028;
  228187. const int KeyPress::numberPad9 = 0x30029;
  228188. const int KeyPress::numberPadAdd = 0x3002a;
  228189. const int KeyPress::numberPadSubtract = 0x3002b;
  228190. const int KeyPress::numberPadMultiply = 0x3002c;
  228191. const int KeyPress::numberPadDivide = 0x3002d;
  228192. const int KeyPress::numberPadSeparator = 0x3002e;
  228193. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228194. const int KeyPress::numberPadEquals = 0x30030;
  228195. const int KeyPress::numberPadDelete = 0x30031;
  228196. const int KeyPress::playKey = 0x30000;
  228197. const int KeyPress::stopKey = 0x30001;
  228198. const int KeyPress::fastForwardKey = 0x30002;
  228199. const int KeyPress::rewindKey = 0x30003;
  228200. #endif
  228201. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  228202. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228203. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228204. // compiled on its own).
  228205. #if JUCE_INCLUDED_FILE
  228206. #if JUCE_MAC
  228207. namespace MouseCursorHelpers
  228208. {
  228209. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228210. {
  228211. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228212. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228213. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228214. [im release];
  228215. return c;
  228216. }
  228217. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228218. {
  228219. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228220. BufferedInputStream buf (&fileStream, 4096, false);
  228221. PNGImageFormat pngFormat;
  228222. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  228223. if (im != 0)
  228224. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  228225. jassertfalse;
  228226. return 0;
  228227. }
  228228. }
  228229. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228230. {
  228231. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228232. }
  228233. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228234. {
  228235. const ScopedAutoReleasePool pool;
  228236. NSCursor* c = 0;
  228237. switch (type)
  228238. {
  228239. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228240. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228241. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228242. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228243. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228244. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228245. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228246. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228247. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228248. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228249. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228250. case UpDownResizeCursor:
  228251. case TopEdgeResizeCursor:
  228252. case BottomEdgeResizeCursor:
  228253. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228254. case TopLeftCornerResizeCursor:
  228255. case BottomRightCornerResizeCursor:
  228256. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228257. case TopRightCornerResizeCursor:
  228258. case BottomLeftCornerResizeCursor:
  228259. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228260. case UpDownLeftRightResizeCursor:
  228261. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228262. default:
  228263. jassertfalse;
  228264. break;
  228265. }
  228266. [c retain];
  228267. return c;
  228268. }
  228269. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228270. {
  228271. [((NSCursor*) cursorHandle) release];
  228272. }
  228273. void MouseCursor::showInAllWindows() const
  228274. {
  228275. showInWindow (0);
  228276. }
  228277. void MouseCursor::showInWindow (ComponentPeer*) const
  228278. {
  228279. [((NSCursor*) getHandle()) set];
  228280. }
  228281. #else
  228282. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228283. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228284. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228285. void MouseCursor::showInAllWindows() const {}
  228286. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228287. #endif
  228288. #endif
  228289. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228290. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  228291. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228292. // compiled on its own).
  228293. #if JUCE_INCLUDED_FILE
  228294. class NSViewComponentInternal : public ComponentMovementWatcher
  228295. {
  228296. Component* const owner;
  228297. NSViewComponentPeer* currentPeer;
  228298. bool wasShowing;
  228299. public:
  228300. NSView* const view;
  228301. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  228302. : ComponentMovementWatcher (owner_),
  228303. owner (owner_),
  228304. currentPeer (0),
  228305. wasShowing (false),
  228306. view (view_)
  228307. {
  228308. [view_ retain];
  228309. if (owner_->isShowing())
  228310. componentPeerChanged();
  228311. }
  228312. ~NSViewComponentInternal()
  228313. {
  228314. [view removeFromSuperview];
  228315. [view release];
  228316. }
  228317. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  228318. {
  228319. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  228320. // The ComponentMovementWatcher version of this method avoids calling
  228321. // us when the top-level comp is resized, but for an NSView we need to know this
  228322. // because with inverted co-ords, we need to update the position even if the
  228323. // top-left pos hasn't changed
  228324. if (comp.isOnDesktop() && wasResized)
  228325. componentMovedOrResized (wasMoved, wasResized);
  228326. }
  228327. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  228328. {
  228329. Component* const topComp = owner->getTopLevelComponent();
  228330. if (topComp->getPeer() != 0)
  228331. {
  228332. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  228333. NSRect r;
  228334. r.origin.x = (float) pos.getX();
  228335. r.origin.y = (float) pos.getY();
  228336. r.size.width = (float) owner->getWidth();
  228337. r.size.height = (float) owner->getHeight();
  228338. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  228339. [view setFrame: r];
  228340. }
  228341. }
  228342. void componentPeerChanged()
  228343. {
  228344. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  228345. if (currentPeer != peer)
  228346. {
  228347. [view removeFromSuperview];
  228348. currentPeer = peer;
  228349. if (peer != 0)
  228350. {
  228351. [peer->view addSubview: view];
  228352. componentMovedOrResized (false, false);
  228353. }
  228354. }
  228355. [view setHidden: ! owner->isShowing()];
  228356. }
  228357. void componentVisibilityChanged (Component&)
  228358. {
  228359. componentPeerChanged();
  228360. }
  228361. juce_UseDebuggingNewOperator
  228362. private:
  228363. NSViewComponentInternal (const NSViewComponentInternal&);
  228364. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  228365. };
  228366. NSViewComponent::NSViewComponent()
  228367. {
  228368. }
  228369. NSViewComponent::~NSViewComponent()
  228370. {
  228371. }
  228372. void NSViewComponent::setView (void* view)
  228373. {
  228374. if (view != getView())
  228375. {
  228376. if (view != 0)
  228377. info = new NSViewComponentInternal ((NSView*) view, this);
  228378. else
  228379. info = 0;
  228380. }
  228381. }
  228382. void* NSViewComponent::getView() const
  228383. {
  228384. return info == 0 ? 0 : info->view;
  228385. }
  228386. void NSViewComponent::paint (Graphics&)
  228387. {
  228388. }
  228389. #endif
  228390. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  228391. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  228392. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228393. // compiled on its own).
  228394. #if JUCE_INCLUDED_FILE
  228395. AppleRemoteDevice::AppleRemoteDevice()
  228396. : device (0),
  228397. queue (0),
  228398. remoteId (0)
  228399. {
  228400. }
  228401. AppleRemoteDevice::~AppleRemoteDevice()
  228402. {
  228403. stop();
  228404. }
  228405. static io_object_t getAppleRemoteDevice()
  228406. {
  228407. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  228408. io_iterator_t iter = 0;
  228409. io_object_t iod = 0;
  228410. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  228411. && iter != 0)
  228412. {
  228413. iod = IOIteratorNext (iter);
  228414. }
  228415. IOObjectRelease (iter);
  228416. return iod;
  228417. }
  228418. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  228419. {
  228420. jassert (*device == 0);
  228421. io_name_t classname;
  228422. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  228423. {
  228424. IOCFPlugInInterface** cfPlugInInterface = 0;
  228425. SInt32 score = 0;
  228426. if (IOCreatePlugInInterfaceForService (iod,
  228427. kIOHIDDeviceUserClientTypeID,
  228428. kIOCFPlugInInterfaceID,
  228429. &cfPlugInInterface,
  228430. &score) == kIOReturnSuccess)
  228431. {
  228432. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  228433. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  228434. device);
  228435. (void) hr;
  228436. (*cfPlugInInterface)->Release (cfPlugInInterface);
  228437. }
  228438. }
  228439. return *device != 0;
  228440. }
  228441. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  228442. {
  228443. if (queue != 0)
  228444. return true;
  228445. stop();
  228446. bool result = false;
  228447. io_object_t iod = getAppleRemoteDevice();
  228448. if (iod != 0)
  228449. {
  228450. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  228451. result = true;
  228452. else
  228453. stop();
  228454. IOObjectRelease (iod);
  228455. }
  228456. return result;
  228457. }
  228458. void AppleRemoteDevice::stop()
  228459. {
  228460. if (queue != 0)
  228461. {
  228462. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  228463. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  228464. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  228465. queue = 0;
  228466. }
  228467. if (device != 0)
  228468. {
  228469. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  228470. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  228471. device = 0;
  228472. }
  228473. }
  228474. bool AppleRemoteDevice::isActive() const
  228475. {
  228476. return queue != 0;
  228477. }
  228478. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  228479. {
  228480. if (result == kIOReturnSuccess)
  228481. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  228482. }
  228483. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  228484. {
  228485. Array <int> cookies;
  228486. CFArrayRef elements;
  228487. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  228488. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  228489. return false;
  228490. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  228491. {
  228492. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  228493. // get the cookie
  228494. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  228495. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  228496. continue;
  228497. long number;
  228498. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  228499. continue;
  228500. cookies.add ((int) number);
  228501. }
  228502. CFRelease (elements);
  228503. if ((*(IOHIDDeviceInterface**) device)
  228504. ->open ((IOHIDDeviceInterface**) device,
  228505. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  228506. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  228507. {
  228508. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  228509. if (queue != 0)
  228510. {
  228511. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  228512. for (int i = 0; i < cookies.size(); ++i)
  228513. {
  228514. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  228515. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  228516. }
  228517. CFRunLoopSourceRef eventSource;
  228518. if ((*(IOHIDQueueInterface**) queue)
  228519. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  228520. {
  228521. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  228522. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  228523. {
  228524. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  228525. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  228526. return true;
  228527. }
  228528. }
  228529. }
  228530. }
  228531. return false;
  228532. }
  228533. void AppleRemoteDevice::handleCallbackInternal()
  228534. {
  228535. int totalValues = 0;
  228536. AbsoluteTime nullTime = { 0, 0 };
  228537. char cookies [12];
  228538. int numCookies = 0;
  228539. while (numCookies < numElementsInArray (cookies))
  228540. {
  228541. IOHIDEventStruct e;
  228542. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  228543. break;
  228544. if ((int) e.elementCookie == 19)
  228545. {
  228546. remoteId = e.value;
  228547. buttonPressed (switched, false);
  228548. }
  228549. else
  228550. {
  228551. totalValues += e.value;
  228552. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  228553. }
  228554. }
  228555. cookies [numCookies++] = 0;
  228556. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  228557. static const char buttonPatterns[] =
  228558. {
  228559. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  228560. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  228561. 0x1f, 0x1d, 0x1c, 0x12, 0,
  228562. 0x1f, 0x1e, 0x1c, 0x12, 0,
  228563. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  228564. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  228565. 0x1f, 0x12, 0x04, 0x02, 0,
  228566. 0x1f, 0x12, 0x03, 0x02, 0,
  228567. 0x1f, 0x12, 0x1f, 0x12, 0,
  228568. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  228569. 19, 0
  228570. };
  228571. int buttonNum = (int) menuButton;
  228572. int i = 0;
  228573. while (i < numElementsInArray (buttonPatterns))
  228574. {
  228575. if (strcmp (cookies, buttonPatterns + i) == 0)
  228576. {
  228577. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  228578. break;
  228579. }
  228580. i += (int) strlen (buttonPatterns + i) + 1;
  228581. ++buttonNum;
  228582. }
  228583. }
  228584. #endif
  228585. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  228586. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228587. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228588. // compiled on its own).
  228589. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228590. #if JUCE_MAC
  228591. END_JUCE_NAMESPACE
  228592. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228593. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228594. {
  228595. CriticalSection* contextLock;
  228596. bool needsUpdate;
  228597. }
  228598. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228599. - (bool) makeActive;
  228600. - (void) makeInactive;
  228601. - (void) reshape;
  228602. @end
  228603. @implementation ThreadSafeNSOpenGLView
  228604. - (id) initWithFrame: (NSRect) frameRect
  228605. pixelFormat: (NSOpenGLPixelFormat*) format
  228606. {
  228607. contextLock = new CriticalSection();
  228608. self = [super initWithFrame: frameRect pixelFormat: format];
  228609. if (self != nil)
  228610. [[NSNotificationCenter defaultCenter] addObserver: self
  228611. selector: @selector (_surfaceNeedsUpdate:)
  228612. name: NSViewGlobalFrameDidChangeNotification
  228613. object: self];
  228614. return self;
  228615. }
  228616. - (void) dealloc
  228617. {
  228618. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228619. delete contextLock;
  228620. [super dealloc];
  228621. }
  228622. - (bool) makeActive
  228623. {
  228624. const ScopedLock sl (*contextLock);
  228625. if ([self openGLContext] == 0)
  228626. return false;
  228627. [[self openGLContext] makeCurrentContext];
  228628. if (needsUpdate)
  228629. {
  228630. [super update];
  228631. needsUpdate = false;
  228632. }
  228633. return true;
  228634. }
  228635. - (void) makeInactive
  228636. {
  228637. const ScopedLock sl (*contextLock);
  228638. [NSOpenGLContext clearCurrentContext];
  228639. }
  228640. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228641. {
  228642. const ScopedLock sl (*contextLock);
  228643. needsUpdate = true;
  228644. }
  228645. - (void) update
  228646. {
  228647. const ScopedLock sl (*contextLock);
  228648. needsUpdate = true;
  228649. }
  228650. - (void) reshape
  228651. {
  228652. const ScopedLock sl (*contextLock);
  228653. needsUpdate = true;
  228654. }
  228655. @end
  228656. BEGIN_JUCE_NAMESPACE
  228657. class WindowedGLContext : public OpenGLContext
  228658. {
  228659. public:
  228660. WindowedGLContext (Component* const component,
  228661. const OpenGLPixelFormat& pixelFormat_,
  228662. NSOpenGLContext* sharedContext)
  228663. : renderContext (0),
  228664. pixelFormat (pixelFormat_)
  228665. {
  228666. jassert (component != 0);
  228667. NSOpenGLPixelFormatAttribute attribs [64];
  228668. int n = 0;
  228669. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228670. attribs[n++] = NSOpenGLPFAAccelerated;
  228671. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228672. attribs[n++] = NSOpenGLPFAColorSize;
  228673. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228674. pixelFormat.greenBits,
  228675. pixelFormat.blueBits);
  228676. attribs[n++] = NSOpenGLPFAAlphaSize;
  228677. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228678. attribs[n++] = NSOpenGLPFADepthSize;
  228679. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228680. attribs[n++] = NSOpenGLPFAStencilSize;
  228681. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228682. attribs[n++] = NSOpenGLPFAAccumSize;
  228683. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228684. pixelFormat.accumulationBufferGreenBits,
  228685. pixelFormat.accumulationBufferBlueBits,
  228686. pixelFormat.accumulationBufferAlphaBits);
  228687. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228688. attribs[n++] = NSOpenGLPFASampleBuffers;
  228689. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228690. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228691. attribs[n++] = NSOpenGLPFANoRecovery;
  228692. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228693. NSOpenGLPixelFormat* format
  228694. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228695. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228696. pixelFormat: format];
  228697. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228698. shareContext: sharedContext] autorelease];
  228699. const GLint swapInterval = 1;
  228700. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228701. [view setOpenGLContext: renderContext];
  228702. [renderContext setView: view];
  228703. [format release];
  228704. viewHolder = new NSViewComponentInternal (view, component);
  228705. }
  228706. ~WindowedGLContext()
  228707. {
  228708. makeInactive();
  228709. [renderContext clearDrawable];
  228710. viewHolder = 0;
  228711. }
  228712. bool makeActive() const throw()
  228713. {
  228714. jassert (renderContext != 0);
  228715. [view makeActive];
  228716. return isActive();
  228717. }
  228718. bool makeInactive() const throw()
  228719. {
  228720. [view makeInactive];
  228721. return true;
  228722. }
  228723. bool isActive() const throw()
  228724. {
  228725. return [NSOpenGLContext currentContext] == renderContext;
  228726. }
  228727. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228728. void* getRawContext() const throw() { return renderContext; }
  228729. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228730. {
  228731. }
  228732. void swapBuffers()
  228733. {
  228734. [renderContext flushBuffer];
  228735. }
  228736. bool setSwapInterval (const int numFramesPerSwap)
  228737. {
  228738. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228739. forParameter: NSOpenGLCPSwapInterval];
  228740. return true;
  228741. }
  228742. int getSwapInterval() const
  228743. {
  228744. GLint numFrames = 0;
  228745. [renderContext getValues: &numFrames
  228746. forParameter: NSOpenGLCPSwapInterval];
  228747. return numFrames;
  228748. }
  228749. void repaint()
  228750. {
  228751. // we need to invalidate the juce view that holds this gl view, to make it
  228752. // cause a repaint callback
  228753. NSView* v = (NSView*) viewHolder->view;
  228754. NSRect r = [v frame];
  228755. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228756. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228757. // repaint message, thus never causing our paint() callback, and never repainting
  228758. // the comp. So invalidating just a little bit around the edge helps..
  228759. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228760. }
  228761. void* getNativeWindowHandle() const { return viewHolder->view; }
  228762. juce_UseDebuggingNewOperator
  228763. NSOpenGLContext* renderContext;
  228764. ThreadSafeNSOpenGLView* view;
  228765. private:
  228766. OpenGLPixelFormat pixelFormat;
  228767. ScopedPointer <NSViewComponentInternal> viewHolder;
  228768. WindowedGLContext (const WindowedGLContext&);
  228769. WindowedGLContext& operator= (const WindowedGLContext&);
  228770. };
  228771. OpenGLContext* OpenGLComponent::createContext()
  228772. {
  228773. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228774. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228775. return (c->renderContext != 0) ? c.release() : 0;
  228776. }
  228777. void* OpenGLComponent::getNativeWindowHandle() const
  228778. {
  228779. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228780. : 0;
  228781. }
  228782. void juce_glViewport (const int w, const int h)
  228783. {
  228784. glViewport (0, 0, w, h);
  228785. }
  228786. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228787. OwnedArray <OpenGLPixelFormat>& results)
  228788. {
  228789. /* GLint attribs [64];
  228790. int n = 0;
  228791. attribs[n++] = AGL_RGBA;
  228792. attribs[n++] = AGL_DOUBLEBUFFER;
  228793. attribs[n++] = AGL_ACCELERATED;
  228794. attribs[n++] = AGL_NO_RECOVERY;
  228795. attribs[n++] = AGL_NONE;
  228796. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228797. while (p != 0)
  228798. {
  228799. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228800. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228801. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228802. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228803. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228804. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228805. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228806. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228807. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228808. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228809. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228810. results.add (pf);
  228811. p = aglNextPixelFormat (p);
  228812. }*/
  228813. //jassertfalse //xxx can't see how you do this in cocoa!
  228814. }
  228815. #else
  228816. END_JUCE_NAMESPACE
  228817. @interface JuceGLView : UIView
  228818. {
  228819. }
  228820. + (Class) layerClass;
  228821. @end
  228822. @implementation JuceGLView
  228823. + (Class) layerClass
  228824. {
  228825. return [CAEAGLLayer class];
  228826. }
  228827. @end
  228828. BEGIN_JUCE_NAMESPACE
  228829. class GLESContext : public OpenGLContext
  228830. {
  228831. public:
  228832. GLESContext (UIViewComponentPeer* peer,
  228833. Component* const component_,
  228834. const OpenGLPixelFormat& pixelFormat_,
  228835. const GLESContext* const sharedContext,
  228836. NSUInteger apiType)
  228837. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228838. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228839. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228840. {
  228841. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228842. view.opaque = YES;
  228843. view.hidden = NO;
  228844. view.backgroundColor = [UIColor blackColor];
  228845. view.userInteractionEnabled = NO;
  228846. glLayer = (CAEAGLLayer*) [view layer];
  228847. [peer->view addSubview: view];
  228848. if (sharedContext != 0)
  228849. context = [[EAGLContext alloc] initWithAPI: apiType
  228850. sharegroup: [sharedContext->context sharegroup]];
  228851. else
  228852. context = [[EAGLContext alloc] initWithAPI: apiType];
  228853. createGLBuffers();
  228854. }
  228855. ~GLESContext()
  228856. {
  228857. makeInactive();
  228858. [context release];
  228859. [view removeFromSuperview];
  228860. [view release];
  228861. freeGLBuffers();
  228862. }
  228863. bool makeActive() const throw()
  228864. {
  228865. jassert (context != 0);
  228866. [EAGLContext setCurrentContext: context];
  228867. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228868. return true;
  228869. }
  228870. void swapBuffers()
  228871. {
  228872. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228873. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228874. }
  228875. bool makeInactive() const throw()
  228876. {
  228877. return [EAGLContext setCurrentContext: nil];
  228878. }
  228879. bool isActive() const throw()
  228880. {
  228881. return [EAGLContext currentContext] == context;
  228882. }
  228883. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228884. void* getRawContext() const throw() { return glLayer; }
  228885. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228886. {
  228887. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228888. if (lastWidth != w || lastHeight != h)
  228889. {
  228890. lastWidth = w;
  228891. lastHeight = h;
  228892. freeGLBuffers();
  228893. createGLBuffers();
  228894. }
  228895. }
  228896. bool setSwapInterval (const int numFramesPerSwap)
  228897. {
  228898. numFrames = numFramesPerSwap;
  228899. return true;
  228900. }
  228901. int getSwapInterval() const
  228902. {
  228903. return numFrames;
  228904. }
  228905. void repaint()
  228906. {
  228907. }
  228908. void createGLBuffers()
  228909. {
  228910. makeActive();
  228911. glGenFramebuffersOES (1, &frameBufferHandle);
  228912. glGenRenderbuffersOES (1, &colorBufferHandle);
  228913. glGenRenderbuffersOES (1, &depthBufferHandle);
  228914. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228915. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228916. GLint width, height;
  228917. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228918. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228919. if (useDepthBuffer)
  228920. {
  228921. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228922. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228923. }
  228924. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228925. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228926. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228927. if (useDepthBuffer)
  228928. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228929. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228930. }
  228931. void freeGLBuffers()
  228932. {
  228933. if (frameBufferHandle != 0)
  228934. {
  228935. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228936. frameBufferHandle = 0;
  228937. }
  228938. if (colorBufferHandle != 0)
  228939. {
  228940. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228941. colorBufferHandle = 0;
  228942. }
  228943. if (depthBufferHandle != 0)
  228944. {
  228945. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228946. depthBufferHandle = 0;
  228947. }
  228948. }
  228949. juce_UseDebuggingNewOperator
  228950. private:
  228951. Component::SafePointer<Component> component;
  228952. OpenGLPixelFormat pixelFormat;
  228953. JuceGLView* view;
  228954. CAEAGLLayer* glLayer;
  228955. EAGLContext* context;
  228956. bool useDepthBuffer;
  228957. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228958. int numFrames;
  228959. int lastWidth, lastHeight;
  228960. GLESContext (const GLESContext&);
  228961. GLESContext& operator= (const GLESContext&);
  228962. };
  228963. OpenGLContext* OpenGLComponent::createContext()
  228964. {
  228965. ScopedAutoReleasePool pool;
  228966. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228967. if (peer != 0)
  228968. return new GLESContext (peer, this, preferredPixelFormat,
  228969. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228970. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228971. return 0;
  228972. }
  228973. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228974. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228975. {
  228976. }
  228977. void juce_glViewport (const int w, const int h)
  228978. {
  228979. glViewport (0, 0, w, h);
  228980. }
  228981. #endif
  228982. #endif
  228983. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228984. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  228985. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228986. // compiled on its own).
  228987. #if JUCE_INCLUDED_FILE
  228988. class JuceMainMenuHandler;
  228989. END_JUCE_NAMESPACE
  228990. using namespace JUCE_NAMESPACE;
  228991. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  228992. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228993. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  228994. #else
  228995. @interface JuceMenuCallback : NSObject
  228996. #endif
  228997. {
  228998. JuceMainMenuHandler* owner;
  228999. }
  229000. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  229001. - (void) dealloc;
  229002. - (void) menuItemInvoked: (id) menu;
  229003. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229004. @end
  229005. BEGIN_JUCE_NAMESPACE
  229006. class JuceMainMenuHandler : private MenuBarModelListener,
  229007. private DeletedAtShutdown
  229008. {
  229009. public:
  229010. static JuceMainMenuHandler* instance;
  229011. JuceMainMenuHandler()
  229012. : currentModel (0),
  229013. lastUpdateTime (0)
  229014. {
  229015. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  229016. }
  229017. ~JuceMainMenuHandler()
  229018. {
  229019. setMenu (0);
  229020. jassert (instance == this);
  229021. instance = 0;
  229022. [callback release];
  229023. }
  229024. void setMenu (MenuBarModel* const newMenuBarModel)
  229025. {
  229026. if (currentModel != newMenuBarModel)
  229027. {
  229028. if (currentModel != 0)
  229029. currentModel->removeListener (this);
  229030. currentModel = newMenuBarModel;
  229031. if (currentModel != 0)
  229032. currentModel->addListener (this);
  229033. menuBarItemsChanged (0);
  229034. }
  229035. }
  229036. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  229037. const String& name, const int menuId, const int tag)
  229038. {
  229039. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  229040. action: nil
  229041. keyEquivalent: @""];
  229042. [item setTag: tag];
  229043. NSMenu* sub = createMenu (child, name, menuId, tag);
  229044. [parent setSubmenu: sub forItem: item];
  229045. [sub setAutoenablesItems: false];
  229046. [sub release];
  229047. }
  229048. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  229049. const String& name, const int menuId, const int tag)
  229050. {
  229051. [parentItem setTag: tag];
  229052. NSMenu* menu = [parentItem submenu];
  229053. [menu setTitle: juceStringToNS (name)];
  229054. while ([menu numberOfItems] > 0)
  229055. [menu removeItemAtIndex: 0];
  229056. PopupMenu::MenuItemIterator iter (menuToCopy);
  229057. while (iter.next())
  229058. addMenuItem (iter, menu, menuId, tag);
  229059. [menu setAutoenablesItems: false];
  229060. [menu update];
  229061. }
  229062. void menuBarItemsChanged (MenuBarModel*)
  229063. {
  229064. lastUpdateTime = Time::getMillisecondCounter();
  229065. StringArray menuNames;
  229066. if (currentModel != 0)
  229067. menuNames = currentModel->getMenuBarNames();
  229068. NSMenu* menuBar = [NSApp mainMenu];
  229069. while ([menuBar numberOfItems] > 1 + menuNames.size())
  229070. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  229071. int menuId = 1;
  229072. for (int i = 0; i < menuNames.size(); ++i)
  229073. {
  229074. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  229075. if (i >= [menuBar numberOfItems] - 1)
  229076. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  229077. else
  229078. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  229079. }
  229080. }
  229081. static void flashMenuBar (NSMenu* menu)
  229082. {
  229083. if ([[menu title] isEqualToString: @"Apple"])
  229084. return;
  229085. [menu retain];
  229086. const unichar f35Key = NSF35FunctionKey;
  229087. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  229088. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  229089. action: nil
  229090. keyEquivalent: f35String];
  229091. [item setTarget: nil];
  229092. [menu insertItem: item atIndex: [menu numberOfItems]];
  229093. [item release];
  229094. if ([menu indexOfItem: item] >= 0)
  229095. {
  229096. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  229097. location: NSZeroPoint
  229098. modifierFlags: NSCommandKeyMask
  229099. timestamp: 0
  229100. windowNumber: 0
  229101. context: [NSGraphicsContext currentContext]
  229102. characters: f35String
  229103. charactersIgnoringModifiers: f35String
  229104. isARepeat: NO
  229105. keyCode: 0];
  229106. [menu performKeyEquivalent: f35Event];
  229107. if ([menu indexOfItem: item] >= 0)
  229108. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  229109. }
  229110. [menu release];
  229111. }
  229112. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  229113. {
  229114. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  229115. {
  229116. NSMenuItem* m = [menu itemAtIndex: i];
  229117. if ([m tag] == info.commandID)
  229118. return m;
  229119. if ([m submenu] != 0)
  229120. {
  229121. NSMenuItem* found = findMenuItem ([m submenu], info);
  229122. if (found != 0)
  229123. return found;
  229124. }
  229125. }
  229126. return 0;
  229127. }
  229128. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  229129. {
  229130. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  229131. if (item != 0)
  229132. flashMenuBar ([item menu]);
  229133. }
  229134. void updateMenus()
  229135. {
  229136. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  229137. menuBarItemsChanged (0);
  229138. }
  229139. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  229140. {
  229141. if (currentModel != 0)
  229142. {
  229143. if (commandManager != 0)
  229144. {
  229145. ApplicationCommandTarget::InvocationInfo info (commandId);
  229146. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  229147. commandManager->invoke (info, true);
  229148. }
  229149. currentModel->menuItemSelected (commandId, topLevelIndex);
  229150. }
  229151. }
  229152. MenuBarModel* currentModel;
  229153. uint32 lastUpdateTime;
  229154. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  229155. const int topLevelMenuId, const int topLevelIndex)
  229156. {
  229157. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  229158. if (text == 0)
  229159. text = @"";
  229160. if (iter.isSeparator)
  229161. {
  229162. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  229163. }
  229164. else if (iter.isSectionHeader)
  229165. {
  229166. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229167. action: nil
  229168. keyEquivalent: @""];
  229169. [item setEnabled: false];
  229170. }
  229171. else if (iter.subMenu != 0)
  229172. {
  229173. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229174. action: nil
  229175. keyEquivalent: @""];
  229176. [item setTag: iter.itemId];
  229177. [item setEnabled: iter.isEnabled];
  229178. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  229179. [sub setDelegate: nil];
  229180. [menuToAddTo setSubmenu: sub forItem: item];
  229181. [sub release];
  229182. }
  229183. else
  229184. {
  229185. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229186. action: @selector (menuItemInvoked:)
  229187. keyEquivalent: @""];
  229188. [item setTag: iter.itemId];
  229189. [item setEnabled: iter.isEnabled];
  229190. [item setState: iter.isTicked ? NSOnState : NSOffState];
  229191. [item setTarget: (id) callback];
  229192. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  229193. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  229194. [item setRepresentedObject: info];
  229195. if (iter.commandManager != 0)
  229196. {
  229197. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  229198. ->getKeyPressesAssignedToCommand (iter.itemId));
  229199. if (keyPresses.size() > 0)
  229200. {
  229201. const KeyPress& kp = keyPresses.getReference(0);
  229202. if (kp.getKeyCode() != KeyPress::backspaceKey
  229203. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  229204. // every time you press the key while editing text)
  229205. {
  229206. juce_wchar key = kp.getTextCharacter();
  229207. if (kp.getKeyCode() == KeyPress::backspaceKey)
  229208. key = NSBackspaceCharacter;
  229209. else if (kp.getKeyCode() == KeyPress::deleteKey)
  229210. key = NSDeleteCharacter;
  229211. else if (key == 0)
  229212. key = (juce_wchar) kp.getKeyCode();
  229213. unsigned int mods = 0;
  229214. if (kp.getModifiers().isShiftDown())
  229215. mods |= NSShiftKeyMask;
  229216. if (kp.getModifiers().isCtrlDown())
  229217. mods |= NSControlKeyMask;
  229218. if (kp.getModifiers().isAltDown())
  229219. mods |= NSAlternateKeyMask;
  229220. if (kp.getModifiers().isCommandDown())
  229221. mods |= NSCommandKeyMask;
  229222. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  229223. [item setKeyEquivalentModifierMask: mods];
  229224. }
  229225. }
  229226. }
  229227. }
  229228. }
  229229. JuceMenuCallback* callback;
  229230. private:
  229231. NSMenu* createMenu (const PopupMenu menu,
  229232. const String& menuName,
  229233. const int topLevelMenuId,
  229234. const int topLevelIndex)
  229235. {
  229236. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  229237. [m setAutoenablesItems: false];
  229238. [m setDelegate: callback];
  229239. PopupMenu::MenuItemIterator iter (menu);
  229240. while (iter.next())
  229241. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  229242. [m update];
  229243. return m;
  229244. }
  229245. };
  229246. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  229247. END_JUCE_NAMESPACE
  229248. @implementation JuceMenuCallback
  229249. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  229250. {
  229251. [super init];
  229252. owner = owner_;
  229253. return self;
  229254. }
  229255. - (void) dealloc
  229256. {
  229257. [super dealloc];
  229258. }
  229259. - (void) menuItemInvoked: (id) menu
  229260. {
  229261. NSMenuItem* item = (NSMenuItem*) menu;
  229262. if ([[item representedObject] isKindOfClass: [NSArray class]])
  229263. {
  229264. // 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
  229265. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  229266. // into the focused component and let it trigger the menu item indirectly.
  229267. NSEvent* e = [NSApp currentEvent];
  229268. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  229269. {
  229270. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  229271. {
  229272. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  229273. if (peer != 0)
  229274. {
  229275. if ([e type] == NSKeyDown)
  229276. peer->redirectKeyDown (e);
  229277. else
  229278. peer->redirectKeyUp (e);
  229279. return;
  229280. }
  229281. }
  229282. }
  229283. NSArray* info = (NSArray*) [item representedObject];
  229284. owner->invoke ((int) [item tag],
  229285. (ApplicationCommandManager*) (pointer_sized_int)
  229286. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  229287. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  229288. }
  229289. }
  229290. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229291. {
  229292. (void) menu;
  229293. if (JuceMainMenuHandler::instance != 0)
  229294. JuceMainMenuHandler::instance->updateMenus();
  229295. }
  229296. @end
  229297. BEGIN_JUCE_NAMESPACE
  229298. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  229299. const PopupMenu* extraItems)
  229300. {
  229301. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  229302. {
  229303. PopupMenu::MenuItemIterator iter (*extraItems);
  229304. while (iter.next())
  229305. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  229306. [menu addItem: [NSMenuItem separatorItem]];
  229307. }
  229308. NSMenuItem* item;
  229309. // Services...
  229310. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  229311. action: nil keyEquivalent: @""];
  229312. [menu addItem: item];
  229313. [item release];
  229314. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  229315. [menu setSubmenu: servicesMenu forItem: item];
  229316. [NSApp setServicesMenu: servicesMenu];
  229317. [servicesMenu release];
  229318. [menu addItem: [NSMenuItem separatorItem]];
  229319. // Hide + Show stuff...
  229320. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  229321. action: @selector (hide:) keyEquivalent: @"h"];
  229322. [item setTarget: NSApp];
  229323. [menu addItem: item];
  229324. [item release];
  229325. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  229326. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  229327. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  229328. [item setTarget: NSApp];
  229329. [menu addItem: item];
  229330. [item release];
  229331. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  229332. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  229333. [item setTarget: NSApp];
  229334. [menu addItem: item];
  229335. [item release];
  229336. [menu addItem: [NSMenuItem separatorItem]];
  229337. // Quit item....
  229338. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  229339. action: @selector (terminate:) keyEquivalent: @"q"];
  229340. [item setTarget: NSApp];
  229341. [menu addItem: item];
  229342. [item release];
  229343. return menu;
  229344. }
  229345. // Since our app has no NIB, this initialises a standard app menu...
  229346. static void rebuildMainMenu (const PopupMenu* extraItems)
  229347. {
  229348. // this can't be used in a plugin!
  229349. jassert (JUCEApplication::getInstance() != 0);
  229350. if (JUCEApplication::getInstance() != 0)
  229351. {
  229352. const ScopedAutoReleasePool pool;
  229353. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  229354. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  229355. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  229356. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  229357. [mainMenu setSubmenu: appMenu forItem: item];
  229358. [NSApp setMainMenu: mainMenu];
  229359. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  229360. [appMenu release];
  229361. [mainMenu release];
  229362. }
  229363. }
  229364. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  229365. const PopupMenu* extraAppleMenuItems)
  229366. {
  229367. if (getMacMainMenu() != newMenuBarModel)
  229368. {
  229369. const ScopedAutoReleasePool pool;
  229370. if (newMenuBarModel == 0)
  229371. {
  229372. delete JuceMainMenuHandler::instance;
  229373. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  229374. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  229375. extraAppleMenuItems = 0;
  229376. }
  229377. else
  229378. {
  229379. if (JuceMainMenuHandler::instance == 0)
  229380. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  229381. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  229382. }
  229383. }
  229384. rebuildMainMenu (extraAppleMenuItems);
  229385. if (newMenuBarModel != 0)
  229386. newMenuBarModel->menuItemsChanged();
  229387. }
  229388. MenuBarModel* MenuBarModel::getMacMainMenu()
  229389. {
  229390. return JuceMainMenuHandler::instance != 0
  229391. ? JuceMainMenuHandler::instance->currentModel : 0;
  229392. }
  229393. void initialiseMainMenu()
  229394. {
  229395. if (JUCEApplication::getInstance() != 0) // only needed in an app
  229396. rebuildMainMenu (0);
  229397. }
  229398. #endif
  229399. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  229400. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  229401. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229402. // compiled on its own).
  229403. #if JUCE_INCLUDED_FILE
  229404. #if JUCE_MAC
  229405. END_JUCE_NAMESPACE
  229406. using namespace JUCE_NAMESPACE;
  229407. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  229408. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229409. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  229410. #else
  229411. @interface JuceFileChooserDelegate : NSObject
  229412. #endif
  229413. {
  229414. StringArray* filters;
  229415. }
  229416. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  229417. - (void) dealloc;
  229418. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  229419. @end
  229420. @implementation JuceFileChooserDelegate
  229421. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  229422. {
  229423. [super init];
  229424. filters = filters_;
  229425. return self;
  229426. }
  229427. - (void) dealloc
  229428. {
  229429. delete filters;
  229430. [super dealloc];
  229431. }
  229432. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  229433. {
  229434. (void) sender;
  229435. const File f (nsStringToJuce (filename));
  229436. for (int i = filters->size(); --i >= 0;)
  229437. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  229438. return true;
  229439. return f.isDirectory();
  229440. }
  229441. @end
  229442. BEGIN_JUCE_NAMESPACE
  229443. void FileChooser::showPlatformDialog (Array<File>& results,
  229444. const String& title,
  229445. const File& currentFileOrDirectory,
  229446. const String& filter,
  229447. bool selectsDirectory,
  229448. bool selectsFiles,
  229449. bool isSaveDialogue,
  229450. bool warnAboutOverwritingExistingFiles,
  229451. bool selectMultipleFiles,
  229452. FilePreviewComponent* extraInfoComponent)
  229453. {
  229454. const ScopedAutoReleasePool pool;
  229455. StringArray* filters = new StringArray();
  229456. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  229457. filters->trim();
  229458. filters->removeEmptyStrings();
  229459. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  229460. [delegate autorelease];
  229461. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  229462. : [NSOpenPanel openPanel];
  229463. [panel setTitle: juceStringToNS (title)];
  229464. if (! isSaveDialogue)
  229465. {
  229466. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  229467. [openPanel setCanChooseDirectories: selectsDirectory];
  229468. [openPanel setCanChooseFiles: selectsFiles];
  229469. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  229470. }
  229471. [panel setDelegate: delegate];
  229472. if (isSaveDialogue || selectsDirectory)
  229473. [panel setCanCreateDirectories: YES];
  229474. String directory, filename;
  229475. if (currentFileOrDirectory.isDirectory())
  229476. {
  229477. directory = currentFileOrDirectory.getFullPathName();
  229478. }
  229479. else
  229480. {
  229481. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  229482. filename = currentFileOrDirectory.getFileName();
  229483. }
  229484. if ([panel runModalForDirectory: juceStringToNS (directory)
  229485. file: juceStringToNS (filename)]
  229486. == NSOKButton)
  229487. {
  229488. if (isSaveDialogue)
  229489. {
  229490. results.add (File (nsStringToJuce ([panel filename])));
  229491. }
  229492. else
  229493. {
  229494. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  229495. NSArray* urls = [openPanel filenames];
  229496. for (unsigned int i = 0; i < [urls count]; ++i)
  229497. {
  229498. NSString* f = [urls objectAtIndex: i];
  229499. results.add (File (nsStringToJuce (f)));
  229500. }
  229501. }
  229502. }
  229503. [panel setDelegate: nil];
  229504. }
  229505. #else
  229506. void FileChooser::showPlatformDialog (Array<File>& results,
  229507. const String& title,
  229508. const File& currentFileOrDirectory,
  229509. const String& filter,
  229510. bool selectsDirectory,
  229511. bool selectsFiles,
  229512. bool isSaveDialogue,
  229513. bool warnAboutOverwritingExistingFiles,
  229514. bool selectMultipleFiles,
  229515. FilePreviewComponent* extraInfoComponent)
  229516. {
  229517. const ScopedAutoReleasePool pool;
  229518. jassertfalse //xxx to do
  229519. }
  229520. #endif
  229521. #endif
  229522. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  229523. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  229524. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229525. // compiled on its own).
  229526. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  229527. END_JUCE_NAMESPACE
  229528. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  229529. @interface NonInterceptingQTMovieView : QTMovieView
  229530. {
  229531. }
  229532. - (id) initWithFrame: (NSRect) frame;
  229533. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  229534. - (NSView*) hitTest: (NSPoint) p;
  229535. @end
  229536. @implementation NonInterceptingQTMovieView
  229537. - (id) initWithFrame: (NSRect) frame
  229538. {
  229539. self = [super initWithFrame: frame];
  229540. [self setNextResponder: [self superview]];
  229541. return self;
  229542. }
  229543. - (void) dealloc
  229544. {
  229545. [super dealloc];
  229546. }
  229547. - (NSView*) hitTest: (NSPoint) point
  229548. {
  229549. return [self isControllerVisible] ? [super hitTest: point] : nil;
  229550. }
  229551. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  229552. {
  229553. return YES;
  229554. }
  229555. @end
  229556. BEGIN_JUCE_NAMESPACE
  229557. #define theMovie (static_cast <QTMovie*> (movie))
  229558. QuickTimeMovieComponent::QuickTimeMovieComponent()
  229559. : movie (0)
  229560. {
  229561. setOpaque (true);
  229562. setVisible (true);
  229563. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  229564. setView (view);
  229565. [view release];
  229566. }
  229567. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  229568. {
  229569. closeMovie();
  229570. setView (0);
  229571. }
  229572. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  229573. {
  229574. return true;
  229575. }
  229576. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  229577. {
  229578. // unfortunately, QTMovie objects can only be created on the main thread..
  229579. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  229580. QTMovie* movie = 0;
  229581. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  229582. if (fin != 0)
  229583. {
  229584. movieFile = fin->getFile();
  229585. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  229586. error: nil];
  229587. }
  229588. else
  229589. {
  229590. MemoryBlock temp;
  229591. movieStream->readIntoMemoryBlock (temp);
  229592. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  229593. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  229594. {
  229595. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  229596. length: temp.getSize()]
  229597. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  229598. MIMEType: @""]
  229599. error: nil];
  229600. if (movie != 0)
  229601. break;
  229602. }
  229603. }
  229604. return movie;
  229605. }
  229606. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  229607. const bool isControllerVisible_)
  229608. {
  229609. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  229610. }
  229611. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  229612. const bool controllerVisible_)
  229613. {
  229614. closeMovie();
  229615. if (getPeer() == 0)
  229616. {
  229617. // To open a movie, this component must be visible inside a functioning window, so that
  229618. // the QT control can be assigned to the window.
  229619. jassertfalse
  229620. return false;
  229621. }
  229622. movie = openMovieFromStream (movieStream, movieFile);
  229623. [theMovie retain];
  229624. QTMovieView* view = (QTMovieView*) getView();
  229625. [view setMovie: theMovie];
  229626. [view setControllerVisible: controllerVisible_];
  229627. setLooping (looping);
  229628. return movie != nil;
  229629. }
  229630. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  229631. const bool isControllerVisible_)
  229632. {
  229633. // unfortunately, QTMovie objects can only be created on the main thread..
  229634. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  229635. closeMovie();
  229636. if (getPeer() == 0)
  229637. {
  229638. // To open a movie, this component must be visible inside a functioning window, so that
  229639. // the QT control can be assigned to the window.
  229640. jassertfalse
  229641. return false;
  229642. }
  229643. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  229644. NSError* err;
  229645. if ([QTMovie canInitWithURL: url])
  229646. movie = [QTMovie movieWithURL: url error: &err];
  229647. [theMovie retain];
  229648. QTMovieView* view = (QTMovieView*) getView();
  229649. [view setMovie: theMovie];
  229650. [view setControllerVisible: controllerVisible];
  229651. setLooping (looping);
  229652. return movie != nil;
  229653. }
  229654. void QuickTimeMovieComponent::closeMovie()
  229655. {
  229656. stop();
  229657. QTMovieView* view = (QTMovieView*) getView();
  229658. [view setMovie: nil];
  229659. [theMovie release];
  229660. movie = 0;
  229661. movieFile = File::nonexistent;
  229662. }
  229663. bool QuickTimeMovieComponent::isMovieOpen() const
  229664. {
  229665. return movie != nil;
  229666. }
  229667. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  229668. {
  229669. return movieFile;
  229670. }
  229671. void QuickTimeMovieComponent::play()
  229672. {
  229673. [theMovie play];
  229674. }
  229675. void QuickTimeMovieComponent::stop()
  229676. {
  229677. [theMovie stop];
  229678. }
  229679. bool QuickTimeMovieComponent::isPlaying() const
  229680. {
  229681. return movie != 0 && [theMovie rate] != 0;
  229682. }
  229683. void QuickTimeMovieComponent::setPosition (const double seconds)
  229684. {
  229685. if (movie != 0)
  229686. {
  229687. QTTime t;
  229688. t.timeValue = (uint64) (100000.0 * seconds);
  229689. t.timeScale = 100000;
  229690. t.flags = 0;
  229691. [theMovie setCurrentTime: t];
  229692. }
  229693. }
  229694. double QuickTimeMovieComponent::getPosition() const
  229695. {
  229696. if (movie == 0)
  229697. return 0.0;
  229698. QTTime t = [theMovie currentTime];
  229699. return t.timeValue / (double) t.timeScale;
  229700. }
  229701. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  229702. {
  229703. [theMovie setRate: newSpeed];
  229704. }
  229705. double QuickTimeMovieComponent::getMovieDuration() const
  229706. {
  229707. if (movie == 0)
  229708. return 0.0;
  229709. QTTime t = [theMovie duration];
  229710. return t.timeValue / (double) t.timeScale;
  229711. }
  229712. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  229713. {
  229714. looping = shouldLoop;
  229715. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  229716. forKey: QTMovieLoopsAttribute];
  229717. }
  229718. bool QuickTimeMovieComponent::isLooping() const
  229719. {
  229720. return looping;
  229721. }
  229722. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  229723. {
  229724. [theMovie setVolume: newVolume];
  229725. }
  229726. float QuickTimeMovieComponent::getMovieVolume() const
  229727. {
  229728. return movie != 0 ? [theMovie volume] : 0.0f;
  229729. }
  229730. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  229731. {
  229732. width = 0;
  229733. height = 0;
  229734. if (movie != 0)
  229735. {
  229736. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  229737. width = (int) s.width;
  229738. height = (int) s.height;
  229739. }
  229740. }
  229741. void QuickTimeMovieComponent::paint (Graphics& g)
  229742. {
  229743. if (movie == 0)
  229744. g.fillAll (Colours::black);
  229745. }
  229746. bool QuickTimeMovieComponent::isControllerVisible() const
  229747. {
  229748. return controllerVisible;
  229749. }
  229750. void QuickTimeMovieComponent::goToStart()
  229751. {
  229752. setPosition (0.0);
  229753. }
  229754. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  229755. const RectanglePlacement& placement)
  229756. {
  229757. int normalWidth, normalHeight;
  229758. getMovieNormalSize (normalWidth, normalHeight);
  229759. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  229760. {
  229761. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  229762. placement.applyTo (x, y, w, h,
  229763. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  229764. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  229765. if (w > 0 && h > 0)
  229766. {
  229767. setBounds (roundToInt (x), roundToInt (y),
  229768. roundToInt (w), roundToInt (h));
  229769. }
  229770. }
  229771. else
  229772. {
  229773. setBounds (spaceToFitWithin);
  229774. }
  229775. }
  229776. #if ! (JUCE_MAC && JUCE_64BIT)
  229777. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  229778. {
  229779. if (movieStream == 0)
  229780. return false;
  229781. File file;
  229782. QTMovie* movie = openMovieFromStream (movieStream, file);
  229783. if (movie != nil)
  229784. result = [movie quickTimeMovie];
  229785. return movie != nil;
  229786. }
  229787. #endif
  229788. #endif
  229789. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  229790. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  229791. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229792. // compiled on its own).
  229793. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  229794. const int kilobytesPerSecond1x = 176;
  229795. END_JUCE_NAMESPACE
  229796. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  229797. @interface OpenDiskDevice : NSObject
  229798. {
  229799. @public
  229800. DRDevice* device;
  229801. NSMutableArray* tracks;
  229802. bool underrunProtection;
  229803. }
  229804. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  229805. - (void) dealloc;
  229806. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  229807. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  229808. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  229809. @end
  229810. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  229811. @interface AudioTrackProducer : NSObject
  229812. {
  229813. JUCE_NAMESPACE::AudioSource* source;
  229814. int readPosition, lengthInFrames;
  229815. }
  229816. - (AudioTrackProducer*) init: (int) lengthInFrames;
  229817. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  229818. - (void) dealloc;
  229819. - (void) setupTrackProperties: (DRTrack*) track;
  229820. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  229821. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  229822. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  229823. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  229824. toMedia:(NSDictionary*)mediaInfo;
  229825. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  229826. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  229827. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  229828. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  229829. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  229830. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  229831. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  229832. ioFlags:(uint32_t*)flags;
  229833. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  229834. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  229835. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  229836. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  229837. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  229838. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  229839. ioFlags:(uint32_t*)flags;
  229840. @end
  229841. @implementation OpenDiskDevice
  229842. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  229843. {
  229844. [super init];
  229845. device = device_;
  229846. tracks = [[NSMutableArray alloc] init];
  229847. underrunProtection = true;
  229848. return self;
  229849. }
  229850. - (void) dealloc
  229851. {
  229852. [tracks release];
  229853. [super dealloc];
  229854. }
  229855. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  229856. {
  229857. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  229858. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  229859. [p setupTrackProperties: t];
  229860. [tracks addObject: t];
  229861. [t release];
  229862. [p release];
  229863. }
  229864. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  229865. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  229866. {
  229867. DRBurn* burn = [DRBurn burnForDevice: device];
  229868. if (! [device acquireExclusiveAccess])
  229869. {
  229870. *error = "Couldn't open or write to the CD device";
  229871. return;
  229872. }
  229873. [device acquireMediaReservation];
  229874. NSMutableDictionary* d = [[burn properties] mutableCopy];
  229875. [d autorelease];
  229876. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  229877. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  229878. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  229879. if (burnSpeed > 0)
  229880. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  229881. if (! underrunProtection)
  229882. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  229883. [burn setProperties: d];
  229884. [burn writeLayout: tracks];
  229885. for (;;)
  229886. {
  229887. JUCE_NAMESPACE::Thread::sleep (300);
  229888. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  229889. if (listener != 0 && listener->audioCDBurnProgress (progress))
  229890. {
  229891. [burn abort];
  229892. *error = "User cancelled the write operation";
  229893. break;
  229894. }
  229895. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  229896. {
  229897. *error = "Write operation failed";
  229898. break;
  229899. }
  229900. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  229901. {
  229902. break;
  229903. }
  229904. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  229905. objectForKey: DRErrorStatusErrorStringKey];
  229906. if ([err length] > 0)
  229907. {
  229908. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  229909. break;
  229910. }
  229911. }
  229912. [device releaseMediaReservation];
  229913. [device releaseExclusiveAccess];
  229914. }
  229915. @end
  229916. @implementation AudioTrackProducer
  229917. - (AudioTrackProducer*) init: (int) lengthInFrames_
  229918. {
  229919. lengthInFrames = lengthInFrames_;
  229920. readPosition = 0;
  229921. return self;
  229922. }
  229923. - (void) setupTrackProperties: (DRTrack*) track
  229924. {
  229925. NSMutableDictionary* p = [[track properties] mutableCopy];
  229926. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  229927. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  229928. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  229929. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  229930. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  229931. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  229932. [track setProperties: p];
  229933. [p release];
  229934. }
  229935. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  229936. {
  229937. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  229938. if (s != nil)
  229939. s->source = source_;
  229940. return s;
  229941. }
  229942. - (void) dealloc
  229943. {
  229944. if (source != 0)
  229945. {
  229946. source->releaseResources();
  229947. delete source;
  229948. }
  229949. [super dealloc];
  229950. }
  229951. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  229952. {
  229953. }
  229954. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  229955. {
  229956. return true;
  229957. }
  229958. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  229959. {
  229960. return lengthInFrames;
  229961. }
  229962. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  229963. toMedia: (NSDictionary*) mediaInfo
  229964. {
  229965. if (source != 0)
  229966. source->prepareToPlay (44100 / 75, 44100);
  229967. readPosition = 0;
  229968. return true;
  229969. }
  229970. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  229971. {
  229972. if (source != 0)
  229973. source->prepareToPlay (44100 / 75, 44100);
  229974. return true;
  229975. }
  229976. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  229977. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  229978. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  229979. {
  229980. if (source != 0)
  229981. {
  229982. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  229983. if (numSamples > 0)
  229984. {
  229985. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  229986. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  229987. info.buffer = &tempBuffer;
  229988. info.startSample = 0;
  229989. info.numSamples = numSamples;
  229990. source->getNextAudioBlock (info);
  229991. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  229992. buffer, numSamples, 4);
  229993. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  229994. buffer + 2, numSamples, 4);
  229995. readPosition += numSamples;
  229996. }
  229997. return numSamples * 4;
  229998. }
  229999. return 0;
  230000. }
  230001. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  230002. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  230003. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  230004. ioFlags: (uint32_t*) flags
  230005. {
  230006. zeromem (buffer, bufferLength);
  230007. return bufferLength;
  230008. }
  230009. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  230010. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  230011. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  230012. {
  230013. return true;
  230014. }
  230015. @end
  230016. BEGIN_JUCE_NAMESPACE
  230017. class AudioCDBurner::Pimpl : public Timer
  230018. {
  230019. public:
  230020. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  230021. : device (0), owner (owner_)
  230022. {
  230023. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  230024. if (dev != 0)
  230025. {
  230026. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  230027. lastState = getDiskState();
  230028. startTimer (1000);
  230029. }
  230030. }
  230031. ~Pimpl()
  230032. {
  230033. stopTimer();
  230034. [device release];
  230035. }
  230036. void timerCallback()
  230037. {
  230038. const DiskState state = getDiskState();
  230039. if (state != lastState)
  230040. {
  230041. lastState = state;
  230042. owner.sendChangeMessage (&owner);
  230043. }
  230044. }
  230045. DiskState getDiskState() const
  230046. {
  230047. if ([device->device isValid])
  230048. {
  230049. NSDictionary* status = [device->device status];
  230050. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  230051. if ([state isEqualTo: DRDeviceMediaStateNone])
  230052. {
  230053. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  230054. return trayOpen;
  230055. return noDisc;
  230056. }
  230057. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  230058. {
  230059. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  230060. return writableDiskPresent;
  230061. else
  230062. return readOnlyDiskPresent;
  230063. }
  230064. }
  230065. return unknown;
  230066. }
  230067. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  230068. const Array<int> getAvailableWriteSpeeds() const
  230069. {
  230070. Array<int> results;
  230071. if ([device->device isValid])
  230072. {
  230073. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  230074. for (unsigned int i = 0; i < [speeds count]; ++i)
  230075. {
  230076. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  230077. results.add (kbPerSec / kilobytesPerSecond1x);
  230078. }
  230079. }
  230080. return results;
  230081. }
  230082. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  230083. {
  230084. if ([device->device isValid])
  230085. {
  230086. device->underrunProtection = shouldBeEnabled;
  230087. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  230088. }
  230089. return false;
  230090. }
  230091. int getNumAvailableAudioBlocks() const
  230092. {
  230093. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  230094. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  230095. }
  230096. OpenDiskDevice* device;
  230097. private:
  230098. DiskState lastState;
  230099. AudioCDBurner& owner;
  230100. };
  230101. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  230102. {
  230103. pimpl = new Pimpl (*this, deviceIndex);
  230104. }
  230105. AudioCDBurner::~AudioCDBurner()
  230106. {
  230107. }
  230108. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  230109. {
  230110. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  230111. if (b->pimpl->device == 0)
  230112. b = 0;
  230113. return b.release();
  230114. }
  230115. static NSArray* findDiskBurnerDevices()
  230116. {
  230117. NSMutableArray* results = [NSMutableArray array];
  230118. NSArray* devs = [DRDevice devices];
  230119. if (devs != 0)
  230120. {
  230121. int num = [devs count];
  230122. int i;
  230123. for (i = 0; i < num; ++i)
  230124. {
  230125. NSDictionary* dic = [[devs objectAtIndex: i] info];
  230126. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  230127. if (name != nil)
  230128. [results addObject: name];
  230129. }
  230130. }
  230131. return results;
  230132. }
  230133. const StringArray AudioCDBurner::findAvailableDevices()
  230134. {
  230135. NSArray* names = findDiskBurnerDevices();
  230136. StringArray s;
  230137. for (unsigned int i = 0; i < [names count]; ++i)
  230138. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  230139. return s;
  230140. }
  230141. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  230142. {
  230143. return pimpl->getDiskState();
  230144. }
  230145. bool AudioCDBurner::isDiskPresent() const
  230146. {
  230147. return getDiskState() == writableDiskPresent;
  230148. }
  230149. bool AudioCDBurner::openTray()
  230150. {
  230151. return pimpl->openTray();
  230152. }
  230153. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  230154. {
  230155. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  230156. DiskState oldState = getDiskState();
  230157. DiskState newState = oldState;
  230158. while (newState == oldState && Time::currentTimeMillis() < timeout)
  230159. {
  230160. newState = getDiskState();
  230161. Thread::sleep (100);
  230162. }
  230163. return newState;
  230164. }
  230165. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  230166. {
  230167. return pimpl->getAvailableWriteSpeeds();
  230168. }
  230169. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  230170. {
  230171. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  230172. }
  230173. int AudioCDBurner::getNumAvailableAudioBlocks() const
  230174. {
  230175. return pimpl->getNumAvailableAudioBlocks();
  230176. }
  230177. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  230178. {
  230179. if ([pimpl->device->device isValid])
  230180. {
  230181. [pimpl->device addSourceTrack: source numSamples: numSamps];
  230182. return true;
  230183. }
  230184. return false;
  230185. }
  230186. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  230187. bool ejectDiscAfterwards,
  230188. bool performFakeBurnForTesting,
  230189. int writeSpeed)
  230190. {
  230191. String error ("Couldn't open or write to the CD device");
  230192. if ([pimpl->device->device isValid])
  230193. {
  230194. error = String::empty;
  230195. [pimpl->device burn: listener
  230196. errorString: &error
  230197. ejectAfterwards: ejectDiscAfterwards
  230198. isFake: performFakeBurnForTesting
  230199. speed: writeSpeed];
  230200. }
  230201. return error;
  230202. }
  230203. #endif
  230204. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  230205. void AudioCDReader::ejectDisk()
  230206. {
  230207. const ScopedAutoReleasePool p;
  230208. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  230209. }
  230210. #endif
  230211. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  230212. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  230213. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230214. // compiled on its own).
  230215. #if JUCE_INCLUDED_FILE
  230216. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230217. for example having more than one juce plugin loaded into a host, then when a
  230218. method is called, the actual code that runs might actually be in a different module
  230219. than the one you expect... So any calls to library functions or statics that are
  230220. made inside obj-c methods will probably end up getting executed in a different DLL's
  230221. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230222. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230223. virtual methods of an object that's known to live inside the right module's space.
  230224. */
  230225. class AppDelegateRedirector
  230226. {
  230227. public:
  230228. AppDelegateRedirector()
  230229. {
  230230. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  230231. runLoop = CFRunLoopGetMain();
  230232. #else
  230233. runLoop = CFRunLoopGetCurrent();
  230234. #endif
  230235. CFRunLoopSourceContext sourceContext;
  230236. zerostruct (sourceContext);
  230237. sourceContext.info = this;
  230238. sourceContext.perform = runLoopSourceCallback;
  230239. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  230240. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230241. }
  230242. virtual ~AppDelegateRedirector()
  230243. {
  230244. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230245. CFRunLoopSourceInvalidate (runLoopSource);
  230246. CFRelease (runLoopSource);
  230247. while (messages.size() > 0)
  230248. delete static_cast <Message*> (messages.remove(0));
  230249. }
  230250. virtual NSApplicationTerminateReply shouldTerminate()
  230251. {
  230252. if (JUCEApplication::getInstance() != 0)
  230253. {
  230254. JUCEApplication::getInstance()->systemRequestedQuit();
  230255. return NSTerminateCancel;
  230256. }
  230257. return NSTerminateNow;
  230258. }
  230259. virtual BOOL openFile (const NSString* filename)
  230260. {
  230261. if (JUCEApplication::getInstance() != 0)
  230262. {
  230263. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  230264. return YES;
  230265. }
  230266. return NO;
  230267. }
  230268. virtual void openFiles (NSArray* filenames)
  230269. {
  230270. StringArray files;
  230271. for (unsigned int i = 0; i < [filenames count]; ++i)
  230272. {
  230273. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  230274. if (filename.containsChar (' '))
  230275. filename = filename.quoted('"');
  230276. files.add (filename);
  230277. }
  230278. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  230279. {
  230280. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  230281. }
  230282. }
  230283. virtual void focusChanged()
  230284. {
  230285. juce_HandleProcessFocusChange();
  230286. }
  230287. struct CallbackMessagePayload
  230288. {
  230289. MessageCallbackFunction* function;
  230290. void* parameter;
  230291. void* volatile result;
  230292. bool volatile hasBeenExecuted;
  230293. };
  230294. virtual void performCallback (CallbackMessagePayload* pl)
  230295. {
  230296. pl->result = (*pl->function) (pl->parameter);
  230297. pl->hasBeenExecuted = true;
  230298. }
  230299. virtual void deleteSelf()
  230300. {
  230301. delete this;
  230302. }
  230303. void postMessage (void* m)
  230304. {
  230305. messages.add (m);
  230306. CFRunLoopSourceSignal (runLoopSource);
  230307. CFRunLoopWakeUp (runLoop);
  230308. }
  230309. private:
  230310. CFRunLoopRef runLoop;
  230311. CFRunLoopSourceRef runLoopSource;
  230312. Array <void*, CriticalSection> messages;
  230313. void runLoopCallback()
  230314. {
  230315. int numDispatched = 0;
  230316. do
  230317. {
  230318. void* const nextMessage = messages.remove (0);
  230319. if (nextMessage == 0)
  230320. return;
  230321. const ScopedAutoReleasePool pool;
  230322. MessageManager::getInstance()->deliverMessage (nextMessage);
  230323. } while (++numDispatched <= 4);
  230324. CFRunLoopSourceSignal (runLoopSource);
  230325. CFRunLoopWakeUp (runLoop);
  230326. }
  230327. static void runLoopSourceCallback (void* info)
  230328. {
  230329. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  230330. }
  230331. };
  230332. END_JUCE_NAMESPACE
  230333. using namespace JUCE_NAMESPACE;
  230334. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  230335. @interface JuceAppDelegate : NSObject
  230336. {
  230337. @private
  230338. id oldDelegate;
  230339. @public
  230340. AppDelegateRedirector* redirector;
  230341. }
  230342. - (JuceAppDelegate*) init;
  230343. - (void) dealloc;
  230344. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  230345. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  230346. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  230347. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  230348. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  230349. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  230350. - (void) performCallback: (id) info;
  230351. - (void) dummyMethod;
  230352. @end
  230353. @implementation JuceAppDelegate
  230354. - (JuceAppDelegate*) init
  230355. {
  230356. [super init];
  230357. redirector = new AppDelegateRedirector();
  230358. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  230359. if (JUCEApplication::getInstance() != 0)
  230360. {
  230361. oldDelegate = [NSApp delegate];
  230362. [NSApp setDelegate: self];
  230363. }
  230364. else
  230365. {
  230366. oldDelegate = 0;
  230367. [center addObserver: self selector: @selector (applicationDidResignActive:)
  230368. name: NSApplicationDidResignActiveNotification object: NSApp];
  230369. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  230370. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  230371. [center addObserver: self selector: @selector (applicationWillUnhide:)
  230372. name: NSApplicationWillUnhideNotification object: NSApp];
  230373. }
  230374. return self;
  230375. }
  230376. - (void) dealloc
  230377. {
  230378. if (oldDelegate != 0)
  230379. [NSApp setDelegate: oldDelegate];
  230380. redirector->deleteSelf();
  230381. [super dealloc];
  230382. }
  230383. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  230384. {
  230385. (void) app;
  230386. return redirector->shouldTerminate();
  230387. }
  230388. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  230389. {
  230390. (void) app;
  230391. return redirector->openFile (filename);
  230392. }
  230393. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  230394. {
  230395. (void) sender;
  230396. return redirector->openFiles (filenames);
  230397. }
  230398. - (void) applicationDidBecomeActive: (NSNotification*) notification
  230399. {
  230400. (void) notification;
  230401. redirector->focusChanged();
  230402. }
  230403. - (void) applicationDidResignActive: (NSNotification*) notification
  230404. {
  230405. (void) notification;
  230406. redirector->focusChanged();
  230407. }
  230408. - (void) applicationWillUnhide: (NSNotification*) notification
  230409. {
  230410. (void) notification;
  230411. redirector->focusChanged();
  230412. }
  230413. - (void) performCallback: (id) info
  230414. {
  230415. if ([info isKindOfClass: [NSData class]])
  230416. {
  230417. AppDelegateRedirector::CallbackMessagePayload* pl
  230418. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  230419. if (pl != 0)
  230420. redirector->performCallback (pl);
  230421. }
  230422. else
  230423. {
  230424. jassertfalse // should never get here!
  230425. }
  230426. }
  230427. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  230428. @end
  230429. BEGIN_JUCE_NAMESPACE
  230430. static JuceAppDelegate* juceAppDelegate = 0;
  230431. void MessageManager::runDispatchLoop()
  230432. {
  230433. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  230434. {
  230435. const ScopedAutoReleasePool pool;
  230436. // must only be called by the message thread!
  230437. jassert (isThisTheMessageThread());
  230438. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  230439. @try
  230440. {
  230441. [NSApp run];
  230442. }
  230443. @catch (NSException* e)
  230444. {
  230445. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  230446. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  230447. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  230448. }
  230449. @finally
  230450. {
  230451. }
  230452. #else
  230453. [NSApp run];
  230454. #endif
  230455. }
  230456. }
  230457. void MessageManager::stopDispatchLoop()
  230458. {
  230459. quitMessagePosted = true;
  230460. [NSApp stop: nil];
  230461. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  230462. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  230463. }
  230464. static bool isEventBlockedByModalComps (NSEvent* e)
  230465. {
  230466. if (Component::getNumCurrentlyModalComponents() == 0)
  230467. return false;
  230468. NSWindow* const w = [e window];
  230469. if (w == 0 || [w worksWhenModal])
  230470. return false;
  230471. bool isKey = false, isInputAttempt = false;
  230472. switch ([e type])
  230473. {
  230474. case NSKeyDown:
  230475. case NSKeyUp:
  230476. isKey = isInputAttempt = true;
  230477. break;
  230478. case NSLeftMouseDown:
  230479. case NSRightMouseDown:
  230480. case NSOtherMouseDown:
  230481. isInputAttempt = true;
  230482. break;
  230483. case NSLeftMouseDragged:
  230484. case NSRightMouseDragged:
  230485. case NSLeftMouseUp:
  230486. case NSRightMouseUp:
  230487. case NSOtherMouseUp:
  230488. case NSOtherMouseDragged:
  230489. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  230490. return false;
  230491. break;
  230492. case NSMouseMoved:
  230493. case NSMouseEntered:
  230494. case NSMouseExited:
  230495. case NSCursorUpdate:
  230496. case NSScrollWheel:
  230497. case NSTabletPoint:
  230498. case NSTabletProximity:
  230499. break;
  230500. default:
  230501. return false;
  230502. }
  230503. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  230504. {
  230505. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  230506. NSView* const compView = (NSView*) peer->getNativeHandle();
  230507. if ([compView window] == w)
  230508. {
  230509. if (isKey)
  230510. {
  230511. if (compView == [w firstResponder])
  230512. return false;
  230513. }
  230514. else
  230515. {
  230516. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  230517. [compView bounds]))
  230518. return false;
  230519. }
  230520. }
  230521. }
  230522. if (isInputAttempt)
  230523. {
  230524. if (! [NSApp isActive])
  230525. [NSApp activateIgnoringOtherApps: YES];
  230526. Component* const modal = Component::getCurrentlyModalComponent (0);
  230527. if (modal != 0)
  230528. modal->inputAttemptWhenModal();
  230529. }
  230530. return true;
  230531. }
  230532. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  230533. {
  230534. const ScopedAutoReleasePool pool;
  230535. jassert (isThisTheMessageThread()); // must only be called by the message thread
  230536. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  230537. while (! quitMessagePosted)
  230538. {
  230539. const ScopedAutoReleasePool pool2;
  230540. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  230541. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  230542. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  230543. inMode: NSDefaultRunLoopMode
  230544. dequeue: YES];
  230545. if (e != 0 && ! isEventBlockedByModalComps (e))
  230546. [NSApp sendEvent: e];
  230547. if (Time::getMillisecondCounter() >= endTime)
  230548. break;
  230549. }
  230550. return ! quitMessagePosted;
  230551. }
  230552. void MessageManager::doPlatformSpecificInitialisation()
  230553. {
  230554. if (juceAppDelegate == 0)
  230555. juceAppDelegate = [[JuceAppDelegate alloc] init];
  230556. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  230557. // correctly (needed prior to 10.5)
  230558. if (! [NSThread isMultiThreaded])
  230559. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  230560. toTarget: juceAppDelegate
  230561. withObject: nil];
  230562. initialiseMainMenu();
  230563. }
  230564. void MessageManager::doPlatformSpecificShutdown()
  230565. {
  230566. if (juceAppDelegate != 0)
  230567. {
  230568. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  230569. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  230570. [juceAppDelegate release];
  230571. juceAppDelegate = 0;
  230572. }
  230573. }
  230574. bool juce_postMessageToSystemQueue (void* message)
  230575. {
  230576. juceAppDelegate->redirector->postMessage (message);
  230577. return true;
  230578. }
  230579. void MessageManager::broadcastMessage (const String& value) throw()
  230580. {
  230581. }
  230582. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  230583. void* data)
  230584. {
  230585. if (isThisTheMessageThread())
  230586. {
  230587. return (*callback) (data);
  230588. }
  230589. else
  230590. {
  230591. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  230592. // deadlock because the message manager is blocked from running, so can never
  230593. // call your function..
  230594. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  230595. const ScopedAutoReleasePool pool;
  230596. AppDelegateRedirector::CallbackMessagePayload cmp;
  230597. cmp.function = callback;
  230598. cmp.parameter = data;
  230599. cmp.result = 0;
  230600. cmp.hasBeenExecuted = false;
  230601. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  230602. withObject: [NSData dataWithBytesNoCopy: &cmp
  230603. length: sizeof (cmp)
  230604. freeWhenDone: NO]
  230605. waitUntilDone: YES];
  230606. return cmp.result;
  230607. }
  230608. }
  230609. #endif
  230610. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  230611. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  230612. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230613. // compiled on its own).
  230614. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  230615. #if JUCE_MAC
  230616. END_JUCE_NAMESPACE
  230617. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  230618. @interface DownloadClickDetector : NSObject
  230619. {
  230620. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  230621. }
  230622. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  230623. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  230624. request: (NSURLRequest*) request
  230625. frame: (WebFrame*) frame
  230626. decisionListener: (id<WebPolicyDecisionListener>) listener;
  230627. @end
  230628. @implementation DownloadClickDetector
  230629. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  230630. {
  230631. [super init];
  230632. ownerComponent = ownerComponent_;
  230633. return self;
  230634. }
  230635. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  230636. request: (NSURLRequest*) request
  230637. frame: (WebFrame*) frame
  230638. decisionListener: (id <WebPolicyDecisionListener>) listener
  230639. {
  230640. (void) sender;
  230641. (void) request;
  230642. (void) frame;
  230643. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  230644. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  230645. [listener use];
  230646. else
  230647. [listener ignore];
  230648. }
  230649. @end
  230650. BEGIN_JUCE_NAMESPACE
  230651. class WebBrowserComponentInternal : public NSViewComponent
  230652. {
  230653. public:
  230654. WebBrowserComponentInternal (WebBrowserComponent* owner)
  230655. {
  230656. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  230657. frameName: @""
  230658. groupName: @""];
  230659. setView (webView);
  230660. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  230661. [webView setPolicyDelegate: clickListener];
  230662. }
  230663. ~WebBrowserComponentInternal()
  230664. {
  230665. [webView setPolicyDelegate: nil];
  230666. [clickListener release];
  230667. setView (0);
  230668. }
  230669. void goToURL (const String& url,
  230670. const StringArray* headers,
  230671. const MemoryBlock* postData)
  230672. {
  230673. NSMutableURLRequest* r
  230674. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  230675. cachePolicy: NSURLRequestUseProtocolCachePolicy
  230676. timeoutInterval: 30.0];
  230677. if (postData != 0 && postData->getSize() > 0)
  230678. {
  230679. [r setHTTPMethod: @"POST"];
  230680. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  230681. length: postData->getSize()]];
  230682. }
  230683. if (headers != 0)
  230684. {
  230685. for (int i = 0; i < headers->size(); ++i)
  230686. {
  230687. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  230688. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  230689. [r setValue: juceStringToNS (headerValue)
  230690. forHTTPHeaderField: juceStringToNS (headerName)];
  230691. }
  230692. }
  230693. stop();
  230694. [[webView mainFrame] loadRequest: r];
  230695. }
  230696. void goBack()
  230697. {
  230698. [webView goBack];
  230699. }
  230700. void goForward()
  230701. {
  230702. [webView goForward];
  230703. }
  230704. void stop()
  230705. {
  230706. [webView stopLoading: nil];
  230707. }
  230708. void refresh()
  230709. {
  230710. [webView reload: nil];
  230711. }
  230712. private:
  230713. WebView* webView;
  230714. DownloadClickDetector* clickListener;
  230715. };
  230716. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  230717. : browser (0),
  230718. blankPageShown (false),
  230719. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  230720. {
  230721. setOpaque (true);
  230722. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  230723. }
  230724. WebBrowserComponent::~WebBrowserComponent()
  230725. {
  230726. deleteAndZero (browser);
  230727. }
  230728. void WebBrowserComponent::goToURL (const String& url,
  230729. const StringArray* headers,
  230730. const MemoryBlock* postData)
  230731. {
  230732. lastURL = url;
  230733. lastHeaders.clear();
  230734. if (headers != 0)
  230735. lastHeaders = *headers;
  230736. lastPostData.setSize (0);
  230737. if (postData != 0)
  230738. lastPostData = *postData;
  230739. blankPageShown = false;
  230740. browser->goToURL (url, headers, postData);
  230741. }
  230742. void WebBrowserComponent::stop()
  230743. {
  230744. browser->stop();
  230745. }
  230746. void WebBrowserComponent::goBack()
  230747. {
  230748. lastURL = String::empty;
  230749. blankPageShown = false;
  230750. browser->goBack();
  230751. }
  230752. void WebBrowserComponent::goForward()
  230753. {
  230754. lastURL = String::empty;
  230755. browser->goForward();
  230756. }
  230757. void WebBrowserComponent::refresh()
  230758. {
  230759. browser->refresh();
  230760. }
  230761. void WebBrowserComponent::paint (Graphics&)
  230762. {
  230763. }
  230764. void WebBrowserComponent::checkWindowAssociation()
  230765. {
  230766. if (isShowing())
  230767. {
  230768. if (blankPageShown)
  230769. goBack();
  230770. }
  230771. else
  230772. {
  230773. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  230774. {
  230775. // when the component becomes invisible, some stuff like flash
  230776. // carries on playing audio, so we need to force it onto a blank
  230777. // page to avoid this, (and send it back when it's made visible again).
  230778. blankPageShown = true;
  230779. browser->goToURL ("about:blank", 0, 0);
  230780. }
  230781. }
  230782. }
  230783. void WebBrowserComponent::reloadLastURL()
  230784. {
  230785. if (lastURL.isNotEmpty())
  230786. {
  230787. goToURL (lastURL, &lastHeaders, &lastPostData);
  230788. lastURL = String::empty;
  230789. }
  230790. }
  230791. void WebBrowserComponent::parentHierarchyChanged()
  230792. {
  230793. checkWindowAssociation();
  230794. }
  230795. void WebBrowserComponent::resized()
  230796. {
  230797. browser->setSize (getWidth(), getHeight());
  230798. }
  230799. void WebBrowserComponent::visibilityChanged()
  230800. {
  230801. checkWindowAssociation();
  230802. }
  230803. bool WebBrowserComponent::pageAboutToLoad (const String&)
  230804. {
  230805. return true;
  230806. }
  230807. #else
  230808. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  230809. {
  230810. }
  230811. WebBrowserComponent::~WebBrowserComponent()
  230812. {
  230813. }
  230814. void WebBrowserComponent::goToURL (const String& url,
  230815. const StringArray* headers,
  230816. const MemoryBlock* postData)
  230817. {
  230818. }
  230819. void WebBrowserComponent::stop()
  230820. {
  230821. }
  230822. void WebBrowserComponent::goBack()
  230823. {
  230824. }
  230825. void WebBrowserComponent::goForward()
  230826. {
  230827. }
  230828. void WebBrowserComponent::refresh()
  230829. {
  230830. }
  230831. void WebBrowserComponent::paint (Graphics& g)
  230832. {
  230833. }
  230834. void WebBrowserComponent::checkWindowAssociation()
  230835. {
  230836. }
  230837. void WebBrowserComponent::reloadLastURL()
  230838. {
  230839. }
  230840. void WebBrowserComponent::parentHierarchyChanged()
  230841. {
  230842. }
  230843. void WebBrowserComponent::resized()
  230844. {
  230845. }
  230846. void WebBrowserComponent::visibilityChanged()
  230847. {
  230848. }
  230849. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  230850. {
  230851. return true;
  230852. }
  230853. #endif
  230854. #endif
  230855. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  230856. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  230857. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230858. // compiled on its own).
  230859. #if JUCE_INCLUDED_FILE
  230860. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  230861. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  230862. #endif
  230863. #undef log
  230864. #if JUCE_COREAUDIO_LOGGING_ENABLED
  230865. #define log(a) Logger::writeToLog (a)
  230866. #else
  230867. #define log(a)
  230868. #endif
  230869. #undef OK
  230870. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  230871. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  230872. {
  230873. if (err == noErr)
  230874. return true;
  230875. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  230876. jassertfalse
  230877. return false;
  230878. }
  230879. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  230880. #else
  230881. #define OK(a) (a == noErr)
  230882. #endif
  230883. class CoreAudioInternal : public Timer
  230884. {
  230885. public:
  230886. CoreAudioInternal (AudioDeviceID id)
  230887. : inputLatency (0),
  230888. outputLatency (0),
  230889. callback (0),
  230890. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  230891. audioProcID (0),
  230892. #endif
  230893. inputDevice (0),
  230894. isSlaveDevice (false),
  230895. deviceID (id),
  230896. started (false),
  230897. sampleRate (0),
  230898. bufferSize (512),
  230899. numInputChans (0),
  230900. numOutputChans (0),
  230901. callbacksAllowed (true),
  230902. numInputChannelInfos (0),
  230903. numOutputChannelInfos (0)
  230904. {
  230905. jassert (deviceID != 0);
  230906. updateDetailsFromDevice();
  230907. AudioObjectPropertyAddress pa;
  230908. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  230909. pa.mScope = kAudioObjectPropertyScopeWildcard;
  230910. pa.mElement = kAudioObjectPropertyElementWildcard;
  230911. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  230912. }
  230913. ~CoreAudioInternal()
  230914. {
  230915. AudioObjectPropertyAddress pa;
  230916. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  230917. pa.mScope = kAudioObjectPropertyScopeWildcard;
  230918. pa.mElement = kAudioObjectPropertyElementWildcard;
  230919. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  230920. stop (false);
  230921. delete inputDevice;
  230922. }
  230923. void allocateTempBuffers()
  230924. {
  230925. const int tempBufSize = bufferSize + 4;
  230926. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  230927. tempInputBuffers.calloc (numInputChans + 2);
  230928. tempOutputBuffers.calloc (numOutputChans + 2);
  230929. int i, count = 0;
  230930. for (i = 0; i < numInputChans; ++i)
  230931. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  230932. for (i = 0; i < numOutputChans; ++i)
  230933. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  230934. }
  230935. // returns the number of actual available channels
  230936. void fillInChannelInfo (const bool input)
  230937. {
  230938. int chanNum = 0;
  230939. UInt32 size;
  230940. AudioObjectPropertyAddress pa;
  230941. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  230942. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  230943. pa.mElement = kAudioObjectPropertyElementMaster;
  230944. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  230945. {
  230946. HeapBlock <AudioBufferList> bufList;
  230947. bufList.calloc (size, 1);
  230948. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  230949. {
  230950. const int numStreams = bufList->mNumberBuffers;
  230951. for (int i = 0; i < numStreams; ++i)
  230952. {
  230953. const AudioBuffer& b = bufList->mBuffers[i];
  230954. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  230955. {
  230956. String name;
  230957. {
  230958. char channelName [256];
  230959. zerostruct (channelName);
  230960. UInt32 nameSize = sizeof (channelName);
  230961. UInt32 channelNum = chanNum + 1;
  230962. pa.mSelector = kAudioDevicePropertyChannelName;
  230963. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  230964. name = String::fromUTF8 (channelName, nameSize);
  230965. }
  230966. if (input)
  230967. {
  230968. if (activeInputChans[chanNum])
  230969. {
  230970. inputChannelInfo [numInputChannelInfos].streamNum = i;
  230971. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  230972. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  230973. ++numInputChannelInfos;
  230974. }
  230975. if (name.isEmpty())
  230976. name << "Input " << (chanNum + 1);
  230977. inChanNames.add (name);
  230978. }
  230979. else
  230980. {
  230981. if (activeOutputChans[chanNum])
  230982. {
  230983. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  230984. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  230985. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  230986. ++numOutputChannelInfos;
  230987. }
  230988. if (name.isEmpty())
  230989. name << "Output " << (chanNum + 1);
  230990. outChanNames.add (name);
  230991. }
  230992. ++chanNum;
  230993. }
  230994. }
  230995. }
  230996. }
  230997. }
  230998. void updateDetailsFromDevice()
  230999. {
  231000. stopTimer();
  231001. if (deviceID == 0)
  231002. return;
  231003. const ScopedLock sl (callbackLock);
  231004. Float64 sr;
  231005. UInt32 size = sizeof (Float64);
  231006. AudioObjectPropertyAddress pa;
  231007. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231008. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231009. pa.mElement = kAudioObjectPropertyElementMaster;
  231010. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  231011. sampleRate = sr;
  231012. UInt32 framesPerBuf;
  231013. size = sizeof (framesPerBuf);
  231014. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231015. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  231016. {
  231017. bufferSize = framesPerBuf;
  231018. allocateTempBuffers();
  231019. }
  231020. bufferSizes.clear();
  231021. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  231022. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231023. {
  231024. HeapBlock <AudioValueRange> ranges;
  231025. ranges.calloc (size, 1);
  231026. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231027. {
  231028. bufferSizes.add ((int) ranges[0].mMinimum);
  231029. for (int i = 32; i < 2048; i += 32)
  231030. {
  231031. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231032. {
  231033. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  231034. {
  231035. bufferSizes.addIfNotAlreadyThere (i);
  231036. break;
  231037. }
  231038. }
  231039. }
  231040. if (bufferSize > 0)
  231041. bufferSizes.addIfNotAlreadyThere (bufferSize);
  231042. }
  231043. }
  231044. if (bufferSizes.size() == 0 && bufferSize > 0)
  231045. bufferSizes.add (bufferSize);
  231046. sampleRates.clear();
  231047. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  231048. String rates;
  231049. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  231050. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231051. {
  231052. HeapBlock <AudioValueRange> ranges;
  231053. ranges.calloc (size, 1);
  231054. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231055. {
  231056. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  231057. {
  231058. bool ok = false;
  231059. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231060. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  231061. ok = true;
  231062. if (ok)
  231063. {
  231064. sampleRates.add (possibleRates[i]);
  231065. rates << possibleRates[i] << ' ';
  231066. }
  231067. }
  231068. }
  231069. }
  231070. if (sampleRates.size() == 0 && sampleRate > 0)
  231071. {
  231072. sampleRates.add (sampleRate);
  231073. rates << sampleRate;
  231074. }
  231075. log ("sr: " + rates);
  231076. inputLatency = 0;
  231077. outputLatency = 0;
  231078. UInt32 lat;
  231079. size = sizeof (lat);
  231080. pa.mSelector = kAudioDevicePropertyLatency;
  231081. pa.mScope = kAudioDevicePropertyScopeInput;
  231082. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  231083. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231084. inputLatency = (int) lat;
  231085. pa.mScope = kAudioDevicePropertyScopeOutput;
  231086. size = sizeof (lat);
  231087. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231088. outputLatency = (int) lat;
  231089. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  231090. inChanNames.clear();
  231091. outChanNames.clear();
  231092. inputChannelInfo.calloc (numInputChans + 2);
  231093. numInputChannelInfos = 0;
  231094. outputChannelInfo.calloc (numOutputChans + 2);
  231095. numOutputChannelInfos = 0;
  231096. fillInChannelInfo (true);
  231097. fillInChannelInfo (false);
  231098. }
  231099. const StringArray getSources (bool input)
  231100. {
  231101. StringArray s;
  231102. HeapBlock <OSType> types;
  231103. const int num = getAllDataSourcesForDevice (deviceID, types);
  231104. for (int i = 0; i < num; ++i)
  231105. {
  231106. AudioValueTranslation avt;
  231107. char buffer[256];
  231108. avt.mInputData = &(types[i]);
  231109. avt.mInputDataSize = sizeof (UInt32);
  231110. avt.mOutputData = buffer;
  231111. avt.mOutputDataSize = 256;
  231112. UInt32 transSize = sizeof (avt);
  231113. AudioObjectPropertyAddress pa;
  231114. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  231115. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231116. pa.mElement = kAudioObjectPropertyElementMaster;
  231117. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  231118. {
  231119. DBG (buffer);
  231120. s.add (buffer);
  231121. }
  231122. }
  231123. return s;
  231124. }
  231125. int getCurrentSourceIndex (bool input) const
  231126. {
  231127. OSType currentSourceID = 0;
  231128. UInt32 size = sizeof (currentSourceID);
  231129. int result = -1;
  231130. AudioObjectPropertyAddress pa;
  231131. pa.mSelector = kAudioDevicePropertyDataSource;
  231132. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231133. pa.mElement = kAudioObjectPropertyElementMaster;
  231134. if (deviceID != 0)
  231135. {
  231136. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  231137. {
  231138. HeapBlock <OSType> types;
  231139. const int num = getAllDataSourcesForDevice (deviceID, types);
  231140. for (int i = 0; i < num; ++i)
  231141. {
  231142. if (types[num] == currentSourceID)
  231143. {
  231144. result = i;
  231145. break;
  231146. }
  231147. }
  231148. }
  231149. }
  231150. return result;
  231151. }
  231152. void setCurrentSourceIndex (int index, bool input)
  231153. {
  231154. if (deviceID != 0)
  231155. {
  231156. HeapBlock <OSType> types;
  231157. const int num = getAllDataSourcesForDevice (deviceID, types);
  231158. if (((unsigned int) index) < (unsigned int) num)
  231159. {
  231160. AudioObjectPropertyAddress pa;
  231161. pa.mSelector = kAudioDevicePropertyDataSource;
  231162. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231163. pa.mElement = kAudioObjectPropertyElementMaster;
  231164. OSType typeId = types[index];
  231165. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  231166. }
  231167. }
  231168. }
  231169. const String reopen (const BigInteger& inputChannels,
  231170. const BigInteger& outputChannels,
  231171. double newSampleRate,
  231172. int bufferSizeSamples)
  231173. {
  231174. String error;
  231175. log ("CoreAudio reopen");
  231176. callbacksAllowed = false;
  231177. stopTimer();
  231178. stop (false);
  231179. activeInputChans = inputChannels;
  231180. activeInputChans.setRange (inChanNames.size(),
  231181. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  231182. false);
  231183. activeOutputChans = outputChannels;
  231184. activeOutputChans.setRange (outChanNames.size(),
  231185. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  231186. false);
  231187. numInputChans = activeInputChans.countNumberOfSetBits();
  231188. numOutputChans = activeOutputChans.countNumberOfSetBits();
  231189. // set sample rate
  231190. AudioObjectPropertyAddress pa;
  231191. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231192. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231193. pa.mElement = kAudioObjectPropertyElementMaster;
  231194. Float64 sr = newSampleRate;
  231195. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  231196. {
  231197. error = "Couldn't change sample rate";
  231198. }
  231199. else
  231200. {
  231201. // change buffer size
  231202. UInt32 framesPerBuf = bufferSizeSamples;
  231203. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231204. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  231205. {
  231206. error = "Couldn't change buffer size";
  231207. }
  231208. else
  231209. {
  231210. // Annoyingly, after changing the rate and buffer size, some devices fail to
  231211. // correctly report their new settings until some random time in the future, so
  231212. // after calling updateDetailsFromDevice, we need to manually bodge these values
  231213. // to make sure we're using the correct numbers..
  231214. updateDetailsFromDevice();
  231215. sampleRate = newSampleRate;
  231216. bufferSize = bufferSizeSamples;
  231217. if (sampleRates.size() == 0)
  231218. error = "Device has no available sample-rates";
  231219. else if (bufferSizes.size() == 0)
  231220. error = "Device has no available buffer-sizes";
  231221. else if (inputDevice != 0)
  231222. error = inputDevice->reopen (inputChannels,
  231223. outputChannels,
  231224. newSampleRate,
  231225. bufferSizeSamples);
  231226. }
  231227. }
  231228. callbacksAllowed = true;
  231229. return error;
  231230. }
  231231. bool start (AudioIODeviceCallback* cb)
  231232. {
  231233. if (! started)
  231234. {
  231235. callback = 0;
  231236. if (deviceID != 0)
  231237. {
  231238. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231239. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  231240. #else
  231241. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  231242. #endif
  231243. {
  231244. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  231245. {
  231246. started = true;
  231247. }
  231248. else
  231249. {
  231250. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231251. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231252. #else
  231253. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231254. audioProcID = 0;
  231255. #endif
  231256. }
  231257. }
  231258. }
  231259. }
  231260. if (started)
  231261. {
  231262. const ScopedLock sl (callbackLock);
  231263. callback = cb;
  231264. }
  231265. if (inputDevice != 0)
  231266. return started && inputDevice->start (cb);
  231267. else
  231268. return started;
  231269. }
  231270. void stop (bool leaveInterruptRunning)
  231271. {
  231272. {
  231273. const ScopedLock sl (callbackLock);
  231274. callback = 0;
  231275. }
  231276. if (started
  231277. && (deviceID != 0)
  231278. && ! leaveInterruptRunning)
  231279. {
  231280. OK (AudioDeviceStop (deviceID, audioIOProc));
  231281. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231282. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231283. #else
  231284. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231285. audioProcID = 0;
  231286. #endif
  231287. started = false;
  231288. { const ScopedLock sl (callbackLock); }
  231289. // wait until it's definately stopped calling back..
  231290. for (int i = 40; --i >= 0;)
  231291. {
  231292. Thread::sleep (50);
  231293. UInt32 running = 0;
  231294. UInt32 size = sizeof (running);
  231295. AudioObjectPropertyAddress pa;
  231296. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  231297. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231298. pa.mElement = kAudioObjectPropertyElementMaster;
  231299. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  231300. if (running == 0)
  231301. break;
  231302. }
  231303. const ScopedLock sl (callbackLock);
  231304. }
  231305. if (inputDevice != 0)
  231306. inputDevice->stop (leaveInterruptRunning);
  231307. }
  231308. double getSampleRate() const
  231309. {
  231310. return sampleRate;
  231311. }
  231312. int getBufferSize() const
  231313. {
  231314. return bufferSize;
  231315. }
  231316. void audioCallback (const AudioBufferList* inInputData,
  231317. AudioBufferList* outOutputData)
  231318. {
  231319. int i;
  231320. const ScopedLock sl (callbackLock);
  231321. if (callback != 0)
  231322. {
  231323. if (inputDevice == 0)
  231324. {
  231325. for (i = numInputChans; --i >= 0;)
  231326. {
  231327. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  231328. float* dest = tempInputBuffers [i];
  231329. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  231330. + info.dataOffsetSamples;
  231331. const int stride = info.dataStrideSamples;
  231332. if (stride != 0) // if this is zero, info is invalid
  231333. {
  231334. for (int j = bufferSize; --j >= 0;)
  231335. {
  231336. *dest++ = *src;
  231337. src += stride;
  231338. }
  231339. }
  231340. }
  231341. }
  231342. if (! isSlaveDevice)
  231343. {
  231344. if (inputDevice == 0)
  231345. {
  231346. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  231347. numInputChans,
  231348. tempOutputBuffers,
  231349. numOutputChans,
  231350. bufferSize);
  231351. }
  231352. else
  231353. {
  231354. jassert (inputDevice->bufferSize == bufferSize);
  231355. // Sometimes the two linked devices seem to get their callbacks in
  231356. // parallel, so we need to lock both devices to stop the input data being
  231357. // changed while inside our callback..
  231358. const ScopedLock sl2 (inputDevice->callbackLock);
  231359. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  231360. inputDevice->numInputChans,
  231361. tempOutputBuffers,
  231362. numOutputChans,
  231363. bufferSize);
  231364. }
  231365. for (i = numOutputChans; --i >= 0;)
  231366. {
  231367. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231368. const float* src = tempOutputBuffers [i];
  231369. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231370. + info.dataOffsetSamples;
  231371. const int stride = info.dataStrideSamples;
  231372. if (stride != 0) // if this is zero, info is invalid
  231373. {
  231374. for (int j = bufferSize; --j >= 0;)
  231375. {
  231376. *dest = *src++;
  231377. dest += stride;
  231378. }
  231379. }
  231380. }
  231381. }
  231382. }
  231383. else
  231384. {
  231385. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  231386. {
  231387. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231388. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231389. + info.dataOffsetSamples;
  231390. const int stride = info.dataStrideSamples;
  231391. if (stride != 0) // if this is zero, info is invalid
  231392. {
  231393. for (int j = bufferSize; --j >= 0;)
  231394. {
  231395. *dest = 0.0f;
  231396. dest += stride;
  231397. }
  231398. }
  231399. }
  231400. }
  231401. }
  231402. // called by callbacks
  231403. void deviceDetailsChanged()
  231404. {
  231405. if (callbacksAllowed)
  231406. startTimer (100);
  231407. }
  231408. void timerCallback()
  231409. {
  231410. stopTimer();
  231411. log ("CoreAudio device changed callback");
  231412. const double oldSampleRate = sampleRate;
  231413. const int oldBufferSize = bufferSize;
  231414. updateDetailsFromDevice();
  231415. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  231416. {
  231417. callbacksAllowed = false;
  231418. stop (false);
  231419. updateDetailsFromDevice();
  231420. callbacksAllowed = true;
  231421. }
  231422. }
  231423. CoreAudioInternal* getRelatedDevice() const
  231424. {
  231425. UInt32 size = 0;
  231426. ScopedPointer <CoreAudioInternal> result;
  231427. AudioObjectPropertyAddress pa;
  231428. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  231429. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231430. pa.mElement = kAudioObjectPropertyElementMaster;
  231431. if (deviceID != 0
  231432. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  231433. && size > 0)
  231434. {
  231435. HeapBlock <AudioDeviceID> devs;
  231436. devs.calloc (size, 1);
  231437. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  231438. {
  231439. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  231440. {
  231441. if (devs[i] != deviceID && devs[i] != 0)
  231442. {
  231443. result = new CoreAudioInternal (devs[i]);
  231444. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  231445. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  231446. if (thisIsInput != otherIsInput
  231447. || (inChanNames.size() + outChanNames.size() == 0)
  231448. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  231449. break;
  231450. result = 0;
  231451. }
  231452. }
  231453. }
  231454. }
  231455. return result.release();
  231456. }
  231457. juce_UseDebuggingNewOperator
  231458. int inputLatency, outputLatency;
  231459. BigInteger activeInputChans, activeOutputChans;
  231460. StringArray inChanNames, outChanNames;
  231461. Array <double> sampleRates;
  231462. Array <int> bufferSizes;
  231463. AudioIODeviceCallback* callback;
  231464. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  231465. AudioDeviceIOProcID audioProcID;
  231466. #endif
  231467. CoreAudioInternal* inputDevice;
  231468. bool isSlaveDevice;
  231469. private:
  231470. CriticalSection callbackLock;
  231471. AudioDeviceID deviceID;
  231472. bool started;
  231473. double sampleRate;
  231474. int bufferSize;
  231475. HeapBlock <float> audioBuffer;
  231476. int numInputChans, numOutputChans;
  231477. bool callbacksAllowed;
  231478. struct CallbackDetailsForChannel
  231479. {
  231480. int streamNum;
  231481. int dataOffsetSamples;
  231482. int dataStrideSamples;
  231483. };
  231484. int numInputChannelInfos, numOutputChannelInfos;
  231485. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  231486. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  231487. CoreAudioInternal (const CoreAudioInternal&);
  231488. CoreAudioInternal& operator= (const CoreAudioInternal&);
  231489. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  231490. const AudioTimeStamp* /*inNow*/,
  231491. const AudioBufferList* inInputData,
  231492. const AudioTimeStamp* /*inInputTime*/,
  231493. AudioBufferList* outOutputData,
  231494. const AudioTimeStamp* /*inOutputTime*/,
  231495. void* device)
  231496. {
  231497. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  231498. return noErr;
  231499. }
  231500. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  231501. {
  231502. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  231503. switch (pa->mSelector)
  231504. {
  231505. case kAudioDevicePropertyBufferSize:
  231506. case kAudioDevicePropertyBufferFrameSize:
  231507. case kAudioDevicePropertyNominalSampleRate:
  231508. case kAudioDevicePropertyStreamFormat:
  231509. case kAudioDevicePropertyDeviceIsAlive:
  231510. intern->deviceDetailsChanged();
  231511. break;
  231512. case kAudioDevicePropertyBufferSizeRange:
  231513. case kAudioDevicePropertyVolumeScalar:
  231514. case kAudioDevicePropertyMute:
  231515. case kAudioDevicePropertyPlayThru:
  231516. case kAudioDevicePropertyDataSource:
  231517. case kAudioDevicePropertyDeviceIsRunning:
  231518. break;
  231519. }
  231520. return noErr;
  231521. }
  231522. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  231523. {
  231524. AudioObjectPropertyAddress pa;
  231525. pa.mSelector = kAudioDevicePropertyDataSources;
  231526. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231527. pa.mElement = kAudioObjectPropertyElementMaster;
  231528. UInt32 size = 0;
  231529. if (deviceID != 0
  231530. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231531. {
  231532. types.calloc (size, 1);
  231533. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  231534. return size / (int) sizeof (OSType);
  231535. }
  231536. return 0;
  231537. }
  231538. };
  231539. class CoreAudioIODevice : public AudioIODevice
  231540. {
  231541. public:
  231542. CoreAudioIODevice (const String& deviceName,
  231543. AudioDeviceID inputDeviceId,
  231544. const int inputIndex_,
  231545. AudioDeviceID outputDeviceId,
  231546. const int outputIndex_)
  231547. : AudioIODevice (deviceName, "CoreAudio"),
  231548. inputIndex (inputIndex_),
  231549. outputIndex (outputIndex_),
  231550. isOpen_ (false),
  231551. isStarted (false)
  231552. {
  231553. internal = 0;
  231554. CoreAudioInternal* device = 0;
  231555. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  231556. {
  231557. jassert (inputDeviceId != 0);
  231558. device = new CoreAudioInternal (inputDeviceId);
  231559. }
  231560. else
  231561. {
  231562. device = new CoreAudioInternal (outputDeviceId);
  231563. if (inputDeviceId != 0)
  231564. {
  231565. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  231566. device->inputDevice = secondDevice;
  231567. secondDevice->isSlaveDevice = true;
  231568. }
  231569. }
  231570. internal = device;
  231571. AudioObjectPropertyAddress pa;
  231572. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231573. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231574. pa.mElement = kAudioObjectPropertyElementWildcard;
  231575. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  231576. }
  231577. ~CoreAudioIODevice()
  231578. {
  231579. AudioObjectPropertyAddress pa;
  231580. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231581. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231582. pa.mElement = kAudioObjectPropertyElementWildcard;
  231583. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  231584. delete internal;
  231585. }
  231586. const StringArray getOutputChannelNames()
  231587. {
  231588. return internal->outChanNames;
  231589. }
  231590. const StringArray getInputChannelNames()
  231591. {
  231592. if (internal->inputDevice != 0)
  231593. return internal->inputDevice->inChanNames;
  231594. else
  231595. return internal->inChanNames;
  231596. }
  231597. int getNumSampleRates()
  231598. {
  231599. return internal->sampleRates.size();
  231600. }
  231601. double getSampleRate (int index)
  231602. {
  231603. return internal->sampleRates [index];
  231604. }
  231605. int getNumBufferSizesAvailable()
  231606. {
  231607. return internal->bufferSizes.size();
  231608. }
  231609. int getBufferSizeSamples (int index)
  231610. {
  231611. return internal->bufferSizes [index];
  231612. }
  231613. int getDefaultBufferSize()
  231614. {
  231615. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  231616. if (getBufferSizeSamples(i) >= 512)
  231617. return getBufferSizeSamples(i);
  231618. return 512;
  231619. }
  231620. const String open (const BigInteger& inputChannels,
  231621. const BigInteger& outputChannels,
  231622. double sampleRate,
  231623. int bufferSizeSamples)
  231624. {
  231625. isOpen_ = true;
  231626. if (bufferSizeSamples <= 0)
  231627. bufferSizeSamples = getDefaultBufferSize();
  231628. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  231629. isOpen_ = lastError.isEmpty();
  231630. return lastError;
  231631. }
  231632. void close()
  231633. {
  231634. isOpen_ = false;
  231635. internal->stop (false);
  231636. }
  231637. bool isOpen()
  231638. {
  231639. return isOpen_;
  231640. }
  231641. int getCurrentBufferSizeSamples()
  231642. {
  231643. return internal != 0 ? internal->getBufferSize() : 512;
  231644. }
  231645. double getCurrentSampleRate()
  231646. {
  231647. return internal != 0 ? internal->getSampleRate() : 0;
  231648. }
  231649. int getCurrentBitDepth()
  231650. {
  231651. return 32; // no way to find out, so just assume it's high..
  231652. }
  231653. const BigInteger getActiveOutputChannels() const
  231654. {
  231655. return internal != 0 ? internal->activeOutputChans : BigInteger();
  231656. }
  231657. const BigInteger getActiveInputChannels() const
  231658. {
  231659. BigInteger chans;
  231660. if (internal != 0)
  231661. {
  231662. chans = internal->activeInputChans;
  231663. if (internal->inputDevice != 0)
  231664. chans |= internal->inputDevice->activeInputChans;
  231665. }
  231666. return chans;
  231667. }
  231668. int getOutputLatencyInSamples()
  231669. {
  231670. if (internal == 0)
  231671. return 0;
  231672. // this seems like a good guess at getting the latency right - comparing
  231673. // this with a round-trip measurement, it gets it to within a few millisecs
  231674. // for the built-in mac soundcard
  231675. return internal->outputLatency + internal->getBufferSize() * 2;
  231676. }
  231677. int getInputLatencyInSamples()
  231678. {
  231679. if (internal == 0)
  231680. return 0;
  231681. return internal->inputLatency + internal->getBufferSize() * 2;
  231682. }
  231683. void start (AudioIODeviceCallback* callback)
  231684. {
  231685. if (internal != 0 && ! isStarted)
  231686. {
  231687. if (callback != 0)
  231688. callback->audioDeviceAboutToStart (this);
  231689. isStarted = true;
  231690. internal->start (callback);
  231691. }
  231692. }
  231693. void stop()
  231694. {
  231695. if (isStarted && internal != 0)
  231696. {
  231697. AudioIODeviceCallback* const lastCallback = internal->callback;
  231698. isStarted = false;
  231699. internal->stop (true);
  231700. if (lastCallback != 0)
  231701. lastCallback->audioDeviceStopped();
  231702. }
  231703. }
  231704. bool isPlaying()
  231705. {
  231706. if (internal->callback == 0)
  231707. isStarted = false;
  231708. return isStarted;
  231709. }
  231710. const String getLastError()
  231711. {
  231712. return lastError;
  231713. }
  231714. int inputIndex, outputIndex;
  231715. juce_UseDebuggingNewOperator
  231716. private:
  231717. CoreAudioInternal* internal;
  231718. bool isOpen_, isStarted;
  231719. String lastError;
  231720. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  231721. {
  231722. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  231723. switch (pa->mSelector)
  231724. {
  231725. case kAudioHardwarePropertyDevices:
  231726. intern->deviceDetailsChanged();
  231727. break;
  231728. case kAudioHardwarePropertyDefaultOutputDevice:
  231729. case kAudioHardwarePropertyDefaultInputDevice:
  231730. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  231731. break;
  231732. }
  231733. return noErr;
  231734. }
  231735. CoreAudioIODevice (const CoreAudioIODevice&);
  231736. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  231737. };
  231738. class CoreAudioIODeviceType : public AudioIODeviceType
  231739. {
  231740. public:
  231741. CoreAudioIODeviceType()
  231742. : AudioIODeviceType ("CoreAudio"),
  231743. hasScanned (false)
  231744. {
  231745. }
  231746. ~CoreAudioIODeviceType()
  231747. {
  231748. }
  231749. void scanForDevices()
  231750. {
  231751. hasScanned = true;
  231752. inputDeviceNames.clear();
  231753. outputDeviceNames.clear();
  231754. inputIds.clear();
  231755. outputIds.clear();
  231756. UInt32 size;
  231757. AudioObjectPropertyAddress pa;
  231758. pa.mSelector = kAudioHardwarePropertyDevices;
  231759. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231760. pa.mElement = kAudioObjectPropertyElementMaster;
  231761. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  231762. {
  231763. HeapBlock <AudioDeviceID> devs;
  231764. devs.calloc (size, 1);
  231765. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  231766. {
  231767. static bool alreadyLogged = false;
  231768. const int num = size / (int) sizeof (AudioDeviceID);
  231769. for (int i = 0; i < num; ++i)
  231770. {
  231771. char name [1024];
  231772. size = sizeof (name);
  231773. pa.mSelector = kAudioDevicePropertyDeviceName;
  231774. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  231775. {
  231776. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  231777. if (! alreadyLogged)
  231778. log ("CoreAudio device: " + nameString);
  231779. const int numIns = getNumChannels (devs[i], true);
  231780. const int numOuts = getNumChannels (devs[i], false);
  231781. if (numIns > 0)
  231782. {
  231783. inputDeviceNames.add (nameString);
  231784. inputIds.add (devs[i]);
  231785. }
  231786. if (numOuts > 0)
  231787. {
  231788. outputDeviceNames.add (nameString);
  231789. outputIds.add (devs[i]);
  231790. }
  231791. }
  231792. }
  231793. alreadyLogged = true;
  231794. }
  231795. }
  231796. inputDeviceNames.appendNumbersToDuplicates (false, true);
  231797. outputDeviceNames.appendNumbersToDuplicates (false, true);
  231798. }
  231799. const StringArray getDeviceNames (bool wantInputNames) const
  231800. {
  231801. jassert (hasScanned); // need to call scanForDevices() before doing this
  231802. if (wantInputNames)
  231803. return inputDeviceNames;
  231804. else
  231805. return outputDeviceNames;
  231806. }
  231807. int getDefaultDeviceIndex (bool forInput) const
  231808. {
  231809. jassert (hasScanned); // need to call scanForDevices() before doing this
  231810. AudioDeviceID deviceID;
  231811. UInt32 size = sizeof (deviceID);
  231812. // if they're asking for any input channels at all, use the default input, so we
  231813. // get the built-in mic rather than the built-in output with no inputs..
  231814. AudioObjectPropertyAddress pa;
  231815. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  231816. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231817. pa.mElement = kAudioObjectPropertyElementMaster;
  231818. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  231819. {
  231820. if (forInput)
  231821. {
  231822. for (int i = inputIds.size(); --i >= 0;)
  231823. if (inputIds[i] == deviceID)
  231824. return i;
  231825. }
  231826. else
  231827. {
  231828. for (int i = outputIds.size(); --i >= 0;)
  231829. if (outputIds[i] == deviceID)
  231830. return i;
  231831. }
  231832. }
  231833. return 0;
  231834. }
  231835. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  231836. {
  231837. jassert (hasScanned); // need to call scanForDevices() before doing this
  231838. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  231839. if (d == 0)
  231840. return -1;
  231841. return asInput ? d->inputIndex
  231842. : d->outputIndex;
  231843. }
  231844. bool hasSeparateInputsAndOutputs() const { return true; }
  231845. AudioIODevice* createDevice (const String& outputDeviceName,
  231846. const String& inputDeviceName)
  231847. {
  231848. jassert (hasScanned); // need to call scanForDevices() before doing this
  231849. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  231850. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  231851. String deviceName (outputDeviceName);
  231852. if (deviceName.isEmpty())
  231853. deviceName = inputDeviceName;
  231854. if (index >= 0)
  231855. return new CoreAudioIODevice (deviceName,
  231856. inputIds [inputIndex],
  231857. inputIndex,
  231858. outputIds [outputIndex],
  231859. outputIndex);
  231860. return 0;
  231861. }
  231862. juce_UseDebuggingNewOperator
  231863. private:
  231864. StringArray inputDeviceNames, outputDeviceNames;
  231865. Array <AudioDeviceID> inputIds, outputIds;
  231866. bool hasScanned;
  231867. static int getNumChannels (AudioDeviceID deviceID, bool input)
  231868. {
  231869. int total = 0;
  231870. UInt32 size;
  231871. AudioObjectPropertyAddress pa;
  231872. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  231873. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231874. pa.mElement = kAudioObjectPropertyElementMaster;
  231875. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231876. {
  231877. HeapBlock <AudioBufferList> bufList;
  231878. bufList.calloc (size, 1);
  231879. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  231880. {
  231881. const int numStreams = bufList->mNumberBuffers;
  231882. for (int i = 0; i < numStreams; ++i)
  231883. {
  231884. const AudioBuffer& b = bufList->mBuffers[i];
  231885. total += b.mNumberChannels;
  231886. }
  231887. }
  231888. }
  231889. return total;
  231890. }
  231891. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  231892. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  231893. };
  231894. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  231895. {
  231896. return new CoreAudioIODeviceType();
  231897. }
  231898. #undef log
  231899. #endif
  231900. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  231901. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  231902. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231903. // compiled on its own).
  231904. #if JUCE_INCLUDED_FILE
  231905. #if JUCE_MAC
  231906. #undef log
  231907. #define log(a) Logger::writeToLog(a)
  231908. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  231909. {
  231910. if (err == noErr)
  231911. return true;
  231912. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  231913. jassertfalse
  231914. return false;
  231915. }
  231916. #undef OK
  231917. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  231918. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  231919. {
  231920. String result;
  231921. CFStringRef str = 0;
  231922. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  231923. if (str != 0)
  231924. {
  231925. result = PlatformUtilities::cfStringToJuceString (str);
  231926. CFRelease (str);
  231927. str = 0;
  231928. }
  231929. MIDIEntityRef entity = 0;
  231930. MIDIEndpointGetEntity (endpoint, &entity);
  231931. if (entity == 0)
  231932. return result; // probably virtual
  231933. if (result.isEmpty())
  231934. {
  231935. // endpoint name has zero length - try the entity
  231936. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  231937. if (str != 0)
  231938. {
  231939. result += PlatformUtilities::cfStringToJuceString (str);
  231940. CFRelease (str);
  231941. str = 0;
  231942. }
  231943. }
  231944. // now consider the device's name
  231945. MIDIDeviceRef device = 0;
  231946. MIDIEntityGetDevice (entity, &device);
  231947. if (device == 0)
  231948. return result;
  231949. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  231950. if (str != 0)
  231951. {
  231952. const String s (PlatformUtilities::cfStringToJuceString (str));
  231953. CFRelease (str);
  231954. // if an external device has only one entity, throw away
  231955. // the endpoint name and just use the device name
  231956. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  231957. {
  231958. result = s;
  231959. }
  231960. else if (! result.startsWithIgnoreCase (s))
  231961. {
  231962. // prepend the device name to the entity name
  231963. result = (s + " " + result).trimEnd();
  231964. }
  231965. }
  231966. return result;
  231967. }
  231968. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  231969. {
  231970. String result;
  231971. // Does the endpoint have connections?
  231972. CFDataRef connections = 0;
  231973. int numConnections = 0;
  231974. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  231975. if (connections != 0)
  231976. {
  231977. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  231978. if (numConnections > 0)
  231979. {
  231980. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  231981. for (int i = 0; i < numConnections; ++i, ++pid)
  231982. {
  231983. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  231984. MIDIObjectRef connObject;
  231985. MIDIObjectType connObjectType;
  231986. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  231987. if (err == noErr)
  231988. {
  231989. String s;
  231990. if (connObjectType == kMIDIObjectType_ExternalSource
  231991. || connObjectType == kMIDIObjectType_ExternalDestination)
  231992. {
  231993. // Connected to an external device's endpoint (10.3 and later).
  231994. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  231995. }
  231996. else
  231997. {
  231998. // Connected to an external device (10.2) (or something else, catch-all)
  231999. CFStringRef str = 0;
  232000. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  232001. if (str != 0)
  232002. {
  232003. s = PlatformUtilities::cfStringToJuceString (str);
  232004. CFRelease (str);
  232005. }
  232006. }
  232007. if (s.isNotEmpty())
  232008. {
  232009. if (result.isNotEmpty())
  232010. result += ", ";
  232011. result += s;
  232012. }
  232013. }
  232014. }
  232015. }
  232016. CFRelease (connections);
  232017. }
  232018. if (result.isNotEmpty())
  232019. return result;
  232020. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  232021. return getEndpointName (endpoint, false);
  232022. }
  232023. const StringArray MidiOutput::getDevices()
  232024. {
  232025. StringArray s;
  232026. const ItemCount num = MIDIGetNumberOfDestinations();
  232027. for (ItemCount i = 0; i < num; ++i)
  232028. {
  232029. MIDIEndpointRef dest = MIDIGetDestination (i);
  232030. if (dest != 0)
  232031. {
  232032. String name (getConnectedEndpointName (dest));
  232033. if (name.isEmpty())
  232034. name = "<error>";
  232035. s.add (name);
  232036. }
  232037. else
  232038. {
  232039. s.add ("<error>");
  232040. }
  232041. }
  232042. return s;
  232043. }
  232044. int MidiOutput::getDefaultDeviceIndex()
  232045. {
  232046. return 0;
  232047. }
  232048. static MIDIClientRef globalMidiClient;
  232049. static bool hasGlobalClientBeenCreated = false;
  232050. static bool makeSureClientExists()
  232051. {
  232052. if (! hasGlobalClientBeenCreated)
  232053. {
  232054. String name ("JUCE");
  232055. if (JUCEApplication::getInstance() != 0)
  232056. name = JUCEApplication::getInstance()->getApplicationName();
  232057. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  232058. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  232059. CFRelease (appName);
  232060. }
  232061. return hasGlobalClientBeenCreated;
  232062. }
  232063. class MidiPortAndEndpoint
  232064. {
  232065. public:
  232066. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  232067. : port (port_), endPoint (endPoint_)
  232068. {
  232069. }
  232070. ~MidiPortAndEndpoint()
  232071. {
  232072. if (port != 0)
  232073. MIDIPortDispose (port);
  232074. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  232075. MIDIEndpointDispose (endPoint);
  232076. }
  232077. MIDIPortRef port;
  232078. MIDIEndpointRef endPoint;
  232079. };
  232080. MidiOutput* MidiOutput::openDevice (int index)
  232081. {
  232082. MidiOutput* mo = 0;
  232083. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  232084. {
  232085. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  232086. CFStringRef pname;
  232087. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232088. {
  232089. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  232090. if (makeSureClientExists())
  232091. {
  232092. MIDIPortRef port;
  232093. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  232094. {
  232095. mo = new MidiOutput();
  232096. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  232097. }
  232098. }
  232099. CFRelease (pname);
  232100. }
  232101. }
  232102. return mo;
  232103. }
  232104. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  232105. {
  232106. MidiOutput* mo = 0;
  232107. if (makeSureClientExists())
  232108. {
  232109. MIDIEndpointRef endPoint;
  232110. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  232111. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  232112. {
  232113. mo = new MidiOutput();
  232114. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  232115. }
  232116. CFRelease (name);
  232117. }
  232118. return mo;
  232119. }
  232120. MidiOutput::~MidiOutput()
  232121. {
  232122. delete (MidiPortAndEndpoint*) internal;
  232123. }
  232124. void MidiOutput::reset()
  232125. {
  232126. }
  232127. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  232128. {
  232129. return false;
  232130. }
  232131. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  232132. {
  232133. }
  232134. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232135. {
  232136. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  232137. if (message.isSysEx())
  232138. {
  232139. const int maxPacketSize = 256;
  232140. int pos = 0, bytesLeft = message.getRawDataSize();
  232141. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  232142. HeapBlock <MIDIPacketList> packets;
  232143. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  232144. packets->numPackets = numPackets;
  232145. MIDIPacket* p = packets->packet;
  232146. for (int i = 0; i < numPackets; ++i)
  232147. {
  232148. p->timeStamp = 0;
  232149. p->length = jmin (maxPacketSize, bytesLeft);
  232150. memcpy (p->data, message.getRawData() + pos, p->length);
  232151. pos += p->length;
  232152. bytesLeft -= p->length;
  232153. p = MIDIPacketNext (p);
  232154. }
  232155. if (mpe->port != 0)
  232156. MIDISend (mpe->port, mpe->endPoint, packets);
  232157. else
  232158. MIDIReceived (mpe->endPoint, packets);
  232159. }
  232160. else
  232161. {
  232162. MIDIPacketList packets;
  232163. packets.numPackets = 1;
  232164. packets.packet[0].timeStamp = 0;
  232165. packets.packet[0].length = message.getRawDataSize();
  232166. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  232167. if (mpe->port != 0)
  232168. MIDISend (mpe->port, mpe->endPoint, &packets);
  232169. else
  232170. MIDIReceived (mpe->endPoint, &packets);
  232171. }
  232172. }
  232173. const StringArray MidiInput::getDevices()
  232174. {
  232175. StringArray s;
  232176. const ItemCount num = MIDIGetNumberOfSources();
  232177. for (ItemCount i = 0; i < num; ++i)
  232178. {
  232179. MIDIEndpointRef source = MIDIGetSource (i);
  232180. if (source != 0)
  232181. {
  232182. String name (getConnectedEndpointName (source));
  232183. if (name.isEmpty())
  232184. name = "<error>";
  232185. s.add (name);
  232186. }
  232187. else
  232188. {
  232189. s.add ("<error>");
  232190. }
  232191. }
  232192. return s;
  232193. }
  232194. int MidiInput::getDefaultDeviceIndex()
  232195. {
  232196. return 0;
  232197. }
  232198. struct MidiPortAndCallback
  232199. {
  232200. MidiInput* input;
  232201. MidiPortAndEndpoint* portAndEndpoint;
  232202. MidiInputCallback* callback;
  232203. MemoryBlock pendingData;
  232204. int pendingBytes;
  232205. double pendingDataTime;
  232206. bool active;
  232207. void processSysex (const uint8*& d, int& size, const double time)
  232208. {
  232209. if (*d == 0xf0)
  232210. {
  232211. pendingBytes = 0;
  232212. pendingDataTime = time;
  232213. }
  232214. pendingData.ensureSize (pendingBytes + size, false);
  232215. uint8* totalMessage = (uint8*) pendingData.getData();
  232216. uint8* dest = totalMessage + pendingBytes;
  232217. while (size > 0)
  232218. {
  232219. if (pendingBytes > 0 && *d >= 0x80)
  232220. {
  232221. if (*d >= 0xfa || *d == 0xf8)
  232222. {
  232223. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  232224. ++d;
  232225. --size;
  232226. }
  232227. else
  232228. {
  232229. if (*d == 0xf7)
  232230. {
  232231. *dest++ = *d++;
  232232. pendingBytes++;
  232233. --size;
  232234. }
  232235. break;
  232236. }
  232237. }
  232238. else
  232239. {
  232240. *dest++ = *d++;
  232241. pendingBytes++;
  232242. --size;
  232243. }
  232244. }
  232245. if (totalMessage [pendingBytes - 1] == 0xf7)
  232246. {
  232247. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  232248. pendingBytes = 0;
  232249. }
  232250. else
  232251. {
  232252. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  232253. }
  232254. }
  232255. };
  232256. namespace CoreMidiCallbacks
  232257. {
  232258. static CriticalSection callbackLock;
  232259. static VoidArray activeCallbacks;
  232260. }
  232261. static void midiInputProc (const MIDIPacketList* pktlist,
  232262. void* readProcRefCon,
  232263. void* /*srcConnRefCon*/)
  232264. {
  232265. double time = Time::getMillisecondCounterHiRes() * 0.001;
  232266. const double originalTime = time;
  232267. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  232268. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232269. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  232270. {
  232271. const MIDIPacket* packet = &pktlist->packet[0];
  232272. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  232273. {
  232274. const uint8* d = (const uint8*) (packet->data);
  232275. int size = packet->length;
  232276. while (size > 0)
  232277. {
  232278. time = originalTime;
  232279. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  232280. {
  232281. mpc->processSysex (d, size, time);
  232282. }
  232283. else
  232284. {
  232285. int used = 0;
  232286. const MidiMessage m (d, size, used, 0, time);
  232287. if (used <= 0)
  232288. {
  232289. jassertfalse // malformed midi message
  232290. break;
  232291. }
  232292. else
  232293. {
  232294. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  232295. }
  232296. size -= used;
  232297. d += used;
  232298. }
  232299. }
  232300. packet = MIDIPacketNext (packet);
  232301. }
  232302. }
  232303. }
  232304. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232305. {
  232306. MidiInput* mi = 0;
  232307. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  232308. {
  232309. MIDIEndpointRef endPoint = MIDIGetSource (index);
  232310. if (endPoint != 0)
  232311. {
  232312. CFStringRef pname;
  232313. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232314. {
  232315. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  232316. if (makeSureClientExists())
  232317. {
  232318. MIDIPortRef port;
  232319. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232320. mpc->active = false;
  232321. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  232322. {
  232323. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  232324. {
  232325. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  232326. mpc->callback = callback;
  232327. mpc->pendingBytes = 0;
  232328. mpc->pendingData.ensureSize (128);
  232329. mi = new MidiInput (getDevices() [index]);
  232330. mpc->input = mi;
  232331. mi->internal = mpc;
  232332. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232333. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232334. }
  232335. else
  232336. {
  232337. OK (MIDIPortDispose (port));
  232338. }
  232339. }
  232340. }
  232341. }
  232342. CFRelease (pname);
  232343. }
  232344. }
  232345. return mi;
  232346. }
  232347. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  232348. {
  232349. MidiInput* mi = 0;
  232350. if (makeSureClientExists())
  232351. {
  232352. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232353. mpc->active = false;
  232354. MIDIEndpointRef endPoint;
  232355. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  232356. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  232357. {
  232358. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  232359. mpc->callback = callback;
  232360. mpc->pendingBytes = 0;
  232361. mpc->pendingData.ensureSize (128);
  232362. mi = new MidiInput (deviceName);
  232363. mpc->input = mi;
  232364. mi->internal = mpc;
  232365. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232366. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232367. }
  232368. CFRelease (name);
  232369. }
  232370. return mi;
  232371. }
  232372. MidiInput::MidiInput (const String& name_)
  232373. : name (name_)
  232374. {
  232375. }
  232376. MidiInput::~MidiInput()
  232377. {
  232378. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  232379. mpc->active = false;
  232380. {
  232381. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232382. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  232383. }
  232384. if (mpc->portAndEndpoint->port != 0)
  232385. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  232386. delete mpc->portAndEndpoint;
  232387. delete mpc;
  232388. }
  232389. void MidiInput::start()
  232390. {
  232391. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232392. ((MidiPortAndCallback*) internal)->active = true;
  232393. }
  232394. void MidiInput::stop()
  232395. {
  232396. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232397. ((MidiPortAndCallback*) internal)->active = false;
  232398. }
  232399. #undef log
  232400. #else
  232401. MidiOutput::~MidiOutput()
  232402. {
  232403. }
  232404. void MidiOutput::reset()
  232405. {
  232406. }
  232407. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  232408. {
  232409. return false;
  232410. }
  232411. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  232412. {
  232413. }
  232414. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232415. {
  232416. }
  232417. const StringArray MidiOutput::getDevices()
  232418. {
  232419. return StringArray();
  232420. }
  232421. MidiOutput* MidiOutput::openDevice (int index)
  232422. {
  232423. return 0;
  232424. }
  232425. const StringArray MidiInput::getDevices()
  232426. {
  232427. return StringArray();
  232428. }
  232429. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232430. {
  232431. return 0;
  232432. }
  232433. #endif
  232434. #endif
  232435. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  232436. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  232437. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232438. // compiled on its own).
  232439. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  232440. #if ! JUCE_QUICKTIME
  232441. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  232442. #endif
  232443. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  232444. class QTCameraDeviceInteral;
  232445. END_JUCE_NAMESPACE
  232446. @interface QTCaptureCallbackDelegate : NSObject
  232447. {
  232448. @public
  232449. CameraDevice* owner;
  232450. QTCameraDeviceInteral* internal;
  232451. int64 firstPresentationTime;
  232452. int64 averageTimeOffset;
  232453. }
  232454. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  232455. - (void) dealloc;
  232456. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  232457. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  232458. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232459. fromConnection: (QTCaptureConnection*) connection;
  232460. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  232461. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232462. fromConnection: (QTCaptureConnection*) connection;
  232463. @end
  232464. BEGIN_JUCE_NAMESPACE
  232465. class QTCameraDeviceInteral
  232466. {
  232467. public:
  232468. QTCameraDeviceInteral (CameraDevice* owner, int index)
  232469. {
  232470. const ScopedAutoReleasePool pool;
  232471. session = [[QTCaptureSession alloc] init];
  232472. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  232473. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  232474. input = 0;
  232475. audioInput = 0;
  232476. audioDevice = 0;
  232477. fileOutput = 0;
  232478. imageOutput = 0;
  232479. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  232480. internalDev: this];
  232481. NSError* err = 0;
  232482. [device retain];
  232483. [device open: &err];
  232484. if (err == 0)
  232485. {
  232486. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  232487. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  232488. [session addInput: input error: &err];
  232489. if (err == 0)
  232490. {
  232491. resetFile();
  232492. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  232493. [imageOutput setDelegate: callbackDelegate];
  232494. if (err == 0)
  232495. {
  232496. [session startRunning];
  232497. return;
  232498. }
  232499. }
  232500. }
  232501. openingError = nsStringToJuce ([err description]);
  232502. DBG (openingError);
  232503. }
  232504. ~QTCameraDeviceInteral()
  232505. {
  232506. [session stopRunning];
  232507. [session removeOutput: imageOutput];
  232508. [session release];
  232509. [input release];
  232510. [device release];
  232511. [audioDevice release];
  232512. [audioInput release];
  232513. [fileOutput release];
  232514. [imageOutput release];
  232515. [callbackDelegate release];
  232516. }
  232517. void resetFile()
  232518. {
  232519. [fileOutput recordToOutputFileURL: nil];
  232520. [session removeOutput: fileOutput];
  232521. [fileOutput release];
  232522. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  232523. [session removeInput: audioInput];
  232524. [audioInput release];
  232525. audioInput = 0;
  232526. [audioDevice release];
  232527. audioDevice = 0;
  232528. [fileOutput setDelegate: callbackDelegate];
  232529. }
  232530. void addDefaultAudioInput()
  232531. {
  232532. NSError* err = nil;
  232533. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  232534. if ([audioDevice open: &err])
  232535. [audioDevice retain];
  232536. else
  232537. audioDevice = nil;
  232538. if (audioDevice != 0)
  232539. {
  232540. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  232541. [session addInput: audioInput error: &err];
  232542. }
  232543. }
  232544. void addListener (CameraImageListener* listenerToAdd)
  232545. {
  232546. const ScopedLock sl (listenerLock);
  232547. if (listeners.size() == 0)
  232548. [session addOutput: imageOutput error: nil];
  232549. listeners.addIfNotAlreadyThere (listenerToAdd);
  232550. }
  232551. void removeListener (CameraImageListener* listenerToRemove)
  232552. {
  232553. const ScopedLock sl (listenerLock);
  232554. listeners.removeValue (listenerToRemove);
  232555. if (listeners.size() == 0)
  232556. [session removeOutput: imageOutput];
  232557. }
  232558. void callListeners (CIImage* frame, int w, int h)
  232559. {
  232560. CoreGraphicsImage image (Image::ARGB, w, h, false);
  232561. CIContext* cic = [CIContext contextWithCGContext: image.context options: nil];
  232562. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  232563. CGContextFlush (image.context);
  232564. const ScopedLock sl (listenerLock);
  232565. for (int i = listeners.size(); --i >= 0;)
  232566. {
  232567. CameraImageListener* l = (CameraImageListener*) listeners[i];
  232568. if (l != 0)
  232569. l->imageReceived (image);
  232570. }
  232571. }
  232572. QTCaptureDevice* device;
  232573. QTCaptureDeviceInput* input;
  232574. QTCaptureDevice* audioDevice;
  232575. QTCaptureDeviceInput* audioInput;
  232576. QTCaptureSession* session;
  232577. QTCaptureMovieFileOutput* fileOutput;
  232578. QTCaptureDecompressedVideoOutput* imageOutput;
  232579. QTCaptureCallbackDelegate* callbackDelegate;
  232580. String openingError;
  232581. VoidArray listeners;
  232582. CriticalSection listenerLock;
  232583. };
  232584. END_JUCE_NAMESPACE
  232585. @implementation QTCaptureCallbackDelegate
  232586. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  232587. internalDev: (QTCameraDeviceInteral*) d
  232588. {
  232589. [super init];
  232590. owner = owner_;
  232591. internal = d;
  232592. firstPresentationTime = 0;
  232593. averageTimeOffset = 0;
  232594. return self;
  232595. }
  232596. - (void) dealloc
  232597. {
  232598. [super dealloc];
  232599. }
  232600. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  232601. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  232602. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232603. fromConnection: (QTCaptureConnection*) connection
  232604. {
  232605. if (internal->listeners.size() > 0)
  232606. {
  232607. const ScopedAutoReleasePool pool;
  232608. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  232609. CVPixelBufferGetWidth (videoFrame),
  232610. CVPixelBufferGetHeight (videoFrame));
  232611. }
  232612. }
  232613. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  232614. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232615. fromConnection: (QTCaptureConnection*) connection
  232616. {
  232617. const Time now (Time::getCurrentTime());
  232618. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  232619. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  232620. #else
  232621. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  232622. #endif
  232623. int64 presentationTime = (hosttime != nil)
  232624. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  232625. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  232626. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  232627. if (firstPresentationTime == 0)
  232628. {
  232629. firstPresentationTime = presentationTime;
  232630. averageTimeOffset = timeDiff;
  232631. }
  232632. else
  232633. {
  232634. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  232635. }
  232636. }
  232637. @end
  232638. BEGIN_JUCE_NAMESPACE
  232639. class QTCaptureViewerComp : public NSViewComponent
  232640. {
  232641. public:
  232642. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  232643. {
  232644. const ScopedAutoReleasePool pool;
  232645. captureView = [[QTCaptureView alloc] init];
  232646. [captureView setCaptureSession: internal->session];
  232647. setSize (640, 480); // xxx need to somehow get the movie size - how?
  232648. setView (captureView);
  232649. }
  232650. ~QTCaptureViewerComp()
  232651. {
  232652. setView (0);
  232653. [captureView setCaptureSession: nil];
  232654. [captureView release];
  232655. }
  232656. QTCaptureView* captureView;
  232657. };
  232658. CameraDevice::CameraDevice (const String& name_, int index)
  232659. : name (name_)
  232660. {
  232661. isRecording = false;
  232662. internal = new QTCameraDeviceInteral (this, index);
  232663. }
  232664. CameraDevice::~CameraDevice()
  232665. {
  232666. stopRecording();
  232667. delete static_cast <QTCameraDeviceInteral*> (internal);
  232668. internal = 0;
  232669. }
  232670. Component* CameraDevice::createViewerComponent()
  232671. {
  232672. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  232673. }
  232674. const String CameraDevice::getFileExtension()
  232675. {
  232676. return ".mov";
  232677. }
  232678. void CameraDevice::startRecordingToFile (const File& file, int quality)
  232679. {
  232680. stopRecording();
  232681. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  232682. d->callbackDelegate->firstPresentationTime = 0;
  232683. file.deleteFile();
  232684. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  232685. // out wrong, so we'll put some audio in there too..,
  232686. d->addDefaultAudioInput();
  232687. [d->session addOutput: d->fileOutput error: nil];
  232688. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  232689. for (;;)
  232690. {
  232691. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  232692. if (connection == 0)
  232693. break;
  232694. QTCompressionOptions* options = 0;
  232695. NSString* mediaType = [connection mediaType];
  232696. if ([mediaType isEqualToString: QTMediaTypeVideo])
  232697. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  232698. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  232699. : @"QTCompressionOptions240SizeH264Video"];
  232700. else if ([mediaType isEqualToString: QTMediaTypeSound])
  232701. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  232702. [d->fileOutput setCompressionOptions: options forConnection: connection];
  232703. }
  232704. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  232705. isRecording = true;
  232706. }
  232707. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  232708. {
  232709. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  232710. if (d->callbackDelegate->firstPresentationTime != 0)
  232711. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  232712. return Time();
  232713. }
  232714. void CameraDevice::stopRecording()
  232715. {
  232716. if (isRecording)
  232717. {
  232718. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  232719. isRecording = false;
  232720. }
  232721. }
  232722. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  232723. {
  232724. if (listenerToAdd != 0)
  232725. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  232726. }
  232727. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  232728. {
  232729. if (listenerToRemove != 0)
  232730. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  232731. }
  232732. const StringArray CameraDevice::getAvailableDevices()
  232733. {
  232734. const ScopedAutoReleasePool pool;
  232735. StringArray results;
  232736. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  232737. for (int i = 0; i < (int) [devs count]; ++i)
  232738. {
  232739. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  232740. results.add (nsStringToJuce ([dev localizedDisplayName]));
  232741. }
  232742. return results;
  232743. }
  232744. CameraDevice* CameraDevice::openDevice (int index,
  232745. int minWidth, int minHeight,
  232746. int maxWidth, int maxHeight)
  232747. {
  232748. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  232749. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  232750. return d.release();
  232751. return 0;
  232752. }
  232753. #endif
  232754. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  232755. #endif
  232756. #endif
  232757. END_JUCE_NAMESPACE
  232758. #endif
  232759. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  232760. #endif
  232761. #endif